
    恕fD                     d   d dl 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 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 	 d dlmZmZ g dZ  G d de!      Z" G d de!      Z# G d de
jH                        Z% G d de%      Z&d Z'd Z(y# e$ r	 d dlmZ Y qw xY w# e$ r dZdZY ]w xY w)    N)secure_filename)FileStorage)ValidationErrorfields__version__)html_params)_unset_value)unset_value)gettext)get_url)Markup)string_typesurljoin)ImageImageOps)FileUploadInputFileUploadFieldImageUploadInputImageUploadFieldnamegen_filenamethumbgen_filenamec                   "    e Zd ZdZdZdZdZd Zy)r   z
        Renders a file input chooser field.

        You can customize `empty_template` and `data_template` members to customize
        look and feel.
    <input %(file)s>filezd<div> <input %(text)s> <input type="checkbox" name="%(marker)s">Delete</input></div><input %(file)s>c           
         |j                  d|j                         |j                  d|j                         |j                  r| j                  n| j
                  }|j                  r| j
                  }|j                  r1t        |j                  t              r|j                  j                  }n|j                  xs d}t        |t        dd||j                        t        dd|d|d	|j                  z  d
z        S )Nidname textreadonly)typer    valuer   r   )r!   r"   
_%s-deleter   r   marker )
setdefaultr   r   datadata_templateempty_templateerrors
isinstancer   filenamer   r   )selffieldkwargstemplater"   s        V/var/www/feuerwehr-webapp/venv/lib/python3.12/site-packages/flask_admin/form/upload.py__call__zFileUploadInput.__call__2   s    $)&%**-).4%%9L9L<<**H::*UZZ=JJ''EJJ$"EhV)3&+%*ZZ1   *V&+*"(* #UZZ/	"
 	
 	 		    N)__name__
__module____qualname____doc__r*   
input_typer)   r3   r&   r4   r2   r   r   "   s     )NJ(Mr4   r   c                   (    e Zd ZdZdZdZdZd Zd Zy)r   z
        Renders a image input chooser field.

        You can customize `empty_template` and `data_template` members to customize
        look and feel.
    r   r   z<div class="image-thumbnail"> <img %(image)s> <input type="checkbox" name="%(marker)s">Delete</input> <input %(text)s></div><input %(file)s>c                    |j                  d|j                         |j                  d|j                         t        d|j                  |j                        t        dddi|d|j                  z  d}|j                  rGt        |j                  t              r-| j                  |      }t        |	      |d
<   | j                  }n| j                  }t        ||z        S )Nr   r   hidden)r!   r"   r   r!   r   r#   r$   )srcimager&   )r'   r   r   r   r(   r,   r   r   r)   r*   r   )r.   r/   r0   argsurlr1   s         r2   r3   zImageUploadInput.__call__]   s    $)&%**-  X&+jj%*ZZ1   *V *"(*"UZZ/
 ::*UZZ>,,u%C'C0DM))H**Hho&&r4   c                     |j                   r|j                  |j                        }n|j                  }|j                  rt	        |j                  |      }t        |j                  |      S )N)r-   )thumbnail_sizethumbnail_fnr(   url_relative_pathr   r   endpoint)r.   r/   r-   s      r2   r   zImageUploadInput.get_urlt   sT    ))%**5HzzH""u66AHu~~99r4   N)	r5   r6   r7   r8   r*   r9   r)   r3   r   r&   r4   r2   r   r   L   s$     )NJ(M'.	:r4   r   c                        e Zd ZdZ e       Z	 	 	 	 d fd	Zd Zd Zd Z	e
df fd	Zd Zd	 Zd
 Zd Zd Zd Z xZS )r   z
        Customizable file-upload field.

        Saves file to configured path, handles updates and deletions. Inherits from `StringField`,
        resulting filename will be stored as string.
    Nc	                     || _         || _        |xs t        | _        || _        || _        || _        d| _        t        t        d         dk  r|	j                  dd       t        t        | 6  ||fi |	 y)a  
            Constructor.

            :param label:
                Display label
            :param validators:
                Validators
            :param base_path:
                Absolute path to the directory which will store files
            :param relative_path:
                Relative path from the directory. Will be prepended to the file name for uploaded files.
                Flask-Admin uses `urlparse.urljoin` to generate resulting filename, so make sure you have
                trailing slash.
            :param namegen:
                Function that will generate filename from the model and uploaded file object.
                Please note, that model is "dirty" model object, before it was committed to database.

                For example::

                    import os.path as op

                    def prefix_name(obj, file_data):
                        parts = op.splitext(file_data.filename)
                        return secure_filename('file-%s%s' % parts)

                    class MyForm(BaseForm):
                        upload = FileUploadField('File', namegen=prefix_name)

            :param allowed_extensions:
                List of allowed extensions. If not provided, will allow any file.
            :param allow_overwrite:
                Whether to overwrite existing files in upload directory. Defaults to `True`.

            .. versionadded:: 1.1.1
                The `allow_overwrite` parameter was added.
        Fr      extra_filtersN)	base_pathrelative_pathr   namegenallowed_extensions
