§
    –õqi×  ã            	       ó€  — d Z ddlZddlZddlZddlmZ ddlmZmZ ddlZddl	m
Z
 ddlZddlZddlZej                             ej                             ej                             ej                             e¦  «        ¦  «        ¦  «        ¦  «         ddlmZmZmZmZ  ej        e¦  «        Z G d„ d¦  «        ZdS )	z<
File management utilities for handling uploads and storage
é    N)ÚPath)ÚdatetimeÚ	timedelta)ÚOptional)ÚTEMP_UPLOAD_DIRÚVALID_UPLOAD_DIRÚALLOWED_EXTENSIONSÚTEMP_FILE_CLEANUP_HOURSc                   óp  — e Zd ZdZdZededefd„¦   «         Zededefd„¦   «         Z	ededefd	„¦   «         Z
ededefd
„¦   «         Zedededefd„¦   «         Zededefd„¦   «         Zedededefd„¦   «         Zededefd„¦   «         Zededefd„¦   «         Zed„ ¦   «         Zedefd„¦   «         ZdS )ÚFileManagerzÀ
    Manages file operations for uploaded images including:
    - Validation
    - Temporary storage
    - Moving to permanent storage
    - Cleanup of old files
    - Duplicate detection
    NÚ
image_pathÚreturnc                 óú   ‡— t          j        ¦   «         }t          | d¦  «        5 Št          ˆfd„d¦  «        D ]}|                     |¦  «         Œ	 ddd¦  «         n# 1 swxY w Y   |                     ¦   «         S )zÙ
        Calculate MD5 hash of an image file for duplicate detection.
        
        Args:
            image_path: Path to the image file
            
        Returns:
            MD5 hash of the image file
        Úrbc                  ó.   •— ‰                       d¦  «        S )Ni   )Úread)Úfs   €úR/var/www/html/cool-property-finder/image-detection-backend/app/utils/file_utils.pyú<lambda>z2FileManager.calculate_image_hash.<locals>.<lambda>6   s   ø€  a§f¢f¨T¡l¤l€ ó    r   N)ÚhashlibÚmd5ÚopenÚiterÚupdateÚ	hexdigest)r   Úhash_md5Úchunkr   s      @r   Úcalculate_image_hashz FileManager.calculate_image_hash)   sÃ   ø€ õ ”;‘=”=ˆÝ�*˜dÑ#Ô#ð 	' qÝÐ2Ð2Ð2Ð2°CÑ8Ô8ð 'ð '�Ø—’ Ñ&Ô&Ð&Ð&ð'ð	'ð 	'ð 	'ñ 	'ô 	'ð 	'ð 	'ð 	'ð 	'ð 	'ð 	'øøøð 	'ð 	'ð 	'ð 	'ð ×!Ò!Ñ#Ô#Ð#s   ¥,AÁA"Á%A"Ú
