|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import platform |
| 4 | +from pathlib import Path |
| 5 | +from typing import Dict, List |
| 6 | + |
| 7 | +from fastapi import APIRouter, HTTPException |
| 8 | +from fastapi.responses import JSONResponse |
| 9 | + |
| 10 | +from .index import check_album_lock |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | +filetree_router = APIRouter() |
| 14 | + |
| 15 | +# On Windows, allow browsing all drives; on Unix, use a root directory |
| 16 | +if platform.system() == "Windows": |
| 17 | + ROOT_DIR = None # Special case for Windows - browse all drives |
| 18 | +else: |
| 19 | + ROOT_DIR = os.environ.get("PHOTOMAP_ALBUM_ROOT", "/") |
| 20 | + |
| 21 | + |
| 22 | +def get_windows_drives(): |
| 23 | + """Get list of available Windows drives""" |
| 24 | + import string |
| 25 | + |
| 26 | + drives = [] |
| 27 | + for letter in string.ascii_uppercase: |
| 28 | + drive_path = Path(f"{letter}:\\") |
| 29 | + if drive_path.exists(): |
| 30 | + try: |
| 31 | + # Test if we can access the drive |
| 32 | + list(drive_path.iterdir()) |
| 33 | + drives.append( |
| 34 | + { |
| 35 | + "name": f"{letter}: Drive", |
| 36 | + "path": str(drive_path.resolve()), # Return absolute path |
| 37 | + "hasChildren": True, |
| 38 | + } |
| 39 | + ) |
| 40 | + except (OSError, PermissionError): |
| 41 | + # Skip inaccessible drives |
| 42 | + continue |
| 43 | + return drives |
| 44 | + |
| 45 | + |
| 46 | +def is_path_safe(path_str: str) -> bool: |
| 47 | + """Check if path is safe to access""" |
| 48 | + if platform.system() == "Windows": |
| 49 | + # On Windows, allow any valid drive path |
| 50 | + try: |
| 51 | + path = Path(path_str) |
| 52 | + # Must be absolute and exist |
| 53 | + return path.is_absolute() and path.exists() |
| 54 | + except: |
| 55 | + return False |
| 56 | + else: |
| 57 | + # On Unix, check if it's within ROOT_DIR or if it's an absolute path we want to allow |
| 58 | + try: |
| 59 | + path = Path(path_str).resolve() |
| 60 | + |
| 61 | + # If ROOT_DIR is set, check if path is within it |
| 62 | + if ROOT_DIR: |
| 63 | + root_path = Path(ROOT_DIR).resolve() |
| 64 | + # Allow paths within ROOT_DIR or absolute paths for browsing |
| 65 | + return path.is_relative_to(root_path) or path.exists() |
| 66 | + else: |
| 67 | + # If no ROOT_DIR restriction, allow any existing absolute path |
| 68 | + return path.exists() |
| 69 | + except: |
| 70 | + return False |
| 71 | + |
| 72 | + |
| 73 | +@filetree_router.get("/filetree/directories", tags=["FileTree"]) |
| 74 | +async def get_directories(path: str = "", show_hidden: bool = False): |
| 75 | + """Get directories in the specified path""" |
| 76 | + check_album_lock() # May raise a 403 exception |
| 77 | + |
| 78 | + # --- Path parsing and validation --- |
| 79 | + try: |
| 80 | + # Handle Windows drives |
| 81 | + if platform.system() == "Windows" and not path: |
| 82 | + drives = get_windows_drives() |
| 83 | + return JSONResponse( |
| 84 | + content={"currentPath": "", "directories": drives, "isRoot": True} |
| 85 | + ) |
| 86 | + |
| 87 | + # Handle regular directory browsing |
| 88 | + if platform.system() == "Windows": |
| 89 | + if path.endswith(":"): |
| 90 | + dir_path = Path(f"{path}\\") |
| 91 | + else: |
| 92 | + dir_path = Path(path) |
| 93 | + else: |
| 94 | + assert ROOT_DIR is not None |
| 95 | + if not path: |
| 96 | + dir_path = Path(ROOT_DIR) |
| 97 | + else: |
| 98 | + if Path(path).is_absolute(): |
| 99 | + dir_path = Path(path) |
| 100 | + else: |
| 101 | + dir_path = Path(ROOT_DIR) / path |
| 102 | + |
| 103 | + # Security check |
| 104 | + if not is_path_safe(str(dir_path)): |
| 105 | + raise HTTPException(status_code=403, detail="Access denied") |
| 106 | + |
| 107 | + # If the path doesn't exist or isn't a directory, return 404 |
| 108 | + if not dir_path.exists() or not dir_path.is_dir(): |
| 109 | + raise HTTPException(status_code=404, detail="Directory not found") |
| 110 | + |
| 111 | + except Exception as e: |
| 112 | + logger.error(f"Invalid path or path error: {e}") |
| 113 | + raise HTTPException(status_code=404, detail="Invalid or non-existent directory") |
| 114 | + |
| 115 | + # --- Directory listing logic --- |
| 116 | + try: |
| 117 | + # Try to trigger automount for autofs directories |
| 118 | + logger.info("calling os.listdir to trigger automount if needed") |
| 119 | + try: |
| 120 | + os.listdir(str(dir_path)) |
| 121 | + except Exception: |
| 122 | + pass |
| 123 | + |
| 124 | + directories = [] |
| 125 | + logger.info("Listing directories in: %s", dir_path) |
| 126 | + for entry in sorted(dir_path.iterdir()): |
| 127 | + if entry.is_dir(): |
| 128 | + if not show_hidden and entry.name.startswith("."): |
| 129 | + continue |
| 130 | + try: |
| 131 | + abs_path = str(entry.resolve()) |
| 132 | + has_children = False |
| 133 | + try: |
| 134 | + has_children = any(child.is_dir() for child in entry.iterdir()) |
| 135 | + except (OSError, PermissionError): |
| 136 | + pass |
| 137 | + directories.append( |
| 138 | + { |
| 139 | + "name": entry.name, |
| 140 | + "path": abs_path, |
| 141 | + "hasChildren": has_children, |
| 142 | + } |
| 143 | + ) |
| 144 | + except (OSError, PermissionError): |
| 145 | + continue |
| 146 | + |
| 147 | + current_display = str(dir_path.resolve()) |
| 148 | + logger.info( |
| 149 | + f"Current directory: {current_display}, found {len(directories)} subdirectories" |
| 150 | + ) |
| 151 | + return JSONResponse( |
| 152 | + content={ |
| 153 | + "currentPath": current_display, |
| 154 | + "directories": directories, |
| 155 | + "isRoot": not path, |
| 156 | + } |
| 157 | + ) |
| 158 | + except Exception as e: |
| 159 | + logger.error(f"FileTree error: {e}") |
| 160 | + return JSONResponse(content={"error": str(e)}, status_code=500) |
| 161 | + |
| 162 | + |
| 163 | +@filetree_router.get("/filetree/home", tags=["FileTree"]) |
| 164 | +async def get_home_directory(): |
| 165 | + """Get the user's home directory path""" |
| 166 | + try: |
| 167 | + home_path = str(Path.home().resolve()) |
| 168 | + return JSONResponse(content={"homePath": home_path}) |
| 169 | + except Exception as e: |
| 170 | + logger.error(f"Error getting home directory: {e}") |
| 171 | + return JSONResponse(content={"error": str(e)}, status_code=500) |
0 commit comments