
    h9=             	          S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKJrJr  SSKJr  SSKJr  SSKJrJrJrJr  SSKJr  SSKJr  SS	KJrJr  SS
KJ r J!r!J"r"  SSK#J$r$  SSK%J&r&J'r'J(r(J)r)J*r*  SSK+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;  SSK<J=r>J?r?J@rAJBrCJDrEJFrGJHrIJJrKJLrMJNrOJPrPJQrR  SSKSJTrTJUrU  SSKVJWrWJXrX  SSKYJZrZJ[r[J\r\J]r]  \^" \_" \`" SS5      SR                  5       5      5      rbS rcS rd " S S5      re " S S5      rf " S S5      rg " S S5      rh " S S 5      riS!rj\k" \" \`" S"5      \`" S#S$5      5      5      rlS%\j-   \l-   rm\mR                  S&5      ro\R                  " S'\o-   S(-   5      rq\k" S) \`" S$5       5       5      rr\" \G5       " S* S+\TR                  \UR                  5      5       ru\!R                  " 5       rw\" \G5       " S, S-\TR                  \UR                  5      5       rxSwS. jryS/rzS0r{\|r}SxS1 jr~S2 rS3 rSwS4 jrS5 rS6 rS7 rSyS8 jrS9 rS:\kS;\k4S< jr " S= S>5      rS?rS@ rSA rSB rSC rSD r\" \>5       " SE SF5      5       r\" \P5       " SG SH\5      5       rSISJSKSLSMSN.rSO rSP rSQ rSR rSS rST rSU r " SV SW5      r " SX SY\5      r " SZ S[\5      r " S\ S]\5      r " S^ S_\5      rSzS` jrSa rSb rSc r " Sd Se5      r " Sf Sg5      r " Sh Si5      rSj r\" \SkSl 5      rSm rSn rSwSo jrSwSp jr " Sq Sr\GRZ                  5      r " Ss St\GR\                  5      r\GR^                  " \\\\5      rSu r\GRd                  " \5        / SvQrg){a  
An IMAP4 protocol implementation

@author: Jp Calderone

To do::
  Suspend idle timeout while server is processing
  Use an async message parser instead of buffering in memory
  Figure out a way to not queue multi-message client requests (Flow? A simple callback?)
  Clarify some API docs (Query, etc)
  Make APPEND recognize (again) non-existent mailboxes before accepting the literal
    N)decodebytesencodebytes)BytesIO)chain)AnyListOptionalcast)implementer)credentials)UnauthorizedLoginUnhandledCredentials)defererror
interfaces)maybeDeferred)CramMD5ClientAuthenticatorLOGINAuthenticatorLOGINCredentialsPLAINAuthenticatorPLAINCredentials)IllegalClientResponseIllegalIdentifierErrorIllegalMailboxEncodingIllegalOperationIllegalQueryErrorIllegalServerResponseIMAP4ExceptionMailboxCollisionMailboxExceptionMismatchedNestingMismatchedQuotingNegativeResponseNoSuchMailboxNoSupportedAuthenticationReadOnlyMailboxUnhandledResponse)IAccountIMAPIClientAuthenticationICloseableMailboxIMAPIMailboxIMAPIMailboxIMAPInfoIMailboxIMAPListenerIMessageIMAPIMessageIMAPCopierIMessageIMAPFileIMessageIMAPPartINamespacePresenterISearchableIMAPMailbox)basicpolicies)logtext)_matchingString	iterbytesnativeStringnetworkString      z/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Decc                     XL a  U$ U $ )z
Swap C{this} with C{that} if C{this} is C{ifIs}.

@param this: The object that may be replaced.

@param that: The object that may replace C{this}.

@param ifIs: An object whose identity will be compared to
    C{this}.
 )thisthatifIss      Y/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/mail/imap4.py_swaprD   _   s     <4)T)    c           
      h    U  VVs/ s H  u  p4[        X1U5      [        XAU5      4PM     snn$ s  snnf )an  
Swap each element in each pair in C{of} with C{that} it is
C{ifIs}.

@param of: A list of 2-L{tuple}s, whose members may be the object
    C{that}
@type of: L{list} of 2-L{tuple}s

@param ifIs: An object whose identity will be compared to members
    of each pair in C{of}

@return: A L{list} of 2-L{tuple}s with all occurences of C{ifIs}
    replaced with C{that}
)rD   )ofrA   rB   firstseconds        rC   _swapAllPairsrJ   m   s=      TVSU-%uD	!5t#<=SU  s   $.c                       \ rS rSr% Sr/ r\\   \S'   \	" S5      r
\\4S jr\S 5       r\R                  S 5       r\4S jrS	 rS
 rS rS rS rS rS rS rS\4S jrS\4S jrS\S\4S jrSrg)
MessageSet   aV	  
A set of message identifiers usable by both L{IMAP4Client} and
L{IMAP4Server} via L{IMailboxIMAP.store} and
L{IMailboxIMAP.fetch}.

These identifiers can be either message sequence numbers or unique
identifiers.  See Section 2.3.1, "Message Numbers", RFC 3501.

This represents the C{sequence-set} described in Section 9,
"Formal Syntax" of RFC 3501:

    - A L{MessageSet} can describe a single identifier, e.g.
      C{MessageSet(1)}

    - A L{MessageSet} can describe C{*} via L{None}, e.g.
      C{MessageSet(None)}

    - A L{MessageSet} can describe a range of identifiers, e.g.
      C{MessageSet(1, 2)}.  The range is inclusive and unordered
      (see C{seq-range} in RFC 3501, Section 9), so that
      C{Message(2, 1)} is equivalent to C{MessageSet(1, 2)}, and
      both describe messages 1 and 2.  Ranges can include C{*} by
      specifying L{None}, e.g. C{MessageSet(None, 1)}.  In all
      cases ranges are normalized so that the smallest identifier
      comes first, and L{None} always comes last; C{Message(2, 1)}
      becomes C{MessageSet(1, 2)} and C{MessageSet(None, 1)}
      becomes C{MessageSet(1, None)}

    - A L{MessageSet} can describe a sequence of single
      identifiers and ranges, constructed by addition.
      C{MessageSet(1) + MessageSet(5, 10)} refers the message
      identified by C{1} and the messages identified by C{5}
      through C{10}.

B{NB: The meaning of * varies, but it always represents the
largest number in use}.

B{For servers}: Your L{IMailboxIMAP} provider must set
L{MessageSet.last} to the highest-valued identifier (unique or
message sequence) before iterating over it.

B{For clients}: C{*} consumes ranges smaller than it, e.g.
C{MessageSet(1, 100) + MessageSet(50, None)} is equivalent to
C{1:*}.

@type getnext: Function taking L{int} returning L{int}
@ivar getnext: A function that returns the next message number,
    used when iterating through the L{MessageSet}.  By default, a
    function returning the next integer is supplied, but as this
    can be rather inefficient for sparse UID iterations, it is
    recommended to supply one when messages are requested by UID.
    The argument is provided as a hint to the implementation and
    may be ignored if it makes sense to do so (eg, if an iterator
    is being used that maintains its own state, it is guaranteed
    that it will not be called out-of-order).