image_hashc                 ó   — dS )zà
        Check if an image hash already exists (duplicate detection).
        
        Args:
            image_hash: MD5 hash of the image
            
        Returns:
            True if duplicate, False otherwise
        F© )r    s    r   Úis_duplicate_imagezFileManager.is_duplicate_image:   s	   € ð ˆur   Úfilenamec                 ó   — dS )z´
        Register an image hash to track uploaded images.
        
        Args:
            image_hash: MD5 hash of the image
            filename: Name of the image file
        Nr"   )r    r$   s     r   Úregister_image_hashzFileManager.register_image_hashG   s	   € ð 	ˆr   c                 ó`   — t          | ¦  «        j                             ¦   «         }|t          v S )zÛ
        Check if file has an allowed extension.
        
        Args:
            filename: Name of the file to validate
            
        Returns:
            True if extension is allowed, False otherwise
        )r   ÚsuffixÚlowerr	   )r$   Úexts     r   Úvalidate_file_extensionz#FileManager.validate_file_extensionR   s*   € õ �8‰nŒnÔ#×)Ò)Ñ+Ô+ˆØÕ(Ð(Ð(r   Ú	file_sizeÚmax_sizec                 ó   — | |k    S )a  
        Check if file size is within allowed limit.
        
        Args:
            file_size: Size of file in bytes
            max_size: Maximum allowed size in bytes
            
        Returns:
            True if size is acceptable, False otherwise
        r"   )r,   r-   s     r   Úvalidate_file_sizezFileManager.validate_file_size`   s   € ð ˜HÒ$Ð$r   Úoriginal_filenamec                 ó°   — t          j        ¦   «                              d¦  «        }t          | ¦  «        j        }t          | ¦  «        j        }|› d|› |› �S )zß
        Generate a unique filename using timestamp.
        
        Args:
            original_filename: Original name of the uploaded file
            
        Returns:
            Unique filename with timestamp
        z%Y%m%d_%H%M%S_%fÚ_)r   ÚnowÚstrftimer   r(   Ústem)r0   Ú	timestampr*   Únames       r   Úgenerate_unique_filenamez$FileManager.generate_unique_filenamen   sY   € õ ”L‘N”N×+Ò+Ð,>Ñ?Ô?ˆ	ÝÐ$Ñ%Ô%Ô,ˆÝÐ%Ñ&Ô&Ô+ˆØÐ)Ð)˜Ð) CÐ)Ð)Ð)r   Úfile_contentc              ƒ   ó4  K  — 	 t           |z  }t          |d¦  «        5 }|                     | ¦  «         ddd¦  «         n# 1 swxY w Y   t                               d|› �¦  «         |S # t
          $ r#}t                               d|› �¦  «         ‚ d}~ww xY w)zï
        Save uploaded file to temporary storage.
        
        Args:
            file_content: Binary content of the file
            filename: Name for the file
            
        Returns:
            Path to the saved file
        ÚwbNzFile saved to temp storage: zError saving temp file: )r   r   ÚwriteÚloggerÚinfoÚ	ExceptionÚerror)r9   r$   Ú	file_pathr   Úes        r   Úsave_temp_filezFileManager.save_temp_file~   së   è è € ð	Ý'¨(Ñ2ˆIõ �i Ñ&Ô&ð &¨!Ø—’˜Ñ%Ô%Ð%ð&ð &ð &ñ &ô &ð &ð &ð &ð &ð &ð &øøøð &ð &ð &ð &õ �KŠKÐA°xÐAÐAÑBÔBÐBØÐøåð 	ð 	ð 	Ý�LŠLÐ7°AÐ7Ð7Ñ8Ô8Ð8Øøøøøð	øøøs9   „A* žA ´A* Á AÁA* ÁAÁ!A* Á*
BÁ4BÂBÚ	temp_pathc                 ó(  — 	 t           | j        z  }t          j        t	          | ¦  «        t	          |¦  «        ¦  «         t
                               d| j        › �¦  «         |S # t          $ r#}t
                               d|› �¦  «         ‚ d}~ww xY w)zÞ
        Move a verified image from temp to permanent storage.
        
        Args:
            temp_path: Path to file in temp storage
            
        Returns:
            Path to file in permanent storage
        zFile moved to valid storage: z$Error moving file to valid storage: N)	r   r7   ÚshutilÚmoveÚstrr=   r>   r?   r@   )rD   Ú
