
    wg;                         d Z ddlZddlZddlZddlmZmZ ddlZddlZ	ddl
mZ ddlmZ  G d de      Zd	 Zd
 Zd Z G d d      Zy)z
This module contains SMBFileSystem class responsible for handling access to
Windows Samba network shares by using package smbprotocol
    N)S_ISDIRS_ISLNK   )AbstractFileSysteminfer_storage_optionsc                        e Zd ZdZdZ	 	 	 	 	 	 	 	 	 	 d fd	Zed        Zd Ze	d        Z
ed        ZddZdd	Zd
 Zd Zd Zd ZddZ	 	 	 	 ddZd Zd ZddZ xZS )SMBFileSystemaa  Allow reading and writing to Windows and Samba network shares.

    When using `fsspec.open()` for getting a file-like object the URI
    should be specified as this format:
    ``smb://workgroup;user:password@server:port/share/folder/file.csv``.

    Example::

        >>> import fsspec
        >>> with fsspec.open(
        ...     'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv'
        ... ) as smbfile:
        ...     df = pd.read_csv(smbfile, sep='|', header=None)

    Note that you need to pass in a valid hostname or IP address for the host
    component of the URL. Do not use the Windows/NetBIOS machine name for the
    host component.

    The first component of the path in the URL points to the name of the shared
    folder. Subsequent path components will point to the directory/folder/file.

    The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be
    optional.

    .. note::

        For working this source require `smbprotocol`_ to be installed, e.g.::

            $ pip install smbprotocol
            # or
            # pip install smbprotocol[kerberos]

    .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements

    Note: if using this with the ``open`` or ``open_files``, with full URLs,
    there is no way to tell if a path is relative, so all paths are assumed
    to be absolute.
    smbc                 L   t        |   di | || _        || _        || _        || _        || _        || _        |j                  dd      | _	        || _
        || _        |	dk  rt        d      |	| _        |
dk  rt        d      |
| _        || _        | j!                          y)	a&
  
        You can use _get_kwargs_from_urls to get some kwargs from
        a reasonable SMB url.

        Authentication will be anonymous or integrated if username/password are not
        given.

        Parameters
        ----------
        host: str
            The remote server name/ip to connect to
        port: int or None
            Port to connect with. Usually 445, sometimes 139.
        username: str or None
            Username to connect with. Required if Kerberos auth is not being used.
        password: str or None
            User's password on the server, if using username
        timeout: int
            Connection timeout in seconds
        encrypt: bool
            Whether to force encryption or not, once this has been set to True
            the session cannot be changed back to False.
        share_access: str or None
            Specifies the default access applied to file open operations
            performed with this file system object.
            This affects whether other processes can concurrently open a handle
            to the same file.

            - None (the default): exclusively locks the file until closed.
            - 'r': Allow other handles to be opened with read access.
            - 'w': Allow other handles to be opened with write access.
            - 'd': Allow other handles to be opened with delete access.
        register_session_retries: int
            Number of retries to register a session with the server. Retries are not performed
            for authentication errors, as they are considered as invalid credentials and not network
            issues. If set to negative value, no register attempts will be performed.
        register_session_retry_wait: int
            Time in seconds to wait between each retry. Number must be non-negative.
        register_session_retry_factor: int
            Base factor for the wait time between each retry. The wait time
            is calculated using exponential function. For factor=1 all wait times
            will be equal to `register_session_retry_wait`. For any number of retries,
            the last wait time will be equal to `register_session_retry_wait` and for retries>1
            the first wait time will be equal to `register_session_retry_wait / factor`.
            Number must be equal to or greater than 1. Optimal factor is 10.
        auto_mkdir: bool
            Whether, when opening a file, the directory containing it should
            be created (if it doesn't already exist). This is assumed by pyarrow
            and zarr-python code.
        temppath r   z:register_session_retry_wait must be a non-negative integer   zSregister_session_retry_factor must be a positive integer equal to or greater than 1N )super__init__hostportusernamepasswordtimeoutencryptpopr   share_accessregister_session_retries
ValueErrorregister_session_retry_waitregister_session_retry_factor
auto_mkdir_connect)selfr   r   r   r   r   r   r   r   r   r   r   kwargs	__class__s                _/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/fsspec/implementations/smb.pyr   zSMBFileSystem.__init__?   s    B 	"6"		  

