
    ,h             
          d dl m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mZ d dlmZ d dlmZmZ d dlmZmZmZmZmZmZmZ dd	l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$m%Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z. ej^                  Z/ere0Z1 ee2      Z3g dZ4dejj                  vrdejj                  d<   dejj                  vrdejj                  d<   dejj                  vrdejj                  d<   dejj                  vrdejj                  d<   dejj                  vrdejj                  d<   dejj                  vrdejj                  d<   dejj                  vrdejj                  d<   dZ6dZ7dZ8d Z9d!Z:d"Z;d#Z<d$Z=d%Z>d&Z?d'Z@d(ZAd)ZBe@d*e>d+e=d,eAd-e?d.iZC G d/ d0eD      ZE G d1 d2 e
d2d3            ZF G d4 d5 e
d5d6            ZG G d7 d8 e
d8d9            ZHd: ZI G d; d<eJ      ZKd= ZLdVd>ZMdVd?ZN G d@ dAe      ZOdB ZPdC ZQdD ZRdE ZSdF ZTdG ZUdH ZVdI ZWdJ ZXdK ZYdL ZZdM Z[dN Z\ eJ       Z] G dO dPeJ      Z^dQ Z_dR Z`dS Za G dT dUe      Zby)W    )unicode_literalsN)
namedtuple)datetimedate)
itemgetter)LoggerAdapter	getLogger)moves	iteritems	text_typeinteger_typesPY3binary_type	iterbytes   )
exceptions)imap4)response_lexer)tls)datetime_to_INTERNALDATEformat_criteria_date)encodedecode)parse_responseparse_message_listparse_fetch_response)to_bytes
to_unicodeassert_imap_protocol)
IMAPClientSocketTimeoutDELETEDSEENANSWEREDFLAGGEDDRAFTRECENTXLIST)NONAUTHAUTHSELECTEDIDLESTARTTLS)r)   IDUNSELECT)r*   r+   ENABLE)r*   MOVEs   \Deleteds   \Seens	   \Answereds   \Flaggeds   \Drafts   \Recents   \Alls   \Archives   \Draftss   \Junks   \Sents   \Trash)) r2   )zINBOX..)Sentz
Sent Itemsz
Sent items)Drafts)Archive)TrashzDeleted ItemszDeleted Messages)JunkSpamc                   f    e Zd Zd Z e ed            Z e ed            Z e ed            Zy)	Namespacec                 4    t         j                  | |||f      S N)tuple__new__)clspersonalothershareds       W/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/imapclient/imapclient.pyr?   zNamespace.__new__h   s    }}S8UF";<<    r   r      N)	__name__
__module____qualname__r?   propertyr   rA   rB   rC    rE   rD   r;   r;   f   s3    = 
1&HZ]#Ejm$FrE   r;   c                       e Zd ZdZy)r!   a  Represents timeout configuration for an IMAP connection.

    :ivar connect: maximum time to wait for a connection attempt to remote server
    :ivar read: maximum time to wait for performing a read/write operation

    As an example, ``SocketTimeout(connect=15, read=60)`` will make the socket
    timeout if the connection takes more than 15 seconds to establish but
    read/write operations can take up to 60 seconds once the connection is done.
    NrG   rH   rI   __doc__rK   rE   rD   r!   r!   p       rE   r!   zconnect readc                       e Zd ZdZy)MailboxQuotaRootszQuota roots associated with a mailbox.

    Represents the response of a GETQUOTAROOT command.

    :ivar mailbox: the mailbox
    :ivar quota_roots: list of quota roots associated with the mailbox
    NrM   rK   rE   rD   rQ   rQ   |   s    rE   rQ   zmailbox quota_rootsc                       e Zd ZdZy)Quotaa>  Resource quota.

    Represents the response of a GETQUOTA command.

    :ivar quota_roots: the quota roots for which the limit apply
    :ivar resource: the resource being limited (STORAGE, MESSAGES...)
    :ivar usage: the current usage of the resource
    :ivar limit: the maximum allowed usage of the resource
    NrM   rK   rE   rD   rS   rS      rO   rE   rS   zquota_root resource usage limitc                       fd}|S )zEDecorator raising CapabilityError when a capability is not available.c                 F     t        j                          fd       }|S )Nc                     | j                        s$t        j                  dj                               | g|i |S )Nz%Server does not support {} capability)has_capabilityr   CapabilityErrorformat)clientargskwargs
capabilityfuncs      rD   wrapperz=require_capability.<locals>.actual_decorator.<locals>.wrapper   sI    ((4 00;BB:N  0000rE   )	functoolswraps)r^   r_   r]   s   ` rD   actual_decoratorz,require_capability.<locals>.actual_decorator   s%    			1 
	1 rE   rK   )r]   rb   s   ` rD   require_capabilityrc      s    
 rE   c                   
   e Zd ZdZej
                  Zej                  Zej                  Z
	 	 d]dZd Zd Zd Zd Zed        Z ed	      d^d
       Zd Zd_dZd^dZd Zd Z ed      d        Z ed      d^d       Zd Zd Zd Zd Z ed      d        Zd`dZ  ed      d`d       Z!d`dZ"d Z#d Z$d  Z%dad!Z& ed"      d#        Z'd$ Z(d% Z) ed&      d'        Z* ed&      d^d(       Z+ ed&      d)        Z,d^d*Z-d+ Z.d, Z/d- Z0d. Z1d/ Z2d0 Z3d1 Z4dbd2Z5 ed3      dcd4       Z6d5 Z7 ed6      ddd7       Z8ded8Z9d9 Z:dad:Z;dad;Z<dad<Z=d= Z>dad>Z?dad?Z@dad@ZAdadAZBd^dBZCdfdCZDdD ZE edE      dF        ZFd^dGZG edH      dI        ZH edH      dJ        ZI edK      dgdL       ZJ edK      dhdM       ZK edK      dN        ZL edK      dO        ZMdP ZNdQ ZOdidRZPdjdSZQdT ZRdU ZSdV ZTdW ZUdX ZVdY ZWdZ ZXd[ ZYed\        ZZy)kr    a  A connection to the IMAP server specified by *host* is made when
    this class is instantiated.

    *port* defaults to 993, or 143 if *ssl* is ``False``.

    If *use_uid* is ``True`` unique message UIDs be used for all calls
    that accept message ids (defaults to ``True``).

    If *ssl* is ``True`` (the default) a secure connection will be made.
    Otherwise an insecure connection over plain text will be
    established.

    If *ssl* is ``True`` the optional *ssl_context* argument can be
    used to provide an ``ssl.SSLContext`` instance used to
    control SSL/TLS connection parameters. If this is not provided a
    sensible default context will be used.

    If *stream* is ``True`` then *host* is used as the command to run
    to establish a connection to the IMAP server (defaults to
    ``False``). This is useful for exotic connection or authentication
    setups.

    Use *timeout* to specify a timeout for the socket connected to the
    IMAP server. The timeout can be either a float number, or an instance
    of :py:class:`imapclient.SocketTimeout`.

    * If a single float number is passed, the same timeout delay applies 
      during the  initial connection to the server and for all future socket 
      reads and writes.

    * In case of a ``SocketTimeout``, connection timeout and
      read/write operations can have distinct timeouts.

    * The default is ``None``, where no timeout is used.

    The *normalise_times* attribute specifies whether datetimes
    returned by ``fetch()`` are normalised to the local system time
    and include no timezone information (native), or are datetimes
    that include timezone information (aware). By default
    *normalise_times* is True (times are normalised to the local
    system time). This attribute can be changed between ``fetch()``
    calls if required.

    Can be used as a context manager to automatically close opened connections:

    >>> with IMAPClient(host="imap.foo.org") as client:
    ...     client.login("bar@foo.org", "passwd")

    Nc                    |r|t        d      |rt        d      |
|xr dxs d}|r|dk(  rt        j                  d       || _        || _        || _        || _        || _        || _        d| _	        d| _
        t        |t              st        ||      }|| _        d| _        d | _        d | _        | j#                         | _        t        j'                  d| j                  |rd	nd
       | j)                          t+        t-        d      t/                     }d| j$                  _        |j&                  | j$                  _        y )Nz#can't set 'port' when 'stream' Truez%can't use 'ssl' when 'stream' is Truei     zfAttempting to establish an encrypted connection to a port (143) often used for unencrypted connectionsTFzConnected to host %s over %szSSL/TLSz