valid_pathrB   s      r   Úmove_to_valid_storagez!FileManager.move_to_valid_storage˜   s‘   € ð	Ý)¨I¬NÑ:ˆJÝŒK�˜I™œ­¨J©¬Ñ8Ô8Ð8Ý�KŠKÐH¸	¼ÐHÐHÑIÔIÐIØÐøåð 	ð 	ð 	Ý�LŠLÐCÀÐCÐCÑDÔDÐDØøøøøð	øøøs   ‚A!A$ Á$
BÁ.BÂBrA   c                 ó
  — 	 |                       ¦   «         r8|                      ¦   «          t                               d| j        › �¦  «         dS dS # t
          $ r(}t                               d|› �¦  «         Y d}~dS d}~ww xY w)zÊ
        Delete a file from storage.
        
        Args:
            file_path: Path to file to delete
            
        Returns:
            True if deleted successfully, False otherwise
        zFile deleted: TFzError deleting file: N)ÚexistsÚunlinkr=   r>   r7   r?   r@   )rA   rB   s     r   Údelete_filezFileManager.delete_file­   s›   € ð		Ø×ÒÑ!Ô!ð Ø× Ò Ñ"Ô"Ð"Ý—’Ð=¨Y¬^Ð=Ð=Ñ>Ô>Ð>Ø�tØ�5øåð 	ð 	ð 	Ý�LŠLÐ4°Ð4Ð4Ñ5Ô5Ð5Ø�5�5�5�5�5øøøøð	øøøs   ‚A
A Á
BÁA=Á=Bc               ƒ   ób  K  — 	 	 t          j        ¦   «         t          t          ¬¦  «        z
  } t	          j        d¦  «        D ]ƒ}|                     ¦   «         rmt          j        |                     ¦   «         j	        ¦  «        }|| k     r<t                               |¦  «         t                               d|j        › �¦  «         Œ„t          j        d¦  «        ƒ d{V —† nN# t"          $ rA}t                               d|› �¦  «         t          j        d¦  «        ƒ d{V —† Y d}~nd}~ww xY w�Œ-)zx
        Delete temporary files older than the configured cleanup time.
        This runs as a background task.
        T)ÚhoursÚ*zCleaned up old temp file: i  Nz Error during temp file cleanup: )r   r3   r   r
   r   ÚglobÚis_fileÚfromtimestampÚstatÚst_mtimer   rN   r=   r>   r7   ÚasyncioÚsleepr?   r@   )Úcutoff_timerA   Ú
file_mtimerB   s       r   Úcleanup_old_temp_filesz"FileManager.cleanup_old_temp_filesÃ   sP  è è € ð	*ð*Ý&œl™nœn­yÕ?VÐ/WÑ/WÔ/WÑW�å!0Ô!5°cÑ!:Ô!:ð Wð W�IØ ×(Ò(Ñ*Ô*ð Wå%-Ô%;¸I¿NºNÑ<LÔ<LÔ<UÑ%VÔ%V˜
ð &¨Ò3Ð3Ý'×3Ò3°IÑ>Ô>Ð>Ý"ŸKšKÐ(UÀYÄ^Ð(UÐ(UÑVÔVÐVøõ ”m DÑ)Ô)Ð)Ð)Ð)Ð)Ð)Ð)Ð)Ð)øåð *ð *ð *Ý—’ÐCÀÐCÐCÑDÔDÐDÝ”m DÑ)Ô)Ð)Ð)Ð)Ð)Ð)Ð)Ð)Ð)Ð)Ð)Ð)Ð)øøøøð*øøøñ#	*s   …CC! Ã!
D,Ã+7D'Ä'D,c                  óÞ  — 	 t          t          j        d¦  «        ¦  «        } t          t          j        d¦  «        ¦  «        }t	          d„ | D ¦   «         ¦  «        }t	          d„ |D ¦   «         ¦  «        }t          | ¦  «        t          |¦  «        t          |dz  d¦  «        t          |dz  d¦  «        dœS # t          $ r)}t           	                    d|› �¦  «         i cY d}~S d}~ww xY w)	z~
        Get statistics about storage usage.
        
        Returns:
            Dictionary with storage statistics
        rQ   c              3   óp   K  — | ]1}|                      ¦   «         ¯|                     ¦   «         j        V — Œ2d S ©N©rS   rU   Úst_size©Ú.0r   s     r   ú	<genexpr>z0FileManager.get_storage_stats.<locals>.<genexpr>ê   s:   è è € ÐPÐP°ÀAÇIÂIÁKÄKÐP˜AŸFšF™HœHÔ,ÐPÐPÐPÐPÐPÐPr   c              3   óp   K  — | ]1}|                      ¦   «         ¯|                     ¦   «         j        V — Œ2d S r^   r_   ra   s     r   rc   z0FileManager.get_storage_stats.<locals>.<genexpr>ë   s:   è è € ÐRÐR°!ÀaÇiÂiÁkÄkÐR˜QŸVšV™XœXÔ-ÐRÐRÐRÐRÐRÐRr   i   é   )Útemp_files_countÚvalid_files_countÚtemp_storage_mbÚvalid_storage_mbzError getting storage stats: N)