:r2((@%&*L  ,G((1,5  .K*$    c                 6    | j                   dS | j                   S )N  r   r!   s    r$   _portzSMBFileSystem._port   s    ii's6TYY6r%   c           	      Z   dd l }| j                  dk  ry g }| j                  | j                  dz
  | j                  t	        fdt        ddz         D              }t        | j                  dz         D ][  }	 t        j                  | j                  | j                  | j                  | j                  | j                  | j                          y  |d   # t        j                  j                   t        j                  j"                  f$ r  t$        $ r<}t'        j(                  dt+        |            r|j-                  |       n Y d }~n*d }~wt.        $ r}|j-                  |       Y d }~nd }~ww xY w|| j                  k  s|j1                  t3        |             1)Nr   r   c              3   :   K   | ]  }|z  d z
  z  z    yw)r   Nr   ).0nfactorn_waits	wait_times     r$   	<genexpr>z)SMBFileSystem._connect.<locals>.<genexpr>   s(      
89Fq7{Q')3
s   )r   r   r   r   connection_timeoutz\[Errno -\d+])timer   r   r   iterrange	smbclientregister_sessionr   r   r   r*   r   r   smbprotocol
exceptionsSMBAuthenticationErrorLogonFailurer   refindallstrappend	Exceptionsleepnext)	r!   r5   retried_errors
wait_timesattemptexcr0   r1   r2   s	         @@@r$   r    zSMBFileSystem._connect   s   ((B.44	))A- 	 33  
=B1gPQk=R
 

 T::Q>? "	-G+**II!]]!]] LL'+|| "	-L R  5 &&==&&33   	::.C9 #))#. 	 /
  + %%c**+
 666

4
+,s&    ACA E=2EE="E88E=c                     t        |      d   S )Npathr   )clsrJ   s     r$   _strip_protocolzSMBFileSystem._strip_protocol   s    $T*622r%   c                 d    t        |       }|j                  dd        |j                  dd        |S )NrJ   protocol)r   r   )rJ   outs     r$   _get_kwargs_from_urlsz#SMBFileSystem._get_kwargs_from_urls   s/     $D)
D!
r%   c                     t        | j                  |      }|r$t        j                  |fd| j                  d| y t        j
                  |fd| j                  i| y )NFexist_okr   r   )_as_unc_pathr   r8   makedirsr*   mkdir)r!   rJ   create_parentsr"   wpaths        r$   rV   zSMBFileSystem.mkdir   sM    TYY-uPu4::PPOOE=

=f=r%   c                     t        |      r9t        | j                  |      }t        j                  ||| j
                         y y )NrR   )_share_has_pathrT   r   r8   rU   r*   )r!   rJ   rS   rX   s       r$   rU   zSMBFileSystem.makedirs   s5    4  D1EuxdjjI !r%   c                     t        |      r8t        | j                  |      }t        j                  || j
                         y y Nr(   )rZ   rT   r   r8   rmdirr*   )r!   rJ   rX   s      r$   r]   zSMBFileSystem.rmdir   s1    4  D1EOOE

3 !r%   c                 f   t        | j                  |      }t        j                  |fd| j                  i|}t        |j                        rd}nt        |j                        rd}nd}|dk(  r|dz   n||j                  ||j                  |j                  |j                  |j                  d}|S )Nr   	directorylinkfile/)namesizetypeuidgidr5   mtime)rT   r   r8   statr*   r   st_moder   st_sizest_uidst_gidst_atimest_mtime)r!   rJ   r"   rX   statsstyperess          r$   infozSMBFileSystem.info   s    TYY-u@4::@@5==!EU]]#EE"';"6D3JDMM<<<<NN^^
 
r%   c                     t        | j                  |      }t        j                  || j                        }t
        j
                  j                  |j                  t
        j                  j                        S )z=Return the created timestamp of a file as a datetime.datetimer(   tz)
rT   r   r8   ri   r*   datetimefromtimestampst_ctimetimezoneutcr!   rJ   rX   rp   s       r$   createdzSMBFileSystem.created  R    TYY-u4::6  ..u~~(BSBSBWBW.XXr%   c                     t        | j                  |      }t        j                  || j                        }t
        j
                  j                  |j                  t
        j                  j                        S )z>Return the modified timestamp of a file as a datetime.datetimer(   ru   )
rT   r   r8   ri   r*   rw   rx   ro   rz   r{   r|   s       r$   modifiedzSMBFileSystem.modified  r~   r%   c                 (   t        | j                  |      }t        j                  |fd| j                  i|}|D cg c]$  }dj                  |j                  d      |g      & }}|r|D cg c]  }| j                  |       }}|S c c}w c c}w )Nr   rb   )rT   r   r8   listdirr*   joinrstriprs   )	r!   rJ   detailr"   unclistedpdirsds	            r$   lszSMBFileSystem.ls  s    499d+""3BTZZB6B9?@A$++c*A./@@*./QDIIaL/D/ A/s   )B
.Bc                    | j                   r&d|v r"| j                  | j                  |      d       ||dk\  r|nd}t        | j                  |      }|j                  d| j                        }	d|v r@|du r<t        | j                  || j                        }
t        ||
|f| j                  |d|S t        j                  ||f||	| j                  d	|S )
a5  
        block_size: int or None
            If 0, no buffering, 1, line buffering, >1, buffer that many bytes

        Notes
        -----
        By specifying 'share_access' in 'kwargs' it is possible to override the
        default shared access setting applied in the constructor of this object.
        wTrS   r   r,   r   F)r   