_emptyinfc                     U R                   U l        / U l        S U l        XR                   L a  g[	        U[
        5      (       a  USS U l        U R                  5         gU R                  X5        g)z
Create a new MessageSet()

@type start: Optional L{int}
@param start: Start of range, or only message number

@type end: Optional L{int}
@param end: End of range.
c                     U S-   $ Nr<   r?   xs    rC   <lambda>%MessageSet.__init__.<locals>.<lambda>   s    QrE   N)rN   _lastrangesgetnext
isinstancelistcleanaddselfstartends      rC   __init__MessageSet.__init__   sY     [[
& KKeT""(DKJJLHHU rE   c                     U R                   $ )zc
The largest number in use.
This is undefined until it has been set by assigning to this property.
)rW   r_   s    rC   lastMessageSet.last   s     zzrE   c                     U R                   U R                  La  [        S5      eXl         [        U R                  5       H)  u  nu  p4Uc  UnUc  UnX4:  a  XCpCX44U R                  U'   M+     U R                  5         g)z
Replaces all occurrences of "*".  This should be the
largest number in use.  Must be set before attempting to
use the MessageSet as a container.

@raises ValueError: if a largest value has already been set.
zlast already setN)rW   rN   
ValueError	enumeraterX   r\   )r_   valueilowhighs        rC   rf   rg      sv     ::T[[(/00
'4NA{{|z T![DKKN 5 	

rE   c           	      H   X R                   L a  UnU R                  U R                   La  Uc  U R                  nUc  U R                  n[        X/[        R
                  " [        U R                  SS9S9u  pU R                  R                  X45        U R                  5         g)z
Add another range

@type start: L{int}
@param start: Start of range, or only message number

@type end: Optional L{int}
@param end: End of range.
NrA   rB   )key)rN   rW   rf   sorted	functoolspartialrD   	_infinityrX   appendr\   r^   s      rC   r]   MessageSet.add   s     ++C::T[[(}		{iiLi//DNNQUV

 	E<(

rE   c                 Z   [        U[        5      (       a$  U R                  UR                  -   n[        U5      $ [        U R                  5      nU R                  U R                  La  U R                  Ul         UR
                  " U6   U$ ! [         a    UR                  U5         U$ f = fN)rZ   rL   rX   rf   rN   r]   	TypeError)r_   otherrX   ress       rC   __add__MessageSet.__add__  s    eZ(([[5<</Ff%%T[[)Cyy+99 J  Js   :B B*)B*c                    [        U[        5      (       a7  U R                  R                  UR                  5        U R	                  5         U $  U R
                  " U6   U $ ! [         a    U R                  U5         U $ f = f)z
Extend our messages with another message or set of messages.

@param other: The messages to include.
@type other: L{MessageSet}, L{tuple} of two L{int}s, or a
    single L{int}
)rZ   rL   rX   extendr\   r]   rz   r_   r{   s     rC   r   MessageSet.extend  sp     eZ((KKu||,JJL  %      s   A A>=A>c                 J   [        [        U R                  U R                  SS95      n[	        S5      [	        S5      4/nU HA  u  p4US   u  pVXcS-
  :  a  UR                  X445        M(  [        XS5      [        Xd5      4US'   MC     [        USS SU R                  S9U l        g)z.
Clean ranges list, combining adjacent ranges
Nrp   z-infr<   )rr   rJ   rX   ru   floatrv   minmax)r_   rX   mergedRangesrm   rn   previousLowpreviousHighs          rC   r\   MessageSet.clean/  s    
 dkkTRSvf67IC(4R(8%KAg%##SK0 #K 5s<7NOL   $L$44dnnUrE   c                 *    U R                   S   S   SL $ )a  
Is there a L{None} in our ranges?

L{MessageSet.clean} merges overlapping or consecutive ranges.
None is represents a value larger than any number.  There are
thus two cases:

    1. C{(x, *) + (y, z)} such that C{x} is smaller than C{y}

    2. C{(z, *) + (x, y)} such that C{z} is larger than C{y}

(Other cases, such as C{y < x < z}, can be split into these
two cases; for example C{(y - 1, y)} + C{(x, x) + (z, z + 1)})

In case 1, C{* > y} and C{* > z}, so C{(x, *) + (y, z) = (x,
*)}

In case 2, C{z > x and z > y}, so the intervals do not merge,
and the ranges are sorted as C{[(x, y), (z, *)]}.  C{*} is
represented as C{(*, *)}, so this is the same as 2.  but with
a C{z} that is greater than everything.

The result is that there is a maximum of two L{None}s, and one
of them has to be the high element in the last tuple in
C{self.ranges}.  That means checking if C{self.ranges[-1][-1]}
is L{None} suffices to check if I{any} element is L{None}.

@return: L{True} if L{None} is in some range in ranges and
    L{False} if otherwise.
r   N)rX   re   s    rC   _noneInRangesMessageSet._noneInRangesC  s    > {{2r"d**rE   c                     U R                  5       (       a  [        S5      eU R                   H  u  p#X!s=::  a
  U::  d  M     g  M     g)zs
May raise TypeError if we encounter an open-ended range

@param value: Is this in our ranges?
@type value: L{int}
z.Can't determine membership; last value not setTF)r   rz   rX   )r_   rk   rm   rn   s       rC   __contains__MessageSet.__contains__d  sG     LMMIC#t# $ % rE   c              #      #    U R                    H<  u  pU R                  US-
  5      nX::  d  M   Uv   U R                  U5      nX::  a  M  M>     g 7frR   )rX   rY   )r_   lhs      rC   	_iteratorMessageSet._iteratoru  sE     KKDAQU#A&LLO &  s   )AAAc                 b    U R                  5       (       a  [        S5      eU R                  5       $ )Nz!Can't iterate; last value not set)r   rz   r   re   s    rC   __iter__MessageSet.__iter__|  s*    ?@@~~rE   c                 x    SnU R                    H'  u  p#Uc  US-  nM  Uc  [        S5      eXU-
  S-   -  nM)     U$ )Nr   r<   z%Can't size object; last value not set)rX   rz   )r_   r|   r   r   s       rC   __len__MessageSet.__len__  sM    KKDAyq GHHA{"   
rE   returnc                    / nU R                    Hk  u  p#X#:X  a2  Uc  UR                  S5        M   UR                  [        U5      5        M<  Uc  UR                  SU4-  5        MV  UR                  SX#4-  5        Mm     SR                  U5      $ )N*z%d:*z%d:%d,)rX   rv   strjoin)r_   prm   rn   s       rC   __str__MessageSet.__str__  sv    IC{;HHSMHHSX&3&)C;./ % xx{rE   c                      S[        U 5       S3$ )Nz<MessageSet >)r   re   s    rC   __repr__MessageSet.__repr__  s    c$i[**rE   r{   c                     [        U[        5      (       a'  [        [        U R                  UR                  :H  5      $ [
        $ ry   )rZ   rL   r
   boolrX   NotImplementedr   s     rC   __eq__MessageSet.__eq__  s/    eZ((dkkU\\9::rE   )rW   rY   rX   N)__name__
__module____qualname____firstlineno____doc__rN   r   r   __annotations__r   ru   rb   propertyrf   setterr]   r}   r   r\   r   r   r   r   r   r   r   r   objectr   r   __static_attributes__r?   rE   rC   rL   rL      s    7r FDIeI# !0   
[[ , $ 2&V(+B"$ 
 +# +F t rE   rL   c                   &    \ rS rSrS rS rS rSrg)LiteralStringi  c                 *    Xl         / U l        X l        g ry   )sizedatar   r_   r   defereds      rC   rb   LiteralString.__init__  s    		
rE   c                 D   U =R                   [        U5      -  sl         S nU R                   S:  a  U R                  R                  U5        U$ U R                   (       a  US U R                    XR                   S  p!OSnU(       a  U R                  R                  U5        U$ Nr   rE   )r   lenr   rv   r_   r   passons      rC   writeLiteralString.write  s    		SY	99q=IIT"  yy#Kdii0$yy{2Cf		  &rE   c                 p    U R                   R                  SR                  U R                  5      U45        g)*
Call deferred with data and rest of line
rE   N)r   callbackr   r   r_   lines     rC   r   LiteralString.callback  s(     	

SXXdii0$78rE   r   r   r   N)r   r   r   r   rb   r   r   r   r?   rE   rC   r   r     s    
9rE   r   c                   *    \ rS rSrSrS rS rS rSrg)LiteralFilei     c                     Xl         X l        XR                  :  a  [        R                  " 5       U l        g [        5       U l        g ry   )r   r   _memoryFileLimittempfileTemporaryFiler   r   r   s      rC   rb   LiteralFile.__init__  s1    	
''' ..0DI	DIrE   c                 D   U =R                   [        U5      -  sl         S nU R                   S:  a  U R                  R                  U5        U$ U R                   (       a  US U R                    XR                   S  p!OSnU(       a  U R                  R                  U5        U$ r   )r   r   r   r   r   s      rC   r   LiteralFile.write  s|    		SY	99q=IIOOD!  yy#Kdii0$yy{2Cf		%rE   c                     U R                   R                  SS5        U R                  R                  U R                   U45        g)r   r   N)r   seekr   r   r   s     rC   r   LiteralFile.callback  s1     			q!

TYY-.rE   r   N)	r   r   r   r   r   rb   r   r   r   r?   rE   rC   r   r     s    '"/rE   r   c                   .    \ rS rSrSrSS jrS rS rSrg)	WriteBufferi  zM
Buffer up a bunch of writes before sending them all to a transport at once.
c                 8    X l         Xl        SU l        / U l        g Nr   )
bufferSize	transport_length_writes)r_   r   r   s      rC   rb   WriteBuffer.__init__  s    "rE   c                     U =R                   [        U5      -  sl         U R                  R                  U5        U R                   U R                  :  a  U R                  5         g g ry   )r   r   r   rv   r   flushr_   ss     rC   r   WriteBuffer.write  sD    AA<<$//)JJL *rE   c                     U R                   (       a4  U R                  R                  U R                   5        / U l         SU l        g g r   )r   r   writeSequencer   re   s    rC   r   WriteBuffer.flush  s2    <<NN((6DLDL rE   )r   r   r   r   N)i    )	r   r   r   r   r   rb   r   r   r   r?   rE   rC   r   r     s    rE   r   c                   N    \ rS rSrSrSrSrSr   SS jrS\	4S jr
S	 rS
 rSrg)Commandi  )
   CAPABILITY   FLAGS   LIST   LSUB   STATUS   SEARCH	   NAMESPACE)   EXISTS   EXPUNGE   FETCH   RECENT)   UIDVALIDITY   UNSEEN
   READ-WRITE	   READ-ONLY   UIDNEXT   PERMANENTFLAGSNc                 V   ^^^ Xl         X l        X0l        UUU4S jU l        / U l        g )Nc                    > T" U /TQ70 TD6$ ry   r?   )rT   contArgscontKwcontinuations    rC   rU   "Command.__init__.<locals>.<lambda>  s    l1&Jx&J6&JrE   )commandargswantResponser  lines)r_   r  r  r  r  r  r  s       ```rC   rb   Command.__init__  s$     	(J
rE   r   c                     SR                  U R                  U R                  U R                  U R                  U R
                  5      $ )Nz(<imap4.Command {!r} {!r} {!r} {!r} {!r}>)formatr  r  r  r  r	  re   s    rC   r   Command.__repr__  s8    9@@LL$))T%6%68I8I4::
 	
rE   c                     U R                   c  SR                  XR                  45      $ SR                  XR                  U R                   45      $ N    )r  r   r  r_   tags     rC   r  Command.format#  s>    9999c<<011yy#||TYY788rE   c                    / n/ nU R                    H  n[        U5      n[        U5      nUS:  a  US   U R                  ;   dV  US:  a  US   U R                  ;   d=  US:  aJ  US   S:X  aA  [        US   [        5      (       a)  US   S   U R                  ;   a  UR                  U5        M  UR                  U5        M     U R                  S sol	        UR                  X145        U(       a	  U" U5        g g )Nr<   r         OK)r	  parseNestedParensr   _1_RESPONSES_2_RESPONSESrZ   r[   _OK_RESPONSESrv   r   r   )	r_   lastLineunusedCallbacksendunuseLnamesNds	            rC   finishCommand.finish(  s    A%a(EE
AQ!H 1 116!H 1 116!H%uQx..!HQK4#5#55E"U#   

D:	

D#$5! rE   )r  r  r  r   r	  r  )Nr?   N)r   r   r   r   r  r  r  r   rb   r   r   r  r#  r   r?   rE   rC   r   r     sE    L @LM E
 
# 

9
"rE   r   r  !         s	   ]\\(){%*"charmap[]c              #   <   #    U  H  o[         ;  d  M  Uv   M     g 7fry   )_nonAtomChars).0chs     rC   	<genexpr>r/  Q  s     H"-0G22s   	c                      \ rS rSrSrSrSrSrSrSr	Sr
SrSrSrSrSrSrSr1 S	krS
rSrSS jrS rS rS rS rS rSrS rS rS rS rSS jr S r!S r"S r#S r$S r%S r&S r'SS jr(\)RT                  " S\)RV                  " \,5      -   S -   5      r-S! r.S" r/S# r0S$ r1S% r2S& r3S' r4S( r5S) r6S* r7S+ r8S, r9SS- jr:SS. jr;SS/ jr<SS0 jr=SS1 jr>S2 r?S3 r@S4 rA\A4rB\BrC\BrD\BrES5 rF\F4rG\GrH\GrI\GrJS6 rK\K4rL\LrM\LrN\LrOS7 rP\P\.4rQS8 rRS9 rSS: rTS; rUS< rVS= rWS> rX\X4rYS? rZ\Z\(\'4r[S@ r\SA r]SB r^SC r_\_4r`\`raSD rbSE rcSF rd\b\(SGSH4re\erf\b\(SISJ4rg\grhSK riSL rj\i4rk\krlSM rm\m\'4rn\nroSN rp\p\'4rq\qrrSO rs\s\(\'4rt\truSP rv\v\'4rw\wrxSQ ry\y\'4rz\zr{SR r|SS r}ST r~\|\(\(SISU4r\r\|\(\(SGSV4r\rSW rSX rSY r\\(\/4r\rSZ rS[ rS\ rS] rS^ r\\(\6\7\04r\rS_ rS` rSa r\4rSb rSc rSd rSe r\4rSf rSg rSh r\4rSi rSj rSSk jr\\8\14rSl rSSm jrSn rSo rSp rSq rSr rSs rSt rSu rSv rSw rSx rSy rSz rS{ rS| rS} rS~ rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rSS jr\\2\34rS rS rSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrS rS rSS jr\\2\.\44rS rS rSS jr\\2\'4rS rS rS rS rS rS r\\.\54rS rS rS rSrg)IMAP4ServeriT  z
Protocol implementation for an IMAP4rev1 server.

The server can be in any of four states:
    - Non-authenticated
    - Authenticated
    - Selected
    - Logout
s   Twisted IMAP4rev1 Ready<   i  FNi   >      OR   NOT   UIDunauthr  c                 R    Uc  0 nXl         X l        Uc  [        nX0l        / U l        g ry   )challengersctxiterateInReactor
_scheduler_queuedAsync)r_   chalcontextFactory	schedulers       rC   rb   IMAP4Server.__init__  s/    <D!(I#rE   c                 "   S[        U R                  R                  5       5      0nU R                  (       aN  U R                  (       a=  U R
                  (       d,  [        R                  " U R                  S 5      c
  S US'   S US'   S US'   S US'   U$ )N   AUTH   LOGINDISABLED   STARTTLSr   s   IDLE)	r[   r8  keysr9  canStartTLS
startedTLSr   ISSLTransportr   )r_   caps     rC   capabilitiesIMAP4Server.capabilities  sz    T--2245688((OO,,T^^TBJ(,$%#'K  LG
rE   c                     0 U l         [        R                  " U R                  S 5      S LU l        U R                  U R                  5        U R                  5         g ry   )tagsr   ITLSTransportr   rF  
setTimeouttimeOutsendServerGreetingre   s    rC   connectionMadeIMAP4Server.connectionMade  sD    	%33DNNDIQUU%!rE   c                 x    U R                  S 5        U R                  (       a  U R                  5         S U l        g g ry   )rO  	_onLogout)r_   reasons     rC   connectionLostIMAP4Server.connectionLost  s+    >>NN!DN rE   c                 d   U R                  S5        U R                  R                  5         U R                  (       am  U R                  R	                  U 5        [        U R                  S 5      nUb2  [        UR                  5      R                  [        R                  5        S U l        SU l        g )Ns*   * BYE Autologout; connection idle too longtimeout)sendLiner   loseConnectionmboxremoveListenerICloseableMailboxr   close
addErrbackr6   errstate)r_   cmbxs     rC   timeoutConnectionIMAP4Server.timeoutConnection  sw    CD%%'99II$$T*$TYY5Ddjj)44SWW=DI
rE   c                     U R                  5         U R                  R                  U5      nUb  U R                  U5        g g ry   )resetTimeout_pendingLiteralr   setLineModer   s      rC   rawDataReceivedIMAP4Server.rawDataReceived  s=    %%++D1V$ rE   c                    U R                   nS U l         U(       aC  U R                   c6  U R                  UR                  S5      5        U(       a  U R                   c  M6  U R                   b  U R                   R                  U5        g g r   )blockedlineReceivedpopr   )r_   commandss     rC   _unblockIMAP4Server._unblock  sc    <<4<</hll1o. 4<</<<#LL) $rE   c           	      ^   U R                   b  U R                   R                  U5        g U R                  5         [        U SU R                  -   5      n U" U5        g ! [
         aE  nU R                  S[        [        U5      5      -   5        [        R                  " 5          S nAg S nAff = f)Nparse_s   BAD Server error: )rn  rv   rh  getattr
parseState	ExceptionsendUntaggedResponser;   r   r6   rb  )r_   r   fes       rC   ro  IMAP4Server.lineReceived  s    <<#LL%D(T__45	dG 	%%&;mCPQF>S&STGGII	s   A 
B,';B''B,c           
         UR                  S S5      nS n[        U5      S:X  a  Uu  pEnON[        U5      S:X  a  Uu  pEO:[        U5      S:X  a  US   nU R                  US5        g U R                  S S5        g UR                  5       n U R	                  XEU5      $ ! [
         a1  nU R                  US[        [        U5      5      -   5         S nAg S nAf[         a1  nU R                  US[        [        U5      5      -   5         S nAg S nAf[         a1  nU R                  US	[        [        U5      5      -   5         S nAg S nAff = f)
Nr     r<   r   s   Missing commands   Null command   Illegal syntax:    Illegal operation:    Illegal mailbox name: )splitr   sendBadResponseupperdispatchCommandr   r;   r   r   sendNegativeResponser   )r_   r   r  restr  cmdr{  s          rC   parse_commandIMAP4Server.parse_command  s2   zz$"t9>!NCdY!^HCY!^q'C  &89  7iik	''$77$ 	S  &9M#a&<Q&QRR 	%%+mCF.CC  & 	%%.s1v1FF 	s0   	B 
E%'CE'D

E'EEc                 Z    U R                   nS U l         SU l        UR                  U5        g )Nr  )ri  rw  r   )r_   r   r"  s      rC   parse_pendingIMAP4Server.parse_pending  s(      ##	

4rE   c                     U R                  U5      nU(       a   US   nUSS  nU R                  XX/XsU5        g U R                  US5        g )Nr   r<   s   Unsupported command)lookupCommand_IMAP4Server__doCommandr  )r_   r  r  r  uidrz  fn	parseargss           rC   r  IMAP4Server.dispatchCommand  sP    s#1B!"IStk9CH  &<=rE   c           
          [        U SR                  U R                  [        UR	                  5       5      45      S 5      $ )N_)rv  r   rc  r:   r  )r_   r  s     rC   r  IMAP4Server.lookupCommand  s/    tSXXtzz<		3L&MNPTUUrE   c           	      b   [        U5       Hq  u  px[        U5      (       aK  XGS-   S  n[        XU5      R                  U R                  XX4U5      R                  U R                  U5          g UR                  U5        Ms     U(       a  [        S[        U5      -   5      eUb	  U" USU06  g U" U6   g )Nr<   z Too many arguments for command: r  )
rj   callabler   addCallback_IMAP4Server__cbDispatchra  _IMAP4Server__ebDispatchrv   r   repr)	r_   r  handlerr  r  r   r  rl   args	            rC   __doCommandIMAP4Server.__doCommand  s    	*FA}}%!eg.	c.::%%sTc*T..4C  + '(JTRVZ(WXX?d##TNrE   c                 T    Uu  pxUR                  U5        U R                  X#XEX5        g ry   )rv   r  )	r_   resultr  r  r  r  r  r  r  s	            rC   __cbDispatchIMAP4Server.__cbDispatch  s'    C$4=rE   c           	      Z   UR                  [        5      (       a2  U R                  US[        [	        UR
                  5      5      -   5        g UR                  [        5      (       a2  U R                  US[        [	        UR
                  5      5      -   5        g UR                  [        5      (       a2  U R                  US[        [	        UR
                  5      5      -   5        g U R                  US[        [	        UR
                  5      5      -   5        [        R                  " U5        g )Nr  r  r     Server error: )checkr   r  r;   r   rk   r   r  r   r6   rb  r_   failurer  s      rC   __ebDispatchIMAP4Server.__ebDispatch$  s    ==.//  (=W]]9K+LL ]]+,,%%+mC<N.OO ]]122%%.s7==?Q1RR   &s7==7I)JJ GGGrE   c                    XR                   :  a  [        SU R                   4-  5      e[        R                  " 5       nSU l        [        X5      U l        U R                  [        SU-  5      5        U R                  5         U$ )Nz,Literal too long! I accept at most %d octetspendingzReady for %d octets of text)
_literalStringLimitr   r   Deferredrw  r   ri  sendContinuationRequestr;   
setRawModer_   r   r"  s      rC   _stringLiteralIMAP4Server._stringLiteral7  s~    ***'>++-.  NN#,T5$$7$>?	
 	rE   c                     [         R                  " 5       nSU l        [        X5      U l        U R                  [        SU-  5      5        U R                  5         U$ )Nr  zReady for %d octets of data)r   r  rw  r   ri  r  r;   r  r  s      rC   _fileLiteralIMAP4Server._fileLiteralF  sO    NN#*43$$7$>?	
 	rE   c                 "    U R                  USS9$ )a  
Parse an astring from line that represents a command's final
argument.  This special case exists to enable parsing empty
string literals.

@param line: A line that contains a string literal.
@type line: L{bytes}

@return: A 2-tuple containing the parsed argument and any
    trailing data, or a L{Deferred} that fires with that
    2-tuple
@rtype: L{tuple} of (L{bytes}, L{bytes}) or a L{Deferred}

@see: https://twistedmatrix.com/trac/ticket/9207
T)final)arg_astringr   s     rC   arg_finalastringIMAP4Server.arg_finalastringP  s      D11rE   c           	      <   UR                  5       nU(       d  [        S5      eSnSu  pEUSS S:X  a   UR                  SS5      u  pdnUSS nOUSS S	:X  aD  US
S S:w  a  [        S5      e [	        USS
 5      nU(       a  U(       d  gU R                  U5      nO6UR                  SS5      n[        U5      S:X  a  UR                  S5        Uu  pEU=(       d    XE4$ ! [         a    [        S5      ef = f! [         a    [        S[        USS
 5      -   5      ef = f)a  
Parse an astring from the line, return (arg, rest), possibly
via a deferred (to handle literals)

@param line: A line that contains a string literal.
@type line: L{bytes}

@param final: Is this the final argument?
@type final L{bool}

@return: A 2-tuple containing the parsed argument and any
    trailing data, or a L{Deferred} that fires with that
    2-tuple
@rtype: L{tuple} of (L{bytes}, L{bytes}) or a L{Deferred}

Missing argumentNNNr   r<      "r  zUnmatched quotes   {r      }Malformed literalBad literal size: )rE   rE   r  rE   )	stripr   r  ri   intr  r  r   rv   )r_   r   r  r"  r  r  spamr   s           rC   r  IMAP4Server.arg_astringb  s=   " zz|'(:;;	!9@"&**T1"54ABx !AY$BCyD +,?@@U4": T!##D)A**T1%C3x1}

3ICSK%  @+,>??@  U+,@4Qr
CS,STTUs   C ,C6 C36%Ds
   (?P<atom>[s   ]+)( (?P<rest>.*$)|$)c                     U(       d  [        S5      eU R                  R                  U5      nU(       a"  UR                  S5      UR                  S5      4$ [        S5      e)z
Parse an atom from the line
r  atomr  zMalformed ATOM)r   atomrematchgroup)r_   r   ms      rC   arg_atomIMAP4Server.arg_atom  sQ     '(:;;KKd#776?AGGFO33'(899rE   c                     U(       d  [        S5      eUSS S:w  a  [        S5      eUR                  S5      nUS:X  a  [        S5      e[        USU S	5      XS
-   S 4$ )z7
Parse a (non-nested) parenthesised list from the line
r  Nr<      (zMissing parenthesis   )r   Mismatched parenthesisr   r  )r   findr  )r_   r   rl   s      rC   	arg_plistIMAP4Server.arg_plist  sm     '(:;;8t'(=>>IIdO7'(@AA!$q)Q/!eg??rE   c                     U(       d  [        S5      eUSS S:w  a  [        S5      eUSS S:w  a  [        S5      e [        USS 5      nU R                  U5      $ ! [         a    [        S	USS < 35      ef = f)
z
Parse a literal from the line
r  Nr<   r  zMissing literalr   r  r  r  )r   r  ri   r  )r_   r   r   s      rC   arg_literalIMAP4Server.arg_literal  s     '(:;;8t'(9::9'(;<<	MtAbz?D   &&  	M'*<T!BZN(KLL	Ms   A A8c                      [        U5      nUS4$ )z
searchkeys
rE   )r  )r_   r   querys      rC   arg_searchkeysIMAP4Server.arg_searchkeys  s     "$' s|rE   c                     SnUR                  SS5      n[        U5      S:X  a  US   nUS   n [        U5      U4$ ! [         a  n[	        S[        U5      -   5      eSnAff = f)z
sequence-set
rE   r  r<   r  r   zBad message number N)r  r   parseIdListr   r   r   )r_   r   r  r  r{  s        rC   
arg_seqsetIMAP4Server.arg_seqset  ss     jjq!s8q=q6D!f	H$d++% 	H'(=A(FGG	Hs   < 
A"AA"c                 T    [        5       nUR                  U5        UR                  S4$ )z
fetch-att
rE   )_FetchParserparseStringr  )r_   r   r   s      rC   arg_fetchattIMAP4Server.arg_fetchatt  s%     N	d#rE   c                    / nUSS S:X  a  USS S:w  a  [        S5      eUSS nU(       a  U R                  R                  U5      nU(       d  [        S5      eUSS S	:X  a8  UR                  5       S:X  a$  UR	                  S	UR                  S
5      -   5        O@UR                  5       S:X  a!  UR	                  UR                  S
5      5        O[        S5      eUR                  S5      nU(       a  M  US4$ )z
Flag part of store-att-flag
r   r<   r  r   Nr  r  zMalformed flag   \r  r  rE   )r   r  searchr`   rv   r  )r_   r   flagsr  s       rC   arg_flaglistIMAP4Server.arg_flaglist  s     !9BCyD +,DEE":D""4(A+,<==AayE!aggi1nUQWWV_45aQWWV_-+,<==776?D d s|rE   c                 
    US4$ )z
Command line of UID command
rE   r?   r   s     rC   arg_lineIMAP4Server.arg_line  s     c{rE   c                 X    UR                  S5      (       a  U R                  U5      $ SU4$ )z
Optional parenthesised list
r  N)
startswithr  r   s     rC   	opt_plistIMAP4Server.opt_plist  s,     ??4  >>$''$<rE   c                     UR                  S5      (       a   UR                  SS5      u  p#nX4SS 4$ SU4$ ! [         a    [        S5      ef = f)z
Optional date-time string
r  r  zMalformed date-timer<   N)r  r  ri   r   )r_   r   r  dater  s        rC   opt_datetimeIMAP4Server.opt_datetime  sh     ??4  C#'::dA#6 D qr(##$<	  C+,ABBCs	   7 Ac                     USS R                  5       S:X  aT  UR                  SS5      n[        U5      S:X  a  [        S5      e[        U5      S:X  a  UR	                  S5        Uu  p2nX$4$ SU4$ )	z$
Optional charset of SEARCH command
N   s   CHARSETr  r  r<   zMissing charset identifierrE   )r  r  r   r   rv   )r_   r   r  r  r  s        rC   opt_charsetIMAP4Server.opt_charset  sq     8>>z)**T1%C3x1}+,HII3x1}

3!ODt;$<rE   c                     SSR                  U R                  5       5      -   S-   U R                  -   nU R                  US9  g )Ns   [CAPABILITY r     ] )message)r   listCapabilitiesIDENTsendPositiveResponser_   msgs     rC   rQ  IMAP4Server.sendServerGreeting)  s=    		$*?*?*A BBUJTZZW!!#!.rE   c                 (    U R                  SX5        g )N   BAD_respondr_   r  r   s      rC   r  IMAP4Server.sendBadResponse-  s    fc+rE   c                 (    U R                  SX5        g )Nr  r	  r  s      rC   r   IMAP4Server.sendPositiveResponse0      eS*rE   c                 (    U R                  SX5        g )N   NOr	  r  s      rC   r   IMAP4Server.sendNegativeResponse3  r  rE   c                     U(       a  U R                   c  U R                  US S 5        g U R                  R                  U5        g ry   )rn  r
  r<  rv   )r_   r   isAsyncs      rC   ry   IMAP4Server.sendUntaggedResponse6  s2    4<</MM'4.$$W-rE   c                 ^    U(       a  U R                  SU-   5        g U R                  S5        g )Ns   +    +r[  r  s     rC   r  #IMAP4Server.sendContinuationRequest<  s!    MM%#+&MM$rE   c                 8   US;   a@  U R                   (       a/  U R                   n/ U l         U H  nU R                  US S 5        M     U(       d  SnU(       a#  U R                  SR                  X!U45      5        g U R                  SR                  X!45      5        g )N)r  r  r     *r  )r<  r
  r[  r   )r_   rc  r  r   r	  r  s         rC   r
  IMAP4Server._respondB  s|    **t/@/@%%E "Dc4. CMM$))S$9:;MM$))SL12rE   c                    S/nU R                  5       R                  5        HT  u  p#Uc  UR                  U5        M  [        U5      (       d  M-  UR	                  U Vs/ s H
  oBS-   U-   PM     sn5        MV     U$ s  snf )Ns	   IMAP4rev1   =)rJ  itemsrv   r   r   )r_   capscvrI  s        rC   r  IMAP4Server.listCapabilitiesO  sm    ~%%'--/DAyAQ;#$hn;<	 0
  <s   A<
c                     U R                  SSR                  U R                  5       5      -   5        U R                  US5        g )Ns   CAPABILITY r  s   CAPABILITY completed)ry  r   r  r  r  s     rC   do_CAPABILITYIMAP4Server.do_CAPABILITYX  s8    !!.499T=R=R=T3U"UV!!#'>?rE   c                 ~    U R                  S5        U R                  US5        U R                  R                  5         g )Ns   BYE Nice talking to yous   LOGOUT successful)ry  r  r   r\  r  s     rC   	do_LOGOUTIMAP4Server.do_LOGOUTa  s2    !!"<=!!#';<%%'rE   c                 (    U R                  US5        g )Ns   NOOP No operation performedr  r  s     rC   do_NOOPIMAP4Server.do_NOOPk  s    !!#'EFrE   c                     UR                  5       R                  5       nX R                  ;  a  U R                  US5        g U R	                  U R                  U   " 5       U5        g )Ns   AUTHENTICATE method unsupported)r  r  r8  r  authenticate)r_   r  r  s      rC   do_AUTHENTICATEIMAP4Server.do_AUTHENTICATEs  sQ    zz|!!#'''%%c+MNd..t46<rE   c                 f    U R                   c  U R                  US5        g U R                  X5        g )Ns    Temporary authentication failure)portalr  _setupChallenge)r_   r=  r  s      rC   r/  IMAP4Server.authenticate|  s.    ;;%%c+NOT'rE   c           
          UR                  5       n[        U5      S S nSU l        [        R                  " 5       U l        U R                  U5        U R
                  R                  U R                  X5        U R
                  R                  U R                  U5        g ! [         a1  nU R                  US[        [        U5      5      -   5         S nAg S nAff = f)Nr   r  r  )getChallenger   rw  r   r  ri  r  r  _IMAP4Server__cbAuthChunkra  _IMAP4Server__ebAuthChunkrx  r  r;   r   )r_   r=  r  	challengecodedr{  s         rC   r4  IMAP4Server._setupChallenge  s    
	E))+I  	*3B/E'DO#(>>#3D ((/  ,,T-?-?K  ++D,>,>D  	Q  &7-A:O&OPP	Qs   B 
C)'CCc                 h    [        U5      nUR	                  U5        UR                  5       (       a  U R                  X#5        g U R                  R                  US [        5      R                  U R                  U R                  U4S U4S 5        g ! [        R                   a    [        S5      ef = f)NzMalformed Response - not base64)r   binasciiErrorr   setResponsemoreChallengesr4  r3  loginIAccountaddCallbacks_IMAP4Server__cbAuthResp_IMAP4Server__ebAuthResp)r_   r  r=  r  uncodeds        rC   __cbAuthChunkIMAP4Server.__cbAuthChunk  s    	K!&)G 	!    +KKdD(3@@!!4#4#4sfdSFD ~~ 	K'(IJJ	Ks   B  B1c                     Uu  p4nU[         L d   S5       eX@l        SU l        XPl        U R	                  US5        U R                  U R                  5        g )Nz(IAccount is the only supported interfaceauths   Authentication successful)rC  accountrc  rU  r  rO  POSTAUTH_TIMEOUTr_   r  r  ifaceavatarlogouts         rC   __cbAuthRespIMAP4Server.__cbAuthResp  sT    "( L"LL 
!!#'CD--.rE   c                    UR                  [        5      (       a  U R                  US5        g UR                  [        5      (       a  U R                  US5        g U R	                  US5        [
        R                  " U5        g )Ns#   Authentication failed: unauthorizeds+   Authentication failed: server misconfigureds'   Server error: login failed unexpectedly)r  r   r  r   r  r6   rb  r  s      rC   __ebAuthRespIMAP4Server.__ebAuthResp  sf    ==*++%%c+QR]]/00%%C   &PQGGGrE   c           	      f    U R                  US[        [        UR                  5      5      -   5        g )Ns   Authentication failed: )r  r;   r   rk   r  s      rC   __ebAuthChunkIMAP4Server.__ebAuthChunk  s)    !!+mC<N.OO	
rE   c                    U R                   (       a  U R                  US5        g U R                  (       a  U R                  (       a  U R	                  US5        U R
                  R                  U R                  5        SU l         U R                  R                  5       U l        SU R                  ;  a  [        U R                  S'   SU R                  ;  a  [        U R                  S'   g g U R                  US5        g )Ns   TLS already negotiateds   Begin TLS negotiation nowT   LOGINs   PLAINs   TLS not available)rG  r  r9  rF  r  r   startTLSr8  copyr   r   r  s     rC   do_STARTTLSIMAP4Server.do_STARTTLS  s    ??%%c+DEXX$**%%c+GHNN##DHH-"DO#//446Dt///-=  *t///-=  * 0 %%c+?@rE   c                     SU R                  5       ;   a  U R                  US5        g [        U R                  X#5      R	                  U R
                  U5      R                  U R                  U5        g )NrC  s!   LOGIN is disabled before STARTTLS)rJ  r  r   authenticateLoginr  _IMAP4Server__cbLoginra  _IMAP4Server__ebLogin)r_   r  userpasswds       rC   do_LOGINIMAP4Server.do_LOGIN  s[    t0022  &JKd,,d;GGNNC	

*T^^S
)rE   c                     U R                   (       a5  U R                   R                  [        R                  " X5      S[        5      $ [        5       e)al  
Lookup the account associated with the given parameters

Override this method to define the desired authentication behavior.

The default behavior is to defer authentication to C{self.portal}
if it is not None, or to deny the login otherwise.

@type user: L{str}
@param user: The username to lookup

@type passwd: L{str}
@param passwd: The password to login with
N)r3  rB  r   UsernamePasswordrC  r   )r_   rd  re  s      rC   ra  IMAP4Server.authenticateLogin  s?     ;;;;$$,,T:D(   !!rE   c                     Uu  p4nU[         La.  U R                  US5        [        R                  " SU< S35        g X@l        XPl        U R                  US5        SU l        U R                  U R                  5        g )Ns-   Server error: login returned unexpected valuez__cbLogin called with z, IAccount expecteds   LOGIN succeededrK  )
rC  r  r6   rb  rL  rU  r  rc  rO  rM  rN  s         rC   	__cbLoginIMAP4Server.__cbLogin  sp    "(   &VWGG,UI5HIJ!L#N%%c+=>DJOOD112rE   c           	          UR                  [        5      (       a  U R                  US5        g U R                  US[	        [        UR                  5      5      -   5        [        R                  " U5        g )Ns   LOGIN failedr  )	r  r   r  r  r;   r   rk   r6   rb  r  s      rC   	__ebLoginIMAP4Server.__ebLogin  sW    ==*++%%c?;  &s7==7I)JJ GGGrE   c                    S =n=p4[        U R                  S 5      nUb0  UR                  5       nUR                  5       nUR                  5       nU R	                  S[        X#U/5      -   5        U R                  US5        g )Ns
   NAMESPACE s   NAMESPACE command completed)r2   rL  getPersonalNamespacesgetSharedNamespacesry  collapseNestedListsr  )r_   r  personalpublicsharednps         rC   do_NAMESPACEIMAP4Server.do_NAMESPACE  s    %)))6 t4>//1H++-F++-F!!/60JKK	
 	!!#'EFrE   c                    U R                   (       at  U R                   R                  U 5        [        U R                   S 5      nUb2  [        UR                  5      R                  [        R                  5        S U l         SU l        [        U5      n[        U R                  R                  [        U5      U5      R                  U R                  XA5      R                  U R                  XA5        g )NrK  )r]  r^  r_  r   r`  ra  r6   rb  rc  
_parseMboxrL  selectr  _cbSelectWork_ebSelectWork)r_   r  namerwcmdNamerd  s         rC   _selectWorkIMAP4Server._selectWork  s    99II$$T*$TYY5Ddjj)44SWW=DIDJ$dll)):d+;R@LL	

*T''
6rE   c                 X    U R                  X2S-   5        [        R                  " U5        g )Ns    failed: Server errorr  r6   rb  )r_   r  r  r  s       rC   r  IMAP4Server._ebSelectWork  s"    S,D"DErE   c                    Uc  U R                  US5        g SUR                  5        Vs/ s H  oDR                  5       PM     sn;   a  U R                  US5        g UR                  5        Vs/ s H  n[        U5      PM     nnU R	                  SUR                  5       4-  5        U R	                  SUR                  5       4-  5        U R	                  SSR                  U5      -   S-   5        U R                  S S	UR                  5       4-  5        UR                  5       =(       a    S
=(       d    SnUR                  U 5        U R                  USU-   S-   U-   S-   5        SU l        Xl        g s  snf s  snf )Ns   No such mailboxz	\noselectzMailbox cannot be selected	   %d EXISTS	   %d RECENT   FLAGS (r  r  s   [UIDVALIDITY %d]r   r      [r  s    successfulr}  )r  getFlagslowerr;   ry  getMessageCountgetRecentCountr   r  getUIDValidityisWriteableaddListenerrc  r]  )r_   r]  r  r  r   flagr  s          rC   r~  IMAP4Server._cbSelectWork  sQ   <%%c+=>t}}?!GGI??%%c+GH15At$A!!,$2F2F2H1J"JK!!,$2E2E2G1I"IJ!!*tyy/?"?$"FG!!$(;t?R?R?T>V(VW0=@L!!#tax%'7''AN'RS
	 @ Bs   E4.E9r<      SELECTr      EXAMINEc                 b    U R                  S 5        Xl        U R                  U l        SU l        g )Nidle)r  parseTagrw  	lastStater  s     rC   do_IDLEIMAP4Server.do_IDLE8  s'    $$T* rE   c                 f    U R                   U l        U ? U R                  U R                  S5        U ?g )Ns   IDLE terminated)r  rw  r  r  )r_   r  s     rC   
parse_idleIMAP4Server.parse_idle>  s,    ..N!!$--1CDMrE   c           	         [        U5      n U R                  R                  U5      nU(       a  U R                  US5        g U R	                  US5        g ! [
         a.  nU R	                  U[        [        U5      5      5         S nAg S nAf[         a*    U R                  US5        [        R                  " 5          g f = f)Ns   Mailbox createds   Mailbox not createds/   Server error encountered while creating mailbox)r|  rL  creater  r  r    r;   r   BaseExceptionr  r6   rb  )r_   r  r  r  r!  s        rC   	do_CREATEIMAP4Server.do_CREATEG  s    $	G\\((.F ))#/AB))#/EF   	B%%c=Q+@AA 	  G GGI		s   A 
B?$B4B?>B?c                    [        U5      nUR                  5       S:X  a  U R                  US5        g  U R                  R	                  U5        U R                  US5        g ! [         a4  nU R                  U[        U5      R                  S5      5         S nAg S nAf[         a*    U R                  US5        [        R                  " 5          g f = f)Ninboxs   You cannot delete the inboxs   Mailbox deletedimap4-utf-7s/   Server error encountered while deleting mailbox)r|  r  r  rL  deleter  r    r   encoder  r  r6   rb  r_   r  r  r  s       rC   	do_DELETEIMAP4Server.do_DELETE[  s    $::<7"%%c+IJ
	?LL% %%c+=>   	I%%c3q6==+GHH 	  G GGI		s   A" "
C,*B4CCc           	         S X#4 5       u  p#UR                  5       S:X  d  UR                  5       S:X  a  U R                  US5        g  U R                  R                  X#5        U R	                  US5        g ! [
         a    U R                  US5         g [         a.  nU R                  U[        [        U5      5      5         S nAg S nAf[         a*    U R                  US5        [        R                  " 5          g f = f)Nc              3   8   #    U  H  n[        U5      v   M     g 7fry   )r|  )r-  ns     rC   r/  (IMAP4Server.do_RENAME.<locals>.<genexpr>p  s     F3EaJqMM3E   r  s@   You cannot rename the inbox, or rename another mailbox to inbox.s   Mailbox renameds   Invalid command syntaxs/   Server error encountered while renaming mailbox)r  r  rL  renamer  rz   r  r    r;   r   r  r6   rb  )r_   r  oldnamenewnamer  s        rC   	do_RENAMEIMAP4Server.do_RENAMEo  s    FG3EF==?g%G)C%%X 	?LL1 %%c+=>  	A  &?@ 	B%%c=Q+@AA 	  G GGI		s$   	A7 7C>	C>$C4C>=C>c           	      P   [        U5      n U R                  R                  U5        U R                  US5        g ! [         a.  nU R                  U[        [        U5      5      5         S nAg S nAf[         a*    U R                  US5        [        R                  " 5          g f = f)Ns
   Subscribeds5   Server error encountered while subscribing to mailbox)r|  rL  	subscriber  r    r  r;   r   r  r  r6   rb  r  s       rC   do_SUBSCRIBEIMAP4Server.do_SUBSCRIBE  s    $
	:LL""4( %%c=9   	B%%c=Q+@AA 	  M GGI		   ; 
B%$A..4B%$B%c           	      P   [        U5      n U R                  R                  U5        U R                  US5        g ! [         a.  nU R                  U[        [        U5      5      5         S nAg S nAf[         a*    U R                  US5        [        R                  " 5          g f = f)Ns   Unsubscribeds9   Server error encountered while unsubscribing from mailbox)r|  rL  unsubscriber  r    r  r;   r   r  r  r6   rb  r  s       rC   do_UNSUBSCRIBEIMAP4Server.do_UNSUBSCRIBE  s    $
	<LL$$T* %%c?;   	B%%c=Q+@AA 	  Q GGI		r  c                     [        U5      n[        U5      n[        U R                  R                  X#5      R	                  U R
                  XU5      R                  U R                  U5        g ry   )r|  r   rL  listMailboxesr  _cbListWorkra  _ebListWork)r_   r  refr]  subr  s         rC   	_listWorkIMAP4Server._listWork  sS    $odll00#<HHc	

*T%%s
+rE   c                    U H  u  pVU(       a"  U R                   R                  U5      (       d  M.  UR                  5        Vs/ s H  n[        U5      PM     nnUR	                  5       R                  S5      n	[        U5      [        [        U5      U	UR                  S5      4n
U R                  [        U
5      5        M     U R                  X$S-   5        g s  snf )Nr  s
    completed)rL  isSubscribedr  r;   getHierarchicalDelimiterr  DontQuoteMemapry  rt  r  )r_   	mailboxesr  r  r  r  boxr  r  delimresps              rC   r  IMAP4Server._cbListWork  s    "ID$,,33D999<Ht,H446==mL(U+KK.	 ))*=d*CD # 	!!#'>? Is   Cc                 T    U R                  US5        [        R                  " U5        g )Ns1   Server error encountered while listing mailboxes.r  r  s      rC   r  IMAP4Server._ebListWork  s    S"VWrE   r   r   c                    / nU H  nUR                  [        U5      5        M     [        U5      n[        U R                  R
                  US5      R                  U R                  XU5      R                  U R                  U5        g r   )
rv   r:   r|  r   rL  r}  r  _cbStatusGotMailboxra  _ebStatusGotMailbox)r_   r  mailboxr   nativeNamesr  s         rC   	do_STATUSIMAP4Server.do_STATUS  sp    D|D12  W%dll))7A6BB$$cK	

*T--s
3rE   c                     U(       aA  [        UR                  U5      R                  U R                  U R                  X#4S X#4S 5        g U R                  US5        g )Ns   Could not open mailbox)r   requestStatusrD  _IMAP4Server__cbStatus_IMAP4Server__ebStatusr  )r_   r]  r  r  r   s        rC   r  IMAP4Server._cbStatusGotMailbox  sQ    $,,e4AA %%c+DErE   c                 T    U R                  US5        [        R                  " U5        g Ns/   Server error encountered while opening mailbox.r  r  s      rC   r  IMAP4Server._ebStatusGotMailbox      S"TUrE   c           	         [        SR                  UR                  5        Vs/ s H  nSU-  PM
     sn5      5      nU R                  SUR	                  S5      -   S-   U-   S-   5        U R                  US5        g s  snf )N z%s %s   STATUS r      (r  s   STATUS complete)r;   r   r  ry  r  r  )r_   statusr  r  rT   r   s         rC   
__cbStatusIMAP4Server.__cbStatus  su    SXXFLLN&KNqw{N&KLM!!M22U:TADH	
 	!!#'9:	 'Ls   A<c           	      r    U R                  USU-   S-   [        [        UR                  5      5      -   5        g )Nr  s	    failed: r  r;   r   rk   )r_   r  r  r  s       rC   
__ebStatusIMAP4Server.__ebStatus  s2    c!L0=W]]AS3TT	
rE   c                     [        U5      n[        U R                  R                  U5      R	                  U R
                  XXE5      R                  U R                  U5        g ry   )r|  r   rL  r}  r  _cbAppendGotMailboxra  _ebAppendGotMailbox)r_   r  r  r  r  r   s         rC   	do_APPENDIMAP4Server.do_APPEND  sJ    W%dll))73??$$c$	

*T--s
3rE   c                    U(       d  U R                  US5        g U Vs/ s H  n[        U5      PM     nnUR                  XWU5      nUR                  U R                  X!5        UR                  U R                  U5        g s  snf )Nz[TRYCREATE] No such mailbox)r  r:   
addMessager  _IMAP4Server__cbAppendra  _IMAP4Server__ebAppend)	r_   r]  r  r  r  r   r  decodedFlagsr"  s	            rC   r  IMAP4Server._cbAppendGotMailbox  sk    %%c+HI7<=utT*u=OOG48	doos1	T__c* >s   Bc                 T    U R                  US5        [        R                  " U5        g r  r  r  s      rC   r  IMAP4Server._ebAppendGotMailbox  r  rE   c                 n    U R                  SUR                  5       4-  5        U R                  US5        g )Nr  s   APPEND complete)ry  r  r  )r_   r  r  r]  s       rC   
__cbAppendIMAP4Server.__cbAppend  s2    !!,$2F2F2H1J"JK!!#'9:rE   c           	      f    U R                  US[        [        UR                  5      5      -   5        g )Ns   APPEND failed: r  r  s      rC   
__ebAppendIMAP4Server.__ebAppend  s)    #mC4F&GG	
rE   c                     U R                  5       nUc  U R                  S U5        g UR                  U R                  U R                  U4U4S9  g )N)callbackArgserrbackArgs)
checkpoint_IMAP4Server__cbCheckrD  _IMAP4Server__ebCheck)r_   r  r"  s      rC   do_CHECKIMAP4Server.do_CHECK  sI    OO9NN4%NNcVRUQW  rE   c                 (    U R                  US5        g )Ns   CHECK completedr+  r_   r  r  s      rC   	__cbCheckIMAP4Server.__cbCheck  s    !!#'9:rE   c           	      f    U R                  US[        [        UR                  5      5      -   5        g )Ns   CHECK failed: r  r  s      rC   	__ebCheckIMAP4Server.__ebCheck"  &    S"3mCDV6W"WXrE   c                     g)a8  
Called when the client issues a CHECK command.

This should perform any checkpoint operations required by the server.
It may be a long running operation, but may not block.  If it returns
a deferred, the client will only be informed of success (or failure)
when the deferred's callback (or errback) is invoked.
Nr?   re   s    rC   r  IMAP4Server.checkpoint%  s     rE   c                   ^ S nU R                   R                  5       (       a  [        U R                   R                  5      n[	        U R                   S 5      mTb.  Ub  UR                  U4S j5        O[        TR                  5      nUb-  UR                  U R                  U R                  U4S U4S 5        g U R                  S U5        g )Nc                 $   > TR                  5       $ ry   )r`  )r  rd  s    rC   rU   &IMAP4Server.do_CLOSE.<locals>.<lambda>7  s    TZZ\rE   )
r]  r  r   expunger_  r  r`  rD  _IMAP4Server__cbClose_IMAP4Server__ebClose)r_   r  r"  rd  s      @rC   do_CLOSEIMAP4Server.do_CLOSE0  s    99  ""dii//0A D1}9:!$**-=NN4>>4>>C64#QUVNN4%rE   c                 z    U R                  US5        U R                  R                  U 5        S U l        SU l        g )Ns   CLOSE completedrK  )r  r]  r^  rc  r  s      rC   	__cbCloseIMAP4Server.__cbCloseA  s3    !!#'9:		  &	
rE   c           	      f    U R                  US[        [        UR                  5      5      -   5        g )Ns   CLOSE failed: r  r  s      rC   	__ebCloseIMAP4Server.__ebCloseG  r  rE   c                     U R                   R                  5       (       aJ  [        U R                   R                  5      R	                  U R
                  U R                  U4S U4S 5        g U R                  US5        g )Ns$   EXPUNGE ignored on read-only mailbox)r]  r  r   r  rD  _IMAP4Server__cbExpunge_IMAP4Server__ebExpunger  r  s     rC   
do_EXPUNGEIMAP4Server.do_EXPUNGEJ  sb    99  ""$))++,99  $"2"2SFD3&$ %%c+RSrE   c                 d    U H  nU R                  SU4-  5        M     U R                  US5        g )Ns
   %d EXPUNGEs   EXPUNGE completed)ry  r  )r_   r  r  r{  s       rC   __cbExpungeIMAP4Server.__cbExpungeT  s2    A%%mqd&:; !!#';<rE   c           	          U R                  US[        [        UR                  5      5      -   5        [        R
                  " U5        g )Ns   EXPUNGE failed: r  r;   r   rk   r6   rb  r  s      rC   __ebExpungeIMAP4Server.__ebExpungeY  s7    $}S5G'HH	
 	rE   c                    [        U R                  S 5      nUbT  [        UR                  X4S9R	                  U R
                  XR                  U5      R                  U R                  U5        g [        S5      n[        U R                  R                  XdS9R	                  U R                  XR                  X45      R                  U R                  U5        g )Nr  s   1:*)ISearchableMailboxr]  r   r  r  _IMAP4Server__cbSearchra  _IMAP4Server__ebSearchr  fetch_IMAP4Server__cbManualSearch)r_   r  charsetr  r  smr   s          rC   	do_SEARCHIMAP4Server.do_SEARCH_  s    		40>"))U4@@iij#. F#A$))//16BB%%sIIuj#.rE   c           
          U(       a  [        UR                  U5      n[        SR                  U Vs/ s H  n[	        U5      PM     sn5      5      nU R                  SU-   5        U R                  US5        g s  snf )Nr     SEARCH    SEARCH completed)r  getUIDr;   r   r   ry  r  )r_   r  r  r]  r  rl   idss          rC   
__cbSearchIMAP4Server.__cbSearcho  sd    f-FCHHf%=fc!ff%=>?!!*s"23!!#':; &>s   A9c           
      h   Uc  / nSnU=(       a    US   S   nU=(       a    US   S   R                  5       n	[        [        [        S5      U5      5       Hb  u  nu  pU R	                  [
        R                  " U5      XX5      (       d  M6  UR                  SU(       a  UR                  5       OU
4-  5        Md     US:X  a5  SSKJ	n  UR                  SU R                  [        USS 5      UUUUU5        gU(       a#  U R                  S	S
R                  U5      -   5        U R                  US5        g)a  
Apply the search filter to a set of messages. Send the response to the
client.

@type result: L{list} of L{tuple} of (L{int}, provider of
    L{imap4.IMessage})
@param result: A list two tuples of messages with their sequence ids,
    sorted by the ids in descending order.

@type tag: L{str}
@param tag: A command tag.

@type mbox: Provider of L{imap4.IMailbox}
@param mbox: The searched mailbox.

@type query: L{list}
@param query: A list representing the parsed form of the search query.

@param uid: A flag indicating whether the search is over message
    sequence numbers or UIDs.

@type searchResults: L{list}
@param searchResults: The search results so far or L{None} if no
    results yet.
Nr   r   r<      s   %d   reactorr;  r  r<  )r=  r[   ziprange_searchFilterr]  deepcopyrv   twisted.internetrE  	callLaterr5  ry  r   r  )r_   r  r  r]  r  r  searchResultsrl   lastSequenceIdlastMessageIdmsgIdr  rE  s                rC   __cbManualSearchIMAP4Server.__cbManualSearchv  s   4  M  1F2JqM96":a=#7#7#9#Ca&$9:OA| !!e$e.  $$Uccjjlu-N%NO  ; 60%%VABZ 	 ))*tyy7O*OP%%c+>?rE   c                 V    U(       a"  U R                  XX4U5      (       d  gU(       a  M"  g)ai  
Pop search terms from the beginning of C{query} until there are none
left and apply them to the given message.

@param query: A list representing the parsed form of the search query.

@param id: The sequence number of the message being checked.

@param msg: The message being checked.

@type lastSequenceId: L{int}
@param lastSequenceId: The highest sequence number of any message in
    the mailbox being searched.

@type lastMessageId: L{int}
@param lastMessageId: The highest UID of any message in the mailbox
    being searched.

@return: Boolean indicating whether all of the query terms match the
    message.
FT_singleSearchStep)r_   r  idr  rM  rN  s         rC   rH  IMAP4Server._searchFilter  s2    , ))3  	 e
 rE   c                    UR                  S5      n[        U[        5      (       a  U R                  XbX4U5      (       d  g gUR	                  5       nUSS R                  5       (       d  [        Xt5      nX(;   $ [        U S[        U5      -   S5      n	U	c  [        S[        U5      -  5      eXpR                  ;   a  U	" XX4U45      n
O	U	" XU5      n
U
(       d  gg)a?  
Pop one search term from the beginning of C{query} (possibly more than
one element) and return whether it matches the given message.

@param query: A list representing the parsed form of the search query.

@param msgId: The sequence number of the message being checked.

@param msg: The message being checked.

@param lastSequenceId: The highest sequence number of any message in
    the mailbox being searched.

@param lastMessageId: The highest UID of any message in the mailbox
    being searched.

@return: Boolean indicating whether the query term matched the message.
r   FNr<   search_zInvalid search command %sT)rp  rZ   r[   rH  r  isalphar  rv  r:   r   _requiresLastMessageInfo)r_   r  rO  r  rM  rN  qr!  
messageSetrz  r  s              rC   rT  IMAP4Server._singleSearchStep  s    ( IIaLa%%a]SS T0 + 	ARa5==?? );
**D)l1o"=tD9+3l1oE  555uS=2QRFuS1F rE   c                     g)a  
Returns C{True} if the message matches the ALL search key (always).

@type query: A L{list} of L{str}
@param query: A list representing the parsed query string.

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
Tr?   r_   r  rU  r  s       rC   
search_ALLIMAP4Server.search_ALL  s     rE   c                 (    SUR                  5       ;   $ )a	  
Returns C{True} if the message has been answered.

@type query: A L{list} of L{str}
@param query: A list representing the parsed query string.

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
	\Answeredr  r_  s       rC   search_ANSWEREDIMAP4Server.search_ANSWERED  s     s||~--rE   c                     UR                  SS5      R                  SS5      nUR                  5       R                  UR	                  S5      R                  5       5      S:g  $ )a  
Returns C{True} if the message has a BCC address matching the query.

@type query: A L{list} of L{str}
@param query: A list whose first element is a BCC L{str}

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
Fbcc r   r   
getHeadersgetr  r  rp  )r_   r  rU  r  rh  s        rC   
search_BCCIMAP4Server.search_BCC  sN     nnUE*..ub9yy{		! 2 2 45;;rE   c                     [        UR                  S5      5      n[        R                  R	                  [        UR                  5       5      5      U:  $ r   )	parseTimerp  emailutils	parsedater:   getInternalDater_   r  rU  r  r  s        rC   search_BEFOREIMAP4Server.search_BEFORE*  s<    1&{{$$\#2E2E2G%HIDPPrE   c                     UR                  S5      R                  5       n[        R                  " XCR	                  5       S5      $ Nr   Frp  r  r7   strFilegetBodyFiler_   r  rU  r  bodys        rC   search_BODYIMAP4Server.search_BODY.  s0    yy|!!#||D//"3U;;rE   c                     UR                  SS5      R                  SS5      nUR                  5       R                  UR	                  S5      R                  5       5      S:g  $ )NFccri  r   r   rj  )r_   r  rU  r  r  s        rC   	search_CCIMAP4Server.search_CC2  J    ^^E4(,,T26xxzuyy|1134::rE   c                 (    SUR                  5       ;   $ Nz\Deletedrd  r_  s       rC   search_DELETEDIMAP4Server.search_DELETED6      clln,,rE   c                 (    SUR                  5       ;   $ Nz\Draftrd  r_  s       rC   search_DRAFTIMAP4Server.search_DRAFT9  s    CLLN**rE   c                 (    SUR                  5       ;   $ Nz\Flaggedrd  r_  s       rC   search_FLAGGEDIMAP4Server.search_FLAGGED<  r  rE   c                     UR                  SS5      R                  SS5      nUR                  5       R                  UR	                  S5      R                  5       5      S:g  $ )NFfromri  r   r   rj  )r_   r  rU  r  fms        rC   search_FROMIMAP4Server.search_FROM?  sJ    ^^E6*..vr:xxzuyy|1134::rE   c                    UR                  S5      R                  5       nUR                  SU5      R                  US5      nUR                  5       R	                  UR                  S5      R                  5       5      S:g  $ )Nr   Fri  r   )rp  r  rk  rl  r  )r_   r  rU  r  hdrs        rC   search_HEADERIMAP4Server.search_HEADERC  sb    iil  "nnUC(,,S"5yy{		! 2 2 45;;rE   c                 &    UR                  S5        gry  rp  r_  s       rC   search_KEYWORDIMAP4Server.search_KEYWORDH      		!rE   c                 X    [        UR                  S5      5      UR                  5       :  $ r   r  rp  getSizer_  s       rC   search_LARGERIMAP4Server.search_LARGERL       599Q< 3;;=00rE   c                 \    SUR                  5       ;   =(       a    SUR                  5       ;  $ )N\Recent\Seenrd  r_  s       rC   
search_NEWIMAP4Server.search_NEWO  s#    S\\^+N0NNrE   c                 :    Uu  pVU R                  XX5U5      (       + $ )ab  
Returns C{True} if the message does not match the query.

@type query: A L{list} of L{str}
@param query: A list representing the parsed form of the search query.

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
@param msg: The message being checked.

@type lastIDs: L{tuple}
@param lastIDs: A tuple of (last sequence id, last message id).
The I{last sequence id} is an L{int} containing the highest sequence
number of a message in the mailbox.  The I{last message id} is an
L{int} containing the highest UID of a message in the mailbox.
rS  )r_   r  rU  r  lastIDsrM  rN  s          rC   
search_NOTIMAP4Server.search_NOTR  s$    & +2'))%S-XXXrE   c                 (    SUR                  5       ;  $ Nr  rd  r_  s       rC   
search_OLDIMAP4Server.search_OLDh  s    //rE   c                     [        UR                  S5      5      n[        R                  R	                  UR                  5       5      U:H  $ r   rp  rp  rq  rr  rs  rt  ru  s        rC   	search_ONIMAP4Server.search_ONk  s7    1&{{$$S%8%8%:;tCCrE   c                 l    Uu  pVU R                  XX5U5      nU R                  XX5U5      nU=(       d    U$ )ar  
Returns C{True} if the message matches any of the first two query
items.

@type query: A L{list} of L{str}
@param query: A list representing the parsed form of the search query.

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
@param msg: The message being checked.

@type lastIDs: L{tuple}
@param lastIDs: A tuple of (last sequence id, last message id).
The I{last sequence id} is an L{int} containing the highest sequence
number of a message in the mailbox.  The I{last message id} is an
L{int} containing the highest UID of a message in the mailbox.
rS  )	r_   r  rU  r  r  rM  rN  abs	            rC   	search_ORIMAP4Server.search_ORo  s=    ( +2'""5c=Q""5c=QvArE   c                 (    SUR                  5       ;   $ r  rd  r_  s       rC   search_RECENTIMAP4Server.search_RECENT  s    S\\^++rE   c                 (    SUR                  5       ;   $ Nr  rd  r_  s       rC   search_SEENIMAP4Server.search_SEEN  s    3<<>))rE   c                     UR                  SS5      R                  SS5      n[        R                  R	                  U5      nU[        UR                  S5      5      :  $ )a  
Returns C{True} if the message date is earlier than the query date.

@type query: A L{list} of L{str}
@param query: A list whose first element starts with a stringified date
    that is a fragment of an L{imap4.Query()}. The date must be in the
    format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
Fr  ri  r   rk  rl  rq  rr  rs  rp  rp  ru  s        rC   search_SENTBEFOREIMAP4Server.search_SENTBEFORE  sM     ~~eV,00<{{$$T*i		!---rE   c                     UR                  SS5      R                  SS5      n[        R                  R	                  U5      nUSS [        UR                  S5      5      SS :H  $ )ag  
Returns C{True} if the message date is the same as the query date.

@type query: A L{list} of L{str}
@param query: A list whose first element starts with a stringified date
    that is a fragment of an L{imap4.Query()}. The date must be in the
    format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.

@type msg: Provider of L{imap4.IMessage}
Fr  ri  Nr~  r   r  ru  s        rC   search_SENTONIMAP4Server.search_SENTON  sZ     ~~eV,00<{{$$T*BQx9UYYq\22A666rE   c                     UR                  SS5      R                  SS5      n[        R                  R	                  U5      nU[        UR                  S5      5      :  $ )af  
Returns C{True} if the message date is later than the query date.

@type query: A L{list} of L{str}
@param query: A list whose first element starts with a stringified date
    that is a fragment of an L{imap4.Query()}. The date must be in the
    format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.

@type msg: Provider of L{imap4.IMessage}
Fr  ri  r   r  ru  s        rC   search_SENTSINCEIMAP4Server.search_SENTSINCE  sM     ~~eV,00<{{$$T*i		!---rE   c                     [        UR                  S5      5      n[        R                  R	                  UR                  5       5      U:  $ r   r  ru  s        rC   search_SINCEIMAP4Server.search_SINCE  s7    1&{{$$S%8%8%:;dBBrE   c                 X    [        UR                  S5      5      UR                  5       :  $ r   r  r_  s       rC   search_SMALLERIMAP4Server.search_SMALLER  r  rE   c                     UR                  SS5      R                  SS5      nUR                  5       R                  UR	                  S5      R                  5       5      S:g  $ )NFsubjectri  r   r   rj  )r_   r  rU  r  subjs        rC   search_SUBJECTIMAP4Server.search_SUBJECT  sL    ~~eY/33IrBzz|  1!3!3!56"<<rE   c                     UR                  S5      R                  5       n[        R                  " XCR	                  5       S5      $ ry  rz  r}  s        rC   search_TEXTIMAP4Server.search_TEXT  s0    yy|!!#||D//"3U;;rE   c                     UR                  SS5      R                  SS5      nUR                  5       R                  UR	                  S5      R                  5       5      S:g  $ )NFtori  r   r   rj  )r_   r  rU  r  r  s        rC   	search_TOIMAP4Server.search_TO  r  rE   c                 h    Uu  pVUR                  S5      n[        Xv5      nUR                  5       U;   $ )a  
Returns C{True} if the message UID is in the range defined by the
search query.

@type query: A L{list} of L{bytes}
@param query: A list representing the parsed form of the search
    query. Its first element should be a L{str} that can be interpreted
    as a sequence range, for example '2:4,5:*'.

@type id: L{int}
@param id: The sequence number of the message being checked.

@type msg: Provider of L{imap4.IMessage}
@param msg: The message being checked.

@type lastIDs: L{tuple}
@param lastIDs: A tuple of (last sequence id, last message id).
The I{last sequence id} is an L{int} containing the highest sequence
number of a message in the mailbox.  The I{last message id} is an
L{int} containing the highest UID of a message in the mailbox.
r   )rp  r  r=  )	r_   r  rU  r  r  rM  rN  r!  r  s	            rC   
search_UIDIMAP4Server.search_UID  s4    , +2'IIaL)zz|q  rE   c                 (    SUR                  5       ;  $ )Nrc  rd  r_  s       rC   search_UNANSWEREDIMAP4Server.search_UNANSWERED  s    3<<>11rE   c                 (    SUR                  5       ;  $ r  rd  r_  s       rC   search_UNDELETEDIMAP4Server.search_UNDELETED      #,,.00rE   c                 (    SUR                  5       ;  $ r  rd  r_  s       rC   search_UNDRAFTIMAP4Server.search_UNDRAFT  s    ..rE   c                 (    SUR                  5       ;  $ r  rd  r_  s       rC   search_UNFLAGGEDIMAP4Server.search_UNFLAGGED  r  rE   c                 &    UR                  S5        gry  r  r_  s       rC   search_UNKEYWORDIMAP4Server.search_UNKEYWORD  r  rE   c                 (    SUR                  5       ;  $ r  rd  r_  s       rC   search_UNSEENIMAP4Server.search_UNSEEN  s    s||~--rE   c           	          U R                  US[        [        UR                  5      5      -   5        [        R
                  " U5        g )Ns   SEARCH failed: r,  r  s      rC   
__ebSearchIMAP4Server.__ebSearch   s7    #mC4F&GG	
 	rE   c                 0   U(       a}  U R                  S 5      U l        [        U R                  R                  X$S9R                  [        5      R                  U R                  XU5      R                  U R                  U5        g U R                  US5        g )Nr0  s   FETCH complete)rO  _oldTimeoutr   r]  r4  r  iter_IMAP4Server__cbFetchra  _IMAP4Server__ebFetchr  )r_   r  messagesr  r  s        rC   do_FETCHIMAP4Server.do_FETCH  sm    #t4D$))//8=IIk$..#c:::< %%c+<=rE   c                 v  ^ ^^^^ T R                   c  / T l          [        T5      u  pVT R                  XVTT5      R                  UUU UU4S j5      R	                  T R
                  5        g ! [         aB    T R                  T R                  5        T ?T R                  TS5        T R                  5          g f = f)Nc                 ,   > TR                  TTTT5      $ ry   )r  )r  r  resultsr_   r  r  s    rC   rU   'IMAP4Server.__cbFetch.<locals>.<lambda>2  s    $..#ucBrE   s   FETCH completed)rn  nextspewMessager  ra  _IMAP4Server__ebSpewMessageStopIterationrO  r  r  rr  )r_   r  r  r  r  rU  r  s   `````  rC   	__cbFetchIMAP4Server.__cbFetch  s    <<DL	/7mGB4 ReS1==BBj--.7  	 OOD,,-  %%c+=>
 MMO/	s   A, ,A	B87B8c                 d    [         R                  " U5        U R                  R                  5         g ry   )r6   rb  r   r\  r_   r  s     rC   __ebSpewMessageIMAP4Server.__ebSpewMessage5  s     
 	%%'rE   c                 r    Uc  U R                   R                  nU" S[        [        U5      /5      -   5        g )Ns	   ENVELOPE )r   r   rt  getEnveloper_   rU  r  _w_fs        rC   spew_envelopeIMAP4Server.spew_envelope=  s1    :%%B
<-{3/?.@AABrE   c                     Uc  U R                   R                  nUR                  5        Vs/ s H  n[        U5      PM     nnU" SSR	                  U5      -   S-   5        g s  snf )Nr  r  r  )r   writenr  r;   r   )r_   rU  r  r  r  r  encodedFlagss          rC   
spew_flagsIMAP4Server.spew_flagsB  sW    :&&B8;Gd+G
dii55<= Hs   A!c                     Uc  U R                   R                  nUR                  5       n[        R                  R                  [        U5      5      nUc&  [        R                  " SXU4-  5        [        S5      e[        R                  " SUS S 5      n[        U[        US      4-  5      nUS   c  US-   nOAUS   S:  a  Sn	OS	n	UU	-   S
[        US   5      S-  S-  [        US   5      S-  S-  -   4-  -   nU" S[        U5      -   5        g )Nz$%d:%r: unpareseable internaldate: %rz(Internal failure generating INTERNALDATEz%d-%%s-%Y %H:%M:%S 	   r<   s   +0000r   r     -s   %04di  d   r2  s   INTERNALDATE )r   r   rt  rq  rr  parsedate_tzr:   r6   r  r   timestrftimer;   _MONTH_NAMESabs_quote)
r_   rU  r  r  r  idatettupstrdateodatesigns
             rC   spew_internaldateIMAP4Server.spew_internaldateH  s#   :%%B##%{{''U(;<<GG:bu=MMN !KLL -- 5tBQx@gd1g)>(@@A7?H$EAw!|QLD(C/3tAw<$3F22MMOPP  	fUm+,rE   c                     Uc  U R                   R                  n[        UR                  S5      5      nU" S[	        U5      -   5        g )NTs   RFC822.HEADER )r   r   _formatHeadersrk  _literal)r_   rU  r  r  r  hdrss         rC   spew_rfc822headerIMAP4Server.spew_rfc822headerc  s;    :%%BcnnT23
x~-.rE   c                     Uc  U R                   R                  nU" S5        U" 5         [        UR                  5       5      R	                  U R                   5      $ )Ns   RFC822.TEXT )r   r   FileProducerr|  beginProducingr  s        rC   spew_rfc822textIMAP4Server.spew_rfc822texti  sD    :%%B
?
COO-.==dnnMMrE   c                 j    Uc  U R                   R                  nU" SUR                  5       4-  5        g )Ns   RFC822.SIZE %d)r   r   r  r  s        rC   spew_rfc822sizeIMAP4Server.spew_rfc822sizep  s-    :%%B
//0rE   c                 4   Uc  U R                   R                  nU" S5        U" 5         [        US 5      nUb2  [        UR	                  5       5      R                  U R                   5      $ [        US U R                  5      R                  U R                   5      $ )Ns   RFC822 )r   r   IMessageFiler3  openr4  MessageProducerr;  )r_   rU  r  r  r  mfs         rC   spew_rfc822IMAP4Server.spew_rfc822u  sz    :%%B
:
#t$>	*99$..IIsD$//:IINN
 	
rE   c                 j    Uc  U R                   R                  nU" SUR                  5       4-  5        g )Ns   UID %d)r   r   r=  r  s        rC   spew_uidIMAP4Server.spew_uid  s+    :%%B
9

&'rE   c           	      B    U" S[        [        US5      /5      -   5        g )Ns   BODYSTRUCTURE T)rt  getBodyStructurer  s        rC   spew_bodystructureIMAP4Server.spew_bodystructure  s!    
24DS$4O3PQQRrE   c                 P   Uc  U R                   R                  nUR                   H<  nUR                  5       (       a  UR	                  U5      nM+  US:  d  M3  [        S5      e   UR                  (       al  UR                  " UR                  R                  /UR                  R                  Q76 n[        U5      nU" UR                  5       S-   [        U5      -   5        g UR                  (       aR  U" UR                  5       S-   5        U" 5         [        UR                  5       5      R!                  U R                   5      $ UR"                  (       a@  [        UR                  S5      5      nU" UR                  5       S-   [        U5      -   5        g UR$                  (       a  U" UR'                  UR)                  5       S9S-   5        U" 5         UR                  (       a2  [        UR                  5       5      R!                  U R                   5      $ [+        US 5      nUb2  [        UR-                  5       5      R!                  U R                   5      $ [/        US U R0                  5      R!                  U R                   5      $ U" S[3        [5        U5      /5      -   5        g )Nr   z*Requested subpart of non-multipart messager  T)lengths   BODY )r   r   partisMultipart
getSubPartrz   headerrk  negatefieldsr-  	__bytes__r.  r7   r3  r|  r4  mimeemptygetBytesr  r;  r<  r=  r;  rt  rE  )	r_   rJ  rU  r  r  r  r   r/  r>  s	            rC   	spew_bodyIMAP4Server.spew_body  s   :%%BA  nnQ'Q   LMM  ;;>>$++"4"4Jt{{7I7IJD!$'Dt~~$&$78YYt~~$&'D 12AA$..QQYY!#.."67Dt~~$&$78ZZt}}CKKM}2T9:Dyy#COO$56EEdnnUU!#t,>'	2AA$..QQ&sD$//BQQNN 
 x-/?/D.EFFGrE   c           
         ^ ^^^^^^^	^
^ [        T R                  5      nUR                  mUR                  mUU4S jm
U4S jmU4S jm	UUUUUU U	U
UU4
S jnT R	                  U" 5       5      $ )Nc                     > T" ST 4-  5        g )Ns   * %d FETCH (r?   )rU  r   s   rC   r`   &IMAP4Server.spewMessage.<locals>.start  s    /RE)*rE   c                     > T " S5        g )Ns   )
r?   r   s   rC   r#  'IMAP4Server.spewMessage.<locals>.finish  s
    (OrE   c                     > T " S5        g r  r?   rZ  s   rC   space&IMAP4Server.spewMessage.<locals>.space  s
    $KrE   c               3     >
#    Sn T
" 5         T Ht  nUR                   S:X  a  Sn UR                   S:X  a  TR                  UTTTT5      v   O&[        TSUR                   -   5      nU" TTTT5      v   UTS   Ld  Mm  T	" 5         Mv     T(       a$  U (       d  T	" 5         TR                  TTTT5      v   T" 5         T" 5         g 7f)NFr  Tr~  spew_r   )typerT  rv  rB  )seenUIDrJ  rz  r#  r   rU  r  r  r_   r]  r`   r  r   s      rC   spew%IMAP4Server.spewMessage.<locals>.spew  s     GG99%"G99&..r3uEEg		&9:ABUE22uRy(G  7mmBUE::HGs   A5C<AC)r   r   r   r   r;  )r_   rU  r  r  r  wbufrc  r#  r   r]  r`   r   s   `````  @@@@@rC   r  IMAP4Server.spewMessage  sP    4>>*



	+			 	& tv&&rE   c           	          U R                  U R                  5        U ?[        R                  " U5        U R	                  US[        [        UR                  5      5      -   5        g )Ns   FETCH failed: )rO  r  r6   rb  r  r;   r   rk   r  s      rC   	__ebFetchIMAP4Server.__ebFetch  sJ    (()S"3mCDV6W"WXrE   c                    UR                  5       nUR                  S5      nUR                  S5      (       a  SnOUR                  S5      (       a  SnOSnU Vs/ s H  n[        U5      PM     nn[	        U R
                  R                  X$X5S9R                  U R                  U R                  XR
                  XV4S U4S 5        g s  snf )Ns   SILENTr  r<   r  r   r   r0  )
r  endswithr  r:   r   r]  storerD  _IMAP4Server__cbStore_IMAP4Server__ebStore)r_   r  r  moder  r  silentr  s           rC   do_STOREIMAP4Server.do_STORE  s    zz|y)??4  D__T""DD056d#6diiooxFSSNNNN))S)F	
 7s   Cc                 @   U(       a  U(       dy  UR                  5        He  u  pgU(       a  SUR                  U5      4-  nOSnU V	s/ s H  n	[        U	5      PM     n
n	U R                  SUSR	                  U
5      U4-  5        Mg     U R                  US5        g s  sn	f )Ns    UID %drE   s   %d FETCH (FLAGS (%b)%b)r  s   STORE completed)r  r=  r;   ry  r   r  )r_   r  r  r]  r  rp  kr"  uidstrr  r  s              rC   	__cbStoreIMAP4Server.__cbStore  s    &'4;;q>*;;F F9:;t,;)).!TYYu5Ev1NN ' 	!!#'9:	 <s   Bc           	      f    U R                  US[        [        UR                  5      5      -   5        g Nr  r  r  s      rC   	__ebStoreIMAP4Server.__ebStore  r  rE   c                     [        U5      n[        U R                  R                  U5      R	                  U R
                  XX45      R                  U R                  U5        g ry   )r|  r   rL  r}  r  _cbCopySelectedMailboxra  _ebCopySelectedMailbox)r_   r  r  r  r  s        rC   do_COPYIMAP4Server.do_COPY  sJ    W%dll))73??''	

*T00#
6rE   c                    U(       d  U R                  USU-   5        g [        U R                  R                  X55      R	                  U R
                  X!5      R	                  U R                  X!5      R                  U R                  U5        g )NzNo such mailbox: )	r  r   r]  r4  r  _IMAP4Server__cbCopy_IMAP4Server__cbCopiedra  _IMAP4Server__ebCopy)r_   r]  r  r  r  r  s         rC   r}  "IMAP4Server._cbCopySelectedMailbox	  sa    %%c+>+HI$))//89EEsk$//35jjPS6TrE   c           	      f    U R                  US[        [        UR                  5      5      -   5        g ry  r  r  s      rC   r~  "IMAP4Server._ebCopySelectedMailbox	  r  rE   c                 6  ^^ / n[        TS 5      nU H  u  pgUb)  [        UR                  U5      nUR                  U5        M1  UR	                  5       n	UR                  5       n
[        US 5      nUb(  UR                  5       n[        TR                  XU
5      nOUS m[        R                  " 5       n[        X}U R                  5      R                  S 5      R                  XU
4UU4S jj5      nUR                  U5        M     [        R                   " U5      $ )Nc                 (    U R                  S5        U $ r   )r   rz  s    rC   rewind$IMAP4Server.__cbCopy.<locals>.rewind)	  s    FF1IHrE   c                 4   > TR                  T" U5      X#5      $ ry   )r  )r  r  rz  r"  r]  r  s       rC   rU   &IMAP4Server.__cbCopy.<locals>.<lambda>2	  s    T__"1Iq>rE   )IMessageCopierr   r]  rv   r  rt  r;  r<  r  r   r   r=  r;  r4  r  r   DeferredList)r_   r  r  r]  addedDeferredsfastCopyMboxrU  r  r"  r  r  r~  bodyFilebufferr  s      `          @rC   __cbCopyIMAP4Server.__cbCopy	  s    %dD1GB'!,"3"3S9%%a(
 LLNE&&(DT*D99;!$//8DI "//1#CA#^D) [$*t   !!!$A  B !!.11rE   c                     / n/ nU H:  u  pgU(       a  UR                  U5        M  UR                  UR                  5        M<     U(       a  U R                  US5        g U R                  US5        g )Nz%[ALERT] Some messages were not copieds   COPY completed)rv   rk   r  r  )r_   deferredIdsr  r]  r>  failuresr  r  s           rC   
__cbCopiedIMAP4Server.__cbCopied:	  s^    )NF

6"-	 *
 %%c+RS%%c+<=rE   c           	          U R                  US[        [        UR                  5      5      -   5        [        R
                  " U5        g )Ns   COPY failed:r,  r  s      rC   __ebCopyIMAP4Server.__ebCopyG	  s1    S/M#gmmBT4U"UVrE   c                 h    UR                  5       nUS;  a  [        U5      eU R                  XUSS9  g )N)   COPYr      STOREr   r<   r0  )r  r   r  )r_   r  r  r   s       rC   do_UIDIMAP4Server.do_UIDK	  s6    --/BB'00S4Q7rE   c                 T    U(       a  U R                  SSS9  g U R                  SSS9  g )Ns   [READ-WRITE]T)r   r  s   [READ-ONLY]ry  r_   	writeables     rC   modeChangedIMAP4Server.modeChangedX	  s+    %%ot%L%%nd%KrE   c                     UR                  5        HF  u  p#U Vs/ s H  n[        U5      PM     nnSUSR                  U5      4-  nU R                  USS9  MH     g s  snf )Ns   %d FETCH (FLAGS (%b))r  Tr  )r  r;   r   ry  )r_   newFlagsmIdr  r  r  r  s          rC   flagsChangedIMAP4Server.flagsChanged^	  s\    "..*JC<ABEDM$/ELB*c499\3J-KKC%%c4%8 +Bs   Ac                 b    Ub  U R                  SU4-  SS9  Ub  U R                  SU4-  SS9  g g )Nr  Tr  r  r  r_   existsrecents      rC   newMessagesIMAP4Server.newMessagesd	  sG    %%lfY&>%M%%lfY&>%M rE   )r  rU  ri  r<  r;  rL  rn  rF  r8  r9  r  r]  rw  r  rG  rc  rM  NNNry   FNrE   )s!   Ready for additional command textr   r  )r   r   r   r   r   r  rP  rM  rG  rF  rM  r3  rL  rU  r]  ri  r  r8  rZ  rc  rw  rb   rJ  rR  rW  re  rk  rn  rr  ro  r  r  r  r  r  r  r  r  r  r  r  recompileescape
_atomCharsr  r  r  r  r  r  r  r  r  r  r  r  rQ  r  r  r  ry  r  r
  r  r%  unauth_CAPABILITYauth_CAPABILITYselect_CAPABILITYlogout_CAPABILITYr(  unauth_LOGOUTauth_LOGOUTselect_LOGOUTlogout_LOGOUTr,  unauth_NOOP	auth_NOOPselect_NOOPlogout_NOOPr0  unauth_AUTHENTICATEr/  r4  r8  rE  rF  r9  r^  unauth_STARTTLSrf  unauth_LOGINra  rb  rc  ry  auth_NAMESPACEselect_NAMESPACEr  r  r~  auth_SELECTselect_SELECTauth_EXAMINEselect_EXAMINEr  r  select_IDLE	auth_IDLEr  auth_CREATEselect_CREATEr  auth_DELETEselect_DELETEr  auth_RENAMEselect_RENAMEr  auth_SUBSCRIBEselect_SUBSCRIBEr  auth_UNSUBSCRIBEselect_UNSUBSCRIBEr  r  r  	auth_LISTselect_LIST	auth_LSUBselect_LSUBr  r  r  auth_STATUSselect_STATUSr  r  r  r  r  auth_APPENDselect_APPENDr  r  r	  select_CHECKr  r  r  r  select_CLOSEr  r  r&  select_EXPUNGEr$  r%  r8  select_SEARCHr2  r5  rH  rT  r`  re  rm  rv  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  r  r  r3  r  select_FETCHr  r  r  r  r*  r0  r5  r8  r?  rB  rF  rT  r  r  rq  select_STORErm  rn  r  select_COPYr}  r~  r  r  r  r  
select_UIDr  r  r  r   r?   rE   rC   r1  r1  T  s    'E G J K D F G I D O  K  7EJ""	% G*:>V(>
&2$, ^ ZZ		*--0HHF
:@"'(H0   /,++. 3@ '('O))(
 LMK!M!MG *KIKK= +H5(E/	

A #nO* k+;<L"*
3
G #_N%7( Q	:KMa<L!N! *KIG" ./KM?" ./KM?* k+;<KM: #$45N%< '(89),@ KaAIKKaAIK	4F k95KM;

4+ k9lKPKM;

 ;L;Y	& ;LYT !]N=
/ ^<M<:@x:.`.<Q<;-+-;<
1OY,0D2,*.$7.C1=<
;!621/1.	> j,7L /D(C
>-6/N1


(
S$HL!'FY
( j(LAL;Y7 J(89KUY&2P>8 (H-J
L9NrE   r1  c                      \ rS rSrSrSrSrSrSrSr	Sr
SrSrSrSrSr\\\S	.rSrSdS
 jrS rS rS rS rS rS rS rS rS rS rS rS rS r S r!S r"S r#S r$SeS jr%S r&S r'S r(S  r)S! r*SdS" jr+S# r,S$ r-S% r.S& r/S' r0S( r1S) r2S* r3S+ r4S, r5S- r6S. r7S/ r8S0 r9S1 r:S2 r;S3 r<S4 r=S5 r>S6 r?S7 r@S8 rAS9 rBS: rCS; rDS< V Vs0 s H  nXR                  S=5      _M     snn rFS> rGS? rHSfS@ jrISA rJSB rKSC rLSD rMSE rNSF rOSSG.SH jrPSI rQSgSJ jrRSgSK jrSSgSL jrTSgSM jrUSgSN jrVSgSO jrWSgSP jrXSgSQ jrYSgSR jrZSgSS jr[SgST jr\SgSU jr]SgSV jr^SW r_SX r`       ShSY jraSgSZ jrbSiS[ jrcSiS\ jrdSiS] jreS^ rfS_ rgS` rhSa riSb rjScrkgs  snn f )jIMAP4Clientin	  zsIMAP4 client protocol implementation

@ivar state: A string representing the state the connection is currently
in.
Nr<   Fr   r   )OKNOBADPREAUTHBYE)MESSAGESRECENTUNSEENc                 d    0 U l         / U l        0 U l        Xl        S U l        S U l        S U l        g ry   )rM  queuedauthenticatorscontext_tag_parts_lastCmd)r_   r>  s     rC   rb   IMAP4Client.__init__	  s2    	 %	rE   c                 X    XR                   UR                  5       R                  5       '   g)a{  
Register a new form of authentication

When invoking the authenticate() method of IMAP4Client, the first
matching authentication scheme found will be used.  The ordering is
that in which the server lists support authentication schemes.

@type auth: Implementor of C{IClientAuthentication}
@param auth: The object to use to perform the client
side of this authentication scheme.
N)r  getNamer  )r_   rK  s     rC   registerAuthenticator!IMAP4Client.registerAuthenticator	  s!     7;DLLN0023rE   c                 T   U R                   S:  a  U R                  5         U =R                  [        U5      -  sl        U R                  S:  a  U R                  R                  U5        g SnU R                  S:  a  US U R                   XR                  S  p!U R                  R                  U5        U R                  nS U l        S U l        UR                  SS5        U R                  R                  UR                  5       5        U R                  UR                  S5      5        g )Nr   rE      
)rZ  rh  _pendingSizer   _pendingBufferr   r   r  rv   readrj  lstrip)r_   r   r   r  s       rC   rk  IMAP4Client.rawDataReceived	  s    <<!SY&q %%d+F  1$#$7d&7&78$?P?P?R:Sf%%d+&&D"&D $DIIaOKKtyy{+V]]734rE   c                     U R                  U5      U l        X l        U R                  c
  US/U l        OU R                  R	                  US/5        U R                  5         g )Nr  )messageFiler  r  r  r   r  )r_   r  octetss      rC   _setupForLiteralIMAP4Client._setupForLiteral	  sP    "..v6";;/DKKKg/rE   c                 \    U R                   S:  a  U R                  U R                   5        g g r   )rZ  rO  re   s    rC   rR  IMAP4Client.connectionMade	  s#    <<!OODLL) rE   c                    U R                   S:  a  U R                  S5        U R                  b7  U R                  nSU l        U H  nUR                  R	                  U5        M      U R
                  bZ  U R
                  nSU l        UR                  5        H2  nUc  M  UR                  c  M  UR                  R	                  U5        M4     gg)z
We are no longer connected
r   N)rZ  rO  r  r   errbackrM  values)r_   rV  r  r  rM  s        rC   rW  IMAP4Client.connectionLost	  s     <<!OOD!;;"[[FDK		!!&) 99 99DDI{{}?syy'<II%%f- % !rE   c                 r   U R                   S:  a  U R                  5         UR                  S5      nUS:w  ah  XS-   S nUR                  S5      (       aK   [	        USS 5      nU R                  c  UR                  SS5      u  U l	        nOUnU R                  XC5        gU R                  c  U R                  U5        gU R                  R                  U5        U R                  SR                  U R                  5      peS=U l	        U l        U R                  XV5        g! [
         a    [        U5      ef = f)a  
Attempt to parse a single line from the server.

@type line: L{bytes}
@param line: The line from the server, without the line delimiter.

@raise IllegalServerResponse: If the line or some part of the line
    does not represent an allowed message from the server at this time.
r   r  r   r<   Nr  rE   )rZ  rh  rfindrk  r  ri   r   r  r  r  r  _regularDispatchrv   r   r  )r_   r   lastPartr  partsr  r  s          rC   ro  IMAP4Client.lineReceived	  s    <<!::d#r>qLN+H  &&6 #2/F ;;&'+zz$':$DIu E%%e4;;!!$'
 KKt$		388DKK#8&**DI  +' " 6/556s   D   D6c                    U R                   (       aS  U R                   R                  b<  U R                   R                  S soR                   l        UR                  [        5        U R                  (       aJ  U R                   H:  nUR                  c  M  UR                  Wsol        UR                  [        5        M<     U R
                  R                  5         g ry   )r  r   r  TIMEOUT_ERRORr  r   r\  )r_   r"  r  s      rC   re  IMAP4Client.timeoutConnection
  s    ==T]]00<%)]]%8%8$"A}}"IIm$;;{{99(#&99aLAyIIm, #
 	%%'rE   c                     UR                  S S5      n[        U5      S:w  a  UR                  S5        Uu  p4U R                  X45        g )Nr<   r  rE   )r  r   rv   r  )r_   r   r  r  r  s        rC   r  IMAP4Client._regularDispatch
  s>    

4#u:?LL	S'rE   c                 ^    XR                   :  a  [        R                  " 5       $ [        5       $ )a   
Create a file to which an incoming message may be written.

@type octets: L{int}
@param octets: The number of octets which will be written to the file

@rtype: Any object which implements C{write(string)} and
C{seek(int, int)}
@return: A file-like object
)r   r   r   r   )r_   r  s     rC   r  IMAP4Client.messageFile
  s'     )))))++9rE   c                 l    SU R                   -  R                  S5      nU =R                   S-  sl         U$ )Nz%0.4Xasciir<   )tagIDr  r  s     rC   makeTagIMAP4Client.makeTag/
  s-    #++G4

a

rE   c                    U R                   c  U R                  nO([        U SU R                   R                  5       -   S 5      nU(       a
   U" X5        g [
        R                  " SU R                    SU< SU< 35        U R                  R                  5         g ! [         a2    [
        R                  " 5         U R                  R                  5          g f = f)N	response_zCannot dispatch: z, )	rc  response_UNAUTHrv  r  r  r6   rb  r   r\  )r_   r  r  rz  s       rC   r  IMAP4Client.dispatchCommand4
  s    ::$$AkDJJ,<,<,>>EA0#
 GG'

|2cWBthGHNN))+ ! 0	--/0s   B 9CCc           	         U R                   c  UR                  S S5      u  p2UR                  5       S:X  a  SU l         OGUR                  5       S:X  a  SU l         O+U R                  R	                  5         [        US-   U-   5      eUR                  S5      UR                  S5      pTUS	:w  a8  US	:w  a2  U R                  U R                  [        X$S-   U 5      /S 45      5        g U R                  S 5        g U R                  X5        g )
Nr<   r  r6  s   PREAUTHrK  r  r     ]r   )rc  r  r  r   r\  r   r  serverGreeting_IMAP4Client__cbCapabilitiesr  _defaultHandler)r_   r  r  r  r  r{  s         rC   r+  IMAP4Client.response_UNAUTHC
  s    ::::dA.LF||~&%
:-#
 --/+C$J,=>>99T?DIIdOqBw17##)),=dq51o,N+OQU*VW ##D)  +rE   c                 &    U R                  X5        g ry   )r1  )r_   r  r  s      rC   response_AUTHIMAP4Client.response_AUTHZ
  s    S'rE   c                    US:X  d  US:X  az  U R                   (       d  U R                  [        U5      /5        g U R                  U R                      nUS:X  a  UR	                  U5        g UR
                  R                  U5        g  U R                  U   nUR                  S S5      u  pEUS:X  a  UR                  X R                  5        O$UR                  R                  [        U5      5        U R                  U	 S U l         U R                  5         g ! [         a,    U R                  R                  5         [!        US-   U-   5      ef = f)Nr  r  r<   r  r  )waiting
_extraInfor  rM  r  r	  rv   r  r#  r   r  r   _flushQueueKeyErrorr   r\  r   )r_   r  r  r  r  r   s         rC   r1  IMAP4Client._defaultHandler]
  s   $;#+<<!24!8 9:ii-$;$$T*II$$T*#iin  $zz$2U?JJt__5II%%nT&:;IIcN#  "  ?--/+C$J,=>>?s   D 6Ec                     U R                   (       a`  U R                   R                  S5      nU R                  5       nXR                  U'   U R	                  UR                  U5      5        X l        g g r   )r  rp  r'  rM  r[  r  r7  r_   r  ts      rC   r9  IMAP4Client._flushQueuey
  sO    ;;++//!$CAIIaLMM#**Q-(L rE   c                    0 nS =p4U GH  n[        U5      nUS:X  a  US   S/:X  a  U R                  S5        M2  US:X  a  US   S/:X  a  U R                  S5        MU  US:X  a  US   S:X  a  [        US   5      nMt  US:X  a  US   S	:X  a  [        US   5      nM  US
:X  a`  US   S:X  aW  [        US   5      nU R                  US   5      u  pUR	                  U/ 5      R                  UR                  SS5      5        M  [        R                  " SU 35        GM     U(       a  U R                  U5        Uc  Ub  U R                  XC5        g g )Nr<   r   r   Fr   Tr  r   r   r~  r   FLAGSr?   z Unhandled unsolicited response: )r   r  r  _parseFetchPairs
setdefaultr   rl  r6   r  r  r  )
r_   r	  r  r  r  responseelementsr  r  r  s
             rC   r8  IMAP4Client._extraInfo
  sI    H8}H1}!!>  'Q8A;=/#A  &Q8A;)#;Xa[)Q8A;)#;Xa[)Q8A;(#:(1+& 11(1+>	  b)00GR1HI:8*EF " e$!3V, "4rE   c                 R   [         R                  " 5       Ul         U R                  (       a'  U R                  R	                  U5        UR                   $ U R                  5       nXR                  U'   U R                  UR                  U5      5        X l        Xl	        UR                   $ ry   )
r   r  r7  r  rv   r'  rM  r[  r  r  r=  s      rC   sendCommandIMAP4Client.sendCommand
  sq    NN$	<<KKs#99LLN		!cjjm$yyrE   c                     U(       a-  U R                   b   [        R                  " U R                   5      $ SnSnU R                  [	        X#S95      nUR                  U R                  5        U$ )a  
Request the capabilities available on this server.

This command is allowed in any state of connection.

@type useCache: C{bool}
@param useCache: Specify whether to use the capability-cache or to
re-retrieve the capabilities from the server.  Server capabilities
should never change, so for normal use, this flag should never be
false.

@rtype: L{Deferred}
@return: A deferred whose callback will be invoked with a
dictionary mapping capability types to lists of supported
mechanisms, or to None if a support list is not applicable.
r   )r   r  )	_capCacher   succeedrH  r   r  r0  )r_   useCacher  r  r"  s        rC   getCapabilitiesIMAP4Client.getCapabilities
  sY    " 2==00WS<=	d++,rE   c                    Uu  p#0 nU H\  nUSS   HP  nUR                  SS5      n[        U5      S:X  a  US   S pOUu  pUR                  U/ 5      R                  U	5        MR     M^     U H  nXH   S /:X  d  M  S XH'   M     X@l        U$ )Nr<   r  r   )r  r   rC  rv   rL  )
r_   r  r	  tagliner   r  rI  r  categoryrk   s
             rC   __cbCapabilitiesIMAP4Client.__cbCapabilities
  s    !DABx		$*u:?&+Ahe&+OH"-44U;    H~$'!%  rE   c                 n    U R                  [        SSS95      nUR                  U R                  5        U$ )z
Inform the server that we are done with the connection.

This command is allowed in any state of connection.

@rtype: L{Deferred}
@return: A deferred whose callback will be invoked with None
when the proper server acknowledgement has been received.
s   LOGOUT)s   BYErK  )rH  r   r  _IMAP4Client__cbLogoutr_   r"  s     rC   rQ  IMAP4Client.logout
  s0     WYYGH	doo&rE   c                 @    Uu  p#U R                   R                  5         g ry   )r   r\  r_   r  r	  rR  s       rC   
__cbLogoutIMAP4Client.__cbLogout
  s    !%%'rE   c                 p    U R                  [        S5      5      nUR                  U R                  5        U$ )z
Perform no operation.

This command is allowed in any state of connection.

@rtype: L{Deferred}
@return: A deferred whose callback will be invoked with a list
of untagged status updates the server responds with.
s   NOOP)rH  r   r  _IMAP4Client__cbNooprX  s     rC   noopIMAP4Client.noop
  s.     WW-.	dmm$rE   c                     Uu  p#U$ ry   r?   r[  s       rC   __cbNoopIMAP4Client.__cbNoop
  s     "rE   c                   ^  T R                   (       a   S5       eUc  T R                  5       nUc  [        R                  " [	        S5      5      $ ST R
                  ;  a  [        R                  " [	        S5      5      $ [        R                  " T R                  S5      nUc  [        R                  " [	        S5      5      $ T R                  [        S5      5      nUR                  T R                  U5        UR                  U 4S j5        U$ )a  
Initiates a 'STARTTLS' request and negotiates the TLS / SSL
Handshake.

@param contextFactory: The TLS / SSL Context Factory to
leverage.  If the contextFactory is None the IMAP4Client will
either use the current TLS / SSL Context Factory or attempt to
create a new one.

@type contextFactory: C{ssl.ClientContextFactory}

@return: A Deferred which fires when the transport has been
secured according to the given contextFactory, or which fails
if the transport cannot be secured.
z5Client and Server are currently communicating via TLSNzEIMAP4Client requires a TLS context to initiate the STARTTLS handshakerD  z:Server does not support secure communication via TLS / SSLzAIMAP4Client transport does not implement interfaces.ITLSTransportc                 $   > TR                  5       $ ry   rO  r  r_   s    rC   rU   &IMAP4Client.startTLS.<locals>.<lambda>/  s     4 4 6rE   )rG  _getContextFactoryr   failr   rL  r   rN  r   rH  r   r  _startedTLS)r_   r>  tlsr"  s   `   rC   r\  IMAP4Client.startTLS
  s    " 	CB	C!!446N!::6  dnn,::S  &&t~~t<;::/  W[12	d&&7	67rE   c                     U R                   c  U R                  5       nO [        R                  " U R                   5      nUR	                  U R
                  U5        U$ )a  
Attempt to enter the authenticated state with the server

This command is allowed in the Non-Authenticated state.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked if the authentication
succeeds and whose errback will be invoked otherwise.
)rL  rO  r   rM  r  _IMAP4Client__cbAuthenticate)r_   secretr"  s      rC   r/  IMAP4Client.authenticate2  sG     >>!$$&Adnn-A	d++V4rE   c           	        ^ ^ UR                  SS5      mT HM  nUR                  5       T R                  ;   d  M#  [        SUST R                  X25      nT R                  U5      s  $    T R                  (       a8  [        R                  " [        TT R                  R                  5       5      5      $ UU 4S jnT R                  5       nUR                  U5        UR                  U 4S j5        UR                  T R                  U5        U$ )NrB  r?      AUTHENTICATEc                    > U R                  [        5        [        R                  " [	        TTR
                  R                  5       5      5      $ ry   )trapr   r   rk  r%   r  rE  )rb  authsr_   s    rC   
ebStartTLS0IMAP4Client.__cbAuthenticate.<locals>.ebStartTLSR  s9    (zz-eT5H5H5M5M5OP rE   c                 $   > TR                  5       $ ry   rg  rh  s    rC   rU   .IMAP4Client.__cbAuthenticate.<locals>.<lambda>[  s    D$8$8$:rE   )rl  r  r  r   _IMAP4Client__cbContinueAuthrH  rG  r   rk  r%   rE  r\  ra  r  _IMAP4Client__cbAuthTLS)r_   r   rq  schemer  rx  r"  rw  s   `      @rC   __cbAuthenticateIMAP4Client.__cbAuthenticateC  s    "%F||~!4!44#VR1F1F '',,  ??::)%1D1D1I1I1KL 
 ALL$MM:;MM$**F3HrE   c                     [        US-   5      nU R                  U   nUR                  X45      nU R                  [	        U5      R                  5       5        g ! [        R                   a    U R                  S5        [        U5      ef = f)N   
r  )	r   r  challengeResponser[  r   r  r>  r?  r   )r_   r  r~  rq  r=  rK  s         rC   __cbContinueAuthIMAP4Client.__cbContinueAuth_  s}    	5te|,D
 &&v.D))&7DMM+d+1134 ~~ 	.MM$'--	.s   A 1B
c           	         UR                  SS5      nU HM  nUR                  5       U R                  ;   d  M#  [        SUSU R                  XB5      nU R                  U5      s  $    [        X0R                  R                  5       5      e)NrB  r?   rt  )rl  r  r  r   r|  rH  r%   rE  )r_   r   rq  rw  r~  r  s         rC   __cbAuthTLSIMAP4Client.__cbAuthTLSj  sz    "%F||~!4!44#VR1F1F '',,  (/B/B/G/G/IJJrE   c                 h    [        U R                  5      nUR                  U R                  X5        U$ )aV  
Authenticate with the server using a username and password

This command is allowed in the Non-Authenticated state.  If the
server supports the STARTTLS capability and our transport supports
TLS, TLS is negotiated before the login command is issued.

A more secure way to log in is to use C{startTLS} or
C{authenticate} or both.

@type username: L{str}
@param username: The username to log in with

@type password: L{str}
@param password: The password to log in with

@rtype: L{Deferred}
@return: A deferred whose callback is invoked if login is successful
and whose errback is invoked otherwise.
)r   rO  r  _IMAP4Client__cbLoginCaps)r_   usernamepasswordr"  s       rC   rB  IMAP4Client.logint  s-    * $../	d(((=rE   c                     g)z
Called when the server has sent us a greeting.

@type caps: C{dict}
@param caps: Capabilities the server advertised in its greeting.
Nr?   )r_   r   s     rC   r/  IMAP4Client.serverGreeting      rE   c                     U R                   b  U R                   $  SSKJn  UR                  5       $ ! [         a     g f = f)Nr   )ssl)r  rJ  r  ClientContextFactoryImportError)r_   r  s     rC   rj  IMAP4Client._getContextFactory  sC    <<#<<	., ++--  		s   1 
>>c                    SU;   n[         R                  " U R                  S 5      S Ln[         R                  " U R                  S 5      S L nU R                  (       dM  U(       aF  U(       a?  U(       a8  U R                  5       nUR                  U R                  U R                  X#4S9  U$ U(       a  [        R                  " S5        SR                  [        U5      [        U5      45      nU R                  [        SU5      5      $ )NrD  )r  z5Server has no TLS support. logging in over cleartext!r  r[  )r   rN  r   rH  rG  r\  rD  _IMAP4Client__cbLoginTLS_IMAP4Client__ebLoginTLSr6   r  r   r$  rH  r   )	r_   rJ  r  r  tryTLStlsableTransportnontlsTransportr"  r  s	            rC   __cbLoginCapsIMAP4Client.__cbLoginCaps  s    , &33DNNDIQUU %224>>4HDP6.>?ANN!!!!&1  
 HOP99fX.x0@ABD##GHd$;<<rE   c                 X    U R                   R                  U5        S U l        SU l        U$ )NT)r   r\  rL  rG  )r_   r  r  s      rC   rl  IMAP4Client._startedTLS  s'    (rE   c                     SR                  [        U5      [        U5      45      nU R                  [        SU5      5      $ )Nr  r[  )r   r$  rH  r   )r_   r  r  r  r  s        rC   __cbLoginTLSIMAP4Client.__cbLoginTLS  s7    yy&*F8,<=>$ 788rE   c                 2    [         R                  " U5        U$ ry   )r6   rb  r  s     rC   __ebLoginTLSIMAP4Client.__ebLoginTLS  s    rE   c                 t    SnSnU R                  [        XS95      nUR                  U R                  5        U$ )a  
Retrieve information about the namespaces available to this account

This command is allowed in the Authenticated and Selected states.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with namespace
information.  An example of this information is::

    [[['', '/']], [], []]

which indicates a single personal namespace called '' with '/'
as its hierarchical delimiter, and no shared or user namespaces.
r   )r   rK  )rH  r   r  _IMAP4Client__cbNamespacer_   r  r  r"  s       rC   	namespaceIMAP4Client.namespace  s:     WS<=	d(()rE   c                    Uu  p#S nU HR  n[        U5      S:X  d  M  US   S:X  d  M  USS   VVs/ s H   nUc  / OU Vs/ s H
  ot" U5      PM     snPM"     snns  $    [        R                  " S5        / / / /$ s  snf s  snnf )Nc                 N    U  Vs/ s H  oR                  S5      PM     sn$ s  snf Nr  )decode)namespaceListelements     rC   _prepareNamespaceOrDelimiter?IMAP4Client.__cbNamespace.<locals>._prepareNamespaceOrDelimiter  s!    ANOgNN=1OOOs   "rC  r   r   r<   z*No NAMESPACE response to NAMESPACE command)r   r6   rb  )r_   r  r	  rf   r  r  
pairOrNonerk   s           rC   __cbNamespaceIMAP4Client.__cbNamespace  s    	P E5zQ58|#;
 ',ABi	 '0
 ") KUV:%6u=:VW '0	   	<=B|	 Ws   B  A;B ;B c                     Sn[        U5      nSnU R                  [        X#US95      nUR                  U R                  S5        U$ )a  
Select a mailbox

This command is allowed in the Authenticated and Selected states.

@type mailbox: L{str}
@param mailbox: The name of the mailbox to select

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with mailbox
information if the select is successful and whose errback is
invoked otherwise.  Mailbox information consists of a dictionary
with the following L{str} keys and values::

        FLAGS: A list of strings containing the flags settable on
                messages in this mailbox.

        EXISTS: An integer indicating the number of messages in this
                mailbox.

        RECENT: An integer indicating the number of "recent"
                messages in this mailbox.

        UNSEEN: The message sequence number (an integer) of the
                first unseen message in the mailbox.

        PERMANENTFLAGS: A list of strings containing the flags that
                can be permanently set on messages in this mailbox.

        UIDVALIDITY: An integer uniquely identifying this mailbox.
r  )rA  EXISTSr  r  PERMANENTFLAGSUIDVALIDITYrK  r<   _prepareMailboxNamerH  r   r  _IMAP4Client__cbSelectr_   r  r  r  r  r"  s         rC   r}  IMAP4Client.select  sJ    @ "7+ XWSTBC	dooq)rE   c                     Sn[        U5      nSnU R                  [        X#US95      nUR                  U R                  S5        U$ )a  
Select a mailbox in read-only mode

This command is allowed in the Authenticated and Selected states.

@type mailbox: L{str}
@param mailbox: The name of the mailbox to examine

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with mailbox
information if the examine is successful and whose errback
is invoked otherwise.  Mailbox information consists of a dictionary
with the following keys and values::

    'FLAGS': A list of strings containing the flags settable on
                messages in this mailbox.

    'EXISTS': An integer indicating the number of messages in this
                mailbox.

    'RECENT': An integer indicating the number of "recent"
                messages in this mailbox.

    'UNSEEN': An integer indicating the number of messages not
                flagged \Seen in this mailbox.

    'PERMANENTFLAGS': A list of strings containing the flags that
                can be permanently set on messages in this mailbox.

    'UIDVALIDITY': An integer uniquely identifying this mailbox.
r  )r   r   r   r   r   r   rK  r   r  r  s         rC   examineIMAP4Client.examine  sK    @ "7+
 WSTBC	dooq)rE   c                 L     [        U5      $ ! [         a    [        U5      ef = f)z
Parse C{value} as an integer and return the result or raise
L{IllegalServerResponse} with C{phrase} as an argument if C{value}
cannot be parsed as an integer.
)r  ri   r   )r_   rk   phrases      rC   _intOrRaiseIMAP4Client._intOrRaiseM  s+    	0u: 	0'//	0s   
 #c                    Uu  p4SU0nUR                  [        U5      5        U GH   n[        U5      S:  a  US   R                  5       S:X  a  US   n[	        U[
        5      (       a  US   nOUnUR                  5       nUS:X  a  SUS'   Mi  US:X  a  SUS'   Mv  US	:X  a  U R                  US   U5      US
'   M  US:X  a  U R                  US   U5      US'   M  US:X  a  U R                  US   U5      US'   M  US:X  a  [        S US    5       5      US'   M  [        R                  " SU 35        GM  [        U5      S:X  a  US   R                  5       S:X  a  [        S US    5       5      US'   GMS  [	        US   [        5      (       a  US   R                  5       S:X  a  U R                  US   U5      US'   GM  US   R                  5       S:X  a  U R                  US   U5      US'   GM  [        R                  " SU 35        GM  [        R                  " SU 35        GM  [        R                  " SU 35        GM#     U$ )za
Handle lines received in response to a SELECT or EXAMINE command.

See RFC 3501, section 6.3.1.
z
READ-WRITEr   r  r<   r   Fr   Tr   r  r   r  r   UIDNEXTr   c              3   8   #    U  H  n[        U5      v   M     g 7fry   r:   r-  r  s     rC   r/  )IMAP4Client.__cbSelect.<locals>.<genexpr>x  s      47AtT**zr  r  zUnhandled SELECT response (2): r  r   c              3   8   #    U  H  n[        U5      v   M     g 7fry   r  r  s     rC   r/  r    s     *S($<+=+=(r  rA  r   r  r   r  zUnhandled SELECT response (0): zUnhandled SELECT response (1): zUnhandled SELECT response (4): )rv   r  r   r  rZ   r[   r  tupler6   rb  bytes)	r_   r  r  r	  rR  datumr  contentrq   s	            rC   
__cbSelectIMAP4Client.__cbSelectX  s7    " r"&w/0E5zA~%(.."2e";(gt,,!!*C "Ciik,&*/E,'M)*.E,'N*+/+;+;GAJ+NE-(I%&*&6&6wqz5&IE(OJ&'+'7'7
E'JE)$--.3 47>qz4 /E*+ GG=eWEFUq8>>#x/%**S%PQ(*S%SE'Na%00 Qx~~'94*.*:*:58U*Khq)Y6*.*:*:58U*Kh"A% IJGG=eWEF9%ABW X rE   c                 J    U R                  [        S[        U5      5      5      $ )a<  
Create a new mailbox on the server

This command is allowed in the Authenticated and Selected states.

@type name: L{str}
@param name: The name of the mailbox to create.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked if the mailbox creation
is successful and whose errback is invoked otherwise.
s   CREATErH  r   r  r_   r  s     rC   r  IMAP4Client.create  "     	3Ft3L MNNrE   c                 J    U R                  [        S[        U5      5      5      $ )a+  
Delete a mailbox

This command is allowed in the Authenticated and Selected states.

@type name: L{str}
@param name: The name of the mailbox to delete.

@rtype: L{Deferred}
@return: A deferred whose calblack is invoked if the mailbox is
deleted successfully and whose errback is invoked otherwise.
s   DELETEr  r  s     rC   r  IMAP4Client.delete  r  rE   c           	          [        U5      n[        U5      nU R                  [        SSR                  X45      5      5      $ )aw  
Rename a mailbox

This command is allowed in the Authenticated and Selected states.

@type oldname: L{str}
@param oldname: The current name of the mailbox to rename.

@type newname: L{str}
@param newname: The new name to give the mailbox.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked if the rename is
successful and whose errback is invoked otherwise.
s   RENAMEr  )r  rH  r   r   )r_   r  r  s      rC   r  IMAP4Client.rename  s<      &g.%g.	499g=O3P QRRrE   c                 J    U R                  [        S[        U5      5      5      $ )aI  
Add a mailbox to the subscription list

This command is allowed in the Authenticated and Selected states.

@type name: L{str}
@param name: The mailbox to mark as 'active' or 'subscribed'

@rtype: L{Deferred}
@return: A deferred whose callback is invoked if the subscription
is successful and whose errback is invoked otherwise.
s	   SUBSCRIBEr  r  s     rC   r  IMAP4Client.subscribe  s"     6I$6O PQQrE   c                 J    U R                  [        S[        U5      5      5      $ )a;  
Remove a mailbox from the subscription list

This command is allowed in the Authenticated and Selected states.

@type name: L{str}
@param name: The mailbox to unsubscribe

@rtype: L{Deferred}
@return: A deferred whose callback is invoked if the unsubscription
is successful and whose errback is invoked otherwise.
s   UNSUBSCRIBEr  r  s     rC   r  IMAP4Client.unsubscribe  s"     8KD8Q RSSrE   c                     SnSU SU S3R                  S5      nSnU R                  [        X4US95      nUR                  U R                  S5        U$ )a  
List a subset of the available mailboxes

This command is allowed in the Authenticated and Selected
states.

@type reference: L{str}
@param reference: The context in which to interpret
    C{wildcard}

@type wildcard: L{str}
@param wildcard: The pattern of mailbox names to match,
    optionally including either or both of the '*' and '%'
    wildcards.  '*' will match zero or more characters and
    cross hierarchical boundaries.  '%' will also match zero
    or more characters, but is limited to a single
    hierarchical level.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a list of
    L{tuple}s, the first element of which is a L{tuple} of
    mailbox flags, the second element of which is the
    hierarchy delimiter for this mailbox, and the third of
    which is the mailbox name; if the command is unsuccessful,
    the deferred's errback is invoked instead.  B{NB}: the
    delimiter and the mailbox name are L{str}s.
r   "z" "r  )r   rK  )r  rH  r   r  _IMAP4Client__cbList)r_   	referencewildcardr  r  r  r"  s          rC   r[   IMAP4Client.list  s[    8 I;c(1-55mDWSTBC	dmmW-rE   c                     SnUR                  S5      nUR                  S5      nSR                  SUSUS/5      nSnU R                  [        X6US95      nUR	                  U R
                  S5        U$ )	a1  
List a subset of the subscribed available mailboxes

This command is allowed in the Authenticated and Selected states.

The parameters and returned object are the same as for the L{list}
method, with one slight difference: Only mailboxes which have been
subscribed can be included in the resulting list.
r   r%  r  rE   r  s   " ")r   rK  )r  r   rH  r   r  r  )	r_   r  r  r  encodedReferenceencodedWildcardr  r  r"  s	            rC   lsubIMAP4Client.lsub  s     $++G4"//-8xx 
 WSTBC	dmmW-rE   c                 "   Uu  p4/ nU H  n[        U5      S:X  d  M  US   U:X  d  M  [        S US    5       5      US'   US   R                  S5      US'   US   R                  S5      US'   UR                  [        USS  5      5        M     U$ )NrC  r   c              3   8   #    U  H  n[        U5      v   M     g 7fry   r  r  s     rC   r/  'IMAP4Client.__cbList.<locals>.<genexpr>'  s      Id!3!3r  r<   r  r  r~  )r   r  r  rv   )r_   r  r  r	  rf   r  r  s          rC   __cbListIMAP4Client.__cbList   s    E5zQ58w#6  Ia IIa !8??=9a 8??=9auU12Y/0) * rE   r  r  r  r  r  r%  c                 h  ^  Sn[        U5      n SR                  U 4S jU 5       5      nSR                  USUS/5      nSnT R                  [        X5US	95      nUR                  T R                  5        U$ ! [         a/    [        S[	        U5      [	        T R
                  5      -
  < 35      ef = f)
a  
Retrieve the status of the given mailbox

This command is allowed in the Authenticated and Selected states.

@type mailbox: L{str}
@param mailbox: The name of the mailbox to query

@type names: L{bytes}
@param names: The status names to query.  These may be any number of:
    C{'MESSAGES'}, C{'RECENT'}, C{'UIDNEXT'}, C{'UIDVALIDITY'}, and
    C{'UNSEEN'}.

@rtype: L{Deferred}
@return: A deferred which fires with the status information if the
    command is successful and whose errback is invoked otherwise.  The
    status information is in the form of a C{dict}.  Each element of
    C{names} is a key in the dictionary.  The value for each key is the
    corresponding response from the server.
r   r  c              3   B   >#    U  H  nTR                   U   v   M     g 7fry   )_statusNames)r-  r  r_   s     rC   r/  %IMAP4Client.status.<locals>.<genexpr>_  s     H%$d//5%s   zUnknown names: rE   r  r  )r   rK  )
r  r   r:  ri   setr  rH  r   r  _IMAP4Client__cbStatus)r_   r  r   r  preparedMailboxr  r  r"  s   `       rC   r  IMAP4Client.statusF  s    * -g6	XIIH%HHE xx%=>WSTBC	doo&  	Xs5zC@Q@Q<R/R.UVWW	Xs   A8 89B1c                    Uu  p#0 nU HV  nUS   S:X  d  M  US   n[        S[        U5      S5       Vs/ s H	  ovXwS-    PM     nnU H  u  p X[        U5      '   M     MX     UR                  5        H4  nU R                  R                  U5      n
U
(       d  M'   U
" XH   5      XH'   M6     U$ s  snf ! [         a    [	        [        U5      5      ef = f! [         a*  n[	        SU-   S-   XH   -   S-   [        U5      -   5      eS nAff = f)Nr   r   r  (r  z): )rG  r   r:   UnicodeDecodeErrorr   r  rE  STATUS_TRANSFORMATIONSrl  rx  r   )r_   r  r	  rf   r  r  r  rl   rt  r"  r>  r{  s               rC   r  IMAP4Client.__cbStatusi  s!   EQx9$a38CJ3JK3Jaqq5)3JK!DAA23|A/ "	  A++//2Aq !&)FI	   L . A3DK@@A ! /a#	1E9CFB s)   B-B2C2C
D%DDc           	         UR                  SS5        UR                  5       nUR                  SS5        U(       a  [        S[        U5      -  5      nOSnU Vs/ s H  n[        U5      PM     nnS[	        U5      SR                  U5      UU4-  nU R                  [        SUSU R                  U5      5      n	U	$ s  snf )	a6  
Add the given message to the given mailbox.

This command is allowed in the Authenticated and Selected states.

@type mailbox: L{str}
@param mailbox: The mailbox to which to add this message.

@type message: Any file-like object opened in B{binary mode}.
@param message: The message to add, in RFC822 format.  Newlines
in this file should be \r\n-style.

@type flags: Any iterable of L{str}
@param flags: The flags to associated with this message.

@type date: L{str}
@param date: The date to associate with this message.  This should
be of the format DD-MM-YYYY HH:MM:SS +/-HHMM.  For example, in
Eastern Standard Time, on July 1st 2004 at half past 1 PM,
"01-07-2004 13:30:00 -0500".

@rtype: L{Deferred}
@return: A deferred whose callback is invoked when this command
succeeds or whose errback is invoked if it fails.
r   r  z "%s"rE   s   %b (%b)%b {%d}r  s   APPENDr?   )	r   tellr;   r:   r  r   rH  r   _IMAP4Client__cbContinueAppend)
r_   r  r   r  r  r  r  r  r  r"  s
             rC   rv   IMAP4Client.append  s    4 	QLLNQ <+=!=>DD8=>d+>(IIl#	#
 
 IsB(?(?I
  ?s   B<c                     [         R                  " 5       nUR                  X R                  S 5      R	                  U R
                  5      $ ry   )r4   
FileSenderbeginFileTransferr   r  _IMAP4Client__cbFinishAppend)r_   r	  r   r   s       rC   __cbContinueAppendIMAP4Client.__cbContinueAppend  s=    ""7NNDAMM!!
 	
rE   c                 &    U R                  S5        g r  r  )r_   foos     rC   __cbFinishAppendIMAP4Client.__cbFinishAppend  s    crE   c                 6    U R                  [        S5      5      $ )z
Tell the server to perform a checkpoint

This command is allowed in the Selected state.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked when this command
succeeds or whose errback is invoked if it fails.
s   CHECKrH  r   re   s    rC   r  IMAP4Client.check  s      122rE   c                 6    U R                  [        S5      5      $ )a  
Return the connection to the Authenticated state.

This command is allowed in the Selected state.

Issuing this command will also remove all messages flagged \Deleted
from the selected mailbox if it is opened in read-write mode,
otherwise it indicates success by no messages are removed.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked when the command
completes successfully or whose errback is invoked if it fails.
s   CLOSEr  re   s    rC   r`  IMAP4Client.close  s      122rE   c                 t    SnSnU R                  [        XS95      nUR                  U R                  5        U$ )a  
Return the connection to the Authenticate state.

This command is allowed in the Selected state.

Issuing this command will perform the same actions as issuing the
close command, but will also generate an 'expunge' response for
every message deleted.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a list of the
'expunge' responses when this command is successful or whose errback
is invoked otherwise.
r   )r   rK  )rH  r   r  _IMAP4Client__cbExpunger  s       rC   r  IMAP4Client.expunge  s:     WS<=	d&&'rE   c                     Uu  p#/ nU HC  n[        U5      S:X  d  M  US   S:X  d  M  UR                  U R                  US   U5      5        ME     U$ )Nr  r<   r   r   )r   rv   r  )r_   r  r	  rf   r>  r  s         rC   r)  IMAP4Client.__cbExpunge  sR    E5zQ58z#9

4++E!He<=  
rE   r0  c                    U Vs/ s H  o3R                  S5      PM     nnU(       a  SOSnSR                  U5      nU R                  [        XEU4S95      nUR	                  U R
                  5        U$ s  snf )a$  
Search messages in the currently selected mailbox

This command is allowed in the Selected state.

Any non-zero number of queries are accepted by this method, as returned
by the C{Query}, C{Or}, and C{Not} functions.

@param uid: if true, the server is asked to return message UIDs instead
    of message sequence numbers.
@type uid: L{bool}

@rtype: L{Deferred}
@return: A deferred whose callback will be invoked with a list of all
    the message sequence numbers return by the search, or whose errback
    will be invoked if there is an error.
r(  s
   UID SEARCHr   r  rK  )r  r   rH  r   r  _IMAP4Client__cbSearch)r_   r  queriesr  r  r  r"  s          rC   r  IMAP4Client.search  sk    ( 9@@u<<	*@"m	yy!WScVDE	doo& As   A4c           
          Uu  p#/ nU HR  n[        U5      S:  d  M  US   S:X  d  M  UR                  USS   Vs/ s H  o`R                  Xe5      PM     sn5        MT     U$ s  snf )Nr   r   r<   )r   r   r  )r_   r  r	  ra   r>  r  r   s          rC   r?  IMAP4Client.__cbSearch  se    E5zA~%(i"7

ab	J	1,,Q6	JK  
 Ks   A!
c                 "    U R                  XSS9$ )a  
Retrieve the unique identifier for one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message sequence numbers to unique message identifiers, or whose
errback is invoked if there is an error.
r<   )useUIDr  _fetchr_   r  r  s      rC   fetchUIDIMAP4Client.fetchUID  s    $ {{8Q{77rE   c                 "    U R                  XSS9$ )a  
Retrieve the flags for one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: The messages for which to retrieve flags.

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to lists of flags, or whose errback is invoked if
there is an error.
r<   )r  r  r  r   s      rC   
fetchFlagsIMAP4Client.fetchFlags*  s    $ {{8q{99rE   c                 "    U R                  XSS9$ )aG  
Retrieve the internal date associated with one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: The messages for which to retrieve the internal date.

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to date strings, or whose errback is invoked
if there is an error.  Date strings take the format of
"day-month-year time timezone".
r<   )r  internaldater  r   s      rC   fetchInternalDateIMAP4Client.fetchInternalDate>  s    & {{8a{@@rE   c                 "    U R                  XSS9$ )a  
Retrieve the envelope data for one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: The messages for which to retrieve envelope
    data.

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of
    message numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict
    mapping message numbers to envelope data, or whose errback
    is invoked if there is an error.  Envelope data consists
    of a sequence of the date, subject, from, sender,
    reply-to, to, cc, bcc, in-reply-to, and message-id header
    fields.  The date, subject, in-reply-to, and message-id
    fields are L{str}, while the from, sender, reply-to, to,
    cc, and bcc fields contain address data as L{str}s.
    Address data consists of a sequence of name, source route,
    mailbox name, and hostname.  Fields which are not present
    for a particular address may be L{None}.
r<   )r  enveloper  r   s      rC   fetchEnvelopeIMAP4Client.fetchEnvelopeS  s    6 {{8!{<<rE   c                 "    U R                  XSS9$ )a(  
Retrieve the structure of the body of one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: The messages for which to retrieve body structure
data.

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to body structure data, or whose errback is invoked
if there is an error.  Body structure data describes the MIME-IMB
format of a message and consists of a sequence of mime type, mime
subtype, parameters, content id, description, encoding, and size.
The fields following the size field are variable: if the mime
type/subtype is message/rfc822, the contained message's envelope
information, body structure data, and number of lines of text; if
the mime type is text, the number of lines of text.  Extension fields
may also be included; if present, they are: the MD5 hash of the body,
body disposition, body language.
r<   )r  bodystructurer  r   s      rC   fetchBodyStructureIMAP4Client.fetchBodyStructurep  s    6 {{8q{AArE   c                 "    U R                  XSS9$ )aY  
Retrieve the simplified body structure of one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to body data, or whose errback is invoked
if there is an error.  The simplified body structure is the same
as the body structure, except that extension fields will never be
present.
r<   )r  r~  r  r   s      rC   fetchSimplifiedBodyIMAP4Client.fetchSimplifiedBody  s    ( {{8a{88rE   c                 "    U R                  XSS9$ )a  
Retrieve one or more entire messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}

@return: A L{Deferred} which will fire with a C{dict} mapping message
    sequence numbers to C{dict}s giving message data for the
    corresponding message.  If C{uid} is true, the inner dictionaries
    have a C{'UID'} key mapped to a L{str} giving the UID for the
    message.  The text of the message is a L{str} associated with the
    C{'RFC822'} key in each dictionary.
r<   )r  rfc822r  r   s      rC   fetchMessageIMAP4Client.fetchMessage  s    , {{8{::rE   c                 "    U R                  XSS9$ )a  
Retrieve headers of one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dicts of message headers, or whose errback is
invoked if there is an error.
r<   )r  rfc822headerr  r   s      rC   fetchHeadersIMAP4Client.fetchHeaders  s    $ {{8a{@@rE   c                 "    U R                  XSS9$ )a  
Retrieve body text of one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to file-like objects containing body text, or whose
errback is invoked if there is an error.
r<   )r  
rfc822textr  r   s      rC   	fetchBodyIMAP4Client.fetchBody      $ {{8A{>>rE   c                 "    U R                  XSS9$ )a  
Retrieve the size, in octets, of one or more messages

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to sizes, or whose errback is invoked if there is
an error.
r<   )r  
rfc822sizer  r   s      rC   	fetchSizeIMAP4Client.fetchSize  rA  rE   c           
      ,    U R                  UUSSSSSS9$ )a  
Retrieve several different fields of one or more messages

This command is allowed in the Selected state.  This is equivalent
to issuing all of the C{fetchFlags}, C{fetchInternalDate},
C{fetchSize}, C{fetchEnvelope}, and C{fetchSimplifiedBody}
functions.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dict of the retrieved data values, or whose
errback is invoked if there is an error.  They dictionary keys
are "flags", "date", "size", "envelope", and "body".
r<   )r  r  r'  rC  r+  r~  r  r   s      rC   	fetchFullIMAP4Client.fetchFull  s/    , {{  
 	
rE   c           	      (    U R                  XSSSSS9$ )a  
Retrieve several different fields of one or more messages

This command is allowed in the Selected state.  This is equivalent
to issuing all of the C{fetchFlags}, C{fetchInternalDate},
C{fetchSize}, and C{fetchEnvelope} functions.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dict of the retrieved data values, or whose
errback is invoked if there is an error.  They dictionary keys
are "flags", "date", "size", and "envelope".
r<   )r  r  r'  rC  r+  r  r   s      rC   fetchAllIMAP4Client.fetchAll  s&    * {{aRS  
 	
rE   c                 &    U R                  XSSSS9$ )a  
Retrieve several different fields of one or more messages

This command is allowed in the Selected state.  This is equivalent
to issuing all of the C{fetchFlags}, C{fetchInternalDate}, and
C{fetchSize} functions.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dict of the retrieved data values, or whose
errback is invoked if there is an error.  They dictionary keys are
"flags", "date", and "size".
r<   )r  r  r'  rC  r  r   s      rC   	fetchFastIMAP4Client.fetchFast0  s    * {{8qqUV{WWrE   c                   ^ U4S jm0 n/ n[        U5      n  [        U5      n [        U5      nUS;  a  SnON[	        U[
        5      (       d  SnO6[        U5      S:  a  SnO$U(       a  [	        US   [
        5      (       a  SnOSn[        U5      nUR                  U5        U(       Ga	  [        U5      S:  a:  U Vs/ s H  n[        U5      PM     nnUR                  U5        U[        U5      4nOL[        US   5      n	US    Vs/ s H  n[        U5      PM     n
nUR                  X/5        XY[        U
5      44n [        U5      nUR                  S	5      (       aR  UR                  S
5      (       a<   [        USS 5        [        U5      nUR                  U5        XV4-   n [        U5      nT" U5      nUR                  U5        XbU'   GM  ! [         a     X#4$ f = f! [         a    [        SU5      ef = fs  snf s  snf ! [         a    [        SU5      ef = f! [         a    [        SU5      ef = f! [         a     Nf = f)a  
Given the result of parsing a single I{FETCH} response, construct a
L{dict} mapping response keys to response values.

@param fetchResponseList: The result of parsing a I{FETCH} response
    with L{parseNestedParens} and extracting just the response data
    (that is, just the part that comes after C{"FETCH"}).  The form
    of this input (and therefore the output of this method) is very
    disagreeable.  A valuable improvement would be to enumerate the
    possible keys (representing them as structured objects of some
    sort) rather than using strings and tuples of tuples of strings
    and so forth.  This would allow the keys to be documented more
    easily and would allow for a much simpler application-facing API
    (one not based on looking up somewhat hard to predict keys in a
    dict).  Since C{fetchResponseList} notionally represents a
    flattened sequence of pairs (identifying keys followed by their
    associated values), collapsing such complex elements of this
    list as C{["BODY", ["HEADER.FIELDS", ["SUBJECT"]]]} into a
    single object would also greatly simplify the implementation of
    this method.

@return: A C{dict} of the response data represented by C{pairs}.  Keys
    in this dictionary are things like C{"RFC822.TEXT"}, C{"FLAGS"}, or
    C{("BODY", ("HEADER.FIELDS", ("SUBJECT",)))}.  Values are entirely
    dependent on the key with which they are associated, but retain the
    same structured as produced by L{parseNestedParens}.
c                    > [        U [        5      (       a  U R                  S5      $ [        U [        5      (       a  U  Vs/ s H  nT" U5      PM     sn$ g s  snf )Nr(  )rZ   r  r  r[   )thingsubthingnativeStringResponses     rC   rS  :IMAP4Client._parseFetchPairs.<locals>.nativeStringResponsem  sO    %''||I..E4((GLMu8,X6uMM )Ms   ATs   Not enough arguments)   BODYs	   BODY.PEEKFr  r   r<      <   >r   )r  r  r  r   rZ   r[   r   r:   rv   r  r  rk  r  ri   )r_   fetchResponseListr  unstructuredresponsePartsrq   rk   
hasSectionr"  	valueHead	valueTailrS  s              @rC   rB  IMAP4Client._parseFetchPairsG  s   L	N ./=)X]+6 11 #
t,, #
Ua"
:eAh55 #
 "

 s#C$u:>6;<e\!_eE< ''.e-C ,U1X 6I:?( C(Qa(I C ''(>?E),< =>C /E ##D))ennT.B.BE!BK(
 !-U 3$++E2!Hn$($7E )/E&3KE  ! @ ##C
 ! X+,CEVWWXj = !D % //1B $  - "7 79J#  & sR   G G& >H 	HH
 9H> )H$ 
G#"G#&G=
H!$H;>
I
Ic                 ^   Uu  pE0 nU H\  n[        U5      S:X  d  M  US   S:X  d  M  U R                  US   U5      nX;  a
  US   /Xh'   MC  Xh   S   R                  US   5        M^     0 n	0 n
UR                  5        Ha  u  pU R	                  US   5      u  pU
R                  U/ /5      S   R                  U5        U	R                  U0 5      R                  U5        Mc     U
n0 n[        U	R                  5       5       H  nX   n[        UR                  5       5       He  nUU;  d  M  US:X  d  M  US   X'   [        [        Xk   S   5      5       H   nXk   S   U   S:X  d  M  Xk   S   UUS-   2	   O   US	 U(       a  Mc  X	 Mg     M     U(       a  U R                  U5        U(       a  U	$ U$ )Nr~  r<   r   r   r  rA  )r   r  r   r  rB  rC  updater[   rE  rG  r  )r_   r  requestedParts
structuredr	  rf   infor  rU  r  decodedInfo	messageIdr  structuredMapunstructuredListflagChangesrJ  rl   s                     rC   _cbFetchIMAP4Client._cbFetch  s   E5zQ58x#7%%eAh6> %azDHHQK&&uQx0  !%I.2.C.CF1I.N+M""9rd3A6==>NOy"-44]C ". glln-I'FV[[]+~-$'/-3G_K*"3tq'9#:;?1-a0G; $ 21q1u9 =! < w!6#. , . k*NKrE   c	                    Sn	Uc  Sn
O@[        U[        5      (       a  [        U5      n
OSR                  [	        [        U5      5      n
Uc  SnOU
(       a  SU-   nOUnU(       a!  US;   a  Ub  SSR                  U5      -  nOSnOSnUc  SnOSXx4-  nU=(       a    S	=(       d    S
nXU=(       a    S=(       d    SXX4-  nUR                  S5      nU R                  [        XSS95      nUR                  U R                  SS5        U$ )aN  
Retrieve a specific section of one or more messages

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
    numbers or of unique message IDs.

@type headerType: L{str}
@param headerType: If specified, must be one of HEADER, HEADER.FIELDS,
    HEADER.FIELDS.NOT, MIME, or TEXT, and will determine which part of
    the message is retrieved.  For HEADER.FIELDS and HEADER.FIELDS.NOT,
    C{headerArgs} must be a sequence of header names.  For MIME,
    C{headerNumber} must be specified.

@type headerNumber: L{int} or L{int} sequence
@param headerNumber: The nested rfc822 index specifying the entity to
    retrieve.  For example, C{1} retrieves the first entity of the
    message, and C{(2, 1, 3}) retrieves the 3rd entity inside the first
    entity inside the second entity of the message.

@type headerArgs: A sequence of L{str}
@param headerArgs: If C{headerType} is HEADER.FIELDS, these are the
    headers to retrieve.  If it is HEADER.FIELDS.NOT, these are the
    headers to exclude from retrieval.

@type peek: C{bool}
@param peek: If true, cause the server to not set the \Seen flag on
    this message as a result of this command.

@type offset: L{int}
@param offset: The number of octets at the beginning of the result to
    skip.

@type length: L{int}
@param length: The number of octets to retrieve.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a mapping of message
    numbers to retrieved data, or whose errback is invoked if there is
    an error.
z%s BODY%s[%s%s%s]%sri  .)zHEADER.FIELDSzHEADER.FIELDS.NOTz (%s)r  z ()z<%d.%d>	   UID FETCHr   z.PEEKr(  r   rK  r?   F)
rZ   r  r   r   r  r  rH  r   r  ri  )r_   r  r  
headerTypeheaderNumber
headerArgspeekoffsetrI  fmtnumberrM  payloadextrar4  r  r"  s                    rC   fetchSpecificIMAP4Client.fetchSpecific  s   n $Fc**&FXXc#|45FF:%FFj$JJ%!CHHZ$88G>E 00E$0t/52vwVV jj#WUkJK	dmmR/rE   c                 >   [        U5      R                  S5      nU=(       a    S=(       d    SnSU;   a  US	 SUS'   SU;   a  US	 SUS'   S	U;   a  US		 SUS
'   U Vs/ s H  n[        U5      PM     nnUS-   SR                  U Vs/ s H  oUR	                  5       PM     sn5      -   S-   nU R                  [        XGSS95      nUR                  U R                  UR                  5        V	s/ s H  oR	                  5       PM     sn	S5        U$ s  snf s  snf s  sn	f )Nr%  rm  r   r>  Trfc822.textrC  rfc822.sizer:  rfc822.headerr  r  r  rn  rK  )
r   r  r;   r   r  rH  r   r  ri  rE  )
r_   r  r  termsr4  r   encodedTermsr  r"  r>  s
             rC   r  IMAP4Client._fetcha  s   x=''0'<385 l##'E- 5 l##'E- U"n%%)E/"
 388%Qa(%8|+L|!GGI|+L!MMPTTWUkJK	dmm%FAggi%FM 9+L &Gs   DD
-D
c                 *    U R                  USX2U5      $ )a  
Set the flags for one or more messages.

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type flags: Any iterable of L{str}
@param flags: The flags to set

@type silent: L{bool}
@param silent: If true, cause the server to suppress its verbose
response.

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a list of the
server's responses (C{[]} if C{silent} is true) or whose
errback is invoked if there is an error.
r   _storer_   r  r  rp  r  s        rC   setFlagsIMAP4Client.setFlagsy  s    2 {{8XvcBBrE   c                 *    U R                  USX2U5      $ )a  
Add to the set flags for one or more messages.

This command is allowed in the Selected state.

@type messages: C{MessageSet} or L{str}
@param messages: A message sequence set

@type flags: Any iterable of L{str}
@param flags: The flags to set

@type silent: C{bool}
@param silent: If true, cause the server to suppress its verbose
response.

@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a list of the
server's responses (C{[]} if C{silent} is true) or whose
errback is invoked if there is an error.
s   +FLAGSr  r  s        rC   addFlagsIMAP4Client.addFlags      2 {{8YsCCrE   c                 *    U R                  USX2U5      $ )a  
Remove from the set flags for one or more messages.

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type flags: Any iterable of L{str}
@param flags: The flags to set

@type silent: L{bool}
@param silent: If true, cause the server to suppress its verbose
response.

@type uid: L{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a list of the
server's responses (C{[]} if C{silent} is true) or whose
errback is invoked if there is an error.
s   -FLAGSr  r  s        rC   removeFlagsIMAP4Client.removeFlags  r  rE   c                    [        U5      R                  S5      nU Vs/ s H  n[        U5      PM     nnU(       a  US-   nU=(       a    S=(       d    SnSR                  XSSR                  U5      -   S-   45      n	U R	                  [        XSS	95      n
S
nU(       d  SnU
R                  U R                  US5        U
$ s  snf )Nr%  s   .SILENTs	   UID STOREr  r  r  r  rn  rK  r?   )rA  T)r   r  r;   r   rH  r   r  ri  )r_   r  r  rp  r  r  r  r  rl  r  r"  expecteds               rC   r  IMAP4Client._store  s    x=''08=>d+>
"C$0yy(		,0G)G$)NOPWU{KL!H	dmmXt4 ?s   Cc                     [        U5      R                  S5      nU(       a  SnOSnSR                  U[        U5      /5      nU R	                  [        XE5      5      $ )a$  
Copy the specified messages to the specified mailbox.

This command is allowed in the Selected state.

@type messages: L{MessageSet} or L{str}
@param messages: A message sequence set

@type mailbox: L{str}
@param mailbox: The mailbox to which to copy the messages

@type uid: C{bool}
@param uid: If true, the C{messages} refers to message UIDs, rather
than message sequence numbers.

@rtype: L{Deferred}
@return: A deferred whose callback is invoked with a true value
when the copy is successful, or whose errback is invoked if there
is an error.
r%  s   UID COPYr  r  )r   r  r   r  rH  r   )r_   r  r  r  r  r  s         rC   r]  IMAP4Client.copy  sT    * x=''0CCyy($7$@AB 233rE   c                     gzOverride meNr?   r  s     rC   r  IMAP4Client.modeChanged  r  rE   c                     gr  r?   )r_   r  s     rC   r  IMAP4Client.flagsChanged  r  rE   c                     gr  r?   r  s      rC   r  IMAP4Client.newMessages  r  rE   )rL  r  r  r  r  r  r  r  r  rG  rc  rM  r7  ry   r<   )r?   Nr  )r   NNNNNN)r<   r   )lr   r   r   r   r   rM  r7  r  r&  rc  rG  rZ  rL  r   r  STATUS_CODESr  r  r  rb   r  rk  r  rR  rW  ro  re  r  r  r'  r  r+  r4  r1  r9  r8  rH  rO  r0  rQ  rW  r`  r_  r\  r/  rp  r|  r}  rB  r/  rj  r  rl  r  r  r  r  r}  r  r  r  r  r  r  r  r  r[   r  r  r  r  r  r  rv   r   r  r  r`  r  r  r  r  r!  r$  r(  r,  r0  r3  r7  r;  r?  rD  rG  rJ  rM  rB  ri  rx  r  r  r  r  r  r]  r  r  r  r   )r-  r  s   00rC   r  r  n	  st    DGFEEJ G
 I' N8L*-LG;5.*.$(,T(( 
,,.(#8-8
2*1f"8	5K2.=29*6'R,\	07rOOS(RT!F8:
	
D 	kk'""
	L!F..`

33 * $) 88(:(A*=:B:9,;0A(?(?(
@
2X.T$l(Z Xt0C6D6D64@G	s   Fr  c                 v   [        5       nU R                  S5      nU H  nSU;   a  UR                  SS5      u  pV US:X  a  SnO[        U5      nUS:X  a  SnO[        U5      nXVs=L a  c  O  O[        U5      eUb  US::  d	  Ub  US::  a  [        U5      eU=(       d    UnU=(       d    UnUR	                  XV5        M   US:X  a  SnO[        U5      nUb  US::  a  [        U5      eUR                  U=(       d    U5        M     U$ ! [
         a    [        U5      ef = f! [
         a    [        U5      ef = f)a  
Parse a message set search key into a C{MessageSet}.

@type s: L{bytes}
@param s: A string description of an id list, for example "1:3, 4:*"

@type lastMessageId: L{int}
@param lastMessageId: The last message sequence id or UID, depending on
    whether we are parsing the list in UID or sequence id context. The
    caller should pass in the correct value.

@rtype: C{MessageSet}
@return: A C{MessageSet} that contains the ids defined in the list
   ,   :r<   r  Nr   )rL   r  r  r   r]   ri   r   )r   rN  r|   r  r   rm   rn   s          rC   r  r    sC    ,CGGDME19a(IC0$;Cc(C4<Dt9D&&033Oqd6F4ST9033,}*]"
/9AAA=Q!V033 

1-.I J J  0,Q//0  0,Q//0s   BD	(D"	D"D8)ALLANSWEREDDELETEDDRAFTFLAGGEDNEWOLDr  SEEN
UNANSWERED	UNDELETEDUNDRAFT	UNFLAGGEDr  )LARGERSMALLERUIDc           	      >   / nUR                  5       nU (       a  [        U5      nU GH<  nX   nUR                  5       nU[        ;   a  U(       a  UR	                  U5        M<  US:X  a.  UR                  U[        US   5      [        US   5      /5        Mp  US:X  d  US:X  a*  [        R                  SU5      nUR                  XE/5        M  U[        ;  aJ  [        U[        5      (       a  SnO[        U[        5      (       a  SnOSnUR                  XFU4-  /5        M  [        U[        5      (       a  UR                  US	U4-  /5        GM)  UR                  XE /5        GM?     [        U5      S:  a  S
SR                  U5      -   S-   $ SR                  U5      $ )a  
Create a query string

Among the accepted keywords are::

    all         : If set to a true value, search all messages in the
                  current mailbox

    answered    : If set to a true value, search messages flagged with
                  \Answered

    bcc         : A substring to search the BCC header field for

    before      : Search messages with an internal date before this
                  value.  The given date should be a string in the format
                  of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

    body        : A substring to search the body of the messages for

    cc          : A substring to search the CC header field for

    deleted     : If set to a true value, search messages flagged with
                  \Deleted

    draft       : If set to a true value, search messages flagged with
                  \Draft

    flagged     : If set to a true value, search messages flagged with
                  \Flagged

    from        : A substring to search the From header field for

    header      : A two-tuple of a header name and substring to search
                  for in that header

    keyword     : Search for messages with the given keyword set

    larger      : Search for messages larger than this number of octets

    messages    : Search only the given message sequence set.

    new         : If set to a true value, search messages flagged with
                  \Recent but not \Seen

    old         : If set to a true value, search messages not flagged with
                  \Recent

    on          : Search messages with an internal date which is on this
                  date.  The given date should be a string in the format
                  of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

    recent      : If set to a true value, search for messages flagged with
                  \Recent

    seen        : If set to a true value, search for messages flagged with
                  \Seen

    sentbefore  : Search for messages with an RFC822 'Date' header before
                  this date.  The given date should be a string in the format
                  of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

    senton      : Search for messages with an RFC822 'Date' header which is
                  on this date  The given date should be a string in the format
                  of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

    sentsince   : Search for messages with an RFC822 'Date' header which is
                  after this date.  The given date should be a string in the format
                  of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

    since       : Search for messages with an internal date that is after
                  this date..  The given date should be a string in the format
                  of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

    smaller     : Search for messages smaller than this number of octets

    subject     : A substring to search the 'subject' header for

    text        : A substring to search the entire message for

    to          : A substring to search the 'to' header for

    uid         : Search only the messages in the given message set

    unanswered  : If set to a true value, search for messages not
                  flagged with \Answered

    undeleted   : If set to a true value, search for messages not
                  flagged with \Deleted

    undraft     : If set to a true value, search for messages not
                  flagged with \Draft

    unflagged   : If set to a true value, search for messages not
                  flagged with \Flagged

    unkeyword   : Search for messages without the given keyword set

    unseen      : If set to a true value, search for messages not
                  flagged with \Seen

@type sorted: C{bool}
@param sorted: If true, the output will be sorted, alphabetically.
The standard does not require it, but it makes testing this function
easier.  The default is zero, and this should be acceptable for any
application.

@rtype: L{str}
@return: The formatted query string
HEADERr   r<   KEYWORD	UNKEYWORDri  z"%s"z"%d"z%dr  r  ))rE  _sortedr  _SIMPLE_BOOLrv   r   r   
_nonAtomREr  
_NO_QUOTESrZ   rL   r  r   r   )rr   kwargr  rE  rt  r"  rt  s          rC   Queryr  Q  sV   \ C::<Dt}HGGIJJqM(]JJ3qt9c!A$i01)^qK/ r1%AJJvj !Z((As##JJ!:'3JJ41$;'(JJS{#1 2 3x!|SXXc]"S((xx}rE   c                      [        U 5      S:  a  [        U 5      e[        U 5      S:X  a  SU -  $ SU S    S[        U SS 6  S3$ )	z(
The disjunction of two or more queries
r  z
(OR %s %s)z(OR r   r  r<   Nr  )r   r   Or)r  s    rC   r  r    sS     4y1}%%	Tad""d1gYaDHa00rE   c                     SU  S3$ )zThe negation of a queryz(NOT r  r?   )r  s    rC   Notr    s    5'rE   c                     U R                  SS5      n Uc  U R                  SS5      n O)U R                  SS[        R                  " U5      -  5      n [        R                  " U [        R                  5      $ )Nr   z(?:.*?)%z(?:(?:[^%s])*?))replacer  r  r  I)r  r  s     rC   wildcardToRegexpr    sa    Y/H}##C3##C):RYYu=M)MN::h%%rE   c                    U R                  5       n / n/ nS=p4[        SU 5      n[        SU 5      n[        SU 5      n[        SU 5      n[        [        U 5      5       GHL  u  pX:X  af  U	(       a.  X	S-
  U	 U:X  a#  UR	                  5         UR                  U5        M@  U(       d  SnMK  SnUR                  UR                  U5      5        / nMq  U(       dA  U(       d:  X[        R                  R                  S5      -   ;  a  SnUR                  U
5        M  U(       aj  U(       dc  U
[        R                  R                  S5      ;   a@  UR                  U5      nX:X  a  UR                  S	5        OUR                  U5        / nSnGM*  U(       d
  U(       d  GM;  UR                  U
5        GMO     U(       a  [        U 5      eU(       a:  UR                  U5      nX:X  a  UR                  S	5        U$ UR                  U5        U$ )
a  
Split a string into whitespace delimited tokens

Tokens that would otherwise be separated but are surrounded by "
remain as a single token.  Any token that is not quoted and is
equal to "NIL" is tokenized as L{None}.

@type s: L{bytes}
@param s: The string to be split

@rtype: L{list} of L{bytes}
@return: A list of the resulting tokens

@raise MismatchedQuoting: Raised if an odd number of quotes are present
Fr  \ri  NILr<   Tr%  N)r  r8   rj   r9   rp  rv   r   string
whitespacer  r"   )r   r  wordinQuoteinWordquescrR  nilrl   r!  ws               rC   splitQuotedr    s     	
	AFDG	a	 B
&!
$CB"E
%
#C)A,'7Q1uq\S(
Bejj./ 1 1 8 8 ABCFKKNGV->->-E-Eg-N(N

4 Axd#a DFwwKKN7 (: ""JJt8MM$ M MM!MrE   c                     / nU" U S   5      nU S   /nU SS   HA  nU" U5      nXt:w  a   UR                  X$   " U5      5        U/nUnM0  UR                  U5        MC     UR                  X$   " U5      5        U$ Nr   r<   )r   rv   )sequence	predicatetransformersr  ro  tmpr{  r   s           rC   splitOnr  =  s    FXa[!DA;-Cab\aL9MM,,S12#CDJJqM  MM,$S)*MrE   c                 D   / nSnS nS S S.n[        U 5       Ha  u  pV[        U[        5      (       a@  Ub   UR                  " [	        XU X45      5        SnUR
                  " [        U5      5        MZ  Ub  M_  UnMc     Ub  UR                  " [	        XS X45      5        U$ )a[  
Turns a list of length-one strings and lists into a list of longer
strings and lists.  For example,

['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']]

@type results: L{list} of L{bytes} and L{list}
@param results: The list to be collapsed

@rtype: L{list} of L{bytes} and L{list}
@return: A new list which is the collapsed form of C{results}
Nc                 "    [        U [        5      $ ry   )rZ   r  r{  s    rC   rU   !collapseStrings.<locals>.<lambda>]  s    Z5)rE   c                 6    [        SR                  U 5      5      $ r  )r  r   r  s    rC   rU   r  _  s    [!-rE   c                 V    SR                  U  Vs/ s H  oS   PM	     sn5      /$ s  snf )NrE   r   )r   )r{  rl   s     rC   rU   r  `  s$    chha0a!a0120s   &)r   r<   )rj   rZ   r[   r   r  rv   collapseStrings)r  r]  begunpredtranrl   r!  s          rC   r  r  M  s     DE)D-2D '"a GG!$4dABKK*+]E # GGFOT89KrE   c                    U R                  5       n Sn/ /n Sn[        U 5      nXE:  Gad  XUS-    nU(       aN  US:X  a   US   R                  XUS-    5        US-  nM:  US:X  a  U(       + nUS   R                  U5        US-  nGO US:X  a!  US   R                  U5        U(       + nUS-  nOU(       ab  US:X  a\  U R                  SU5      nUS:X  a  [	        S	5      e[        XS-   U 5      nUS   R                  XS
-   US
-   U-    45        US
-   U-   nOpUS:X  d  US:X  a  UR                  / 5        US-  nOMUS:X  d  US:X  a(  US   R                  UR                  5       5        US-  nOUS   R                  U5        US-  nXE:  a  GMd  [        U5      S:w  a  [        U 5      e[        US   5      $ ! [         a    [        U 5      ef = f)aK  
Parse an s-exp-like string into a more useful data structure.

@type s: L{bytes}
@param s: The s-exp-like string to parse

@rtype: L{list} of L{bytes} and L{list}
@return: A list containing the tokens present in the input.

@raise MismatchedNesting: Raised if the number or placement
of opening or closing parenthesis is invalid.
r   r<   r  r   r  r  r  r  r  r~  r  r  r  r.  )
r  r   rv   r  ri   r  rp  
IndexErrorr!   r  )	r   handleLiteralr  contentStackrl   r  r!  ra   literalSizes	            rC   r  r  o  s    	
	AG4L$#Fea!eA: $++A!a%L9FA$Y")kGR ''*Q9 $++A.")kGFA"qDy&&q/Cby()<=="%aAn"5K $++QQwq;9N-O,QRa+-A$Y!t) ''+FA$Y!t) $++L,<,<,>?FA $++A.FA? eD <A""<?++	  #""#s   E4F6 6Gc                     [        SU 5      n[        SU 5      nXR                  X"U-   5      R                  XU-   5      -   U-   $ )Nr  r  )r8   r  )r   r  r  s      rC   r$  r$    sD    	a	 B
&!
$C		#Sy)11"Bh??"DDrE   r   r   c                 "    S[        U 5      U 4-  $ )Ns   {%d}
%b)r   r   s    rC   r.  r.    s    CFA;&&rE   c                   (    \ rS rSrS rS\4S jrSrg)r  i  c                     Xl         g ry   rk   )r_   rk   s     rC   rb   DontQuoteMe.__init__  s    
rE   r   c                 ,    [        U R                  5      $ ry   )r   rk   re   s    rC   r   DontQuoteMe.__str__  s    4::rE   r  N)r   r   r   r   rb   r   r   r   r?   rE   rC   r  r    s     rE   r  s   (){ %*"c                 j    U S:X  a  g[        U 5       H  nUS:  d  US:  a    gU[        ;   d  M    g   g)NrE   r<   r     r   )r9   _ATOM_SPECIALS)r   r!  s     rC   _needsQuoter    s:    Cxq\w;!g+	 
 rE   c                     [        U [        5      (       a  U $  U R                  S5      $ ! [         a!    [        R
                  " 5         [        U 5      ef = fr  )rZ   r   r  r  r6   rb  r   r  s    rC   r|  r|    sK    $+{{=)) +	$T**+s	   * +Ac                     [        U [        5      (       d  U R                  S5      n U R                  S5      n [	        U 5      (       a  [        U 5      $ U $ )Nr(  r  )rZ   r   r  r  r  r$  r  s    rC   r  r    sE    dC  {{9%;;}%D4d|KrE   c                 z    [        SU 5      n[        SU 5      nX;   =(       d    X ;   =(       d    [        U 5      S:  $ )N
i  )r8   r   )r   crlfs      rC   _needsLiteralr    s6    	q	!B	q	!B7.bg.Q$.rE   c           	      z   / nU  GH  n[        U[        5      (       a  UR                  S5      nUc  UR                  SS/5        MB  [        U[        5      (       a'  UR                  S[        [        U5      5      /5        M~  [        U[        5      (       a  UR                  SUR                  /5        M  [        U[        5      (       ab  [        U5      (       a3  UR                  SS[        U5      4-  [        R                  U/5        GM
  UR                  S[        U5      /5        GM)  [        US5      (       aC  UR                  5       nUR                  SS[        U5      4-  [        R                  U/5        GM}  UR                  SS[!        U5      -   S-   /5        GM     S	R#                  US
S 5      $ )ap  
Turn a nested list structure into an s-exp-like string.

Strings in C{items} will be sent as literals if they contain CR or LF,
otherwise they will be quoted.  References to None in C{items} will be
translated to the atom NIL.  Objects with a 'read' attribute will have
it called on them with no arguments and the returned string will be
inserted into the output as a literal.  Integers will be converted to
strings and inserted into the output unquoted.  Instances of
C{DontQuoteMe} will be converted to strings and inserted into the output
unquoted.

This function used to be much nicer, and only quote things that really
needed to be quoted (and C{DontQuoteMe} did not exist), however, many
broken IMAP4 clients were unable to deal with this level of sophistication,
forcing the current behavior to be adopted for practical reasons.

@type items: Any iterable

@rtype: L{str}
r%  Nr  s   NILs   {%d}r	  r  r  rE   r<   )rZ   r   r  r   r  r;   r  rk   r  r  r   r1  	delimiterr$  hasattrr	  rt  r   )r  piecesrl   r"  s       rC   rt  rt    sW   , Fa !A9MM4.)3MM4s1v!678;''MM4/*5!!QtWAy%8+:O:OQRSTtVAY/0QAMM4CF9!4k6K6KQOPMM4(;A(>!>!EFG- . 88F12JrE   c                   v    \ rS rSrSrSrSrS rS rSS jr	S r
S rSS	 jrS
 rS rS rS rS rS rS rSrg)MemoryAccountWithoutNamespacesi  Nr   c                 ,    Xl         0 U l        / U l        g ry   )r  r  subscriptionsr  s     rC   rb   'MemoryAccountWithoutNamespaces.__init__  s    	rE   c                 H    U R                   nU =R                   S-  sl         U$ rR   )top_id)r_   rU  s     rC   
allocateID)MemoryAccountWithoutNamespaces.allocateID  s    [[q	rE   c                     [        UR                  5       5      nXR                  ;   a  [        U5      eUc  U R	                  XR                  5       5      nX R                  U'   grR   )r|  r  r  r   _emptyMailboxr  )r_   r  r]  s      rC   
addMailbox)MemoryAccountWithoutNamespaces.addMailbox'  sR    $**,'>>!"4((<%%dOO,=>D#trE   c                    UR                  S5       Vs/ s H  o"(       d  M  UPM     nn[        S[        U5      5       H'  n U R                  SR	                  US U 5      5        M)      U R                  SR	                  U5      5        gs  snf ! [
         a     M_  f = f! [
         a    UR                  S5      (       d   g gf = f)N/r<   FT)r  rG  r   r  r   r   rk  )r_   pathspecpathpathsaccums        rC   r  %MemoryAccountWithoutNamespaces.create0  s    "*.."5>"5$"5>1c%j)Ev 78 *
	OOCHHUO,  ? $    	$$S)) *	s.   
BB#B+ B" 
BB" CCc                     [         ery   )NotImplementedError)r_   r  rU  s      rC   r
  ,MemoryAccountWithoutNamespaces._emptyMailbox>  s    !!rE   c                 f    U R                   R                  [        UR                  5       5      5      $ ry   )r  rl  r|  r  )r_   r  	readwrites      rC   r}  %MemoryAccountWithoutNamespaces.selectA  s"    ~~!!*TZZ\":;;rE   c                    [        UR                  5       5      nU R                  R                  U5      nU(       d  [	        S5      eSUR                  5       ;   aI  U R                  R                  5        H+  nX1:w  d  M
  UR                  U5      (       d  M"  [	        S5      e   UR                  5         [        U R                  U5      5      S:  a  [	        SU S35      eU R                  U	 g )NzNo such mailboxz	\Noselectz<Hierarchically inferior mailboxes exist and \Noselect is setr<   zName "z!" has inferior hierarchical names)r|  r  r  rl  r    r  rE  r  destroyr   _inferiorNames)r_   r  r]  otherss       rC   r  %MemoryAccountWithoutNamespaces.deleteD  s    $**,'~~!!$'"#4554==?* ..--/>f&7&7&=&=*W  0
 	 t""4()A-"VD61R#STTNN4 rE   c           	         [        UR                  5       5      n[        UR                  5       5      nXR                  ;  a  [        U5      eU R	                  U5      nU Vs/ s H  oDUR                  XS5      4PM     nnU H  u  pVX`R                  ;   d  M  [        U5      e   U H.  u  pVU R                  U   U R                  U'   U R                  U	 M0     g s  snf rR   )r|  r  r  r$   r  r  r   )r_   r  r  	inferiorsooldnews          rC   r  %MemoryAccountWithoutNamespaces.rename[  s    W]]_-W]]_-..(((''0	BKL)Q7Q78)	L!HCnn$&s++ " "HC"&.."5DNN3s# " Ms   "Cc                     / nU R                   R                  5        H,  nUR                  U5      (       d  M  UR                  U5        M.     U$ ry   )r  rE  r  rv   )r_   r  r   infnames       rC   r  -MemoryAccountWithoutNamespaces._inferiorNamesl  sE    	~~**,G!!$''  ) - rE   c                 N    [        UR                  5       5      U R                  ;   $ ry   )r|  r  r  r  s     rC   r  +MemoryAccountWithoutNamespaces.isSubscribeds  s    $**,'4+=+===rE   c                     [        UR                  5       5      nXR                  ;  a  U R                  R                  U5        g g ry   )r|  r  r  rv   r  s     rC   r  (MemoryAccountWithoutNamespaces.subscribev  s7    $**,')))%%d+ *rE   c                     [        UR                  5       5      nXR                  ;  a  [        SU 35      eU R                  R	                  U5        g )NzNot currently subscribed to )r|  r  r  r    remover  s     rC   r  *MemoryAccountWithoutNamespaces.unsubscribe{  sE    $**,')))"%A$#HII!!$'rE   c                     U R                  [        UR                  5       5      5      n[        US5      nU Vs/ s H*  o2R	                  U5      (       d  M  X0R
                  U   4PM,     sn$ s  snf )Nr  )r  r|  r  r  r  r  )r_   r  r  rl   s       rC   r  ,MemoryAccountWithoutNamespaces.listMailboxes  sY    !!*SYY["9:#Hc203I1~~a7H&NN1%&IIIs   A-A-)r  r  r  ry   r  )r   r   r   r   r  r  r  rb   r  r  r  r
  r}  r  r  r  r  r  r  r  r   r?   rE   rC   r  r    sS    IMF 
"<!.$">,
(JrE   r  c                   ,    \ rS rSrS rS rS rS rSrg)MemoryAccounti  c                     SS//$ )NrE      /r?   re   s    rC   rr  #MemoryAccount.getPersonalNamespaces  s    d}rE   c                     g ry   r?   re   s    rC   rs  !MemoryAccount.getSharedNamespaces      rE   c                     g ry   r?   re   s    rC   getOtherNamespaces MemoryAccount.getOtherNamespaces  r8  rE   c                     g ry   r?   re   s    rC   getUserNamespacesMemoryAccount.getUserNamespaces  s    rE   r?   N)	r   r   r   r   rr  rs  r:  r=  r   r?   rE   rC   r2  r2    s    
rE   r2  r  r  
getUIDNextr  getUnseenCountr  c                 l    0 nU H+  n[        U [        UR                  5          5      " 5       X#'   M-     U$ ry   )rv  _statusRequestDictr  )r]  r   rr  s       rC   statusRequestHelperrD    s3    
At/	:;= HrE   c                     U c  S/$ [         R                  R                  U /5      n U  VVs/ s H$  u  pU=(       d    S S /UR                  S5      -   PM&     snn$ s  snnf )Nr  @)rq  rr  getaddressesr  )addrr  addresss      rC   	parseAddrrJ    s]    |
 	
 ;;##TF+DGKLtRZ4s!33tLLLs   +Ac           
      H   U R                  S5      nUR                  S5      nUR                  S5      nUR                  S5      nUR                  SU5      nUR                  SU5      nUR                  S5      nUR                  S5      nUR                  S	5      n	UR                  S
5      n
UR                  S5      nUU[        U5      [        U5      U=(       a    [        U5      U=(       a    [        U5      U=(       a    [        U5      U	=(       a    [        U	5      U
U4
$ )NTr  r  r  senderzreply-tor  r  rh  zin-reply-toz
message-id)rk  rl  rJ  )r  headersr  r  from_rL  reply_tor  r  rh  in_reply_tomids               rC   r  r    s    nnT"G;;vDkk)$GKKE[[5)F{{:u-H	T	B	T	B
++e
C++m,K
++l
#C%&(Yx(
y}
y}	# rE   c                 B    SnU R                  5        H  nUS-  nM
     U$ r  )r|  )r  r	  r  s      rC   getLineCountrS    s(     E__
 LrE   c                 >    U S   U S   s=:X  a  S:X  a	  O  U $ U SS $ U $ )Nr   r   r  r<   r?   r  s    rC   unquoterU    s.    tquH 2wHrE   c                 R   SnU R                  SS5      R                  SS5      nSR                  UR                  5       5      nU(       aW  UR	                  S5      nUS   R	                  SS5      n[        U5      S:X  a  US   nSnOUu  pV[        S	 USS  5       5      nOS=pVXVU4$ )
zB
Return a two-tuple of the main and subtype of the given message.
NFcontent-typeri  ;r   r  r<   c              3   |   #    U  H2  oR                  5       R                  5       R                  S S5      v   M4     g7f)=r<   N)r  r  r  )r-  rT   s     rC   r/  "_getContentType.<locals>.<genexpr>  s+     KlWWY__&,,S!44ls   :<)rk  rl  r   
splitlinesr  r   dict)r  attrsmmmimetypera  majorminors          rC   _getContentTyperc    s     E	~	.	2	2>2	FB		!B	88C={  a(t9>GEE  LEKhqrlKKrE   c                     [        U 5      u  pnUb  UR                  5       nUb  UR                  5       nUS:X  a  [        XU5      $ X4S:X  a  [        XX#5      $ US:X  a  [	        XX#5      $ [        XX#5      $ )a)  
Construct an appropriate type of message structure object for the given
message object.

@param message: A L{IMessagePart} provider

@return: A L{_MessageStructure} instance of the most specific type available
    for the given message, determined by inspecting the MIME type of the
    message.
	multipart)r   r6  r7   )rc  r  _MultipartMessageStructure_RFC822MessageStructure_TextMessageStructure_SinglepartMessageStructure)r   mainsubtyper^  s       rC   _getMessageStructurerl    s     +73D5zz|--/{)'EBB
1	1&wgEE	$WGCC*7'IIrE   c                   *    \ rS rSrSrS rS rS rSrg)_MessageStructurei  z
L{_MessageStructure} is a helper base class for message structure classes
representing the structure of particular kinds of messages, as defined by
their MIME type.
c                     Xl         X l        g)z
@param message: An L{IMessagePart} provider which this structure object
    reports on.

@param attrs: A C{dict} giving the parameters of the I{Content-Type}
    header of the message.
N)r   r^  )r_   r   r^  s      rC   rb   _MessageStructure.__init__  s     
rE   c                 6   U(       a  UR                  S5      n[        U5      S:X  a  US   R                  5       S4nU$ [        U5      S:  aD  USS  VVs/ s H  o"R                  SS5        H  o3PM     M     nnnUS   R                  5       U/nU$ gs  snnf )z
Parse a I{Content-Disposition} header into a two-sequence of the
disposition and a flattened list of its parameters.

@return: L{None} if there is no disposition header value, a L{list} with
    two elements otherwise.
z; r<   r   NrZ  )r  r   r  )r_   dispparamrT   paramss        rC   _disposition_MessageStructure._disposition  s     ::d#D4yA~Q.
 K	 TQ)-abO;;sA;Na!;N!OQ0K	 Ps   $Bc                     U R                   (       a_  U R                   R                  5        VVs/ s H  u  pU[        U5      4PM     nnn[        U5       VVs/ s H  oD  H  oUPM     M     snn$ gs  snnf s  snnf )z
@return: The I{Content-Type} parameters, unquoted, as a flat list with
    each Nth element giving a parameter name and N+1th element giving
    the corresponding parameter value.
N)r^  r  rU  rr   )r_   rt  r"  unquotedrT   ys         rC   _unquotedAttrs _MessageStructure._unquotedAttrs2  sh     ::6:jj6F6F6HI6HFQGAJ6HHI%h/;/!AAA/;; J;s   A2A8)r^  r   N)	r   r   r   r   r   rb   ru  rz  r   r?   rE   rC   rn  rn    s    	(	rE   rn  c                   8    \ rS rSrSr/ SQrS rS rS rS r	Sr
g	)
ri  i>  zb
L{_SinglepartMessageStructure} represents the message structure of a
non-I{multipart/*} message.
)
content-idcontent-descriptioncontent-transfer-encodingc                 T    [         R                  XU5        X l        X0l        X@l        g)ax  
@param message: An L{IMessagePart} provider which this structure object
    reports on.

@param main: A L{str} giving the main MIME type of the message (for
    example, C{"text"}).

@param subtype: A L{str} giving the MIME subtype of the message (for
    example, C{"plain"}).

@param attrs: A C{dict} giving the parameters of the I{Content-Type}
    header of the message.
N)rn  rb   rj  rk  r^  )r_   r   rj  rk  r^  s        rC   rb   $_SinglepartMessageStructure.__init__F  s#     	""4%8	
rE   c                 >   U R                   R                  " S/U R                  Q76 nU R                   R                  5       nU R                  U R
                  pCU R                  5       nUUUUR                  S5      UR                  S5      UR                  S5      U/$ )z>
Return a list of the basic fields for a single-part message.
Fr}  r~  r  )r   rk  _HEADERSr  rj  rk  rz  rl  )r_   rM  r   ra  rb  unquotedAttrss         rC   _basicFields(_SinglepartMessageStructure._basicFieldsY  s     ,,))%@$--@ ||##%yy$,,u ++- KK%KK-.KK34
 	
rE   c                 r    U R                  5       nU(       a  UR                  U R                  5       5        U$ )z
Construct and return a list of the basic and extended fields for a
single-part message.  The list suitable to be encoded into a BODY or
BODYSTRUCTURE response.
)r  r   	_extendedr_   extendedr  s      rC   r  "_SinglepartMessageStructure.encodeq  s-     ""$MM$..*+rE   c                 f   / nU R                   R                  SSSSS5      nUR                  UR                  S5      5        UR                  U R	                  UR                  S5      5      5        UR                  UR                  S5      5        UR                  UR                  S5      5        U$ )a  
The extension data of a non-multipart body part are in the
following order:

  1. body MD5

     A string giving the body MD5 value as defined in [MD5].

  2. body disposition

     A parenthesized list with the same content and function as
     the body disposition for a multipart body part.

  3. body language

     A string or parenthesized list giving the body language
     value as defined in [LANGUAGE-TAGS].

  4. body location

     A string list giving the body content URI as defined in
     [LOCATION].

Fzcontent-md5content-dispositioncontent-languagecontent-location)r   rk  rv   rl  ru  r_   r  rM  s      rC   r  %_SinglepartMessageStructure._extended|  s    2 ,,))!
 	gkk-01d''4I(JKLgkk"456gkk"456rE   )r^  rj  rk  N)r   r   r   r   r   r  rb   r  r  r  r   r?   rE   rC   ri  ri  >  s#    
 RH&
0	'rE   ri  c                       \ rS rSrSrS rSrg)rh  i  zS
L{_TextMessageStructure} represents the message structure of a I{text/*}
message.
c                     [         R                  U 5      nUR                  [        U R                  5      5        U(       a  UR                  U R                  5       5        U$ )z
A body type of type TEXT contains, immediately after the basic
fields, the size of the body in text lines.  Note that this
size is the size in its content transfer encoding and not the
resulting size after any decoding.
)ri  r  rv   rS  r   r   r  r  s      rC   r  _TextMessageStructure.encode  sD     -99$?l4<<01MM$..*+rE   r?   Nr   r   r   r   r   r  r   r?   rE   rC   rh  rh    s    
rE   rh  c                       \ rS rSrSrS rSrg)rg  i  z]
L{_RFC822MessageStructure} represents the message structure of a
I{message/rfc822} message.
c                    [         R                  X5      nU R                  R                  S5      nUR	                  [        U5      5        UR	                  [        US5      5        UR	                  [        U5      5        U$ )z
A body type of type MESSAGE and subtype RFC822 contains,
immediately after the basic fields, the envelope structure,
body structure, and size in text lines of the encapsulated
message.
r   F)ri  r  r   rL  rv   r  rE  rS  )r_   r  r  	containeds       rC   r  _RFC822MessageStructure.encode  sc     -33DCLL++A.	k),-&y%89l9-.rE   r?   Nr  r?   rE   rC   rg  rg    s    
rE   rg  c                   0    \ rS rSrSrS rS rS rS rSr	g)	rf  i  z]
L{_MultipartMessageStructure} represents the message structure of a
I{multipart/*} message.
c                 <    [         R                  XU5        X l        g)a  
@param message: An L{IMessagePart} provider which this structure object
    reports on.

@param subtype: A L{str} giving the MIME subtype of the message (for
    example, C{"plain"}).

@param attrs: A C{dict} giving the parameters of the I{Content-Type}
    header of the message.
N)rn  rb   rk  )r_   r   rk  r^  s       rC   rb   #_MultipartMessageStructure.__init__  s     	""4%8rE   c              #   ~   #    Sn  U R                   R                  U5      nUv   US-  nM'  ! [         a     gf = f7f)zB
Return an iterator over all of the sub-messages of this message.
r   r<   N)r   rL  r  )r_   rl   rJ  s      rC   	_getParts$_MultipartMessageStructure._getParts  sP      ||..q1 
Q   s   =- =
:=:=c                    U R                  5        Vs/ s H  n[        U5      R                  U5      PM     nnUR                  U R                  5        U(       a  UR                  U R                  5       5        U$ s  snf )zG
Encode each sub-message and added the additional I{multipart} fields.
)r  rl  r  rv   rk  r   r  )r_   r  r   r  s       rC   r  !_MultipartMessageStructure.encode  se     EINNDTUDTq&q)00:DTUdll#MM$..*+	 Vs   $A<c                 f   / nU R                   R                  SSSS5      nUR                  U R                  5       5        UR                  U R	                  UR                  S5      5      5        UR                  UR                  SS5      5        UR                  UR                  SS5      5        U$ )a  
The extension data of a multipart body part are in the following order:

  1. body parameter parenthesized list
       A parenthesized list of attribute/value pairs [e.g., ("foo"
       "bar" "baz" "rag") where "bar" is the value of "foo", and
       "rag" is the value of "baz"] as defined in [MIME-IMB].

  2. body disposition
       A parenthesized list, consisting of a disposition type
       string, followed by a parenthesized list of disposition
       attribute/value pairs as defined in [DISPOSITION].

  3. body language
       A string or parenthesized list giving the body language
       value as defined in [LANGUAGE-TAGS].

  4. body location
       A string list giving the body content URI as defined in
       [LOCATION].
Fr  r  r  N)r   rk  rv   rz  ru  rl  r  s      rC   r  $_MultipartMessageStructure._extended  s    , ,,))%'9;P
 	d))+,d''4I(JKLgkk"4d;<gkk"4d;<rE   )rk  N)
r   r   r   r   r   rb   r  r  r  r   r?   rE   rC   rf  rf    s    
 rE   rf  c                 6    [        U 5      R                  U5      $ )aN  
RFC 3501, 7.4.2, BODYSTRUCTURE::

  A parenthesized list that describes the [MIME-IMB] body structure of a
  message.  This is computed by the server by parsing the [MIME-IMB] header
  fields, defaulting various fields as necessary.

    For example, a simple text message of 48 lines and 2279 octets can have
    a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL
    "7BIT" 2279 48)

This is represented as::

    ["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 2279, 48]

These basic fields are documented in the RFC as:

  1. body type

     A string giving the content media type name as defined in
     [MIME-IMB].

  2. body subtype

     A string giving the content subtype name as defined in
     [MIME-IMB].

  3. body parameter parenthesized list

     A parenthesized list of attribute/value pairs [e.g., ("foo"
     "bar" "baz" "rag") where "bar" is the value of "foo" and
     "rag" is the value of "baz"] as defined in [MIME-IMB].

  4. body id

     A string giving the content id as defined in [MIME-IMB].

  5. body description

     A string giving the content description as defined in
     [MIME-IMB].

  6. body encoding

     A string giving the content transfer encoding as defined in
     [MIME-IMB].

  7. body size

     A number giving the size of the body in octets.  Note that this size is
     the size in its transfer encoding and not the resulting size after any
     decoding.

Put another way, the body structure is a list of seven elements.  The
semantics of the elements of this list are:

   1. Byte string giving the major MIME type
   2. Byte string giving the minor MIME type
   3. A list giving the Content-Type parameters of the message
   4. A byte string giving the content identifier for the message part, or
      None if it has no content identifier.
   5. A byte string giving the content description for the message part, or
      None if it has no content description.
   6. A byte string giving the Content-Encoding of the message body
   7. An integer giving the number of octets in the message body

The RFC goes on::

    Multiple parts are indicated by parenthesis nesting.  Instead of a body
    type as the first element of the parenthesized list, there is a sequence
    of one or more nested body structures.  The second element of the
    parenthesized list is the multipart subtype (mixed, digest, parallel,
    alternative, etc.).

    For example, a two part message consisting of a text and a
    BASE64-encoded text attachment can have a body structure of: (("TEXT"
    "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN"
    ("CHARSET" "US-ASCII" "NAME" "cc.diff")
    "<960723163407.20117h@cac.washington.edu>" "Compiler diff" "BASE64" 4554
    73) "MIXED")

This is represented as::

    [["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 1152,
      23],
     ["TEXT", "PLAIN", ["CHARSET", "US-ASCII", "NAME", "cc.diff"],
      "<960723163407.20117h@cac.washington.edu>", "Compiler diff",
      "BASE64", 4554, 73],
     "MIXED"]

In other words, a list of N + 1 elements, where N is the number of parts in
the message.  The first N elements are structures as defined by the previous
section.  The last element is the minor MIME subtype of the multipart
message.

Additionally, the RFC describes extension data::

    Extension data follows the multipart subtype.  Extension data is never
    returned with the BODY fetch, but can be returned with a BODYSTRUCTURE
    fetch.  Extension data, if present, MUST be in the defined order.

The C{extended} flag controls whether extension data might be returned with
the normal data.
)rl  r  )r  r  s     rC   rE  rE    s    R  $++H55rE   c                    U R                  5        VVs/ s HC  u  pSR                  UR                  5       SR                  UR                  5       5      45      PME     nnnSR                  U5      S-   n[	        U5      $ s  snnf )Nz: z
)r  r   titler\  r;   )rM  rt  r"  r/  s       rC   r-  r-    st     mmo%FQ 			1779fkk!,,.9:;% 	  ;;tv%Ds   A
B c              #   f   #    Sn  U R                  U5      v   US-  nM  ! [         a     g f = f7fr  )rL  r  )r  rl   s     rC   subpartsr    sA     	A,,q/!FA   s   1! 
.1.1c                 f   ^ ^^^ SSK Jm  [        R                  " 5       mUUU U4S jmT" S5        T$ )a  
Consume an interator at most a single iteration per reactor iteration.

If the iterator produces a Deferred, the next iteration will not occur
until the Deferred fires, otherwise the next iteration will be taken
in the next reactor iteration.

@rtype: C{Deferred}
@return: A deferred which fires (with None) when the iterator is
exhausted or whose errback is called if there is an exception.
r   rD  c                   >  [        T5      n[        U[        R                  5      (       a  UR	                  T5        g TR                  STU5        g ! [         a    TR                  U 5         g [         a    TR                  5          g f = fr   )
r  rZ   r   r  r  rK  r  r   r  r  )rf   rC  r"  gorl   rE  s     rC   r  iterateInReactor.<locals>.go  sp    
	,QA !U^^,,b!!!!R+  	JJt 	IIK	s   A B0BBN)rJ  rE  r   r  )rl   r"  r  rE  s   `@@@rC   r:  r:    s,     )A, , tHHrE   c                   R    \ rS rSrSr\" \R                  5      rSS jr	S r
S rSrg)	r=  i     Nc                     Xl         Uc  [        R                  " 5       nX l        Uc  [        nX0l        U R                  R                  U l        g)z
Produce this message.

@param msg: The message I am to produce.
@type msg: L{IMessage}

@param buffer: A buffer to hold the message in.  If None, I will
    use a L{tempfile.TemporaryFile}.
@type buffer: file-like
N)r  r   r   r  r:  r?  r   )r_   r  r  r?  s       rC   rb   MessageProducer.__init__  sB     >++-F(I"[[&&
rE   c                 L    Xl         U R                  U R                  5       5      $ ry   )consumerr?  _produce)r_   r  s     rC   r4  MessageProducer.beginProducing  s     ~~dmmo..rE   c              #     ^ #    T R                   R                  S5      nS nT R                   R                  5       (       a  UR                  S5      nUR	                  S5      SS   Vs/ s H  oDR	                  SS5      PM     nnU VVs0 s H$  u  pgUR                  5       R                  5       U_M&     nnnUR                  S5      nUc/  ST R                  5       R                   3nUS==   SU S	3-  ss'   O1UR                  S	5      (       a  UR                  S	5      (       a  USS
 n[        U5      nT R                  [        U5      5        T R                  S5        T R                   R                  5       (       a}  [        T R                   5       HL  nT R                  SU-   S-   5        [        UT R                   T R"                  5      R%                  S 5      v   MN     T R                  SU-   S-   5        O`T R                   R'                  5       n	 U	R)                  T R*                  5      n
U
(       a   T R                   R                  U
5        S v   OOME  T R,                  (       a`  T R                   R/                  SS5        [1        T R                   5      R%                  T R,                  5      R3                  U 4S j5      v   g g s  snf s  snnf 7f)NTrW  rX  r<   rZ  boundaryz----=z; boundary="r  r   r  s   
--s   --
r   c                    > T$ ry   r?   rh  s    rC   rU   *MessageProducer._produce.<locals>.<lambda>  s    $rE   )r  rk  rK  rl  r  r  r  _uuid4hexr  rk  r;   r   r-  r  r=  r  r?  r4  r|  r	  
CHUNK_SIZEr  r   r3  r  )r_   rM  r  r  rT   r  rt  r"  r   rz  r  s   `          rC   r  MessageProducer._produce  sL    ((%%d+88!!kk.1G.5mmC.@.DE.DWWS!_.DEE8=>fqQWWY__&)E>yy,H"4;;=#4#4"56'\(1+EE'&&s++0A0A#0F0F'"~H$X.H

>'*+

788!!dhh'

9x/'9:%adnnETT  (
 JJy8+i78$$&AFF4??+KK%%a(J  ==KKQ"t{{+::4==IUU  = F>s   A$K'KK	+K4H&K)r  r  r  r?  r   r  )r   r   r   r   r  staticmethoduuiduuid4r  rb   r4  r  r   r?   rE   rC   r=  r=    s$    J$**%F'(/'rE   r=  c            
          \ rS rSr " S S5      r " S S5      r " S S5      r " S S	5      r " S
 S5      r " S S5      r	 " S S5      r
 " S S5      r " S S5      r " S S5      r " S S5      r " S S5      r " S S5      rSrS\4S\4S\4S \4S!\4S"\	4S#\
4S$\4S%\4/	rS& rS' rS( rS) rS* rS+ rS, rS- rS. r\R:                  " S/5      rS0 rS1 r S2 r!S3 r"S4 r#S5r$g)6r  i  c                       \ rS rSrSrS rSrg)_FetchParser.Envelopei  r+  c                     g)Nr+  r?   re   s    rC   rU   _FetchParser.Envelope.<lambda>  s    zrE   r?   Nr   r   r   r   ra  r   r   r?   rE   rC   Enveloper    s     )rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.Flagsi  r  c                     g)Nr  r?   re   s    rC   rU   _FetchParser.Flags.<lambda>  s    wrE   r?   Nr  r?   rE   rC   Flagsr    s    &rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.InternalDatei  r'  c                     g)Nr'  r?   re   s    rC   rU   "_FetchParser.InternalDate.<lambda>  s    ~rE   r?   Nr  r?   rE   rC   InternalDater    s    -rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.RFC822Headeri  r:  c                     g)Nr}  r?   re   s    rC   rU   "_FetchParser.RFC822Header.<lambda>      rE   r?   Nr  r?   rE   rC   RFC822Headerr    s    .rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.RFC822Texti   r>  c                     g)Nr{  r?   re   s    rC   rU    _FetchParser.RFC822Text.<lambda>"      }rE   r?   Nr  r?   rE   rC   
RFC822Textr         ,rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.RFC822Sizei$  rC  c                     g)Nr|  r?   re   s    rC   rU    _FetchParser.RFC822Size.<lambda>&  r  rE   r?   Nr  r?   rE   rC   
RFC822Sizer  $  r  rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.RFC822i(  r6  c                     g)Nr6  r?   re   s    rC   rU   _FetchParser.RFC822.<lambda>*  s    xrE   r?   Nr  r?   rE   rC   RFC822r  (  s    'rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.UIDi,  r  c                     g)Nr  r?   re   s    rC   rU   _FetchParser.UID.<lambda>.  s    urE   r?   Nr  r?   rE   rC   r  r  ,  s    $rE   r  c                   p    \ rS rSrSrSrSrSrSrSr	Sr
SrSrS\4S jrSS\\   S\4S	 jjrS\4S
 jrSrg)_FetchParser.Bodyi0  r~  FNr?   r   c                 @    U R                  5       R                  S5      $ Nr%  rP  r  re   s    rC   r   _FetchParser.Body.__str__;      >>#**733rE   rI  c           	         SnSnSnU R                   (       aI  SR                  U R                    Vs/ s H   n[        US-   5      R                  S5      PM"     sn5      nSnU R                  (       a4  USU-   U-   [        U R                  5      R                  S5      -   S-   -  nO\U R
                  (       a  USU-   U-   S-   -  nO<U R                  (       a  USU-   U-   S	-   -  nOU R                  (       a  USU-   S-   -  nU R                  b7  Ub  XR                  :  a   US
U R                  U R                  4-  -  nU$ US-  nU$ s  snf )a  
Prepare the initial command response for a Fetch BODY request.
Interpret the Fetch request from the client and return the
appropriate response based on RFC 3501.
This is not the body itself of the response, merely the section
of the first response line that describes the body part.
rU  rE      .r<   r%  r  r.  s   TEXT]s   MIME]s   <%d.%d>s   <0>)
rJ  r   r   r  rM  r7   rQ  rR  partialBeginpartialLength)r_   rI  baserJ  	separatorrT   s         rC   rS  _FetchParser.Body.getBytes>  sD    DDIyyyydii!Pi#a!e*"3"3G"<i!PQ 	 {{4K)+c$++.>.E.Eg.NNQUU ti/(::ti/(::td**  ,>V.@.@%@J$*;*;T=O=O)PPPD K FNDK/ "Qs   'Ec                 "    U R                  5       $ ry   )rS  re   s    rC   rP  _FetchParser.Body.__bytes__c  s    ==?"rE   ry   )r   r   r   r   ra  rr  rM  rQ  r7   rJ  rR  r  r  r   r   r	   r  r  rS  rP  r   r?   rE   rC   Bodyr  0  s_    	4S 	4#	8C= #	E #	J	#u 	#rE   r  c                       \ rS rSrSrS rSrg)_FetchParser.BodyStructureif  r/  c                     g)Nr/  r?   re   s    rC   rU   #_FetchParser.BodyStructure.<lambda>h  r  rE   r?   Nr  r?   rE   rC   BodyStructurer  f  s    .rE   r  c                   <    \ rS rSrSrSrSrS\4S jrS\	4S jr
Srg)_FetchParser.Headerik  FNr   c                 @    U R                  5       R                  S5      $ r  r  re   s    rC   r   _FetchParser.Header.__str__p  r  rE   c                    SnU R                   (       a  US-  nU R                  (       a  US-  n/ nU R                    H?  nUR                  5       n[        U5      (       a  [	        U5      nUR                  U5        MA     USSR                  U5      -   S-   -  nU R                  (       aB  SR                  U R                   Vs/ s H  oDS-   R                  5       PM     sn5      S-   U-   nU$ s  snf )	Ns   HEADERs   .FIELDSs   .NOTr  r  r  r  r<   )	rO  rN  r  r  r$  rv   r   rJ  rP  )r_   r  rO  rz  rT   s        rC   rP  _FetchParser.Header.__bytes__s  s    D{{
";;GODA	A"1~~"1IMM!$	 %
 		& 11D88yy yytyy!Iy!q5"3"3"5y!IJTQTXXK "Js   C/r?   )r   r   r   r   rN  rO  rJ  r   r   r  rP  r   r?   rE   rC   Headerr  k  s)    	4S 	4	u 	rE   r  c                       \ rS rSrSrg)_FetchParser.Texti  r?   Nr   r   r   r   r   r?   rE   rC   Textr
        rE   r  c                       \ rS rSrSrg)_FetchParser.MIMEi  r?   Nr  r?   rE   rC   MIMEr    r  rE   r  Ns   envelopes   flagss   internaldates   rfc822.headers   rfc822.texts   rfc822.sizes   rfc822s   uids   bodystructurec                 0    S/U l         / U l        SU l        g )NinitialrE   )rc  r  	remainingre   s    rC   rb   _FetchParser.__init__  s    [
rE   c                    U R                   U-   n U(       d  U R                  (       al  U R                  (       d  [        S5      eU R                  R                  5       n [	        U SU-   5      " U5      nXS  nU(       a  MY  U R                  (       a  Ml  Xl         g ! [
         a    U R                  R                  U5        e f = f! Xl         f = f)NzInvalid Argumentstate_)r  rc  r   rp  rv  r  rv   )r_   r   rc  useds       rC   r  _FetchParser.parseString  s    NNQ	tzzzz/0BCC

(!"4E)9:1=D %A !tzzz N % JJ%%e, Ns*   AC  B 5C C 'CC Cc                 `   US:X  a  gUR                  5       nUR                  S5      (       aX  U R                  R                  U R	                  5       U R                  5       U R                  5       U R                  5       45        gUR                  S5      (       ag  U R                  R                  U R	                  5       U R                  5       U R                  5       U R                  5       U R                  5       45        gUR                  S5      (       aI  U R                  R                  U R	                  5       U R                  5       U R                  5       45        gUR                  S5      (       a  U R                  R                  S	5        g
U R                  R                  S5        g)NrE   r   s   allr~  s   fullrC  s   fastr  )close_parenmaybe_fetch_att	fetch_attr<   r  )r  r  r  r   r  r  r  r  r  rc  rv   )r_   r   r   s      rC   state_initial_FetchParser.state_initial  sG    8GGI<<KKt002DOO4Et}}W <<  KKJJL%%'OO%MMOIIK <<  KKJJL%%'OO% <<JJMN

+&rE   c                 F    UR                  S5      (       a  g[        S5      e)Nr  r<   z	Missing )r  rx  r   s     rC   state_close_paren_FetchParser.state_close_paren  s!    << $$rE   c                     U(       a  USS R                  5       (       d  [        S5      eSn[        [        U5      5       H   nXUS-    R                  5       (       a  M    U$    U$ )Nr   r<   zWhitespace expected, none found)isspacerx  rG  r   )r_   r   rl   s      rC   state_whitespace_FetchParser.state_whitespace  s`    !A((=>>s1vAQ<''))  rE   c                 f    UR                  S5      (       d  U R                  R                  S5        g)Nr  )r  r  r  r   r  rc  r   r   s     rC   state_maybe_fetch_att"_FetchParser.state_maybe_fetch_att  s'    ||D!!JJLMrE   c                    UR                  5       nU R                   HH  u  p4UR                  U5      (       d  M  U R                  R	                  U" 5       5        [        U5      s  $    U R                  5       nUR                  S5      (       a
  SUl        SnO'UR                  S5      (       a  SnO[        SU 35      eXPl	        U R                  R                  S5        U$ )Ns	   body.peekTr  s   bodyrC  z!Nothing recognized in fetch_att: )got_bodymaybe_partialmaybe_section)r  _simple_fetch_attr  r  rv   r   r  rr  rx  pending_bodyrc  r   )r_   r   r   r  clsr  r  s          rC   state_fetch_att_FetchParser.state_fetch_att  s     GGI//ID||D!!""35)4y  0
 IIK<<%%AFD\\'""D?sCDD

HIrE   c                 R    U R                   R                  U R                  5        U ?gr   )r  rv   r0  r   s     rC   state_got_body_FetchParser.state_got_body
  s#    4,,-rE   c                 h    UR                  S5      (       d  gU R                  R                  S5        g)Nr  r   )sectionpart_numberr<   r(  r   s     rC   state_maybe_section _FetchParser.state_maybe_section  s*    ||D!!

45rE   s   (\d+(?:\.\d+)*)\.?c                     U R                   R                  U5      nUbT  UR                  5       S   R                  S5       Vs/ s H  n[	        U5      S-
  PM     snU l        UR                  5       $ / U l        gs  snf )Nr   r  r<   )	_partExprr  groupsr  r  r  ra   )r_   r   r  r   s       rC   state_part_number_FetchParser.state_part_number  sk    NN  #=./hhjm.A.A$.GH.G#a&1*.GHDJ557NDJ	 Is   A;c                 n   UR                  5       nSnUR                  S5      (       a  SU R                  l        US-  nGOIUR                  S5      (       a4  U R	                  5       =o@R                  l        SUl        SUl        US-  nOUR                  S5      (       a%  U R                  5       U R                  l	        US	-  nOUR                  S
5      (       a%  U R                  5       U R                  l        US	-  nOU R	                  5       nUR                  S5      (       a  SUl        US-  nO+UR                  S5      (       a  US-  nO[        SU< 35      eX@R                  l        U R                  R                  S5        [        U R                   5      U R                  l        S U l        U$ )Nr   r.  Tr<   s   header]r?   r  s   text]rB  s   mime]s   header.fields.not   s   header.fieldsr=   zUnhandled section contents: )finish_sectionheader_listr  )r  r  r0  rR  r  rM  rN  rO  r  r7   r  rQ  rx  rc  r   r  r  rJ  )r_   r   r   r  r   s        rC   state_section_FetchParser.state_section!  sh   
 GGI<<&*D#AID\\*%%+/;;=8A!!(AHAHAID\\(##%)YY[D"AID\\(##%)YY[D"AIDA||011
.//
">qe DEE'($JJMN!&tzz!2
rE   c                 F    UR                  S5      (       d  [        S5      eg)Nr.  zsection must end with ]r<   r   r   s     rC   state_finish_section!_FetchParser.state_finish_sectionF  s     ||D!!566rE   c                 4   UR                  S5      (       d  [        S5      eUR                  S5      nUS:X  a  [        S5      eUSU R                  5       nU Vs/ s H  oDR	                  5       PM     snU R
                  R                  l        US-   $ s  snf )Nr  zHeader list must begin with (r  r   zHeader list must end with )r<   )r  rx  r  r  r  r0  rM  rO  )r_   r   ra   rM  r   s        rC   state_header_list_FetchParser.state_header_listK  s    ||D!!;<<ffTl"99::Ac(..">E*Fg779g*F  'Qw +Gs   Bc                 D   UR                  S5      (       d  gUR                  S5      nUS:X  a  [        S5      eUSU nUR                  SS5      n[	        U5      S:w  a  [        S	5      e[        [        U5      u  pVXPR                  l        X`R                  l	        US-   $ )
NrV  r   rW  r   zFound < but not >r<   r  r  z>Partial specification did not include two .-delimited integers)
r  r  rx  r  r   r  r  r0  r  r  )r_   r   ra   rt   r  beginrI  s          rC   state_maybe_partial _FetchParser.state_maybe_partialV  s    ||D!!ffTl"9/00Ac(dA&u:?P  C).&*0'QwrE   )r  r0  r  r  rc  )%r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r/  rb   r  r  r!  r%  r)  r2  r5  r:  r  r  r=  r?  rE  rH  rK  rO  r   r?   rE   rC   r  r    s6   * *' '. ./ /- -- -( (% %4# 4#l/ /
 6   E 
h	5	,'	<(	$	$	F		=)

&'R%
2
 

12I#J
	rE   r  c                   @    \ rS rSrSrSrS rS rS rS r	S r
S	 rS
rg)r3  ik  r  Tc                     Xl         g ry   r  )r_   rz  s     rC   rb   FileProducer.__init__p  s    rE   c                     Xl         UR                  U l        [        R                  " 5       =o l        U R                   R                  U S5        U$ )NF)r  r   producer   r  _onDoneregisterProducer)r_   r  r"  s      rC   r4  FileProducer.beginProducings  s<     ~~ >>++L&&tU3rE   c                    SnU R                   (       a  SU R                  5       4-  nSU l         U R                  (       d  g XR                  R                  U R                  5      -   nU(       dK  U R
                  R                  5         U R                  R                  U 5        S =U l        =U l        U l        g U R                  U5        g )NrE   s   {%d}
F)

firstWrite_sizerz  r	  r  r  unregisterProducerrV  r   rU  )r_   r  s     rC   resumeProducingFileProducer.resumeProducingz  s    ??tzz|o-A#DOvvDOO,,MM,,.LL!!$'488DL846DMLLOrE   c                     g)z)
Pause the producer.  This does nothing.
Nr?   re   s    rC   pauseProducingFileProducer.pauseProducing  r  rE   c                     g)z(
Stop the producer.  This does nothing.
Nr?   re   s    rC   stopProducingFileProducer.stopProducing  r  rE   c                     U R                   R                  5       nU R                   R                  SS5        U R                   R                  5       nU R                   R                  US5        X!-
  $ )Nr   r  )rz  r  r   )r_   r  r{  s      rC   r[  FileProducer._size  sK    FFKKMAqFFKKMAqurE   )rV  r  rz  rZ  rU  N)r   r   r   r   r  rZ  rb   r4  r]  r`  rc  r[  r   r?   rE   rC   r3  r3  k  s*    JJ

rE   r3  c                    / SQnSSSS.n[         R                  " SU-  U 5      nU(       d  [        SU < 35      eUR                  5       n SUR	                  US	   R                  5       5      S
-  -   US	'   [        US   5      US'   [        US   5      US'   [        R                  " US   US	   US   SSSSSS4	5      $ ! [         a    [        SU < 35      ef = f)N)janfebmaraprmayjunjulaugsepoctnovdecjanuaryfebruarymarchaprilrl  junejulyaugust	septemberoctobernovemberdecemberz+(?P<day>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])z(?P<mon>\w+)z(?P<year>\d\d\d\d))daymonyearz%(day)s-%(mon)s-%(year)szCannot parse time string r<   r     r  r  r   r   )	r  r  ri   	groupdictindexr  r  r   struct_time)r   monthsexprr  r"  s        rC   rp  rp    s    F6 >%D
 	+d2A6A4QE:;;	AVQuX^^%56;<%&	N&	qx=% 6AeHah1aRQS TUU  <4QE:;;<s   AC Cr
   c                      U S   $ r   r?   rS   s    rC   rU   rU     s    QqTrE   c                 N    U R                  S5      nUSS R                  SS5      $ )Nutf-7r<   r   r4  r  )r  r  r   s_utf7s     rC   modified_base64r    s)    XXgF!B<d++rE   c                 T    SU R                  SS5      -   S-   nUR                  S5      $ )Nr  r  r4  r  r  )r  r  r  s     rC   modified_unbase64r    s+    AIIdD))D0F==!!rE   c           	      L   [        5       n/ n[        [        [        [	        SS5      5      5      S1-
  nU  H  nXT;   aK  U(       a(  US[        SR                  U5      5      -   S-   -  nUSS2	 UR                  [        U5      5        MS  US:X  a6  U(       a(  US[        SR                  U5      5      -   S-   -  nUSS2	 US-  nM  UR                  U5        M     U(       a/  UR                  S[        SR                  U5      5      -   S-   5        [        U5      [        U 5      4$ )	aP  
Encode the given C{unicode} string using the IMAP4 specific variation of
UTF-7.

@type s: C{unicode}
@param s: The text to encode.

@param errors: Policy for handling encoding errors.  Currently ignored.

@return: L{tuple} of a L{str} giving the encoded bytes and an L{int}
    giving the number of code units consumed from the input.
       &   &ri  r  Ns   &-)	bytearrayr  r  chrrG  r  r   rv   ordr   r  r   )r   errorsrC  _invalid_charsr!  s         rC   encoderr    s     	A
Cc#uT4012cU:KTOBGGCL99D@@FHHSV#XTOBGGCL99D@@FJAJJqM  	55<=!Hc!frE   c           
      R   / n/ n[        [        U 5      S5      n U  H  nUS:X  a  U(       d  UR                  S5        M#  US:X  aX  U(       aQ  [        U5      S:X  a  UR                  S5        O,UR                  [	        SR                  USS 5      5      5        / nM  U(       a  UR                  U5        M  UR                  UR                  5       5        M     U(       a,  UR                  [	        SR                  USS 5      5      5        SR                  U5      [        U 5      4$ )	aW  
Decode the given L{str} using the IMAP4 specific variation of UTF-7.

@type s: L{str}
@param s: The bytes to decode.

@param errors: Policy for handling decoding errors.  Currently ignored.

@return: a L{tuple} of a C{unicode} string giving the text which was
    decoded and an L{int} giving the number of bytes consumed from the
    input.
r!  r  r  r<   r  rE   Nri  )memory_cast
memoryviewrv   r   r  r   r  )r   r  rC  r  r!  s        rC   decoderr    s     	AFJqM3'A9VMM$$Y66{a*388F12J+?@AFMM!HHQXXZ   	"388F12J#789GGAJArE   c                       \ rS rSrSS jrSrg)StreamReaderi  c                     [        U5      $ ry   )r  r_   r   r  s      rC   r  StreamReader.decode      qzrE   r?   Nstrict)r   r   r   r   r  r   r?   rE   rC   r  r        rE   r  c                       \ rS rSrSS jrSrg)StreamWriteri#  c                     [        U5      $ ry   )r  r  s      rC   r  StreamWriter.encode$  r  rE   r?   Nr  )r   r   r   r   r  r   r?   rE   rC   r  r  #  r  rE   r  c                 <    U R                  SS5      S:X  a  [        $ g )N-r  imap4_utf_7)r  
_codecInfor  s    rC   r  r  +  s"     ||C. /rE   )(r1  r  IMailboxListenerr)   rC  IMailboxr2   r_  IMailboxInfoIMessager  r;  r1  IMessagePartr   r   r   r   r'   r#   r%   r   r   r   r!   r"   r    r   r$   r&   r   r   r   r   r   r  r  r  r2  rD  ry   r  r  r  )r   r>  codecsr]  email.utilsrq  rs   r  r  r   r   r  base64r   r   ior   	itertoolsr   typingr   r   r	   r
   zope.interfacer   twisted.credr   twisted.cred.errorr   r   rJ  r   r   r   twisted.internet.deferr   twisted.mail._credr   r   r   r   r   twisted.mail._exceptr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   twisted.mail.interfacesr(   rC  r)   r*   r_  r+   r  r,   r  r-   r  r.   r  r/   r  r0   r;  r1   r  r2   r3   r1  twisted.protocolsr4   r5   twisted.pythonr6   r7   twisted.python.compatr8   r9   r:   r;   r]  rF  rG  r  r"  rD   rJ   rL   r   r   r   r   _SPr  _CTLr,  r  _nativeNonAtomCharsr  r  r  LineReceiverTimeoutMixinr1  TimeoutErrorr  r  r  r  r  rr   r  r  r  r  r  r  r  r  r  r$  r.  r  r  r  r|  r  r  rt  r  r2  rB  rD  rJ  r  rS  rU  rc  rl  rn  ri  rh  rg  rf  rE  r-  r  r:  r=  r  r3  rp  rv  r  r  r  r  r  r  r  r  	CodecInfor  r  register__all__r?   rE   rC   <module>r     s  
      	     +   , , & $ F 5 5 0     (    . $  aGMMOP
*(a aH	9 98/ /B 0D" D"V U5;dE 234 $t+ $**95 ZZ11C78
 HeHH
 SN%$$h&;&; SN SNl8 ""$ P%$$h&;&; P Pf<6r" *

Nb	1
&>B D7,tE' '% '  +/. b XoJ oJ oJd  !2  "& "# M4,J4/ /de"3 eP7 (9 *L!2 L^i6XBC CLc cL- -`,Vd j&/:,
"
D D6&& 
6&& 
 gwlK
	  /rE   