
    FCfu                    8   U d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	m
Z
mZmZmZ ddlmZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ejV                  Z,ejZ                  Z.ej^                  Z0dZ1dZ2	 dZ3eZ4dZ5dZ6eedZ7de8d<   eedZ9de8d<   	 	 d(	 	 	 	 	 	 	 	 	 d)dZ:d*dZ;d+dZ<d,dZ= G d d      Z> G d  d!ej~                        Z@ G d" d#      ZA G d$ d%      ZB G d& d'e      ZCy)-z.Tools for representing files stored in GridFS.    )annotationsN)AnyIterableMappingNoReturnOptional)Int64)ObjectId)CorruptGridFile
FileExistsNoFile)	ASCENDING)ClientSession)
Collection)MAX_MESSAGE_SIZE)Cursor)BulkWriteErrorConfigurationErrorCursorNotFoundDuplicateKeyErrorInvalidOperationOperationFailure)_check_write_command_response)ReadPreference       
i  i <   )files_idnzdict[str, Any]_C_INDEX)filename
uploadDate_F_INDEXc                     d|j                  d      rd  dd fd}d fd}|r|dz  }nrdj                  |d	      }|sst        |||
      S t        ||
      S )zCreate a GridIn property. DEPRECATED,zGridIn property '2' is deprecated and will be removed in PyMongo 5.0c                    rt        j                  dt               r| j                  st	        dz        dk(  r| j
                  j                  d      S | j
                  j                  d       S )N   
stacklevelcategoryz can only get %r on a closed filelengthr   )warningswarnDeprecationWarning_closedAttributeError_fileget)selfclosed_only
field_namewarn_strs    P/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/gridfs/grid_file.pygetterz!_grid_in_property.<locals>.getterO   sc    MM(q;MNt|| !Cj!PQQ!::>>*a00zz~~j$//r   c                    rt        j                  dt               | j                  r9| j                  j
                  j                  d| j                  d   id|ii       || j                  <   y )Nr)   r*   _id$set)r.   r/   r0   r1   _collfiles
update_oner3   )r5   valuer7   r8   s     r9   setterz!_grid_in_property.<locals>.setterY   s_    MM(q;MN<<JJ''

50A(BVjZ_M`Dab!&

:r   

This attribute is read-only.z{}

{}zUThis attribute is read-only and can only be read after :meth:`close` has been called.docr5   r   returnr   )r5   r   rA   r   rG   r   )
startswithformatproperty)r7   	docstring	read_onlyr6   r:   rB   r8   s   `  `  @r9   _grid_in_propertyrM   B   s     HM*
|+]^ 	0' 77		%%
	 [I66F	**r   c                j     d|j                  d      rd  dd fd}|dz  }t        ||      S )	zCreate a GridOut property.r%   r&   zGridOut property 'r'   c                    rt        j                  dt               | j                          dk(  r| j                  j                  d      S | j                  j                  d       S )Nr)   r*   r-   r   )r.   r/   r0   _ensure_filer3   r4   )r5   r7   r8   s    r9   r:   z"_grid_out_property.<locals>.getterw   sW    MM(q;MN !::>>*a00zz~~j$//r   rC   rD   rF   )rH   rJ   )r7   rK   r:   r8   s   `  @r9   _grid_out_propertyrQ   o   sG    HM* ,^_ 	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 )rT   with_options)entitykwargs	codecoptss      r9   _clear_entity_type_registryrZ      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    r9   _disallow_transactionsr_      s     7))TUU *wr   c                     e Zd ZU dZ	 d8	 	 	 	 	 	 	 d9dZd:dZd;dZd;dZed<d	       Z	 e