plain textzimapclient.imaplib   )
ValueErrorloggerwarninghostportsslssl_contextstreamuse_uidfolder_encodenormalise_times
isinstancer!   _timeout_starttls_done_cached_capabilities	_idle_tag_create_IMAP4_imapdebug_set_read_timeoutIMAPlibLoggerAdapterr	   dict_mesg)	selfrk   rl   rp   rm   ro   rn   timeoutimaplib_loggers	            rD   __init__zIMAPClient.__init__   s7    !FGG !HII\;3%#D43;NN ) * 		&!# '=1#GW5G#$(!'')
3TYY"%Y<	9 	 -*+TV
 

)//

rE   c                     | S r=   rK   r   s    rD   	__enter__zIMAPClient.__enter__
  s    rE   c                     	 | j                          y# t        $ rA 	 | j                          Y y# t        $ r!}t        j	                  d|       Y d}~Y yd}~ww xY ww xY w)zLogout and closes the connection when exiting the context manager.

        All exceptions during logout and connection shutdown are caught because
        an error here usually means the connection was already closed.
        z*Could not close the connection cleanly: %sN)logout	Exceptionshutdownri   info)r   exc_typeexc_valexc_tbes        rD   __exit__zIMAPClient.__exit__  sU    	MKKM 	MM MH!LLM	Ms)    	A/	AAAAAc                 Z   | j                   rt        j                  | j                        S | j                  r@t        j                  | j                  | j                  | j                  | j                        S t        j                  | j                  | j                  | j                        S r=   )ro   imaplibIMAP4_streamrk   rm   r   	IMAP4_TLSrl   rn   rt   r   IMAP4WithTimeoutr   s    rD   rx   zIMAPClient._create_IMAP4  st    ;;''		2288==DIIt7G7G!%0 0 %%diiDMMJJrE   c                 |    | j                   0| j                  j                  | j                   j                         y y r=   )rt   _sock
settimeoutreadr   s    rD   r{   zIMAPClient._set_read_timeout%  s-    ==$JJ!!$--"4"45 %rE   c                 X    t        | j                  d| j                  j                        S )Nsslobj)getattrry   sockr   s    rD   r   zIMAPClient._sock)  s     tzz8TZZ__==rE   r-   c                    | j                   s| j                  rt        j                  d      | j                  j                  d      \  }}| j                  d||       d| _        t        j                  | j                  j                  || j                        | j                  _	        | j                  j                  j                  d      | j                  _        |d   S )a  Switch to an SSL encrypted connection by sending a STARTTLS command.

        The *ssl_context* argument is optional and should be a
        :py:class:`ssl.SSLContext` object. If no SSL context is given, a SSL 
        context with reasonable default settings will be used.

        You can enable checking of the hostname in the certificate presented
        by the server  against the hostname which was used for connecting, by
        setting the *check_hostname* attribute of the SSL context to ``True``.
        The default SSL context has this setting enabled.

        Raises :py:exc:`Error` if the SSL connection could not be established.

        Raises :py:exc:`AbortError` if the server does not support STARTTLS
        or an SSL connection is already established.
        zTLS session already establishedr-   starttlsTrbr   )rm   ru   r   IMAPClientAbortErrorry   _simple_command_checkokr   wrap_socketr   rk   makefilefile)r   rn   typdatas       rD   r   zIMAPClient.starttls/  s    $ 88t**112STTJJ..z:	Tj#t,"//$**//;		R

**//2248

AwrE   c                     	 | j                  dt        |      t        |      d      }t        j                  d|       |S # t        j                  $ r#}t        j                  t        |            d}~ww xY w)zVLogin using *username* and *password*, returning the
        server response.
        loginTunpackNzLogged in as %s)_command_and_checkr   r   IMAPClientError
LoginErrorstrri   r   )r   usernamepasswordrvr   s        rD   r   zIMAPClient.loginM  su    	0((8$8$	 ) B 	%x0		 )) 	0''A//	0s   'A A7A22A7c                     d|d|d|rd|z  z  dz  	 | j                  d|fd      S # t        j                  $ r#}t        j                  t	        |            d}~ww xY w)zAuthenticate using the OAUTH2 method.

        Gmail and Yahoo both support the 'XOAUTH2' mechanism, but Yahoo requires
        the 'vendor' portion in the payload.
        zuser=zauth=Bearer z
vendor=%sauthenticatec                     S r=   rK   )xauth_strings    rD   <lambda>z)IMAPClient.oauth2_login.<locals>.<lambda>i  s    ; rE   Nr   r   r   r   r   )r   useraccess_tokenmechvendorr   r   s         @rD   oauth2_loginzIMAPClient.oauth2_login^  sq     6:<H=611Kt	0**>4AVWW)) 	0''A//	0s   1 A'A""A'c                     |sd}|d|d|	 | j                  ddfdd      S # t        j                  $ r#}t        j                  t	        |            d}~ww xY w)	zGAuthenticate using the PLAIN method (requires server support).
        r2    r   PLAINc                     S r=   rK   )_r   s    rD   r   z(IMAPClient.plain_login.<locals>.<lambda>t  s    k rE   Tr   Nr   )r   identityr   authorization_identityr   r   s        @rD   plain_loginzIMAPClient.plain_loginm  sf     &%'"&<hQ	0**>7DYbf*gg)) 	0''A//	0s   ) AAAc                     | j                   j                         \  }}| j                  dd||       t        j	                  d       |d   S )z/Logout, returning the server response.
        BYEr   zLogged out, connection closedr   )ry   r   _check_respri   r   )r   r   r   s      rD   r   zIMAPClient.logoutx  sD     JJ%%'	T#t434AwrE   c                 b    | j                   j                          t        j                  d       y)zClose the connection to the IMAP server (without logging out)

        In most cases, :py:meth:`.logout` should be used instead of
        this. The logout method also shutdown down the connection.
        zConnection closedN)ry   r   ri   r   r   s    rD   r   zIMAPClient.shutdown  s!     	

'(rE   r0   c           	         | j                   j                  dk7  r,t        j                  d| j                   j                  z        | j	                  d|D cg c]  }t        |       c}ddd      }|sg S |j                         S c c}w )a0  Activate one or more server side capability extensions.

        Most capabilities do not need to be enabled. This is only
        required for extensions which introduce backwards incompatible
        behaviour. Two capabilities which may require enable are
        ``CONDSTORE`` and ``UTF8=ACCEPT``.

        A list of the requested extensions that were successfully
        enabled on the server is returned.

        Once enabled each extension remains active until the IMAP
        connection is closed.

        See :rfc:`5161` for more details.
        r*   z"ENABLE command illegal in state %ss   ENABLEFENABLEDT)uidresponse_namer   )ry   stater   IllegalStateError_raw_command_untaggedr   split)r   capabilitiescresps       rD   enablezIMAPClient.enable  s    " ::v%..4tzz7G7GG  ))"./QXa[/# *  Izz| 0s   B
r.   c                 v   |d}nXt        |t              st        d      t        d t        j
                  j                  |j                               D              }| j                  j                  d|      \  }}| j                  d||       | j                  j                  ||d      \  }}t        |      S )zIssue the ID command, returning a dict of server implementation
        fields.

        *parameters* should be specified as a dictionary of field/value pairs,
        for example: ``{"name": "IMAPClient", "version": "0.12"}``
        NILz#'parameters' should be a dictionaryc              3   2   K   | ]  }t        |        y wr=   )_quote).0vs     rD   	<genexpr>z!IMAPClient.id_.<locals>.<genexpr>  s      #Cq	#C   r.   id)rs   r}   	TypeErrorseq_to_parenstr	itertoolschainfrom_iterableitemsry   r   r   _untagged_responser   )r   
parametersr[   r   r   s        rD   id_zIMAPClient.id_  s     Dj$/ EFF" #C--j.>.>.@A#C CD JJ..tT:	TdC&JJ11#tTB	Td##rE   c                    | j                   r0| j                  j                  dk(  rd| _        | j	                         S | j                  r| j                  S t        | j                  j                        }|j                  dd      }|r%| j                  |d         | _        | j                  S | j                  j                  dv r!| j	                         | _        | j                  S t        d | j                  j                  D              S )a  Returns the server capability list.

        If the session is authenticated and the server has returned an
        untagged CAPABILITY response at authentication time, this
        response will be returned. Otherwise, the CAPABILITY command
        will be issued to the server, with the results cached for
        future calls.

        If the session is not yet authenticated, the capabilities
        requested at connection time will be returned.
        r)   N