permission_allow_overwrite_should_deleteintwtforms_versionpopsuperr   __init__)r.   label
validatorsrJ   rK   rL   rM   rN   allow_overwriter0   	__class__s             r2   rU   zFileUploadField.__init__   sw    R #*2"2"4$ /#q!"Q&JJ-ot-eZJ6Jr4   c                     | j                   syd|v xr: |j                  dd      d   j                         t        d | j                         v S )zz
            Check if file extension is allowed.

            :param filename:
                File name to check
        T.   c                 "    | j                         S N)lower)xs    r2   <lambda>z1FileUploadField.is_file_allowed.<locals>.<lambda>   s    aggi r4   )rM   rsplitr_   mapr.   r-   s     r2   is_file_allowedzFileUploadField.is_file_allowed   sV     &&x BQ'*002')@)@AB	Cr4   c                 F    |xr t        |t              xr |j                  S r^   )r,   r   r-   )r.   r(   s     r2   _is_uploaded_filez!FileUploadField._is_uploaded_file   s    HD+6H4==Ir4   c                    | j                  | j                        r9| j                  | j                  j                        st	        t        d            | j                  | j                        sy | j                  snt        j                  j                  | j                  | j                  j                              r+t	        t        d| j                  j                  z              y y )NzInvalid file extensionFile "%s" already exists.)rg   r(   re   r-   r   r   rO   ospathexists	_get_path)r.   forms     r2   pre_validatezFileUploadField.pre_validate   s    !!$)),T5I5I$))J\J\5]!'*B"CDD %%dii0$$tyyGYGY8Z)[!'*E		HZHZ*Z"[\\ *\$r4   c                     |rd| j                   z  }||v rd| _        t        t        d         dk  rt        t
        |   ||      S t        t
        |   |||      S )Nr#   Tr   rH   )r   rP   rQ   rR   rT   r   process)r.   formdatar(   rI   r%   rY   s        r2   rq   zFileUploadField.process   s`    !DII-F!&*#q!"Q&$7$GG$7$VVr4   c                 t    | j                   rd | _        y |r"|D ]  }| j                  |      s|| _         y  y y r^   )rP   r(   rg   )r.   	valuelistr(   s      r2   process_formdataz FileUploadField.process_formdata   sA    DI! ))$/ $DI r4   c                    t        ||d       }|r+| j                  r| j                  |       t        ||d        y | j	                  | j
                        rj|r| j                  |       | j                  || j
                        }| j                  | j
                  |      }|| j
                  _        t        |||       y y r^   )	getattrrP   _delete_filesetattrrg   r(   generate_name
_save_filer-   )r.   objr   r/   r-   s        r2   populate_objzFileUploadField.populate_obj   s    T4(""!!%(T4(!!$)),!!%())#tyy9Htyy(;H!)DIICx( -r4   c                 n    | j                  ||      }| j                  s|S t        | j                  |      S r^   )rL   rK   r   )r.   r|   	file_datar-   s       r2   rz   zFileUploadField.generate_name  s3    <<Y/!!Ot))844r4   c                     | j                   st        d      t        | j                         r$t        j                  | j                         |      S t        j                  | j                   |      S )Nz3FileUploadField field requires base_path to be set.)rJ   
ValueErrorcallableopjoinrd   s     r2   rm   zFileUploadField._get_path  sN    ~~RSSDNN#774>>+X66wwt~~x00r4   c                 |    | j                  |      }t        j                  |      rt        j                  |       y y r^   )rm   r   rl   rj   remover.   r-   rk   s      r2   rx   zFileUploadField._delete_file  s+    ~~h'99T?IIdO r4   c                    | j                  |      }t        j                  t        j                  |            s@t	        j
                  t        j                  j                  |      | j                  dz         | j                  du r6t        j                  j                  |      rt        t        d|z              |j                  |       |S )NI   Fri   )rm   r   rl   dirnamerj   makedirsrk   rN   rO   r   r   save)r.   r(   r-   rk   s       r2   r{   zFileUploadField._save_file  s    ~~h'yyD)*KK-t/FG!!U*t0DW%@4%GHII		$r4   )NNNNNN  T)r5   r6   r7   r8   r   widgetrU   re   rg   ro   r
   rq   ru   r}   rz   rm   rx   r{   __classcell__rY   s   @r2   r   r      sb     F.2/326376KpCJ	] &1 	W)(51
r4   r   c                        e Zd ZdZ e       ZdZ	 	 	 	 	 	 	 	 d fd	Z fdZ fdZ	d Z
d Zd Zd	 Zdd
Zd Z xZS )r   z
        Image upload field.

        Does image validation, thumbnail generation, updating and deleting images.

        Requires PIL (or Pillow) to be installed.
    )PNGc           	          t         t        d      || _        |xs t        | _        |	| _        || _        d| _        || _        |sd}t        t        | .  ||f|||||