d
dd      Zded
<    e
dd      Zded<    e
dd      Zded<    e
dd      Zded<    e
ddd      Zded<    e
ddd      Zded<    e
ddd      Zded <    e
d!d"d      Zded!<   d#ed$<   ded%<   d&ed'<   ded(<   d=d)Zd>d*Zd?d@d+Zd?dAd,ZdBd-ZdCd.Zd;d/ZdDdEd0Zd<d1Zd<d2ZdFd3ZdGd4Zd<d5Z dHd6Z!dId7Z"y)JGridInzClass to write data to GridFS.Nr   c                   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                        }|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#        j$                                t        j                  | dd       t        j                  | dd       t        j                  | dd       t        j                  | dd       t        j                  | dg        t        j                  | dd       y)a}  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. Any :class:`str`
            that is written to the file will be converted to :class:`bytes`.

        :param root_collection: root collection to write to
        :param session: a
            :class:`~pymongo.client_session.ClientSession` to use for all
            commands
        :param kwargs: Any: file level options (see above)

        .. versionchanged:: 4.0
           Removed the `disable_md5` parameter. See
           :ref:`removed-gridfs-checksum` for details.

        .. versionchanged:: 3.7
           Added the `disable_md5` parameter.

        .. 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_preferencer<   _sessionr>   _chunksr3   _buffer	_positionr   _chunk_numberr1   F_ensured_index_buffered_docs_buffered_docs_sizeN)
isinstancer   	TypeErrorwrite_concernacknowledgedr   r_   poprZ   r   PRIMARYr4   r
   DEFAULT_CHUNK_SIZEobject__setattr__chunksioBytesIO)r5   root_collectionr^   rX   colls        r9   __init__zGridIn.__init__   s   j /:6OPP,,99$%Z[[w' V#$*JJ~$>F=!6!"(**\":F;*?NLbLbc 

5(*5u$jj6HI{4W54$/4DKK84&14BJJL94a04!44E24!1594!1264!6:r   boolc                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<      )
projectionr^   r]   key)uniquer^   )find_oneri   list_indexesr   create_indexitems)r5   
collection	index_keyr   rE   
index_spec
index_keyss          r9   __create_indexzGridIn.__create_index   s    !!eQZ!O;  '1&=&=dmm&=&T" u%
  
*''	(9&RVR_R_'` +  $  
 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 )Nrn   FT)rx   __getattribute__r_   ri   _GridIn__create_indexr>   r?   r#   rz   r    ry   r5   s    r9   __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)z>Remove all chunks/files that may have been uploaded and close.r   r<   r]   r1   TN)	r>   rz   delete_manyr3   ri   r?   
delete_onerx   ry   r   s    r9   abortzGridIn.abort   sr    

%%z4::e3D&Et}}%]