CAPABILITYr   )r+   r*   c              3   2   K   | ]  }t        |        y wr=   )r   r   r   s     rD   r   z*IMAPClient.capabilities.<locals>.<genexpr>  s     BQXa[Br   )ru   ry   r   rv   _do_capabilites_dict_bytes_normaliseruntagged_responsespop_normalise_capabilitesr>   r   )r   untaggedresponses      rD   r   zIMAPClient.capabilities  s     4::#3#3y#@(,D%'')) $$,,, *$***G*GH<<d3(,(C(CHQK(PD%,,, ::33(,(<(<(>D%,,, B$***A*ABBBrE   c                 J    | j                  dd      }| j                  |      S )Nr]   Tr   )r   r   r   raw_responses     rD   r   zIMAPClient._do_capabilites  s(    ..|D.I**<88rE   c                 f    t        |      }t        |j                         j                               S r=   )r   r>   upperr   r   s     rD   r   z!IMAPClient._normalise_capabilites  s)    -\'')//122rE   c                 T    t        |      j                         | j                         v S )zGReturn ``True`` if the IMAP server has the given *capability*.
        )r   r   r   )r   r]   s     rD   rW   zIMAPClient.has_capability  s&     
#))+t/@/@/BBBrE   	NAMESPACEc                 2   | j                  d      }g }t        |      D ]o  }||j                  |       g }|D ]8  \  }}| j                  rt	        |      }|j                  |t        |      f       : |j                  t        |             q t        | S )a  Return the namespace for the account as a (personal, other,
        shared) tuple.

        Each element may be None if no namespace of that type exists,
        or a sequence of (prefix, separator) pairs.

        For convenience the tuple elements may be accessed
        positionally or using attributes named *personal*, *other* and
        *shared*.

        See :rfc:`2342` for more details.
        	namespace)r   r   appendrq   decode_utf7r   r>   r;   )r   r   partsitem	convertedprefix	separators          rD   r   zIMAPClient.namespace  s     &&{3"4( 		/D|T"	)- F%FI))!,V!4$$fj.C%DEF U9-.		/ %  rE   c                 (    | j                  d||      S )a*  Get a listing of folders on the server as a list of
        ``(flags, delimiter, name)`` tuples.

        Specifying *directory* will limit returned folders to the
        given base directory. The directory and any child directories
        will returned.

        Specifying *pattern* will limit returned folders to those with
        matching names. The wildcards are supported in
        *pattern*. ``*`` matches zero or more of any character and
        ``%`` matches 0 or more characters except the folder
        delimiter.

        Calling list_folders with no arguments will recursively list
        all folders available for the logged in user.

        Folder names are always returned as unicode strings, and
        decoded from modified UTF-7, except if folder_decode is not
        set.
        LIST_do_listr   	directorypatterns      rD   list_folderszIMAPClient.list_folders  s    * }}VY88rE   r(   c                 (    | j                  d||      S )a0  Execute the XLIST command, returning ``(flags, delimiter,
        name)`` tuples.

        This method returns special flags for each folder and a
        localized name for certain folders (e.g. the name of the
        inbox may be localized and the flags can be used to
        determine the actual inbox, even if the name has been
        localized.

        A ``XLIST`` response could look something like::

            [((b'\HasNoChildren', b'\Inbox'), b'/', u'Inbox'),
             ((b'\Noselect', b'\HasChildren'), b'/', u'[Gmail]'),
             ((b'\HasNoChildren', b'\AllMail'), b'/', u'[Gmail]/All Mail'),
             ((b'\HasNoChildren', b'\Drafts'), b'/', u'[Gmail]/Drafts'),
             ((b'\HasNoChildren', b'\Important'), b'/', u'[Gmail]/Important'),
             ((b'\HasNoChildren', b'\Sent'), b'/', u'[Gmail]/Sent Mail'),
             ((b'\HasNoChildren', b'\Spam'), b'/', u'[Gmail]/Spam'),
             ((b'\HasNoChildren', b'\Starred'), b'/', u'[Gmail]/Starred'),
             ((b'\HasNoChildren', b'\Trash'), b'/', u'[Gmail]/Trash')]

        This is a *deprecated* Gmail-specific IMAP extension (See
        https://developers.google.com/gmail/imap_extensions#xlist_is_deprecated
        for more information).

        The *directory* and *pattern* arguments are as per
        list_folders().
        r(   r  r	  s      rD   xlist_folderszIMAPClient.xlist_folders+  s    < }}Wi99rE   c                 (    | j                  d||      S )zReturn a list of subscribed folders on the server as
        ``(flags, delimiter, name)`` tuples.

        The default behaviour will list all subscribed folders. The
        *directory* and *pattern* arguments are as per list_folders().
        LSUBr  r	  s      rD   list_sub_folderszIMAPClient.list_sub_foldersK  s     }}VY88rE   c                    | j                  |      }| j                  |      }| j                  j                  |||      \  }}| j                  |||       | j                  j	                  |||      \  }}| j                  |      S r=   )_normalise_folderry   r   r   r   _proc_folder_list)r   cmdr
  r  r   dats         rD   r  zIMAPClient._do_listT  s{    **95	((1::--c9gFSc3$::00c3?S%%c**rE   c                    |D cg c]	  }|dvs| }}g }t        |      }|r^|d d \  }}}|dd  }t        |t        t        f      rt	        |      }n| j
                  rt        |      }|j                  |||f       |r^|S c c}w )N)rE   N   )r   rs   intlongr   rq   r   r   )r   folder_datar  retparsedflagsdelimnames           rD   r  zIMAPClient._proc_folder_list\  s     )4Ot;7NtOO,!'E5$ABZF$d, !##"4(JJud+,  
% Ps
   	BBc                    | j                  d      r<| j                         D ])  }|st        |d         dkD  s|d   d   |k(  s$|d   c S  | j                  d      r| j                         j                  }nt
        }|D ]M  }t        j                  |t                     D ]*  }|d   |z   }| j                  |      }|s |d   d   c c S  O y)a  Try to locate a special folder, like the Sent or Trash folder.

        >>> server.find_special_folder(imapclient.SENT)
        'INBOX.Sent'

        This function tries its best to find the correct folder (if any) but
        uses heuristics when the server is unable to precisely tell where
        special folders are located.

        Returns the name of the folder if found, or None otherwise.
        zSPECIAL-USEr   r   rF   r   )r  N)	rW   r  lenr   rA   _POPULAR_PERSONAL_NAMESPACES_POPULAR_SPECIAL_FOLDERSgetr>   )r   folder_flagfolderpersonal_namespacespersonal_namespacer  sent_folderss          rD   find_special_folderzIMAPClient.find_special_foldert  s     }-++- %c&)nq0VAYq\[5P!!9$% {+"&.."2";";">"5 	.377UWM .,Q/'9#000A'?1--	.	. rE   c                     | j                  d| j                  |      |       | j                  | j                  j                        S )a  Set the current folder on the server.

        Future calls to methods such as search and fetch will act on
        the selected folder.

        Returns a dictionary containing the ``SELECT`` response. At least
        the ``b'EXISTS'``, ``b'FLAGS'`` and ``b'RECENT'`` keys are guaranteed
        to exist. An example::

            {b'EXISTS': 3,
             b'FLAGS': (b'\Answered', b'\Flagged', b'\Deleted', ... ),
             b'RECENT': 0,
             b'PERMANENTFLAGS': (b'\Answered', b'\Flagged', b'\Deleted', ... ),
             b'READ-WRITE': True,
             b'UIDNEXT': 11,
             b'UIDVALIDITY': 1239278212}
        select)r   r  _process_select_responsery   r   )r   r'  readonlys      rD   select_folderzIMAPClient.select_folder  s<    $ 	$*@*@*H(S,,TZZ-J-JKKrE   r/   c                 r    t         j                  d       | j                  j                  d      \  }}|d   S )a"  Unselect the current folder and release associated resources.

        Unlike ``close_folder``, the ``UNSELECT`` command does not expunge
        the mailbox, keeping messages with \Deleted flag set for example.

        Returns the UNSELECT response string returned by the server.
        z