Úlistr   rR   r   ÚsumÚlenÚroundr?   r=   r@   )Ú
temp_filesÚvalid_filesÚ	temp_sizeÚ
valid_sizerB   s        r   Úget_storage_statszFileManager.get_storage_statsÞ   s  € ð	Ý�oÔ2°3Ñ7Ô7Ñ8Ô8ˆJÝÕ/Ô4°SÑ9Ô9Ñ:Ô:ˆKåÐPÐP°jÐPÑPÔPÑPÔPˆIÝÐRÐR°{ÐRÑRÔRÑRÔRˆJõ %(¨
¡O¤OÝ%(¨Ñ%5Ô%5Ý#(¨°kÑ)BÀAÑ#FÔ#FÝ$)¨*¸Ñ*DÀaÑ$HÔ$Hð	ð ð øõ ð 	ð 	ð 	Ý�LŠLÐ<¸Ð<Ð<Ñ=Ô=Ð=ØˆIˆIˆIˆIˆIˆIøøøøð	øøøs   ‚B6B9 Â9
C,ÃC'Ã!C,Ã'C,)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú_image_hashesÚstaticmethodrH   r   Úboolr#   r&   r+   Úintr/   r8   Úbytesr   rC   rJ   rN   r[   Údictrr   r"   r   r   r   r      s  € € € € € ðð ð €Màð$¨ð $°ð $ð $ð $ñ „\ð$ð  ð
 sð 
¨tð 
ð 
ð 
ñ „\ð
ð ð¨ð °sð ð ð ñ „\ðð ð)¨#ð )°$ð )ð )ð )ñ „\ð)ð ð% cð %°Sð %¸Tð %ð %ð %ñ „\ð%ð ð*°Cð *¸Cð *ð *ð *ñ „\ð*ð ð¨5ð ¸Cð ÀDð ð ð ñ „\ðð2 ð¨ð °$ð ð ð ñ „\ðð( ð˜tð ¨ð ð ð ñ „\ðð* ð*ð *ñ „\ð*ð4 ð˜tð ð ð ñ „\ðð ð r   r   )rv   ÚosrF   r   Úpathlibr   r   r   rW   Útypingr   ÚloggingÚsysÚpathÚappendÚdirnameÚabspathÚ__file__Úconfigr   r   r	   r
   Ú	getLoggerrs   r=   r   r"   r   r   ú<module>r‰      sX  ððð ð 
€	€	€	Ø €€€Ø €€€Ø Ð Ð Ð Ð Ð Ø (Ð (Ð (Ð (Ð (Ð (Ð (Ð (Ø €€€Ø Ð Ð Ð Ð Ð Ø €€€ð €
€
€
Ø 	€	€	€	Ø „‡‚�”—’ ¤§¢°´·²ÀÑ0IÔ0IÑ JÔ JÑKÔKÑ LÔ LÐ Lðð ð ð ð ð ð ð ð ð ð ð ð 
ˆÔ	˜8Ñ	$Ô	$€ðYð Yð Yð Yð Yñ Yô Yð Yð Yð Yr   