##UDJJu,=$>#V4D1r   c                    | j                   S )zIs this file closed?)r1   r   s    r9   closedzGridIn.closed   s     ||r   r<   "The ``'_id'`` value for this file.T)rL   r!   Name of this file.Optional[str]Alias for `filename`.namere   DDEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file.rd   r-   Length (in bytes) of this file.)r6   intrg   Chunk size for this file.rf   r"   z!Date that this file was uploaded.datetime.datetimeupload_datemd5gDEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.z
io.BytesIOrk   r1   zlist[dict[str, Any]]ro   rp   c                X    || j                   v r| j                   |   S t        d|z        )Nz#GridIn object has no attribute '%s')r3   r2   r5   r   s     r9   __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 )Nr<   r=   )	__dict__	__class__rx   ry   r3   r1   r>   r?   r@   )r5   r   rA   s      r9   ry   zGridIn.__setattr__   s     4== DDNN,C,C$CtT51
  %DJJt||

  ++UDJJu4E,FRVX]Q^H_` r   c                x   | j                          t        |      | j                  k  sJ |r[| j                  j	                  | j
                  d   | j                  |d       | xj                  t        |      t        z   z  c_        | j                  sy|s/| j                  t        k\  st        | j                        t        k\  r@	 | j                  j                  | j                  | j                         g | _        d| _        | xj                  dz  c_        | xj&                  t        |      z  c_        y# t        $ rv}|j                  d   }|D ]4  }|j!                  d      dv s| j#                  | j
                  d          6 d|i}|j                  d   }|r|d	   |d
<   t%        |        d}~ww xY w)zFlush `data` to a chunk.r<   )r   r   dataNr]   writeErrorscode)i*  i*  i&1  writeConcernErrorswriteConcernErrorr   r   )_GridIn__ensure_indexeslenrf   ro   appendr3   rm   rp   _CHUNK_OVERHEAD_UPLOAD_BUFFER_SIZE_UPLOAD_BUFFER_CHUNKSrj   insert_manyri   r   detailsr4   _raise_file_existsr   rl   )r5   r   forceexcwrite_errorserrresultwcess           r9   __flush_datazGridIn.__flush_data-  s   4yDOO+++&&!ZZ.T5G5GQUV $$D	O(CC$"" ''+>>4&&'+@@(()<)<dmm(T #%D'(D$a#d)# " "{{=9' CCwwv*??//

50ABC (6{{#7826r(F./-f5s   1D: :	F9'F4+A	F44F9c                    | j                  | j                  j                         |       | j                  j                          t	        j
                         | _        y)z)Flush the buffer contents out to a chunk.r   N)_GridIn__flush_datark   getvaluecloser{   r|   )r5   r   s     r9   __flush_bufferzGridIn.__flush_bufferQ  s?    $,,//1?zz|r   c                   	 | j                  d       t        | j                        | j                  d<   t        j                  j                  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.Tr   r-   )tzr"   r]   N)_GridIn__flush_bufferr	   rl   r3   datetimenowtimezoneutcr>   r?   
insert_oneri   r   r   r<   r   s    r9   __flushzGridIn.__flushW  s    	.d+#(#8DJJx '/'8'8'<'<@Q@Q@U@U'<'VDJJ|$::##..tzz4==.QQ  	.##DHH-	.s   B3B6 6$CCc                    t        d|z        )z3Raise a FileExists exception for the given file_id.zfile with _id %r already exists)r   )r5   file_ids     r9   r   zGridIn._raise_file_existsc  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.
        r1   TN)r1   _GridIn__flushrx   ry   r   s    r9   r   zGridIn.closeg  s+     ||LLNtY5 r   c                ,    t        j                  d      )Nreadr{   UnsupportedOperationr5   sizes     r9   r   zGridIn.readq  s    %%f--r   c                     yNFrU   r   s    r9   readablezGridIn.readablet      r   c                     yr   rU   r   s    r9   seekablezGridIn.seekablew  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      dt	        |t
              r6	 |j                  | j                        }n# t        $ r t        d      dw xY wt        j                  |      j                  }Y w xY w# t        $ r | j!                           w xY w)ag  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:`str` 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:`bytes`, a file-like object, or an instance of :class:`str`.
        Unicode data is only allowed if the file has an :attr:`encoding`
        attribute.

        :param 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 objectsNz7must specify an encoding for file in order to write strr   )r1   
ValueErrorr   r2   rq   strbytesrr   encodeencodingr{   r|   rk   tellrf   BaseExceptionr   writer   r   r   )r5   r   r   spaceto_writes        r9   r   zGridIn.writez  s   ( <<<==	)99D <<"OOdll&7&7&99E#E{H ""8,x=5(!(3x=DOO;h'DOO,H 3x=DOO; 	8$=  	)dS%L1 MNTXX$$ ;;t}}5D%  #Q   ::d#((D	)& % JJLs5   D4 ,G 4;G0FGF"""GGG&c                4    |D ]  }| j                  |        y)zSWrite a sequence of strings to the file.

        Does not add separators.
        N)r   )r5   sequencelines      r9   
writelineszGridIn.writelines  s    
  	DJJt	r   c                     yNTrU   r   s    r9   	writeablezGridIn.writeable      r   c                    | S )z)Support for the context manager protocol.rU   r   s    r9   	__enter__zGridIn.__enter__  s    r   c                X    || j                          yt        j                  | dd       y)zSupport for the context manager protocol.

        Close the file if no exceptions occur and allow exceptions to propagate.
        r1   TF)r   rx   ry   r5   exc_typeexc_valexc_tbs       r9   __exit__zGridIn.__exit__  s1    
 JJL  tY5 r   N)r}   r   r^   Optional[ClientSession]rX   r   rG   None)r   r   r   r   r   r   rG   r   rG   r   rG   r   r   r   rG   r   )r   r   rA   r   rG   r   )F)r   r   r   r   rG   r   )r   r   rG   r   )rG   r   )r   r   rG   r   r   )r   r   rG   r   )r   r   rG   r   )r   zIterable[Any]rG   r   )rG   ra   r   r   r   r   r   r   rG   r   )#__name__
__module____qualname____doc__r   r   r   r   rJ   r   rM   r<   __annotations__r!   r   rd   r-   rf   r   r   r   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   rU   r   r9   ra   ra      sx   ( OSQ;)Q;4KQ;^aQ;	Q;fa=2   !(LX\]C]/
<PQHmQ+J8OPD-P"3]#L-  $H.O]abFCb'5P\`aJa%69t&K"  +qC  M((K
a"$H$
.F6.8%tr   ra   c                  ,    e Zd ZU dZ	 	 	 d9	 	 	 	 	 	 	 	 	 d: fdZ edd      Zded<    edd      Zded<    edd	      Z	ded
<    edd      Z
ded<    edd      Zded<    edd      Zded<    edd      Zded<    edd      Zded<    edd      Zded<    edd       Zded<   ded!<   ded"<   d;d#Zd<d$Zd=d%Zd>d&Zd?d@d'ZdAdBd(ZdAdBd)ZdCd*ZefdDd+Zd=d,ZdEd-Zd; fd.ZdFd/ZdGd0Zd=d1Z dEd2Z!dHd3Z"dId4Z#d;d5Z$d=d6Z%dJdKd7Z&d;d8Z' xZ(S )LGridOutz!Class to read data out of GridFS.c                2   t        |t              st        d      t        |       t	        |      }t
        |           |j                  | _        |j                  | _
        || _        t        | _        d| _        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`.

        :param root_collection: root collection to read from
        :param file_id: value of ``"_id"`` for the file to read
        :param file_document: file document from
            `root_collection.files`
        :param session: 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.
        rc   r   N)rq   r   rr   r_   rZ   superr   rz   _GridOut__chunksr?   _GridOut__files_GridOut__file_idEMPTY_GridOut__buffer_GridOut__buffer_pos_GridOut__chunk_iter_GridOut__positionr3   ri   )r5   r}   r   file_documentr^   r   s        r9   r   zGridOut.__init__  s    L /:6OPPw'5oF'..&,,  "