< UNSELECTr/   r   )ri   rz   ry   r   )r   _typr   s      rD   unselect_folderzIMAPClient.unselect_folder  s1     	\"ZZ//
;
dAwrE   c                    t        |      }i }|j                  dg       D ]]  }t        j                  d|      }|s|j	                  d      }|dk(  s3t        |j	                  d      j                               ||<   _ t        |      D ]^  \  }}|j                         }|dv r|dv rt        |d         }n,|d	k(  rd
}n$|dk(  rt        |d   dd j                               }|||<   ` |S )NOKs(   \[(?P<key>[A-Z-]+)( \((?P<data>.*)\))?\]key   PERMANENTFLAGSr   )s   OKr7  )s   EXISTSs   RECENTs   UIDNEXTs   UIDVALIDITYs   HIGHESTMODSEQr   s
   READ-WRITET   FLAGSr   )
r   r%  rematchgroupr>   r   r   r   r  )r   r   r   outliner;  r6  values           rD   r.  z#IMAPClient._process_select_response  s   )$/ LLr* 	BDHHI4PEkk%(++$U[[%8%>%>%@ACH	B $H- 
	JC))+C00\\E!H%eAhqn2245CH
	 
rE   c                 \    | j                   j                  d      }| j                  |d      S )a  Execute the NOOP command.

        This command returns immediately, returning any server side
        status updates. It can also be used to reset any auto-logout
        timers.

        The return value is the server command response message
        followed by a list of status responses. For example::

            (b'NOOP completed.',
             [(4, b'EXISTS'),
              (3, b'FETCH', (b'FLAGS', (b'bar', b'sne'))),
              (6, b'FETCH', (b'FLAGS', (b'sne',)))])

        NOOP)ry   _command_consume_until_tagged_response)r   tags     rD   noopzIMAPClient.noop  s+      jj!!&)223??rE   r,   c                     | j                   j                  d      | _        | j                   j                         }|t	        j
                  d|z        y)a  Put the server into IDLE mode.

        In this mode the server will return unsolicited responses
        about changes to the selected mailbox. This method returns
        immediately. Use ``idle_check()`` to look for IDLE responses
        and ``idle_done()`` to stop IDLE mode.

        .. note::

            Any other commmands issued while the server is in IDLE
            mode will fail.

        See :rfc:`2177` for more information about the IDLE extension.
        r,   NzUnexpected IDLE response: %s)ry   rB  rw   _get_responser   r   )r   r   s     rD   idlezIMAPClient.idle  sN      ,,V4zz''),,-Kd-RSS rE   c                 n   | j                   }|j                  d       |j                  d       	 g }t        j                  |gg g |      \  }}}|r7	 	 | j                  j                         }|j                  t        |             6||j                  d       | j!                          S # t        j                  t        j                  f$ r Y Ht        j                  $ r, t        j                         d   }d|j                  d   v rY  w xY w# |j                  d       | j!                          w xY w)a  Check for any IDLE responses sent by the server.

        This method should only be called if the server is in IDLE
        mode (see ``idle()``).

        By default, this method will block until an IDLE response is
        received. If *timeout* is provided, the call will block for at
        most this many seconds while waiting for an IDLE response.

        The return value is a list of received IDLE responses. These
        will be parsed with values converted to appropriate types. For
        example::

            [(b'OK', b'Still here'),
             (1, b'EXISTS'),
             (1, b'FETCH', (b'FLAGS', (b'\NotJunk',)))]
        Nr   r   EOF)r   r   setblockingr-  ry   	_get_liner   _parse_untagged_responsesocketr   errorr    
AbortErrorsysexc_infor[   r{   )r   r   r   respsrsr   r>  errs           rD   
idle_checkzIMAPClient.idle_check  s   & zz 		%E}}dVRW=HB1E#zz335 %=d%CD  Q""$ #NNFLL9 %00 " "llnQ/ CHHQK/!!" Q""$s;   "D B+ -D +#DD :D
D DD #D4c                     t         j                  d       | j                  j                  d       | j	                  | j
                  d      S )a  Take the server out of IDLE mode.

        This method should only be called if the server is already in
        IDLE mode.

        The return value is of the form ``(command_text,
        idle_responses)`` where *command_text* is the text sent by the
        server when the IDLE command finished (eg. ``b'Idle
        terminated'``) and *idle_responses* is a list of parsed idle
        responses received since the last call to ``idle_check()`` (if
        any). These are returned in parsed form as per
        ``idle_check()``.
        z< DONEs   DONE
r,   )ri   rz   ry   sendrC  rw   r   s    rD   	idle_donezIMAPClient.idle_done-  s7     	X

$224>>6JJrE   c                 $   |d}nt        |      }ddj                  |      z  }| j                  |      }| j                  d||      }t	        |      }	 |d   }t        t        |            S # t
        $ r t        dt        |      z         w xY w)a+  Return the status of *folder*.

        *what* should be a sequence of status items to query. This
        defaults to ``('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY',
        'UNSEEN')``.

        Returns a dictionary of the status items for the folder with
        keys matching *what*.
        )MESSAGESr'   UIDNEXTUIDVALIDITYUNSEENz(%s) statusr9  z folder_status ValueError: Input )
normalise_text_listjoinr  r   r   rh   r   r   r}   as_pairs)r   r'  whatwhat_fnamer   r   status_itemss           rD   folder_statuszIMAPClient.folder_status@  s     <MD&t,D#((4.)&&v.&&x>!$'	P#B<L H\*++  	P>XNOO	Ps   A. .!Bc                 (    | j                  dd      S )z[Close the currently selected folder, returning the server
        response string.
        closeTr   )r   r   s    rD   close_folderzIMAPClient.close_folderY  s     &&wt&<<rE   c                 H    | j                  d| j                  |      d      S )zLCreate *folder* on the server returning the server response string.
        createTr   r   r  r   r'  s     rD   create_folderzIMAPClient.create_folder_  (     &&x1G1G1OX\&]]rE   c                 h    | j                  d| j                  |      | j                  |      d      S )z3Change the name of a folder on the server.
        renameTr   rn  )r   old_namenew_names      rD   rename_folderzIMAPClient.rename_folderd  s=     &&x'+'='=h'G'+'='=h'G.2 ' 4 	4rE   c                 H    | j                  d| j                  |      d      S )zLDelete *folder* on the server returning the server response string.
        deleteTr   rn  ro  s     rD   delete_folderzIMAPClient.delete_folderl  rq  rE   c                 >    t        | j                  d|            dkD  S )z:Return ``True`` if *folder* exists on the server.
        r2   r   )r"  r  ro  s     rD   folder_existszIMAPClient.folder_existsq  s!     4$$R01A55rE   c                 D    | j                  d| j                  |            S )zESubscribe to *folder*, returning the server response string.
        	subscribern  ro  s     rD   subscribe_folderzIMAPClient.subscribe_folderv  s"     &&{D4J4J64RSSrE   c                 D    | j                  d| j                  |            S )zGUnsubscribe to *folder*, returning the server response string.
        unsubscribern  ro  s     rD   unsubscribe_folderzIMAPClient.unsubscribe_folder{  s"     &&}d6L6LV6TUUrE   c                 &    | j                  ||      S )a$	  Return a list of messages ids from the currently selected
        folder matching *criteria*.

        *criteria* should be a sequence of one or more criteria
        items. Each criteria item may be either unicode or
        bytes. Example values::

            [u'UNSEEN']
            [u'SMALLER', 500]
            [b'NOT', b'DELETED']
            [u'TEXT', u'foo bar', u'FLAGGED', u'SUBJECT', u'baz']
            [u'SINCE', date(2005, 4, 3)]

        IMAPClient will perform conversion and quoting as
        required. The caller shouldn't do this.

        It is also possible (but not recommended) to pass the combined
        criteria as a single string. In this case IMAPClient won't
        perform quoting, allowing lower-level specification of
        criteria. Examples of this style::

            u'UNSEEN'
            u'SMALLER 500'
            b'NOT DELETED'
            u'TEXT "foo bar" FLAGGED SUBJECT "baz"'
            b'SINCE 03-Apr-2005'

        To support complex search expressions, criteria lists can be
        nested. IMAPClient will insert parentheses in the right
        places. The following will match messages that are both not
        flagged and do not have "foo" in the subject:

            ['NOT', ['SUBJECT', 'foo', 'FLAGGED']]

        *charset* specifies the character set of the criteria. It
        defaults to US-ASCII as this is the only charset that a server
        is required to support by the RFC. UTF-8 is commonly supported
        however.

        Any criteria specified using unicode will be encoded as per
        *charset*. Specifying a unicode criteria that can not be
        encoded using *charset* will result in an error.

        Any criteria specified using bytes will be sent as-is but
        should use an encoding that matches *charset* (the character
        set given is still passed on to the server).

        See :rfc:`3501#section-6.4.4` for more details.

        Note that criteria arguments that are 8-bit will be
        transparently sent by IMAPClient as IMAP literals to ensure
        adherence to IMAP standards.

        The returned list of message ids will have a special *modseq*
        attribute. This is set if the server included a MODSEQ value
        to the search response (i.e. if a MODSEQ criteria was included
        in the search).

        _search)r   criteriacharsets      rD   searchzIMAPClient.search  s    x ||Hg..rE   z
