File size: 3,220 Bytes
e92e423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""

檔案處理工具模組

"""

import os
import shutil
import tempfile
from typing import Optional, List
import logging

logger = logging.getLogger(__name__)

class FileHandler:
    """檔案處理工具類別"""
    
    def __init__(self, temp_dir: str = "temp", output_dir: str = "output"):
        self.temp_dir = temp_dir
        self.output_dir = output_dir
        self._ensure_directories()
    
    def _ensure_directories(self):
        """確保必要目錄存在"""
        for directory in [self.temp_dir, self.output_dir]:
            os.makedirs(directory, exist_ok=True)
    
    def save_uploaded_file(self, file_path: str, file_type: str = "unknown") -> str:
        """

        儲存上傳的檔案到臨時目錄

        

        Args:

            file_path: 原始檔案路徑

            file_type: 檔案類型 (image, video, audio, etc.)

            

        Returns:

            新的檔案路徑

        """
        try:
            # 生成新的檔案名
            filename = os.path.basename(file_path)
            name, ext = os.path.splitext(filename)
            
            # 創建臨時檔案
            temp_file = tempfile.NamedTemporaryFile(
                delete=False,
                suffix=ext,
                dir=self.temp_dir,
                prefix=f"{file_type}_"
            )
            temp_path = temp_file.name
            temp_file.close()
            
            # 複製檔案
            shutil.copy2(file_path, temp_path)
            
            logger.info(f"檔案已儲存到: {temp_path}")
            return temp_path
            
        except Exception as e:
            logger.error(f"儲存檔案失敗: {e}")
            raise
    
    def cleanup_temp_files(self, file_paths: List[str]):
        """清理臨時檔案"""
        for file_path in file_paths:
            try:
                if os.path.exists(file_path):
                    os.remove(file_path)
                    logger.info(f"已刪除臨時檔案: {file_path}")
            except Exception as e:
                logger.error(f"刪除檔案失敗: {e}")
    
    def get_file_info(self, file_path: str) -> dict:
        """獲取檔案資訊"""
        try:
            stat = os.stat(file_path)
            return {
                "size": stat.st_size,
                "modified": stat.st_mtime,
                "extension": os.path.splitext(file_path)[1].lower(),
                "basename": os.path.basename(file_path)
            }
        except Exception as e:
            logger.error(f"獲取檔案資訊失敗: {e}")
            return {}
    
    def is_valid_file_type(self, file_path: str, allowed_types: List[str]) -> bool:
        """檢查檔案類型是否有效"""
        file_info = self.get_file_info(file_path)
        extension = file_info.get("extension", "")
        return extension in allowed_types
    
    def validate_file_size(self, file_path: str, max_size: int) -> bool:
        """檢查檔案大小是否有效"""
        file_info = self.get_file_info(file_path)
        size = file_info.get("size", 0)
        return size <= max_size