r   r<   r   r   r!   r   r   r   r   re   r   r   rd   r-   r   r   rg   r   rf   r"   z'Date that this file was first uploaded.r   r   aliaseszJDEPRECATED, will be removed in PyMongo 5.0. List of aliases for this file.zOptional[list[str]]metadatazMetadata attached to this file.Optional[Mapping[str, Any]]r   r   r3   r  c                   | j                   st        | j                         | j                  j	                  d| j
                  i| j                        | _         | j                   s%t        d| j                  d| j
                        y y )Nr<   r]   zno file in gridfs collection z
 with _id )r3   r_   ri   r  r   r  r   r   s    r9   rP   zGridOut._ensure_file)  sx    zz"4==1..t~~/FPTP]P].^DJ::3DLL3C:dnnM_`   r   c                x    | j                          || j                  v r| j                  |   S t        d|z        )Nz$GridOut object has no attribute '%s')rP   r3   r2   r   s     r9   r   zGridOut.__getattr__2  s:    4::::d##CdJKKr   c                     yr   rU   r   s    r9   r   zGridOut.readable8  r   r   c                v   t        | j                        | j                  z
  }t        }t	        | j
                        }|dkD  r| j                  | j                  d }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        | _        d| _        |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  r  r   rf   r  r-   r  _GridOutChunkIteratorr  ri   nextr   )r5   received