X-GM-EXT-1c                 *    | j                  d|g|      S )a  Search using Gmail's X-GM-RAW attribute.

        *query* should be a valid Gmail search query string. For
        example: ``has:attachment in:unread``. The search string may
        be unicode and will be encoded using the specified *charset*
        (defaulting to UTF-8).

        This method only works for IMAP servers that support X-GM-RAW,
        which is only likely to be Gmail.

        See https://developers.google.com/gmail/imap_extensions#extension_of_the_search_command_x-gm-raw
        for more info.
        s   X-GM-RAWr  )r   queryr  s      rD   gmail_searchzIMAPClient.gmail_search  s     ||[%0'::rE   c           
         g }|r|j                  dt        |      g       |j                  t        ||             	 | j                  d|      }t!        |      S # t        j
                  j                  $ rz}t        j                  dt        |            }|rSt        j                  dj                  |j                  d      t        |t              sd|z              |             d }~ww xY w)Ns   CHARSETs   SEARCHz"SEARCH command error: BAD \[(.+)\]z{original_msg}

This error may have been caused by a syntax error in the criteria: {criteria}
Please refer to the documentation for more information about search criteria syntax..
https://imapclient.readthedocs.io/en/master/#imapclient.IMAPClient.searchr   "%s")original_msgr  )extendr   _normalise_search_criteriar   r   IMAP4rO  r:  r;  r   r   InvalidCriteriaErrorrY   r<  rs   listr   )r   r  r  r[   r   r   ms          rD   r  zIMAPClient._search  s    KKXg%678.xAB	--i>D( "$''' }}"" 	>AGA 55`
 V%&WWQZ:DXt:T(!2  
 
 [c  
 
 #	s   A C17A5C,,C1SORTc                     t        |      t        |      g}|j                  t        ||             | j	                  d|d      }|j                         D cg c]  }t        |       c}S c c}w )a  Return a list of message ids from the currently selected
        folder, sorted by *sort_criteria* and optionally filtered by
        *criteria*.

        *sort_criteria* may be specified as a sequence of strings or a
        single string. IMAPClient will take care any required
        conversions. Valid *sort_criteria* values::

            ['ARRIVAL']
            ['SUBJECT', 'ARRIVAL']
            'ARRIVAL'
            'REVERSE SIZE'

        The *criteria* and *charset* arguments are as per
        :py:meth:`.search`.

        See :rfc:`5256` for full details.

        Note that SORT is an extension to the IMAP4 standard so it may
        not be supported by all IMAP servers.
        s   SORTTr   )_normalise_sort_criteriar   r  r  r   r   r  )r   sort_criteriar  r  r[   idsis          rD   sortzIMAPClient.sort  sf    0 %]3W
 	.xAB(($t(D!$-AQ---s   A-c                     t        |      }| j                  d|z         st        j                  d|z        |t        |      gt	        ||      z   }| j                  d|      }t        |      S )a  Return a list of messages threads from the currently
        selected folder which match *criteria*.

        Each returned thread is a list of messages ids. An example
        return value containing three message threads::

            ((1, 2), (3,), (4, 5, 6))

        The optional *algorithm* argument specifies the threading
        algorithm to use.

        The *criteria* and *charset* arguments are as per
        :py:meth:`.search`.

        See :rfc:`5256` for more details.
        s   THREAD=z2The server does not support %s threading algorithms   THREAD)r   rW   r   rX   r  r   r   )r   	algorithmr  r  r[   r   s         rD   threadzIMAPClient.thread  sy    " Y'	"":	#9:,,DyP  8G,-&x9:)))T:d##rE   c                 L    | j                  |dg      }| j                  |d      S )zReturn the flags set for each message in *messages* from
        the currently selected folder.

        The return value is a dictionary structured like this: ``{
        msgid1: (flag1, flag2, ... ), }``.
        FLAGSr8  )fetch_filter_fetch_dict)r   messagesr   s      rD   	get_flagszIMAPClient.get_flags'  s)     ::h	2&&x::rE   c                 .    | j                  d||d|      S )zAdd *flags* to *messages* in the currently selected folder.

        *flags* should be a sequence of strings.

        Returns the flags set for each modified message (see
        *get_flags*), or None if *silent* is true.
        s   +FLAGSr8  silent_storer   r  r  r  s       rD   	add_flagszIMAPClient.add_flags1  s     {{9hx{OOrE   c                 .    | j                  d||d|      S )a   Remove one or more *flags* from *messages* in the currently
        selected folder.

        *flags* should be a sequence of strings.

        Returns the flags set for each modified message (see
        *get_flags*), or None if *silent* is true.
        s   -FLAGSr8  r  r  r  s       rD   remove_flagszIMAPClient.remove_flags;  s     {{9hx{OOrE   c                 .    | j                  d||d|      S )zSet the *flags* for *messages* in the currently selected
        folder.

        *flags* should be a sequence of strings.

        Returns the flags set for each modified message (see
        *get_flags*), or None if *silent* is true.
        r8  r  r  r  s       rD   	set_flagszIMAPClient.set_flagsF  s     {{8Xuhv{NNrE   c                     | j                  |dg      }| j                  |d      }t        |      D ci c]  \  }}|t        |       c}}S c c}}w )a>  Return the label set for each message in *messages* in the
        currently selected folder.

        The return value is a dictionary structured like this: ``{
        msgid1: (label1, label2, ... ), }``.

        This only works with IMAP servers that support the X-GM-LABELS
        attribute (eg. Gmail).
           X-GM-LABELS)r  r  r   utf7_decode_sequence)r   r  r   msglabelss        rD   get_gmail_labelszIMAPClient.get_gmail_labelsQ  s]     ::h(89**8^D#,X#68C )&11 8 	8 8s   Ac                 ,    | j                  d|||      S )aW  Add *labels* to *messages* in the currently selected folder.

        *labels* should be a sequence of strings.

        Returns the label set for each modified message (see
        *get_gmail_labels*), or None if *silent* is true.

        This only works with IMAP servers that support the X-GM-LABELS
        attribute (eg. Gmail).
        s   +X-GM-LABELSr  _gm_label_storer   r  r  r  s       rD   add_gmail_labelszIMAPClient.add_gmail_labels`  s%     ##OXv+1 $ 3 	3rE   c                 ,    | j                  d|||      S )ap  Remove one or more *labels* from *messages* in the
        currently selected folder, or None if *silent* is true.

        *labels* should be a sequence of strings.

        Returns the label set for each modified message (see
        *get_gmail_labels*).

        This only works with IMAP servers that support the X-GM-LABELS
        attribute (eg. Gmail).
        s   -X-GM-LABELSr  r  r  s       rD   remove_gmail_labelszIMAPClient.remove_gmail_labelsn  s%     ##OXv+1 $ 3 	3rE   c                 ,    | j                  d|||      S )ad  Set the *labels* for *messages* in the currently selected
        folder.

        *labels* should be a sequence of strings.

        Returns the label set for each modified message (see
        *get_gmail_labels*), or None if *silent* is true.

        This only works with IMAP servers that support the X-GM-LABELS
        attribute (eg. Gmail).
        r  r  r  r  s       rD   set_gmail_labelszIMAPClient.set_gmail_labels}  s%     ##NHf+1 $ 3 	3rE   c                 2    | j                  |t        |      S )zDelete one or more *messages* from the currently selected
        folder.

        Returns the flags set for each modified message (see
        *get_flags*).
        r  )r  r"   )r   r  r  s      rD   delete_messageszIMAPClient.delete_messages  s     ~~h~??rE   c                    |si S dt        |      t        |      |rt        |      ndg}| j                  r|j                  dd        | j                  j
                  | }| j                  j                  d|      \  }}| j                  d||       | j                  j                  ||d      \  }}t        || j                  | j                        S )a  Retrieve selected *data* associated with one or more
        *messages* in the currently selected folder.

        *data* should be specified as a sequnce of strings, one item
        per data selector, for example ``['INTERNALDATE',
        'RFC822']``.

        *modifiers* are required for some extensions to the IMAP
        protocol (eg. :rfc:`4551`). These should be a sequnce of strings
        if specified, for example ``['CHANGEDSINCE 123']``.

        A dictionary is returned, indexed by message number. Each item
        in this dictionary is also a dictionary, with an entry
        corresponding to each item in *data*. Returned values will be
        appropriately typed. For example, integer values will be returned as
        Python integers, timestamps will be returned as datetime
        instances and ENVELOPE responses will be returned as
        :py:class:`Envelope <imapclient.response_types.Envelope>` instances.

        String data will generally be returned as bytes (Python 3) or
        str (Python 2).

        In addition to an element for each *data* item, the dict
        returned for each message also contains a *SEQ* key containing
        the sequence number for the message. This allows for mapping
        between the UID and sequence number (when the *use_uid*
        property is ``True``).

        Example::

            >> c.fetch([3293, 3230], ['INTERNALDATE', 'FLAGS'])
            {3230: {b'FLAGS': (b'\Seen',),
                    b'INTERNALDATE': datetime.datetime(2011, 1, 30, 13, 32, 9),
                    b'SEQ': 84},
             3293: {b'FLAGS': (),
                    b'INTERNALDATE': datetime.datetime(2011, 2, 24, 19, 30, 36),
                    b'SEQ': 110}}

        FETCHNr   UIDr  )join_message_idsseq_to_parenstr_upperrp   insertry   rB  _command_completer   r   r   rr   )r   r  r   	modifiersr[   rD  r   s          rD   r  zIMAPClient.fetch  s    P I X&!$'09!),t	
 <<KK5!!djj!!4(JJ00#>	TgsD)JJ11#tWE	T#D$*>*>MMrE   c           	          |r,dt        |      z  }t        rt        |      }nt        |      }nd}| j	                  d| j                  |      t        |      |t        |      d      S )ao  Append a message to *folder*.

        *msg* should be a string contains the full message including
        headers.

        *flags* should be a sequence of message flags to set. If not
        specified no flags will be set.

        *msg_time* is an optional datetime instance specifying the
        date and time to set on the message. The server will set a
        time if it isn't specified. If *msg_time* contains timezone
        information (tzinfo), this will be honoured. Otherwise the
        local machine's time zone sent to the server.

        Returns the APPEND response as returned by the server.
        r  Nr   Tr   )r   r   r   r   r   r  r   )r   r'  r  r  msg_timetime_vals         rD   r   zIMAPClient.append  sp    "  8 BBH%h/#H-H&&x'+'='=f'E'6u'='/'/}.2 ' 4 	4rE   c                 ^    | j                  dt        |      | j                  |      dd      S )zCopy one or more messages from the current folder to
        *folder*. Returns the COPY response string returned by the
        server.
        copyTr   r   r   r  r  r   r  r'  s      rD   r  zIMAPClient.copy  s9    
 &&v'7'A'+'='=f'E+/ ' > 	>rE   r1   c                 ^    | j                  dt        |      | j                  |      dd      S )zAtomically move messages to another folder.

        Requires the MOVE capability, see :rfc:`6851`.

        :param messages: List of message UIDs to move.
        :param folder: The destination folder name.
        moveTr  r  r  s      rD   r  zIMAPClient.move  s9     &&v'7'A'+'='=f'E+/ ' > 	>rE   c                     |r4| j                   st        d      | j                  dt        |      d      S | j                  j                  d      }| j                  |d      S )a2  When, no *messages* are specified, remove all messages
        from the currently selected folder that have the
        ``\Deleted`` flag set.

        The return value is the server response message
        followed by a list of expunge responses. For example::

            ('Expunge completed.',
             [(2, 'EXPUNGE'),
              (1, 'EXPUNGE'),
              (0, 'RECENT')])

        In this case, the responses indicate that the message with
        sequence numbers 2 and 1 where deleted, leaving no recent
        messages in the folder.

        See :rfc:`3501#section-6.4.3` section 6.4.3 and
        :rfc:`3501#section-7.4.1` section 7.4.1 for more details.

        When *messages* are specified, remove the specified messages
        from the selected folder, provided those messages also have
        the ``\Deleted`` flag set. The return value is ``None`` in
        this case.

        Expunging messages by id(s) requires that *use_uid* is
        ``True`` for the client.

        See :rfc:`4315#section-2.1` section 2.1 for more details.
        z(cannot EXPUNGE by ID when not using uidsEXPUNGETr   )rp   rh   r   r  ry   rB  rC  )r   r  rD  s      rD   expungezIMAPClient.expunge  s`    < << !KLL**96Fx6PVZ*[[jj!!),223	BBrE   ACLc                     | j                  d| j                  |            }t        t        j                  |            }|dd }t        dt        |      d      D cg c]  }||   ||dz      f c}S c c}w )zeReturns a list of ``(who, acl)`` tuples describing the
        access controls for *folder*.
        getaclr   Nr   rF   )r   r  r  r   TokenSourcexranger"  )r   r'  r   r   r  s        rD   r  zIMAPClient.getacl+  ss    
 &&x1G1G1OP^//56ab	28CJ2JKQq5Q<(KKKs   A4c                 L    | j                  d| j                  |      ||d      S )zSet an ACL (*what*) for user (*who*) for a folder.

        Set *what* to an empty string to remove an ACL. Returns the
        server response string.
        setaclTr   rn  )r   r'  whord  s       rD   r  zIMAPClient.setacl5  s4     &&x'+'='=f'E'*D.2 ' 4 	4rE   QUOTAc                 *    | j                  |      d   S )z\Get the quotas associated with a mailbox.

        Returns a list of Quota objects.
        r   )get_quota_root)r   mailboxs     rD   	get_quotazIMAPClient.get_quotaA  s     ""7+A..rE   c                 J    t        | j                  dt        |                  S )a	  Get the quotas associated with a quota root.

        This method is not private but put behind an underscore to show that
        it is a low-level function. Users probably want to use `get_quota`
        instead.

        Returns a list of Quota objects.
        getquota)_parse_quotar   r   )r   
quota_roots     rD   
_get_quotazIMAPClient._get_quotaI  s&     ##Jz0BC
 	
rE   c           	         | j                  dt        |      dd      }t        | j                  j                  dg       }t        |      }t        t        |d         |dd D cg c]  }t        |       c}      }|t        |      fS c c}w )	a/  Get the quota roots for a mailbox.

        The IMAP server responds with the quota root and the quotas associated
        so there is usually no need to call `get_quota` after.

        See :rfc:`2087` for more details.

        Return a tuple of MailboxQuotaRoots and list of Quota associated
        s   GETQUOTAROOTF	QUOTAROOTr   r   r  r   r   N)	r   r   pop_with_defaultry   r   r   rQ   r   r  )r   r  quota_root_rep	quota_repqr  s         rD   r  zIMAPClient.get_quota_rootW  s     33Xg.E% 4 
 %TZZ%B%BGRP	'7&~a()$212$67qZ]7

 <	222 8s   $B

c                    |syd}t               }|D ]`  }||j                  }n||j                  k7  rt        d      |j                  dj	                  |j
                  |j                               b dj                  |      }t        t        |            t        dj	                  |            g}| j                  d|dd	      }t        |      S )