d| y)a  
            Constructor.

            :param label:
                Display label
            :param validators:
                Validators
            :param base_path:
                Absolute path to the directory which will store files
            :param relative_path:
                Relative path from the directory. Will be prepended to the file name for uploaded files.
                Flask-Admin uses `urlparse.urljoin` to generate resulting filename, so make sure you have
                trailing slash.
            :param namegen:
                Function that will generate filename from the model and uploaded file object.
                Please note, that model is "dirty" model object, before it was committed to database.

                For example::

                    import os.path as op

                    def prefix_name(obj, file_data):
                        parts = op.splitext(file_data.filename)
                        return secure_filename('file-%s%s' % parts)

                    class MyForm(BaseForm):
                        upload = FileUploadField('File', namegen=prefix_name)

            :param allowed_extensions:
                List of allowed extensions. If not provided, then gif, jpg, jpeg, png and tiff will be allowed.
            :param max_size:
                Tuple of (width, height, force) or None. If provided, Flask-Admin will
                resize image to the desired size.

                Width and height is in pixels. If `force` is set to `True`, will try to fit image into dimensions and
                keep aspect ratio, otherwise will just resize to target size.
            :param thumbgen:
                Thumbnail filename generation function. All thumbnails will be saved as JPEG files,
                so there's no need to keep original file extension.

                For example::

                    import os.path as op

                    def thumb_name(filename):
                        name, _ = op.splitext(filename)
                        return secure_filename('%s-thumb.jpg' % name)

                    class MyForm(BaseForm):
                        upload = ImageUploadField('File', thumbgen=thumb_name)

            :param thumbnail_size:
                Tuple or (width, height, force) values. If not provided, thumbnail won't be created.

                Width and height is in pixels. If `force` is set to `True`, will try to fit image into dimensions and
                keep aspect ratio, otherwise will just resize to target size.
            :param url_relative_path:
                Relative path from the root of the static directory URL. Only gets used when generating
                preview image URLs.

                For example, your model might store just file names (`relative_path` set to `None`), but
                `base_path` is pointing to subdirectory.
            :param endpoint:
                Static endpoint for images. Used by widget to display previews. Defaults to 'static'.
        NzPIL library was not found)gifjpgjpegpngtiff)rJ   rK   rL   rM   rN   )r   ImportErrormax_sizer   rC   rB   rE   r>   rD   rT   r   rU   )r.   rV   rW   rJ   rK   rL   rM   r   thumbgenrB   rN   rD   rE   r0   rY   s                 r2   rU   zImageUploadField.__init__9  s    T =9:: $9(9, 
!2!!F.uj 	99B=J7>BT:D	9 28	9r4   c                     t         t        |   |       | j                  | j                        r&	 t        j                  | j                        | _        y y # t        $ r}t        d|z        d }~ww xY w)NzInvalid image: %s)
rT   r   ro   rg   r(   r   openr>   	Exceptionr   )r.   rn   erY   s      r2   ro   zImageUploadField.pre_validate  sf    248!!$)),?"ZZ		2
 -  ?%&9A&=>>?s   $A 	A3 A..A3c                 N    t         t        |   |       | j                  |       y r^   )rT   r   rx   _delete_thumbnail)r.   r-   rY   s     r2   rx   zImageUploadField._delete_file  s!    28<x(r4   c                     | j                  | j                  |            }t        j                  |      rt	        j
                  |       y y r^   )rm   rC   r   rl   rj   r   r   s      r2   r   z"ImageUploadField._delete_thumbnail  s6    ~~d//9:99T?IIdO r4   c                    | j                  |      }t        j                  t        j                  |            s@t	        j
                  t        j                  j                  |      | j                  dz         | j                  || j                        \  }}| j                  r| j                  j                  |k7  s| j                  rb| j                  r'| j                  | j                  | j                        }n| j                  }| j                  || j                  |      |       n1|j                  d       |j                  | j                  |             | j!                  |||       |S )Nr   r   )rm   r   rl   r   rj   r   rk   rN   _get_save_formatr>   formatr   _resize_save_imageseekr   _save_thumbnail)r.   r(   r-   rk   r   r>   s         r2   r{   zImageUploadField._save_file  s    ~~h'yyD)*KK-t/FG  004::F&::4::,,6$--}}TZZ?