chunk_datarf   chunk_numberchunks         r9   	readchunkzGridOut.readchunk;  s    t}}%(9(99
)
a<t'8'8':;J__s4;;//4?? :jHIL  ($9$--%! %%**,Evt'C'EFJ%&7883z?*r   c                   | j                          t        | j                        | j                  z
  }|dk  s||kD  r|}|dk(  rt        S d}g }||k  rO||z
  }| j
                  ra| j
                  }| j                  }t        |      | j                  d }	t        | _        d| _        | xj                  t        |	      z  c_        n| j                         }d}t        |      }	|r/|j                  t        |||z         |z
  }
|
dk\  r||
z   dz   }|
dz   }t        |	      |kD  r[|j                  |	d|        || _        ||z   | _        | xj                  t        | j
                        | j                  z
  z  c_        n|j                  |	       |t        |	      z  }||k  rO||k(  r'| j                  r	 | j                  j                          dj!                  |      S # t        $ r Y w xY w)z&Internal read() and readline() helper.r   Nr   r   )rP   r   r-   r  r  r  r  
memoryviewr   r%  findNEWLNr   r  r   StopIterationjoin)r5   r   r   	remainderr!  r   neededbufchunk_startr"  poss              r9   _read_size_or_linezGridOut._read_size_or_lineW  s   $t6	!8ti'D19LoH_F}}mm"//'_T->->-@A
 %$%!3z?2nn&'_
hhuk;3GH;V!8#c>A-D 1WF:'Jw/0 #$/&$8!3t}}#58I8I#IIJ'J'H9 o> 9!2!2!!&&( xx~ ! s   5G   	G,+G,c                &    | j                  |      S )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:`bytes`
        If `size` is negative or omitted all data is read.

        :param size: 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   r1  r   s     r9   r   zGridOut.read  s     &&D&11r   c                (    | j                  |d      S )zuRead one line or up to `size` bytes from the file.

        :param size: the maximum number of bytes to read
        T)r   r   r3  r   s     r9   readlinezGridOut.readline  s    
 &&Dt&<<r   c                    | j                   S )z)Return the current position of this file.)r  r   s    r9   r   zGridOut.tell  s    r   c                |   |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|S || _        t        | _        d| _	        | j                  r!| j                  j                          d| _
        |S )aK  Set the current position of this file.

        :param pos: the position (or offset if using relative
           positioning) to seek to
        :param whence: 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.

        .. versionchanged:: 4.1
           The method now returns the new position in the file, to
           conform to the behavior of :meth:`io.IOBase.seek`.
           zInvalid value for `whence`r   z*Invalid value for `pos` - must be positiveN)	_SEEK_SET	_SEEK_CURr  	_SEEK_ENDr   r-   OSErrorr  r  r  r  r   )r5   r0  whencenew_poss       r9   seekzGridOut.seek  s     YGy oo+Gy $++&,G":;;Q;"JKK doo%N!##% $Dr   c                     yr   rU   r   s    r9   r   zGridOut.seekable  r   r   c                    | S )a-  Return an iterator over all of this file's data.

        The iterator will return lines (delimited by ``b'\n'``) of
        :class:`bytes`. This can be useful when serving files
        using a webserver that handles such an iterator efficiently.

        .. 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.

        .. versionchanged:: 4.0
           The iterator now iterates over *lines* in the file, instead
           of chunks, to conform to the base class :py:class:`io.IOBase`.
           Use :meth:`GridOut.readchunk` to read chunk by chunk instead
           of line by line.
        rU   r   s    r9   __iter__zGridOut.__iter__  s	    & r   c                |    | j                   r!| j                   j                          d| _         t        |           y)z(Make GridOut more generically file-like.N)r  r   r  )r5   r   s    r9   r   zGridOut.close  s/    ##% $Dr   c                ,    t        j                  d      )Nr   r   )r5   rA   s     r9   r   zGridOut.write  s    %%g..r   c                ,    t        j                  d      )Nr   r   )r5   liness     r9   r   zGridOut.writelines  s    %%l33r   c                     yr   rU   r   s    r9   writablezGridOut.writable  r   r   c                    | S )cMakes it possible to use :class:`GridOut` files
        with the context manager protocol.
        rU   r   s    r9   r   zGridOut.__enter__  s	     r   c                $    | j                          y)rJ  F)r   r   s       r9   r   zGridOut.__exit__  s     	