z[Set one or more quotas on resources.

        :param quotas: list of Quota objects
        Nz*set_quota only accepts a single quota rootz{} {}r_  z({})s   SETQUOTAFr  r  )r  r  rh   r   rY   resourcelimitrb  r   r   r   r  )r   quotasr  set_quota_argsquotar[   r   s          rD   	set_quotazIMAPClient.set_quotan  s     
 	E!"--
u/// !MNN!!u~~u{{;	 .1VJ'(V]]>23

 --5 . 
 H%%rE   c                 Z    ||k7  r&t        j                  |dt        |d               y)zcCheck command responses for errors.

        Raises IMAPClient.Error if the command fails.
        z	 failed: r   N)r   r   r   )r   expectedcommandr   r   s        rD   r   zIMAPClient._check_resp  s2    
 (?,,TXYZT[I\-]^^ rE   c                    | j                   j                  }g }	 | j                   j                         }||   rn|j                  t	        |             ;|j                  |      \  }}| j                  |||       |d   |fS )Nr   )ry   tagged_commandsrG  r   rM  r   r   )r   rD  r  r  rS  r>  r   r   s           rD   rC  z)IMAPClient._consume_until_tagged_response  s    **44::++-Ds#LL1$78	 
 $'',	TgsD)Aw~rE   c                     | j                  |||      \  }}||}| j                  j                  ||t        |            \  }}| j	                  t        |      ||       |r|d   S |S )Nr  r   )_raw_commandry   r   r   r   )r   r  r[   r   r   r   r   r   s           rD   r   z IMAPClient._raw_command_untagged  so    %%gt%=	T #MJJ11#tZ=VW	Tj)357NrE   c                    |j                         }t        |t              rt        |      }t        |t              s|g}| j                  j                         }t        |      g}|r| j                  r|j                  d       |j                  |       g }t        ||z         D ]  \  }}t        |t              st        d      t        |      r|rDdj                  |      }	t        j                  d|	       | j                  j!                  |	       g }t        |t"              r|j$                  }| j'                  ||       |r| j                  j!                  d       |j                  |        |rBdj                  |      }	t        j                  d|	       | j                  j!                  |	       | j                  j!                  d       | j                  j)                  t+        |      |      S )a}  Run the specific command with the arguments given. 8-bit arguments
        are sent as literals. The return value is (typ, data).

        This sidesteps much of imaplib's command sending
        infrastructure because imaplib can't send more than one
        literal.

        *command* should be specified as bytes.
        *args* should be specified as a list of bytes.
        s   UIDz$command args must be passed as bytes    z> %ss   
)r   rs   r>   r  ry   _new_tagr   rp   r   _iter_with_lastbytesrh   _is8bitrb  ri   rz   rX  _quotedoriginal_send_literalr  r   )
r   r  r[   r   rD  r  r>  r  is_lastr=  s
             rD   r  zIMAPClient._raw_command  s    --/dE":D$%6Djj!!#3-4<<MM&!g,Vd]; 	"MD'dE* !GHHt}))D/CLL-JJOOC(D dG,==D""3-JJOOD)D!'	"* ))D/CLL%JJOOC 

 zz++Jw,?EErE   c                 &   dt        t        |            j                  d      z   dz   }t        j	                  |       | j
                  j                  |       | j
                  j                         rc| j
                  j                  j                  |      }|r!t        j                  dt        |      z         | j
                  j                         rct        j	                  dt        |d             | j
                  j                  |       y)z:Send a single literal for the command with *tag*.
        s    {asciis   }
