
    h+y                        d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZm Z  ddl!m"Z" 	 ejF                  Z$ejJ                  Z&ejN                  Z(dZ*dZ+	 dZ, e	defdefg      Z- e	defdefg      Z.	 	 d%dZ/d Z0d Z1d Z2 G d de3      Z4 G d de3      Z5 G d d e3      Z6 G d! d"e3      Z7 G d# d$e      Z8y# e)$ r	 dZ$dZ&dZ(Y ww xY w)&z.Tools for representing files stored in GridFS.    N)Int64)SON)Binary)ObjectId)	text_typeStringIO)CorruptGridFile
FileExistsNoFile)	ASCENDING)
Collection)Cursor)ConfigurationErrorCursorNotFoundDuplicateKeyErrorInvalidOperationOperationFailure)ReadPreference             
i  files_idnfilename
uploadDatec                 |      fd} fd}|r|dz  }n	r|dd}|sst        |||      S t        ||      S )zCreate a GridIn property.c                     r| j                   st        dz        dk(  r| j                  j                  d      S | j                  j                  d       S )Nz can only get %r on a closed filelengthr   )_closedAttributeError_fileget)selfclosed_only
field_names    S/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/gridfs/grid_file.pygetterz!_grid_in_property.<locals>.getter>   sX    t|| !C!+", - - !::>>*a00zz~~j$//r   c                     | j                   r9| j                  j                  j                  d| j                  d   id|ii       || j                  <   y N_idz$set)r    _collfiles
update_oner"   )r$   valuer&   s     r'   setterz!_grid_in_property.<locals>.setterG   sN    <<JJ''