block_size)	bufferingr   r   )r   rU   _parentrT   r   r   r   _as_temp_pathr   SMBFileOpenerr*   r8   	open_file)r!   rJ   moder   
autocommitcache_optionsr"   blsrX   r   temps              r$   _openzSMBFileSystem._open   s    $ ??sd{MM$,,t,tM<&2zQjBTYY-zz.$2C2CD$;:. D$--@D tT(,

sFL  ""
 %
 
 	
r%   c                     t        | j                  |      }t        | j                  |      }| j                  r"| j                  | j	                  |      d       t        j                  ||fd| j                  i| y)z0Copy within two locations in the same filesystemTr   r   N)rT   r   r   rU   r   r8   copyfiler*   )r!   path1path2r"   wpath1wpath2s         r$   copyzSMBFileSystem.copyE  s`    dii/dii/??MM$,,u-M=66E

EfEr%   c                 :   t        |      rt        | j                  |      }t        j                  || j
                        }t        |j                        r"t        j                  || j
                         y t        j                  || j
                         y y r\   )
rZ   rT   r   r8   ri   r*   r   rj   r]   remover|   s       r$   _rmzSMBFileSystem._rmM  se    4  D1ENN5tzz:Eu}}%DJJ7  TZZ8 !r%   c                     t        | j                  |      }t        | j                  |      }t        j                  ||fd| j                  i| y )Nr   )rT   r   r8   renamer*   )r!   r   r   	recursivemaxdepthr"   r   r   s           r$   mvzSMBFileSystem.mvV  s@    dii/dii/CdjjCFCr%   )
NNN<   NN   r   
   F)T)F)rbr,   TN)NN)__name__
__module____qualname____doc__rN   r   propertyr*   r    classmethodrL   staticmethodrP   rV   rU   r]   rs   r}   r   r   r   r   r   r   __classcell__)r#   s   @r$   r
   r
      s    %N H !"$%&(Wr 7 7<!| 3 3  >J
4
(YY #
JF9Dr%   r
   c                 8    |j                  dd      }d|  | }|S )Nrb   \z\\)replace)r   rJ   rpathr   s       r$   rT   rT   \  s'    LLd#Eug
CJr%   c                 ~    |j                  d      d   }d| | dt        j                          }t        | |      }|S )Nrb   r   )splituuiduuid4rT   )r   rJ   r   share	temp_filer   s         r$   r   r   b  sA    JJsOAEE78*Adjjl^4I
tY
'CJr%   c                 Z    | j                  d      }| j                  d      r|dkD  S |dkD  S )Nrb   r   r   )countendswith)rJ   partss     r$   rZ   rZ   i  s/    JJsOE}}Sqy19r%   c                   H    e Zd ZdZddZd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zy)r   z/writes to remote temporary file, move on commitc                     || _         || _        || _        || _        || _        d | _        d| _        || _        | j                          y NF)	rJ   r   r   r   r"   smbfile
_incontextr   r   )r!   rJ   r   r   r   r   r"   s          r$   r   zSMBFileOpener.__init__s  sC    			$	

r%   c                     | j                   | j                   j                  rRt        j                  | j                  | j
                  f| j                  | j                  d| j                  | _         y y )N)r   r   )	r   closedr8   r   r   r   r   r   r"   r)   s    r$   r   zSMBFileOpener._open~  s`    <<4<<#6#6$..				 YY//	
 ++DL $7r%   c                 p    t        j                  | j                  | j                  | j                         y)z(Move temp file to definitive on success.r(   N)r8   r   r   rJ   r   r)   s    r$   commitzSMBFileOpener.commit  s"     	$))TYYTYY?r%   c                 Z    t        j                  | j                  | j                         y)z Remove the temp file on failure.r(   N)r8   r   r   r   r)   s    r$   discardzSMBFileOpener.discard  s    3r%   c                     | j                   S N)rJ   r)   s    r$   
__fspath__zSMBFileOpener.__fspath__  s    yyr%   c                 6    | j                   j                         S r   )r   __iter__r)   s    r$   r   zSMBFileOpener.__iter__  s    ||$$&&r%   c                 .    t        | j                  |      S r   )getattrr   )r!   items     r$   __getattr__zSMBFileOpener.__getattr__  s    t||T**r%   c                 D    d| _         | j                  j                         S )NT)r   r   	__enter__r)   s    r$   r   zSMBFileOpener.__enter__  s    ||%%''r%   c                 L    d| _         | j                  j                  |||       y r   )r   r   __exit__)r!   exc_type	exc_value	tracebacks       r$   r   zSMBFileOpener.__exit__  s    h	9=r%   N)r'   r,   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r%   r$   r   r   p  s3    9	@
4'+(>r%   r   )r   rw   r>   r   ri   r   r   r8   smbprotocol.exceptionsr:   r   r   utilsr   r
   rT   r   rZ   r   r   r%   r$   <module>r      sO   
  	  !   ! )
ED& EDP
0> 0>r%   