z=unexpected response while waiting for continuation response: z   (literal) > %s   N)r   r"  r   ri   rz   ry   rX  rG  r  r%  r   r   reprdebug_trunc)r   rD  r  r=  tagged_resps        rD   r  zIMAPClient._send_literal  s     c#d)n++G44x?S

 jj&&(**4488=K 55S%&' ' jj&&( 	(+dC*@A

rE   c                 r   t        |dd      }t        |dd      }|rJ ddj                  |      z          |r>| j                  r2t        rt	        |      } | j
                  j                  |g| \  }}n't        | j
                  t	        |            } || \  }}| j                  |||       |r|d   S |S )Nr   Fr   zunexpected keyword args: z, r   )	r  rb  rp   r   r   ry   r   r   r   )	r   r  r[   r\   r   r   r   r   meths	            rD   r   zIMAPClient._command_and_check  s    !&(E:vue4J669JJJ4<<$W-&

w66IC4::z'':;DdICgsD)7NrE   c                 ,    | j                  d|||       y )Nr5  )r   )r   r  r   r   s       rD   r   zIMAPClient._checkok  s    wT2rE   c                     | j                  ||| j                  |      d|      }|r(t        |      D ci c]  \  }}|t        |       c}}S d S c c}}w )Nr  r  )r  _normalise_labelsr   r  )r   r  r  r  r  r   r  s          rD   r  zIMAPClient._gm_label_store  sn    ;;sHd.D.DV.L)&  : <D9X#68C )&11 8 	NIM	N 8s   Ac                     |si S |r|dz  }| j                  dt        |      |t        |      d      }|ry| j                  t	        |      |      S )z~Worker function for the various flag manipulation methods.

        *cmd* is the STORE command to use (eg. '+FLAGS').
        s   .SILENTstoreTr  N)r   r  r   r  r   )r   r  r  r  	fetch_keyr  r   s          rD   r  zIMAPClient._store  sl    
 I:C&&w'7'A'*'6u'=+/	 ' 1
 &&';D'A'02 	2rE   c                 >    t        fdt        |      D              S )Nc              3   2   K   | ]  \  }}||   f  y wr=   rK   )r   msgidr   r6  s      rD   r   z0IMAPClient._filter_fetch_dict.<locals>.<genexpr>&  s&      >#t DI& >s   )r}   r   )r   
fetch_dictr6  s     `rD   r  zIMAPClient._filter_fetch_dict%  s"     >'0'<> > 	>rE   c                     t        |t              r|j                  d      }| j                  rt	        |      }t        |      S )Nr  )rs   r   r   rq   encode_utf7r   )r   folder_names     rD   r  zIMAPClient._normalise_folder)  s:    k;/%,,W5K%k2Kk""rE   c                     t        |t        t        f      r|f}|D cg c]  }t        t	        |             c}S c c}w r=   )rs   r   r   r   r  )r   r  ls      rD   r  zIMAPClient._normalise_labels0  s5    fy+67YF0671{1~&777s   <c                 N    	 | j                   j                  S # t        $ r Y yw xY w)z"access the server greeting messageN)ry   welcomeAttributeErrorr   s    rD   r  zIMAPClient.welcome5  s)    	::%%% 		s    	$$)NTTFNNr=   )XOAUTH2N)r2   *)F)ALLN)UTF-8)r#  r$  )
REFERENCESr#  r$  )rK   N)INBOX)r2   )NFT)T)[rG   rH   rI   rN   r   r   Errorr   rP  IMAPClientReadOnlyErrorReadOnlyErrorr   r   r   rx   r{   rJ   r   rc   r   r   r   r   r   r   r   r   r   r   r   rW   r   r  r  r  r  r  r+  r0  r3  r.  rE  rH  rV  rY  rh  rk  rp  rv  ry  r{  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r   rC  r   r  r  r   r   r  r  r  r  r  r  rK   rE   rD   r    r       s`   0j &&E00J66MGL+/,0\MK6 > >
 