50A(B)/*e1D(EG!&

:r   

This attribute is read-only.z

zUThis attribute is read-only and can only be read after :meth:`close` has been called.docproperty)r&   	docstring	read_onlyr%   r(   r0   s   `  `  r'   _grid_in_propertyr8   ;   sR    0' 77		"+ .5 6	 [I66F	**r   c                 2      fd}|dz  }t        ||      S )zCreate a GridOut property.c                     | j                          dk(  r| j                  j                  d      S | j                  j                  d       S )Nr   r   )_ensure_filer"   r#   )r$   r&   s    r'   r(   z"_grid_out_property.<locals>.getter[   sC     !::>>*a00zz~~j$//r   r1   r2   r4   )r&   r6   r(   s   `  r'   _grid_out_propertyr<   Y   s"    0 33IF	**r   c                 b    | j                   j                  d      } | j                  dd|i|S )z;Clear the given database/collection object's type registry.N)type_registrycodec_options )r?   with_options)entitykwargs	codecoptss      r'   _clear_entity_type_registryrE   g   s6    $$111EI6AYA&AAr   c                 8    | r| j                   rt        d      y y )Nz3GridFS does not support multi-document transactions)in_transactionr   sessions    r'   _disallow_transactionsrJ   m   s&    7))AC 	C *wr   c                   <   e Zd ZdZ	 d)dZd Zd Zd Zed        Z	 e
dd	d
      Z e
dd      Z e
dd      Z e
dd      Z e
ddd
      Z e
ddd
      Z e
ddd
      Z e
ddd
      Zd Zd Zd Zd Zd Zd Zd  Zd*d!Zd" Zd# Zd$ Zd% Zd& Zd' Z d( Z!y)+GridInz#Class to write data to GridFS.
    Nc                    t        |t              st        d      |j                  j                  st        d      t        |       d|v r|j                  d      |d<   d|v r|j                  d      |d<   t        |t        j                        }|st        j                         |d<   |j                  d	t                     |d	<   |j                  dt              |d<   t         j#                  | d
|       t         j#                  | d|       t         j#                  | d|j$                         t         j#                  | d|       t         j#                  | dt'                      t         j#                  | dd       t         j#                  | dd       t         j#                  | dd       t         j#                  | dd       y)aP  Write a file to GridFS

        Application developers should generally not need to
        instantiate this class directly - instead see the methods
        provided by :class:`~gridfs.GridFS`.

        Raises :class:`TypeError` if `root_collection` is not an
        instance of :class:`~pymongo.collection.Collection`.

        Any of the file level options specified in the `GridFS Spec
        <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as
        keyword arguments. Any additional keyword arguments will be
        set as additional fields on the file document. Valid keyword
        arguments include:

          - ``"_id"``: unique ID for this file (default:
            :class:`~bson.objectid.ObjectId`) - this ``"_id"`` must
            not have already been used for another file

          - ``"filename"``: human name for the file

          - ``"contentType"`` or ``"content_type"``: valid mime-type
            for the file

          - ``"chunkSize"`` or ``"chunk_size"``: size of each of the
            chunks, in bytes (default: 255 kb)

          - ``"encoding"``: encoding used for this file. In Python 2,
            any :class:`unicode` that is written to the file will be
            converted to a :class:`str`. In Python 3, any :class:`str`
            that is written to the file will be converted to
            :class:`bytes`.

        :Parameters:
          - `root_collection`: root collection to write to
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession` to use for all
            commands
          - `disable_md5` (optional): When True, an MD5 checksum will not be
            computed for the uploaded file. Useful in environments where
            MD5 cannot be used for regulatory or other reasons. Defaults to
            False.
          - `**kwargs` (optional): file level options (see above)

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.0
           `root_collection` must use an acknowledged
           :attr:`~pymongo.collection.Collection.write_concern`
        1root_collection must be an instance of Collectionz3root_collection must use acknowledged write_concerncontent_typecontentType
chunk_size	chunkSize)read_preferencemd5r+   _sessionr,   _chunksr"   _buffer	_positionr   _chunk_numberr    F_ensured_indexN)
isinstancer   	TypeErrorwrite_concernacknowledgedr   rJ   poprE   r   PRIMARYhashlibrT   r#   r   DEFAULT_CHUNK_SIZEobject__setattr__chunksr   )r$   root_collectionrI   disable_md5rC   colls         r'   __init__zGridIn.__init__v   s   j /:6 5 6 6 ,,99$ &B C Cw' V#$*JJ~$>F=!6!"(**\":F;*^-C-CE #KKMF5M

5(*5u$jj6HI{4W54$/4DKK84&14HJ74a04!44E24!159r   c                 0   |j                  ddi| j                        }|_	 |j                  | j                        D cg c]  }|d   	 }}||vr-|j	                  |j                         || j                         y y y c c}w # t        $ r g }Y Ew xY w)Nr+   r   )
projectionrI   rH   key)uniquerI   )find_onerU   list_indexesr   create_indexitems)r$   
collection	index_keyrm   r3   
index_spec
index_keyss          r'   __create_indexzGridIn.__create_index   s    !!eQZ!O; (55dmm5LNJj/ N
 N 
*''OO%fdmm ( M + N#  
 s#   B BB B BBc                 6   t         j                  | d      st        | j                         | j	                  | j
                  j                  t        d       | j	                  | j
                  j                  t        d       t         j                  | dd       y y )NrZ   FT)rc   __getattribute__rJ   rU   _GridIn__create_indexr,   r-   _F_INDEXre   _C_INDEXrd   r$   s    r'   __ensure_indexeszGridIn.__ensure_indexes   so    &&t-=>"4==1

 0 0(EB

 1 18TBt%5t<	 ?r   c                 2   | j                   j                  j                  d| j                  d   i| j                         | j                   j
                  j                  d| j                  d   i| j                         t        j                  | dd       y)zGRemove all chunks/files that may have been uploaded and close.
        r   r+   rH   r    TN)	r,   re   delete_manyr"   rU   r-   
delete_onerc   rd   r|   s    r'   abortzGridIn.abort   s     	

%%E*+T]] 	& 	D

##DJJu%& 	$ 	?4D1r   c                     | j                   S )zIs this file closed?
        )r    r|   s    r'   closedzGridIn.closed   s     ||r   r+   "The ``'_id'`` value for this file.T)r7   r   Name of this file.Alias for `filename`.rP   Mime-type for this file.r   Length (in bytes) of this file.)r%   rR   Chunk size for this file.r   z!Date that this file was uploaded.rT   ;MD5 of the contents of this file if an md5 sum was created.c                 X    || j                   v r| j                   |   S t        d|z        )Nz#GridIn object has no attribute '%s')r"   r!   r$   names     r'   __getattr__zGridIn.__getattr__   s.    4::::d##BTIJJr   c                 *   || j                   v s|| j                  j                   v rt        j                  | ||       y || j                  |<   | j
                  r:| j                  j                  j                  d| j                  d   id||ii       y y r*   )	__dict__	__class__rc   rd   r"   r    r,   r-   r.   )r$   r   r/   s      r'   rd   zGridIn.__setattr__  s     4== DDNN,C,C$CtT51
  %DJJt||

  ++UDJJu4E,F-3dE],CE r   c                    | j                          d| j                  v r| j                  d   j                  |       |syt        |      | j                  k  sJ | j                  d   | j
                  t        |      d}	 | j                  j                  || j                         | xj
                  dz  c_        | xj                  t        |      z  c_        y# t        $ r! | j                  | j                  d          Y ]w xY w)z!Flush `data` to a chunk.
        rT   Nr+   )r   r   datarH   r   )_GridIn__ensure_indexesr"   updatelenrQ   rY   r   rV   
insert_onerU   r   _raise_file_existsrX   )r$   r   chunks      r'   __flush_datazGridIn.__flush_data  s     	DJJJJu$$T*4yDOO+,+!ZZ.(('	7LL##E4==#A 	a#d)# ! 	7##DJJu$56	7s   'C 'DDc                     | j                  | j                  j                                | j                  j                          t	               | _        y)z2Flush the buffer contents out to a chunk.
        N)_GridIn__flush_datarW   getvaluecloser   r|   s    r'   __flush_bufferzGridIn.__flush_buffer'  s8     	$,,//12zr   c                    	 | j                          d| j                  v r*| j                  d   j                         | j                  d<   t        | j                        | j                  d<   t
        j
                  j                         | j                  d<   | j                  j                  j                  | j                  | j                        S # t        $ r | j                  | j                         Y yw xY w)z(Flush the file to the database.
        rT   r   r   rH   N)_GridIn__flush_bufferr"   	hexdigestr   rX   datetimeutcnowr,   r-   r   rU   r   r   r+   r|   s    r'   __flushzGridIn.__flush.  s    	.!

"$(JJu$5$?$?$A

5!#(#8DJJx '/'8'8'?'?'ADJJ|$::##..

DMM / 3 3  	.##DHH-	.s   CC $C98C9c                     t        d|z        )z3Raise a FileExists exception for the given file_id.zfile with _id %r already exists)r
   )r$   file_ids     r'   r   zGridIn._raise_file_exists?  s    :WDEEr   c                 l    | j                   s(| j                          t        j                  | dd       yy)zFlush the file and close it.

        A closed file cannot be written any more. Calling
        :meth:`close` more than once is allowed.
        r    TN)r    _GridIn__flushrc   rd   r|   s    r'   r   zGridIn.closeC  s+     ||LLNtY5 r   c                 ,    t        j                  d      )NreadioUnsupportedOperation)r$   sizes     r'   r   zGridIn.readM  s    %%f--r   c                      yNFr@   r|   s    r'   readablezGridIn.readableP      r   c                      yr   r@   r|   s    r'   seekablezGridIn.seekableS  r   r   c                    | j                   rt        d      	 |j                  }| j                  j                         dkD  rl| j                  | j                  j                         z
  }|r3	  ||      }| j                  j!                  |       t#        |      |k  ry| j%                           || j                        }|rVt#        |      | j                  k(  r>| j'                  |        || j                        }|rt#        |      | j                  k(  r>| j                  j!                  |       y# t        $ r t	        |t
        t        f      st        d      t	        |t
              rF	 |j                  | j                        }n)# t        $ r t        dt
        j                        w xY wt        |      j                  }Y w xY w#  | j                           xY w)a  Write data to the file. There is no return value.

        `data` can be either a string of bytes or a file-like object
        (implementing :meth:`read`). If the file has an
        :attr:`encoding` attribute, `data` can also be a
        :class:`unicode` (:class:`str` in python 3) instance, which
        will be encoded as :attr:`encoding` before being written.

        Due to buffering, the data may not actually be written to the
        database until the :meth:`close` method is called. Raises
        :class:`ValueError` if this file is already closed. Raises
        :class:`TypeError` if `data` is not an instance of
        :class:`str` (:class:`bytes` in python 3), a file-like object,
        or an instance of :class:`unicode` (:class:`str` in python 3).
        Unicode data is only allowed if the file has an :attr:`encoding`
        attribute.

        :Parameters:
          - `data`: string of bytes or file-like object to be written
            to the file
        zcannot write to a closed filez+can only write strings or file-like objectsz4must specify an encoding for file in order to write r   N)r    
ValueErrorr   r!   r[   r   bytesr\   encodeencoding__name__r   rW   tellrQ   r   writer   r   r   )r$   r   r   spaceto_writes        r'   r   zGridIn.writeV  s   , <<<==	'99D <<"OOdll&7&7&99E#E{H ""8,x=5(!(3x=DOO;h'DOO,H 3x=DOO; 	8$;  
	'dY$67 MNN$	*Q;;t}}5D% Q#;D;M;M%P Q QQ D>&&D
	'$JJLs5   D4 ,G 4:G/F
G&F11GGG#c                 4    |D ]  }| j                  |        y)zSWrite a sequence of strings to the file.

        Does not add seperators.
        N)r   )r$   sequencelines      r'   
writelineszGridIn.writelines  s    
  	DJJt	r   c                      yNTr@   r|   s    r'   	writeablezGridIn.writeable      r   c                     | S )z2Support for the context manager protocol.
        r@   r|   s    r'   	__enter__zGridIn.__enter__  s	     r   c                 $    | j                          y)zmSupport for the context manager protocol.

        Close the file and allow exceptions to propagate.
        Fr   r$   exc_typeexc_valexc_tbs       r'   __exit__zGridIn.__exit__  s    
 	

 r   r   )"r   
__module____qualname____doc__ri   ry   r   r   r5   r   r8   r+   r   r   rO   r   rQ   upload_daterT   r   rd   r   r   r   r   r   r   r   r   r   r   r   r   r   r@   r   r'   rL   rL   s   s    >CT:l
M=2  
 E#G&*,C -ABHZ)@AD$]4NOLx)J+/1F";0K-13J#L$G046K E $9(,.CK
E$,"."F6.9%v
r   rL   c                   ,   e Zd ZdZ	 	 d%dZ edd      Z edd      Z edd      Z ed	d
      Z	 edd      Z
 edd      Z edd      Z edd      Z edd      Z edd      Zd Zd Zd Zd Zd&dZd&dZd ZefdZd Zd  Zd! Zd" Zd# Zd$ Zy)'GridOutz&Class to read data out of GridFS.
    Nc                    t        |t              st        d      t        |       t	        |      }|j
                  | _        |j                  | _        || _	        t        | _        d| _        d| _        || _        || _        y)a  Read a file from GridFS

        Application developers should generally not need to
        instantiate this class directly - instead see the methods
        provided by :class:`~gridfs.GridFS`.

        Either `file_id` or `file_document` must be specified,
        `file_document` will be given priority if present. Raises
        :class:`TypeError` if `root_collection` is not an instance of
        :class:`~pymongo.collection.Collection`.

        :Parameters:
          - `root_collection`: root collection to read from
          - `file_id` (optional): value of ``"_id"`` for the file to read
          - `file_document` (optional): file document from
            `root_collection.files`
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession` to use for all
            commands

        .. versionchanged:: 3.8
           For better performance and to better follow the GridFS spec,
           :class:`GridOut` now uses a single cursor to read all the chunks in
           the file.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.0
           Creating a GridOut does not immediately retrieve the file metadata
           from the server. Metadata is fetched when first needed.
        rN   Nr   )r[   r   r\   rJ   rE   re   _GridOut__chunksr-   _GridOut__files_GridOut__file_idEMPTY_GridOut__buffer_GridOut__chunk_iter_GridOut__positionr"   rU   )r$   rf   r   file_documentrI   s        r'   ri   zGridOut.__init__  sx    D /:6 5 6 6w'5oF'..&,,  "
r   r+   r   r   r   r   rP   r   r   r   rR   r   r   z'Date that this file was first uploaded.aliaseszList of aliases for this file.metadatazMetadata attached to this file.rT   r   c                    | j                   st        | j                         | j                  j	                  d| j
                  i| j                        | _         | j                   s%t        d| j                  d| j
                        y y )Nr+   rH   zno file in gridfs collection z
 with _id )r"   rJ   rU   r   rn   r   r   r|   s    r'   r;   zGridOut._ensure_file  ss    zz"4==1..t~~/F7;}} / FDJ::"llDNN< = = 	 r   c                 x    | j                          || j                  v r| j                  |   S t        d|z        )Nz$GridOut object has no attribute '%s')r;   r"   r!   r   s     r'   r   zGridOut.__getattr__  s:    4::::d##CdJKKr   c                      yr   r@   r|   s    r'   r   zGridOut.readable  r   r   c                 4   t        | j                        }t        }t        | j                        }|dkD  r| j                  }n| j
                  t        | j                        k  rt        || j
                  z   |z        }| j                  't        | | j                  | j                  |      | _        | j                  j                         }|d   | j
                  |z  d }|st        d      | xj
                  t        |      z  c_        t        | _        |S )z{Reads a chunk at a time. If the current position is within a
        chunk the remainder of the chunk is returned.
        r   Nr   ztruncated chunk)r   r   r   intrQ   r   r   r   _GridOutChunkIteratorr   rU   nextr	   )r$   received
chunk_datarQ   chunk_numberr   s         r'   	readchunkzGridOut.readchunk   s     t}}%
)
a<J__s4;;//4?? :jHIL  ($9$--%F! %%**,Evt'C'DEJ%&7883z?*r   c                 V   | j                          t        | j                        | j                  z
  }|dk  s||kD  r|}|dk(  rt        S d}t               }||k  r5| j                         }|t        |      z  }|j                  |       ||k  r5||k(  r'| j                  r	 | j                  j                          | xj                  ||z
  z  c_        |j                  |       |j                         | _        |j                  d       |j                  |      S # t        $ r Y kw xY w)a  Read at most `size` bytes from the file (less if there
        isn't enough data).

        The bytes are returned as an instance of :class:`str` (:class:`bytes`
        in python 3). If `size` is negative or omitted all data is read.

        :Parameters:
          - `size` (optional): the number of bytes to read

        .. versionchanged:: 3.8
           This method now only checks for extra chunks after reading the
           entire file. Previously, this method would check for extra chunks
           on every call.
        r   )r;   r   r   r   r   r   r   r   r   r   r   StopIterationseekr   r   )r$   r   	remainderr   r   r   s         r'   r   zGridOut.read  s    	$t6	!8ti'D19Lzo)JJ'HJJz" o 9!2!2!!&&( 	8d?* 			$				!yy ! s   "D 	D('D(c                    t        | j                        | j                  z
  }|dk  s||kD  r|}|dk(  rt        S d}t	               }||k  r_| j                         }|j                  t        d|      }|dk7  r||z   dz   }|t        |      z  }|j                  |       |dk7  rn||k  r_| xj                  ||z
  z  c_        |j                  |       |j                         | _        |j                  d       |j                  |      S )zRead one line or up to `size` bytes from the file.

        :Parameters:
         - `size` (optional): the maximum number of bytes to read
        r   r   r   )r   r   r   r   r   r   findNEWLNr   r   r   r   r   )r$   r   r   r   r   r   poss          r'   readlinezGridOut.readlineH  s     $t6	!8ti'D19Lzo)J//%D1Cby#~)J'HJJz"by o 	8d?* 			$				!yyr   c                     | j                   S )z2Return the current position of this file.
        )r   r|   s    r'   r   zGridOut.tellj  s     r   c                 l   |t         k(  r|}nG|t        k(  r| j                  |z   }n.|t        k(  rt	        | j
                        |z   }nt        dd      |dk  rt        dd      || j                  k(  ry|| _        t        | _        | j                  r"| j                  j                          d| _	        yy)a  Set the current position of this file.

        :Parameters:
         - `pos`: the position (or offset if using relative
           positioning) to seek to
         - `whence` (optional): where to seek
           from. :attr:`os.SEEK_SET` (``0``) for absolute file
           positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative
           to the current position, :attr:`os.SEEK_END` (``2``) to
           seek relative to the file's end.
           zInvalid value for `whence`r   z*Invalid value for `pos` - must be positiveN)	_SEEK_SET	_SEEK_CURr   	_SEEK_ENDr   r   IOErrorr   r   r   r   )r$   r   whencenew_poss       r'   r   zGridOut.seeko  s     YGy oo+Gy $++&,G":;;Q;"JKK doo%!##% $D r   c                      yr   r@   r|   s    r'   r   zGridOut.seekable  r   r   c                 D    t        | | j                  | j                        S )a  Return an iterator over all of this file's data.

        The iterator will return chunk-sized instances of
        :class:`str` (:class:`bytes` in python 3). This can be
        useful when serving files using a webserver that handles
        such an iterator efficiently.

        .. note::
           This is different from :py:class:`io.IOBase` which iterates over
           *lines* in the file. Use :meth:`GridOut.readline` to read line by
           line instead of chunk by chunk.

        .. versionchanged:: 3.8
           The iterator now raises :class:`CorruptGridFile` when encountering
           any truncated, missing, or extra chunk in a file. The previous
           behavior was to only raise :class:`CorruptGridFile` on a missing
           chunk.
        )GridOutIteratorr   rU   r|   s    r'   __iter__zGridOut.__iter__  s    & tT]]DMMBBr   c                 `    | j                   r"| j                   j                          d| _         yy)z(Make GridOut more generically file-like.N)r   r   r|   s    r'   r   zGridOut.close  s*    ##% $D r   c                 ,    t        j                  d      )Nr   r   )r$   r/   s     r'   r   zGridOut.write  s    %%g..r   c                     | S )cMakes it possible to use :class:`GridOut` files
        with the context manager protocol.
        r@   r|   s    r'   r   zGridOut.__enter__  s	     r   c                 $    | j                          y)r  Fr   r   s       r'   r   zGridOut.__exit__  s     	

r   )NNNr   )r   r   r   r   ri   r<   r+   r   r   rO   r   rQ   r   r   r   rT   r;   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r@   r   r'   r   r     s    DH0 d U$H
IC!*.BCHj*ABD%m5OPL*KLF#K1LMJ$\%NPK ,LMG!*.OPH
U %: ;C=L4,\ D
  )  %DC*%/r   r   c                   >    e Zd ZdZd Zd Zd Zd Zd Zd Z	e	Z
d Zy	)
r   zIterates over a file's chunks using a single cursor.

    Raises CorruptGridFile when encountering any truncated, missing, or extra
    chunk in a file.
    c                 :   |j                   | _         t        |j                        | _        t        |j                        | _        || _        || _        || _        t        j                  t        | j
                        | j                  z        | _        d | _        y N)r+   r   rQ   _chunk_sizer   _lengthrV   rU   _next_chunkmathceilfloat_num_chunks_cursor)r$   grid_outre   rI   
next_chunks        r'   ri   z_GridOutChunkIterator.__init__  sr    <<x2238??+%99U4<<%84;K;K%KLr   c                     || j                   dz
  k  r| j                  S | j                  | j                  | j                   dz
  z  z
  S )Nr   )r  r  r  )r$   chunk_ns     r'   expected_chunk_lengthz+_GridOutChunkIterator.expected_chunk_length  sF    T%%))###||t//43C3Ca3GHIIr   c                     | S r  r@   r|   s    r'   r  z_GridOutChunkIterator.__iter__      r   c                     d| j                   i}| j                  dkD  rd| j                  i|d<   t        | j                         | j                  j                  |dg| j                        | _        y )Nr   r   z$gter   )r   r   )sortrI   )r+   r  rJ   rU   rV   r   r  )r$   filters     r'   _create_cursorz$_GridOutChunkIterator._create_cursor  sg    dhh'a!4#3#34F3Kt}}-||((xj15 ) @r   c                    | j                   | j                          	 | j                   j                         S # t        $ rG | j                   j	                          | j                          | j                   j                         cY S w xY w)a  Return the next chunk and retry once on CursorNotFound.

        We retry on CursorNotFound to maintain backwards compatibility in
        cases where two calls to read occur more than 10 minutes apart (the
        server's default cursor timeout).
        )r  r  r   r   r   r|   s    r'   _next_with_retryz&_GridOutChunkIterator._next_with_retry  sp     <<!	'<<$$&& 	'LL !<<$$&&	's   8 ABBc           	         	 | j                         }|d   | j                  k7  r-| j                          t	        d| j                  |d   fz        |d   | j                  k\  r;t        |d         r-| j                          t	        d| j                  |d   fz        | j                  |d         }t        |d         |k7  r0| j                          t	        d|d   |t        |d         fz        | xj                  dz  c_        |S # t        $ r3 | j                  | j                  k\  r t	        d| j                  z        w xY w)Nzno chunk #%dr   z;Missing chunk: expected chunk #%d but found chunk with n=%dr   z?Extra chunk found: expected %d chunks but found chunk with n=%dzRtruncated chunk #%d: expected chunk length to be %d but found chunk with length %dr   )r!  r   r  r  r	   r   r   r  )r$   r   expected_lengths      r'   r   z_GridOutChunkIterator.next  sp   	E))+E :)))JJL!"%)%5%5uSz$BCD D :)))5=!

%&)-)9)95:(FGH H 44U3Z@uV}0JJL!-#JU6]1C0EEF F
 	A9  	E4#3#33!.43C3C"CDD	Es   D
 
<Ec                 `    | j                   r"| j                   j                          d | _         y y r  )r  r   r|   s    r'   r   z_GridOutChunkIterator.close  s%    <<LL DL r   N)r   r   r   r   ri   r  r  r  r!  r   __next__r   r@   r   r'   r   r     s4    
J
@'"B H r   r   c                   "    e Zd Zd Zd Zd ZeZy)r  c                 *    t        |||d      | _        y )Nr   )r   _GridOutIterator__chunk_iter)r$   r  re   rI   s       r'   ri   zGridOutIterator.__init__  s    1(FGQOr   c                     | S r  r@   r|   s    r'   r  zGridOutIterator.__iter__  r  r   c                 R    | j                   j                         }t        |d         S )Nr   )r(  r   r   )r$   r   s     r'   r   zGridOutIterator.next!  s%    !!&&(U6]##r   N)r   r   r   ri   r  r   r%  r@   r   r'   r  r    s    P$ Hr   r  c                   J     e Zd ZdZ	 	 	 d fd	Z fdZeZd Zd Zd Z	 xZ
S )GridOutCursorzA cursor / iterator for returning GridOut objects as the result
    of an arbitrary query against the GridFS files collection.
    c	           
          t        |       t        |      }|| _        t        t        |   |j                  |||||||       y)a/  Create a new cursor, similar to the normal
        :class:`~pymongo.cursor.Cursor`.

        Should not be called directly by application developers - see
        the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead.

        .. versionadded 2.7

        .. mongodoc:: cursors
        )skiplimitno_cursor_timeoutr  
batch_sizerI   N)rJ   rE   _GridOutCursor__root_collectionsuperr,  ri   r-   )
r$   rr   r  r.  r/  r0  r  r1  rI   r   s
            r'   ri   zGridOutCursor.__init__,  sN     	w'0<
 ",mT+f4u/d!7 	, 	4r   c                     t        | j                         t        t        |          }t        | j                  || j                        S )z-Get next GridOut object from cursor.
        )r   rI   )rJ   rI   r3  r,  r   r   r2  )r$   	next_filer   s     r'   r   zGridOutCursor.nextD  s>     	t||,-35	t--Y#||- 	-r   c                     t        d      Nz'Method does not exist for GridOutCursorNotImplementedErrorr$   argsrC   s      r'   
add_optionzGridOutCursor.add_optionO      !"KLLr   c                     t        d      r7  r8  r:  s      r'   remove_optionzGridOutCursor.remove_optionR  r=  r   c                 0    t        | j                  |      S )zJCreates an empty GridOutCursor for information to be copied into.
        rH   )r,  r2  )r$   rI   s     r'   _clone_basezGridOutCursor._clone_baseU  s     T33WEEr   )Nr   r   FNr   N)r   r   r   r   ri   r   r%  r<  r?  rA  __classcell__)r   s   @r'   r,  r,  (  s7     ?@@A40- HMMFr   r,  )FF)9r   r   ra   r   r  os
bson.int64r   bson.sonr   bson.binaryr   bson.objectidr   bson.py3compatr   r   gridfs.errorsr	   r
   r   pymongor   pymongo.collectionr   pymongo.cursorr   pymongo.errorsr   r   r   r   r   pymongo.read_preferencesr   SEEK_SETr   SEEK_CURr   SEEK_ENDr   r!   r   r   rb   r{   rz   r8   r<   rE   rJ   rc   rL   r   r   r  r,  r@   r   r'   <module>rR     s3   5   	  	    " . = =  ) !. .
 4III 	 # Y'#y)9:;Y',	)BCD 8="'+<+BCvV vr	Qf QhW F W tf 0FF 0F{  IIIs   ($C6 6DD