r   c                ,    t        j                  d      )Nfilenor   r   s    r9   rM  zGridOut.fileno  s    %%h//r   c                     y r   rU   r   s    r9   flushzGridOut.flush  s    r   c                     yr   rU   r   s    r9   isattyzGridOut.isatty  r   r   c                ,    t        j                  d      )Ntruncater   r   s     r9   rS  zGridOut.truncate  s     %%j11r   c                     y r   rU   r   s    r9   __del__zGridOut.__del__  s    r   )NNN)
r}   r   r   Optional[int]r  Optional[Any]r^   r   rG   r   r  r  r  rG   r   )r   F)r   r   r   r   rG   r   r  )r   r   rG   r   )rG   r   )r0  r   r=  r   rG   r   rG   r  )rA   r   rG   r   )rF  r   rG   r   r  )rG   r   r   )r   rV  rG   r   ))r  r  r  r	  r   rQ   r<   r
  r!   r   rd   r-   rf   r   r  r  r   rP   r   r   r%  r1  r   r5  r   r9  r?  r   rB  r   r   r   rH  r   r   rM  rO  rQ  rS  rU  __classcell__r   s   @r9   r  r    s   +
 "&'++/8 #8  8  %	8 
 )8  
8 t "%)MNCN&z3GHHcH":/FGD#G"4]#L-  %X/PQFCQ(6QRJR%7?&K"  $6_$G   -?5-H)  ,qC 
 JL81f2 = ,5 %N*/402r   r  c                  l    e Zd ZU dZ	 	 	 	 	 	 	 	 	 	 ddZded<   ddZddZddZddZ	dd	Z
e
Zd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 r   )r<   r   rf   _chunk_sizer-   _lengthrj   ri   _next_chunkmathceilfloat_num_chunks_cursor)r5   grid_outrz   r^   
next_chunks        r9   r   z_GridOutChunkIterator.__init__  st     <<x2238??+%99U4<<%84;K;K%KLr   zOptional[Cursor]re  c                    || j                   dz
  k  r| j                  S | j                  | j                  | j                   dz
  z  z
  S )Nr   )rd  r^  r_  )r5   chunk_ns     r9   expected_chunk_lengthz+_GridOutChunkIterator.expected_chunk_length0  sF    T%%))###||t//43C3Ca3GHIIr   c                    | S r   rU   r   s    r9   rB  z_GridOutChunkIterator.__iter__5      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   )sortr^   )r<   r`  r_   ri   rj   r(  re  )r5   filters     r9   _create_cursorz$_GridOutChunkIterator._create_cursor8  sa    dhh'a!4#3#34F3Kt}}-||((xj$--(Xr   c                2   | j                   | j                          | 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).
        )re  rp  r   r   r   r   s    r9   _next_with_retryz&_GridOutChunkIterator._next_with_retry?  s     <<!<<+++	'<<$$&& 	'LL !<<$$&&	's   A 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        $ r4 | j                  | j                  k\  r t	        d| j                  z        d 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   )rr  r*  r`  rd  r   r   r   rj  )r5   r$  expected_lengths      r9   r   z_GridOutChunkIterator.nextP  sl   	O))+E :)))JJL!"%)%5%5uSz$BC 
 :)))5=!

%&)-)9)95:(FG 
 44U3Z@uV}0JJL!-05c