# $:"0	0) ! "> $ $*%CN93C $! %!69.  : !:>9+0!FL* 
# $4@& T  T( .%  .%` K  K$,2=^
4^
6
T
V
</| %; &; (: .  .<$8;P	P	O8333@7Nr4@> >  >#CJ L L 	4 	4  / !/  
 !
  3 !3,  & !&@_
	5Fn$"3N2(>#8
  rE   r    c                     t        | t              r'| j                  dd      } | j                  dd      } d}n&| j                  dd      } | j                  dd      } d}|| z   |z   S )	N\z\\"z\"   \   \\   "   \")rs   r   replace)argr  s     rD   r   r   >  sd    #y!kk$'kk#u%kk%)kk$'s7Q;rE   c           	      X   | st        j                  d      |sd}t        | t        t        f      rt        | |      gS g }| D ]  }t        |t              r*|j                  t        |      j                  d             =t        |t        t        f      r|j                  t        |             nt        |t        t        f      r3t        |      }d|d   z   |d<   |d   dz   |d<   |j!                  |       |j                  t"        j%                  t        ||                    |S )Nzno criteria specifiedus-asciir     (r   r9     ))r   r  rs   r   r   r   r  r   r   r   r   r   r   r  r>   r  r  r  maybe)r  r  r=  r  inners        rD   r  r  I  s   --.EFF(Y457+,,
C ?dC JJs4y''01x./JJ+D12tUm,.t4EeAhE!Hb	D(E"IJJuJJw}}XdG%<=>? JrE   c                 p    t        | t        t        f      r| g} ddj                  d | D              z   dz   S )Nr5  r  c              3   N   K   | ]  }t        |      j                           y wr=   )r   r   r   r  s     rD   r   z+_normalise_sort_criteria.<locals>.<genexpr>f  s     HtHTN002Hs   #%r6  )rs   r   r   rb  )r  r  s     rD   r  r  c  s7    (Y45:$))HxHHH4OOrE   c                        e Zd ZdZed        Zy)r  z
    This class holds a quoted bytes value which provides access to the
    unquoted value via the *original* attribute.

    They should be created via the *maybe* classmethod.
    c                     |j                  dd      }|j                  dd      }||k7  sd|v s|s | d|z   dz         }||_        |S |S )a!  Maybe quote a bytes value.

        If the input requires no quoting it is returned unchanged.

        If quoting is required a *_quoted* instance is returned. This
        holds the quoted version of the input while also providing
        access to the original unquoted source.
        r-  r.  r/  r0  r  )r1  r  )r@   r  quotedr=  s       rD   r7  z_quoted.maybeq  sZ     !!%1f-XvdVmd*+C#CLJrE   N)rG   rH   rI   rN   classmethodr7  rK   rE   rD   r  r  i  s      rE   r  c                 *    t        t        |             S r=   )r  _normalise_text_listr   s    rD   ra  ra    s    $U+,,rE   c                 *    t        t        |             S r=   _join_and_parenrA  rB  s    rD   r   r     s    /677rE   c                 8    t        d t        |       D              S )Nc              3   <   K   | ]  }|j                           y wr=   )r   r;  s     rD   r   z(seq_to_parenstr_upper.<locals>.<genexpr>  s     PD4::<Ps   rD  rB  s    rD   r  r    s    P4H4OPPPrE   c                 0    ddj                  |       z   dz   S )N(r_  ))rb  rB  s    rD   rE  rE    s    % 3&&rE   c                 F    t        | t        t        f      r| f} d | D        S )Nc              3   2   K   | ]  }t        |        y wr=   )r   r   s     rD   r   z'_normalise_text_list.<locals>.<genexpr>  s     )aJqM)r   )rs   r   r   rB  s    rD   rA  rA    s#    %)[12)5))rE   c                     t        | t        t        t        f      rt	        |       f} dj                  d | D              S )z|Convert a sequence of messages ids or a single integer message id
    into an id byte string for use with IMAP commands
       ,c              3   2   K   | ]  }t        |        y wr=   )_maybe_int_to_bytes)r   r  s     rD   r   z#join_message_ids.<locals>.<genexpr>  s     >(+>r   )rs   r   r   r   r   rb  )r  s    rD   r  r    s7     (Y]CDX&(99>X>>>rE   c                 l    t        | t              rt        |       j                  d      S t	        |       S )Nr4  )rs   r   r   r   r   )vals    rD   rP  rP    s)    #}%3xz**C=rE   c                     t        | j                  d             | dd  } | j                  d      rt        | j                  dd            S t	        | g      S )Ns   * rF   )s   OK s   NO r  r   )r   
startswithr>   r   r   )texts    rD   rM  rM    sN    /08D'(TZZa())4&!!rE   c                 0    || v r| j                  |      S |S r=   )r   )dctr6  defaults      rD   r  r    s    
czwws|NrE   c              #   H   K   d}d }| D ]  }|dz  r||f n|}|dz  } y w)Nr   rF   r   rK   )r   r  	last_itemr  s       rD   rc  rc    s>     	AI q5T/!I	Qs    "c                 2    t        |       }t        |||      S r=   )iterzip)r   as     rD   as_tripletsr_    s    UAq!Q<rE   c                 8    t        d t        |       D              S )Nc              3   &   K   | ]	  }|d kD    yw)   NrK   )r   bs     rD   r   z_is8bit.<locals>.<genexpr>  s     01q3w0s   )anyr   )r   s    rD   r  r    s    0	$000rE   c              #   `   K   t        |       dz
  }t        |       D ]  \  }}|||k(  f  y w)Nr   )r"  	enumerate)r   last_ir  r  s       rD   r   r     s:     Z!^FU#  4AK s   ,.c                   @    e Zd ZdZd Zd ZeZd ZefdZ	efdZ
d Zy)	r   zMWrap a dict with unicode/bytes keys and normalise the keys to
    bytes.
    c                     || _         y r=   )_d)r   ds     rD   r   z_dict_bytes_normaliser.__init__  s	    rE   c              #   d   K   t        | j                        D ]  \  }}t        |      |f  y wr=   )r   rj  r   )r   r6  r?  s      rD   r   z _dict_bytes_normaliser.iteritems  s1     #DGG, 	'JC3-&&	's   .0c                 P    | j                  |      D ]  }|| j                  v s y y)NTF)	_gen_keysrj  )r   inkks      rD   __contains__z#_dict_bytes_normaliser.__contains__  s-    $ 	ADGG|	 rE   c                     | j                  |      D ]  }	 | j                  |   c S  |t        k(  rt        |      |S # t        $ r Y 7w xY wr=   )rn  rj  KeyError_not_presentr   ro  rX  rp  s       rD   r%  z_dict_bytes_normaliser.get  sZ    $ 	Awwqz!	
 l"3-	  s   >	A
	A
c                     | j                  |      D ]  }	 | j                  j                  |      c S  |t        k(  rt        |      |S # t        $ r Y Cw xY wr=   )rn  rj  r   rs  rt  ru  s       rD   r   z_dict_bytes_normaliser.pop  s^    $ 	Aww{{1~%	
 l"3-	  s   A

	AAc              #   j   K   | t        |t              rt        |       y t        |       y wr=   )rs   r   r   r   )r   rp  s     rD   rn  z _dict_bytes_normaliser._gen_keys  s)     a%Q-1+s   13N)rG   rH   rI   rN   r   r   r   rq  rt  r%  r   rn  rK   rE   rD   r   r     s6    '
 E  ,   , rE   r   c                     t        |       |k  rt        |       S |dz  }t        | d |       dz   t        | | d        z   S )NrF   z...)r"  r
  )r   maxlenhls      rD   r  r    sE    
1vAw	1B#2<5 42#$=00rE   c                 >    | D cg c]  }t        |       c}S c c}w r=   )r   )seqss     rD   r  r    s    $'(qKN(((s   c                     t        |       } t               }t        |       D ]N  \  }}t        |      D ];  }|j	                  t        t        |      t        |d         |d   |d                = P |S )Nr   r   rF   )r  r  usager  )r   r  rc  r_  r   rS   r   )r  r   r  quota_resource_infosquota_resource_infos        rD   r  r    s    y)I	B,4Y,? (
(#./C#D 	IIe%j1#$7$:;)!,)!,	 	 IrE   c                   "     e Zd ZdZ fdZ xZS )r|   zCAdapter preventing IMAP secrets from going to the logging facility.c                     dD ]@  }|j                  d      s||v s|j                  |      d   }dj                  ||      } n t        t        |   ||      S )N)LOGINAUTHENTICATE>r   z{}{} **REDACTED**)rT  r   rY   superr|   process)r   r  r\   r  	msg_start	__class__s        rD   r  zIMAPlibLoggerAdapter.process#  sh    0 	G~~c"w#~IIg.q1	)00GD		
 )48
 	
rE   )rG   rH   rI   rN   r  __classcell__)r  s   @rD   r|   r|      s    M
 
rE   r|   r=   )c
__future__r   r`   r   r   r-  rN  rQ  r:  collectionsr   r   r   operatorr   loggingr   r	   sixr
   r   r   r   r   r   r   r2   r   r   r   r   datetime_utilr   r   	imap_utf7r   r  r   r   response_parserr   r   r   utilr   r   r   r  r  r  rG   ri   __all__Commandsr"   r#   r$   r%   r&   r'   r#  ARCHIVEDRAFTSJUNKSENTTRASHr#  r$  r>   r;   r!   rQ   rS   rc   objectr    r   r  r  r  ra  r   r  rE  rA  r  rP  rM  r  rc  r_  r  r   rt  r   r  r  r  r|   rK   rE   rD   <module>r     s  
 (      
 	 " #  , W W W     I C U U < <	D 
8	H
 '""" ?GW 
!!!>GV W%%%#/GZ 
 w<GT W%%%#7GZ  7###!*GX 
!!!3GV 
	 
	  ;  	
.
K\	9
 % %	J? 	
#68MN 	Jw AB 	"Y Yx,	4Pk <-8Q'*
?"
1  x.V .b1)
= 
rE   