File size: 2,458 Bytes
22087d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Utility functions for sandbox file operations."""

from datetime import datetime
from pathlib import Path
from typing import Optional
from daytona_sdk import AsyncSandbox
from core.utils.logger import logger
from core.utils.files_utils import normalize_filename


async def generate_unique_filename(sandbox: AsyncSandbox, base_path: str, original_filename: str) -> str:
    """
    Generate a unique filename by appending a timestamp if the file already exists.

    Also normalizes the filename to handle Unicode characters (e.g., macOS screenshot
    filenames with narrow no-break spaces).

    Args:
        sandbox: The sandbox instance
        base_path: The base directory path (e.g., /workspace/uploads)
        original_filename: The original filename

    Returns:
        A unique filename that doesn't conflict with existing files
    """
    # Normalize filename to handle Unicode characters (macOS screenshots, etc.)
    original_filename = normalize_filename(original_filename)

    # Parse filename and extension
    file_path = Path(original_filename)
    name_without_ext = file_path.stem
    extension = file_path.suffix
    
    # Try original filename first
    full_path = f"{base_path}/{original_filename}"
    
    try:
        # Check if file exists by trying to list it
        files = await sandbox.fs.list_files(base_path)
        existing_files = {f.name for f in files}
        
        if original_filename not in existing_files:
            return original_filename
        
        # File exists, generate unique filename with timestamp
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        counter = 1
        
        while True:
            unique_filename = f"{name_without_ext}_{timestamp}_{counter}{extension}"
            if unique_filename not in existing_files:
                logger.info(f"Generated unique filename: {unique_filename} (original: {original_filename})")
                return unique_filename
            counter += 1
            
    except Exception as e:
        # If the directory doesn't exist yet or there's an error, use original filename
        logger.debug(f"Could not check for existing files in {base_path}: {str(e)}")
        return original_filename


def get_uploads_directory() -> str:
    """
    Get the standard uploads directory path for sandbox file uploads.
    
    Returns:
        The path to the uploads directory
    """
    return "/workspace/uploads"