OSQVW]Q^M_/`a 
 	A=  	O4#3#33!.43C3C"CD$N	Os   D
 
=Ec                `    | j                   r"| j                   j                          d | _         y y r   )re  r   r   s    r9   r   z_GridOutChunkIterator.closeu  s%    <<LL DL r   N)
rf  r  rz   r   r^   r   rg  r   rG   r   )ri  r   rG   r   )rG   r  r  )rG   zMapping[str, Any])r  r  r  r	  r   r
  rj  rB  rp  rr  r   __next__r   rU   r   r9   r  r    sl      )	
  
  J
Y'"!F H r   r  c                  (    e Zd ZddZddZddZeZy)GridOutIteratorc                *    t        |||d      | _        y )Nr   )r  _GridOutIterator__chunk_iter)r5   rf  rz   r^   s       r9   r   zGridOutIterator.__init__|  s    1(FGQOr   c                    | S r   rU   r   s    r9   rB  zGridOutIterator.__iter__  rl  r   c                R    | j                   j                         }t        |d         S )Nr   )rz  r   r   )r5   r$  s     r9   r   zGridOutIterator.next  s%    !!&&(U6]##r   N)rf  r  rz   r   r^   r   )rG   rx  rX  )r  r  r  r   rB  r   rv  rU   r   r9   rx  rx  {  s    P$ Hr   rx  c                  ~     e Zd ZdZ	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZd	 fdZeZd
dZd
dZd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        	|   |j
                  |||||||       y)ay  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

        .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
        )skiplimitno_cursor_timeoutrn  
batch_sizer^   N)r_   rZ   _GridOutCursor__root_collectionr  r   r?   )
r5   r   ro  r  r  r  rn  r  r^   r   s
            r9   r   zGridOutCursor.__init__  sQ    * 	w'0<
 ",/! 	 		
r   c                    t        | j                         t        |          }t	        | j
                  || j                        S )z$Get next GridOut object from cursor.)r  r^   )r_   r^   r  r   r  r  )r5   	next_filer   s     r9   r   zGridOutCursor.next  s6    t||,GLN	t--YPTP\P\]]r   c                    t        d      Nz'Method does not exist for GridOutCursorNotImplementedErrorr5   argsrX   s      r9   
add_optionzGridOutCursor.add_option      !"KLLr   c                    t        d      r  r  r  s      r9   remove_optionzGridOutCursor.remove_option  r  r   c                0    t        | j                  |      S )zACreates an empty GridOutCursor for information to be copied into.r]   )r~  r  )r5   r^   s     r9   _clone_basezGridOutCursor._clone_base  s    T33WEEr   )Nr   r   FNr   N)r   r   ro  r  r  r   r  r   r  r   rn  rW  r  r   r^   r   rG   r   rY  )r  r   rX   r   rG   r   )r^   r   rG   r~  )r  r  r  r	  r   r   rv  r  r  r  rZ  r[  s   @r9   r~  r~    s     /3"'"+/$
$
 ,$
 	$

 $
  $
 $
 $
 )$
 
$
L^ HMMFr   r~  )FF)
r7   r   rK   r   rL   Optional[bool]r6   r  rG   r   )r7   r   rK   r   rG   r   )rW   r   rX   r   rG   r   )r^   r   rG   r   )Dr	  
__future__r   r   r{   ra  osr.   typingr   r   r   r   r   
bson.int64r	   bson.objectidr
   gridfs.errorsr   r   r   pymongor   pymongo.client_sessionr   pymongo.collectionr   pymongo.commonr   pymongo.cursorr   pymongo.errorsr   r   r   r   r   r   pymongo.helpersr   pymongo.read_preferencesr   SEEK_SETr9  SEEK_CURr:  SEEK_ENDr;  r  r)  rw   r   r   r   r    r
  r#   rM   rQ   rZ   r_   ra   IOBaser  r  rx  r~  rU   r   r9   <module>r     s@   5 "  	  	  = =  " = =  0 ) + !  : 3KK	KK	KK	 # &   (1	B. B(1K. K !&"'	*+*+*+ *+  	*+
 	*+Z+,BV
@ @F
Abii AH
a  a H ;FF ;Fr   