Просмотр исходного кода

fix import issue & windows path

tuanchris 5 месяцев назад
Родитель
Сommit
8bd63a742c
4 измененных файлов с 41 добавлено и 32 удалено
  1. 19 11
      main.py
  2. 3 15
      modules/core/pattern_manager.py
  3. 11 4
      static/js/base.js
  4. 8 2
      static/js/index.js

+ 19 - 11
main.py

@@ -44,7 +44,16 @@ logger = logging.getLogger(__name__)
 
 def normalize_file_path(file_path: str) -> str:
     """Normalize file path separators for consistent cross-platform handling."""
-    return file_path.replace('\\', '/')
+    # First normalize path separators
+    normalized = file_path.replace('\\', '/')
+    
+    # Remove any patterns directory prefixes that might be present
+    if normalized.startswith('./patterns/'):
+        normalized = normalized[11:]
+    elif normalized.startswith('patterns/'):
+        normalized = normalized[9:]
+    
+    return normalized
 
 @asynccontextmanager
 async def lifespan(app: FastAPI):
@@ -311,15 +320,8 @@ async def upload_theta_rho(file: UploadFile = File(...)):
 async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
     """Get theta-rho coordinates for animated preview."""
     try:
-        # Handle file paths that may include the patterns directory prefix
-        file_name = request.file_name
-        if file_name.startswith('./patterns/'):
-            file_name = file_name[11:]  # Remove './patterns/' prefix
-        elif file_name.startswith('patterns/'):
-            file_name = file_name[9:]   # Remove 'patterns/' prefix
-        
-        # Normalize file path for cross-platform compatibility
-        file_name = normalize_file_path(file_name)
+        # Normalize file path for cross-platform compatibility and remove prefixes
+        file_name = normalize_file_path(request.file_name)
         file_path = os.path.join(THETA_RHO_DIR, file_name)
         
         if not os.path.exists(file_path):
@@ -353,7 +355,9 @@ async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTa
         file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
         logger.info(f'Clear pattern file: {file_path}')
     if not file_path:
-        file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
+        # Normalize file path for cross-platform compatibility
+        normalized_file_name = normalize_file_path(request.file_name)
+        file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
     if not os.path.exists(file_path):
         logger.error(f'Theta-rho file not found: {file_path}')
         raise HTTPException(status_code=404, detail="File not found")
@@ -556,11 +560,15 @@ async def serve_preview(encoded_filename: str):
     # First try forward slash (most common case), then backslash if needed
     file_name = encoded_filename.replace('--', '/')
     
+    # Apply normalization to handle any remaining path prefixes
+    file_name = normalize_file_path(file_name)
+    
     # Check if the decoded path exists, if not try backslash decoding
     cache_path = get_cache_path(file_name)
     if not os.path.exists(cache_path):
         # Try with backslash for Windows paths
         file_name_backslash = encoded_filename.replace('--', '\\')
+        file_name_backslash = normalize_file_path(file_name_backslash)
         cache_path_backslash = get_cache_path(file_name_backslash)
         if os.path.exists(cache_path_backslash):
             file_name = file_name_backslash

+ 3 - 15
modules/core/pattern_manager.py

@@ -581,25 +581,13 @@ def get_status():
 
 async def broadcast_progress():
     """Background task to broadcast progress updates."""
-    from app import active_status_connections
+    from main import broadcast_status_update
     while True:
         # Send status updates regardless of pattern_lock state
         status = get_status()
-        disconnected = set()
         
-        # Create a copy of the set for iteration
-        active_connections = active_status_connections.copy()
-        
-        for websocket in active_connections:
-            try:
-                await websocket.send_json(status)
-            except Exception as e:
-                logger.warning(f"Failed to send status update: {e}")
-                disconnected.add(websocket)
-        
-        # Clean up disconnected clients
-        if disconnected:
-            active_status_connections.difference_update(disconnected)
+        # Use the existing broadcast function from main.py
+        await broadcast_status_update(status)
             
         # Check if we should stop broadcasting
         if not state.current_playlist:

+ 11 - 4
static/js/base.js

@@ -1,4 +1,11 @@
 // Player status bar functionality - Updated to fix logMessage errors
+
+// Helper function to normalize file paths for cross-platform compatibility
+function normalizeFilePath(filePath) {
+    if (!filePath) return '';
+    return filePath.replace('./patterns\\', '').replace('./patterns/', '').replace('patterns\\', '').replace('patterns/', '');
+}
+
 let ws = null;
 let reconnectAttempts = 0;
 const maxReconnectAttempts = 5;
@@ -66,7 +73,7 @@ function connectWebSocket() {
                 
                 // Check if current file has changed and reload preview data if needed
                 if (data.data.current_file) {
-                    const newFile = data.data.current_file.replace('./patterns/', '');
+                    const newFile = normalizeFilePath(data.data.current_file);
                     if (newFile !== currentPreviewFile) {
                         currentPreviewFile = newFile;
                         loadPlayerPreviewData(data.data.current_file);
@@ -395,7 +402,7 @@ async function loadPlayerPreviewData(pattern) {
         
         playerPreviewData = data.coordinates;
         // Store the filename for comparison
-        playerPreviewData.fileName = pattern.replace('./patterns/', '');
+        playerPreviewData.fileName = normalizeFilePath(pattern);
         
     } catch (error) {
         console.error(`Error loading player preview data: ${error.message}`);
@@ -626,7 +633,7 @@ async function exitModalSpeedEditMode(save = false) {
 // Helper function to clean up pattern names
 function getCleanPatternName(filePath) {
     if (!filePath) return '';
-    const fileName = filePath.replace('./patterns/', '');
+    const fileName = normalizeFilePath(filePath);
     return fileName.split('/').pop().replace('.thr', '');
 }
 
@@ -641,7 +648,7 @@ function syncModalControls(status) {
     // Pattern preview image
     const modalPatternPreviewImg = document.getElementById('modal-pattern-preview-img');
     if (modalPatternPreviewImg && status.current_file) {
-        const encodedFilename = status.current_file.replace('./patterns/', '').replace(/\//g, '--');
+        const encodedFilename = normalizeFilePath(status.current_file).replace(/[\\/]/g, '--');
         const previewUrl = `/preview/${encodedFilename}`;
         modalPatternPreviewImg.src = previewUrl;
     }

+ 8 - 2
static/js/index.js

@@ -1,5 +1,11 @@
 // Global variables
 let allPatterns = [];
+
+// Helper function to normalize file paths for cross-platform compatibility
+function normalizeFilePath(filePath) {
+    if (!filePath) return '';
+    return filePath.replace('./patterns\\', '').replace('./patterns/', '').replace('patterns\\', '').replace('patterns/', '');
+}
 let selectedPattern = null;
 let previewObserver = null;
 let currentBatch = 0;
@@ -1219,7 +1225,7 @@ function updateCurrentlyPlayingUI(status) {
 
     // Update file name display
     if (status.current_file) {
-        const fileName = status.current_file.replace('./patterns/', '');
+        const fileName = normalizeFilePath(status.current_file);
         fileNameElement.textContent = fileName;
     } else {
         fileNameElement.textContent = 'No pattern playing';
@@ -1229,7 +1235,7 @@ function updateCurrentlyPlayingUI(status) {
     const nextFileElement = document.getElementById('next-file');
     if (nextFileElement) {
         if (status.playlist && status.playlist.next_file) {
-            const nextFileName = status.playlist.next_file.replace('./patterns/', '');
+            const nextFileName = normalizeFilePath(status.playlist.next_file);
             nextFileElement.textContent = `(Next: ${nextFileName})`;
             nextFileElement.style.display = 'block';
         } else {