UDNN8$<fEIIaLIIdnnX./T8V4r4   c                     | j                   re| j                  rX| j                  | j                  |            }| j	                  | j                  | j                   | j                        ||       y y y r^   )r>   rB   rm   rC   r   r   )r.   r(   r-   r   rk   s        r2   r   z ImageUploadField._save_thumbnail  s\    ::$-->>$"3"3H"=>DT\\$**d6I6IJ!#% .:r4   c                 <   |\  }}}|j                   d   |kD  s|j                   d   |kD  rq|r1t        j                  | j                  ||ft        j
                        S | j                  j                         }|j                  ||ft        j
                         |S |S )Nr   r\   )sizer   fitr>   r   	ANTIALIAScopy	thumbnail)r.   r>   r   widthheightforcethumbs          r2   r   zImageUploadField._resize  s    !%::a=5 EJJqMF$:||DJJQQ

)Ar4   c                     |dk(  r!|j                   dk7  r|j                  d      }n|j                   dvr|j                  d      }t        |d      5 }|j                  ||       d d d        y # 1 sw Y   y xY w)NJPEGRGB)r   RGBAr   wb)modeconvertr   r   )r.   r>   rk   r   fps        r2   r   zImageUploadField._save_image  sl    V

e 3MM%(EZZ.MM&)E$ 	#JJr6"	# 	# 	#s   A..A7c                     |j                   | j                  vr!t        j                  |      \  }}d|z  }|dfS ||j                   fS )Nz%s.jpgr   )r   keep_image_formatsr   splitext)r.   r-   r>   r   exts        r2   r   z!ImageUploadField._get_save_format  sI    <<t666H-ID#$HV##%%r4   )NNNNNNNNNr   Nstatic)r   )r5   r6   r7   r8   r   r   r   rU   ro   rx   r   r{   r   r   r   r   r   r   s   @r2   r   r   )  sc     F!
 /3/326/3!2:]9~?)
0%#&r4   r   c                 ,    t        |j                        S )z9
        Generate secure filename for uploaded file.
    )r   r-   )r|   r   s     r2   r   r     s     9--..r4   c                 @    t        j                  |       \  }}|d|S )z4
        Generate thumbnail name from filename.
    _thumb)r   r   )r-   r   r   s      r2   r   r     s!     H%ID#%%r4   ))rj   os.pathrk   r   werkzeug.utilsr   werkzeug.datastructuresr   wtformsr   r   r   rR   wtforms.widgetsr   wtforms.fields.corer	   r
   r   wtforms.utilsflask_admin.babelr   flask_admin.helpersr   flask_admin._backwardsr   flask_admin._compatr   r   PILr   r   __all__objectr   r   StringFieldr   r   r   r   r&   r4   r2   <module>r      s    	  * / K K '*? & ' ) 5#
4'f 'T1:v 1:jef(( ePB& B&L/&U  *)*  EHs#   B 	B# B B #	B/.B/