From 7086184eaeaa106e0786b7d9037eaac46e6c9e98 Mon Sep 17 00:00:00 2001 From: tapframe Date: Sat, 21 Jun 2025 02:02:46 +0530 Subject: [PATCH] Refactor logging and error handling in various components for improved clarity and performance This update removes unnecessary console logs from the CatalogSection, ContentItem, and HomeScreen components to streamline the code and enhance performance. Additionally, it introduces a dedicated error handling function for logo loading in the FeaturedContent component, improving code organization and readability. The useTraktAutosync hook is also updated to enhance deduplication logic, allowing significant progress updates even after a session has stopped, thereby improving session management. --- src/components/home/CatalogSection.tsx | 3 --- src/components/home/ContentItem.tsx | 3 --- src/components/home/FeaturedContent.tsx | 29 ++++++++++++---------- src/hooks/useTraktAutosync.ts | 5 +++- src/screens/HomeScreen.tsx | 32 +------------------------ src/services/stremioService.ts | 7 ++---- 6 files changed, 23 insertions(+), 56 deletions(-) diff --git a/src/components/home/CatalogSection.tsx b/src/components/home/CatalogSection.tsx index 1a2987d..78b25f8 100644 --- a/src/components/home/CatalogSection.tsx +++ b/src/components/home/CatalogSection.tsx @@ -36,11 +36,8 @@ const calculatePosterLayout = (screenWidth: number) => { const usableWidth = availableWidth - 8; const posterWidth = (usableWidth - (n - 1) * SPACING) / (n + 0.25); - console.log(`[CatalogSection] Testing ${n} posters: width=${posterWidth.toFixed(1)}px, screen=${screenWidth}px`); - if (posterWidth >= MIN_POSTER_WIDTH && posterWidth <= MAX_POSTER_WIDTH) { bestLayout = { numFullPosters: n, posterWidth }; - console.log(`[CatalogSection] Selected layout: ${n} full posters at ${posterWidth.toFixed(1)}px each`); } } diff --git a/src/components/home/ContentItem.tsx b/src/components/home/ContentItem.tsx index 0483bc2..b8d6bc6 100644 --- a/src/components/home/ContentItem.tsx +++ b/src/components/home/ContentItem.tsx @@ -34,11 +34,8 @@ const calculatePosterLayout = (screenWidth: number) => { const usableWidth = availableWidth - 8; const posterWidth = (usableWidth - (n - 1) * SPACING) / (n + 0.25); - console.log(`[ContentItem] Testing ${n} posters: width=${posterWidth.toFixed(1)}px, screen=${screenWidth}px`); - if (posterWidth >= MIN_POSTER_WIDTH && posterWidth <= MAX_POSTER_WIDTH) { bestLayout = { numFullPosters: n, posterWidth }; - console.log(`[ContentItem] Selected layout: ${n} full posters at ${posterWidth.toFixed(1)}px each`); } } diff --git a/src/components/home/FeaturedContent.tsx b/src/components/home/FeaturedContent.tsx index 89389d8..f35fd66 100644 --- a/src/components/home/FeaturedContent.tsx +++ b/src/components/home/FeaturedContent.tsx @@ -355,7 +355,6 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat })); } else { setLogoLoadError(true); - console.warn(`[FeaturedContent] Logo prefetch failed, falling back to text: ${logoUrl}`); } } }; @@ -363,6 +362,20 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat loadImages(); }, [featuredContent?.id, logoUrl]); + const onLogoLoadError = () => { + setLogoLoaded(true); // Treat error as "loaded" to stop spinner + setLogoError(true); + }; + + const handleInfoPress = () => { + if (featuredContent) { + navigation.navigate('Metadata', { + id: featuredContent.id, + type: featuredContent.type + }); + } + }; + if (!featuredContent) { return ; } @@ -412,10 +425,7 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat contentFit="contain" cachePolicy="memory-disk" transition={400} - onError={() => { - console.warn(`[FeaturedContent] Logo failed to load: ${logoUrl}`); - setLogoLoadError(true); - }} + onError={onLogoLoadError} /> ) : ( @@ -473,14 +483,7 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat { - if (featuredContent) { - navigation.navigate('Metadata', { - id: featuredContent.id, - type: featuredContent.type - }); - } - }} + onPress={handleInfoPress} activeOpacity={0.7} > diff --git a/src/hooks/useTraktAutosync.ts b/src/hooks/useTraktAutosync.ts index 299efd4..8955525 100644 --- a/src/hooks/useTraktAutosync.ts +++ b/src/hooks/useTraktAutosync.ts @@ -215,6 +215,7 @@ export function useTraktAutosync(options: TraktAutosyncOptions) { // ENHANCED DEDUPLICATION: Check if we've already stopped this session // However, allow updates if the new progress is significantly higher (>5% improvement) + let isSignificantUpdate = false; if (hasStopped.current) { const currentProgressPercent = duration > 0 ? (currentTime / duration) * 100 : 0; const progressImprovement = currentProgressPercent - lastSyncProgress.current; @@ -223,6 +224,7 @@ export function useTraktAutosync(options: TraktAutosyncOptions) { logger.log(`[TraktAutosync] Session already stopped, but progress improved significantly by ${progressImprovement.toFixed(1)}% (${lastSyncProgress.current.toFixed(1)}% → ${currentProgressPercent.toFixed(1)}%), allowing update`); // Reset stopped flag to allow this significant update hasStopped.current = false; + isSignificantUpdate = true; } else { logger.log(`[TraktAutosync] Already stopped this session, skipping duplicate call (reason: ${reason})`); return; @@ -230,7 +232,8 @@ export function useTraktAutosync(options: TraktAutosyncOptions) { } // ENHANCED DEDUPLICATION: Prevent rapid successive calls (within 5 seconds) - if (now - lastStopCall.current < 5000) { + // Bypass for significant updates + if (!isSignificantUpdate && now - lastStopCall.current < 5000) { logger.log(`[TraktAutosync] Ignoring rapid successive stop call within 5 seconds (reason: ${reason})`); return; } diff --git a/src/screens/HomeScreen.tsx b/src/screens/HomeScreen.tsx index 1601483..75ed40a 100644 --- a/src/screens/HomeScreen.tsx +++ b/src/screens/HomeScreen.tsx @@ -202,8 +202,6 @@ const HomeScreen = () => { items }; - console.log(`[HomeScreen] Loaded catalog: ${displayName} at position ${currentIndex} (${items.length} items)`); - // Update the catalog at its specific position setCatalogs(prevCatalogs => { const newCatalogs = [...prevCatalogs]; @@ -226,7 +224,6 @@ const HomeScreen = () => { } totalCatalogsRef.current = catalogIndex; - console.log(`[HomeScreen] Starting to load ${catalogIndex} enabled catalogs progressively...`); // Initialize catalogs array with proper length setCatalogs(new Array(catalogIndex).fill(null)); @@ -234,10 +231,8 @@ const HomeScreen = () => { // Start all catalog loading promises but don't wait for them // They will update the state progressively as they complete Promise.allSettled(catalogPromises).then(() => { - console.log('[HomeScreen] All catalogs processed'); - // Final cleanup: Filter out null values to get only successfully loaded catalogs - setCatalogs(prevCatalogs => prevCatalogs.filter(catalog => catalog !== null)); + setCatalogs(prevCatalogs => prevCatalogs.filter(catalog => catalog !== null)); }); } catch (error) { @@ -388,37 +383,15 @@ const HomeScreen = () => { }, [featuredContent, navigation]); const refreshContinueWatching = useCallback(async () => { - console.log('[HomeScreen] Refreshing continue watching...'); if (continueWatchingRef.current) { try { const hasContent = await continueWatchingRef.current.refresh(); - console.log(`[HomeScreen] Continue watching has content: ${hasContent}`); setHasContinueWatching(hasContent); - // Debug: Let's check what's in storage - const allProgress = await storageService.getAllWatchProgress(); - console.log('[HomeScreen] All watch progress in storage:', Object.keys(allProgress).length, 'items'); - console.log('[HomeScreen] Watch progress items:', allProgress); - - // Check if any items are being filtered out due to >85% progress - let filteredCount = 0; - for (const [key, progress] of Object.entries(allProgress)) { - const progressPercent = (progress.currentTime / progress.duration) * 100; - if (progressPercent >= 85) { - filteredCount++; - console.log(`[HomeScreen] Filtered out ${key}: ${progressPercent.toFixed(1)}% complete`); - } else { - console.log(`[HomeScreen] Valid progress ${key}: ${progressPercent.toFixed(1)}% complete`); - } - } - console.log(`[HomeScreen] Filtered out ${filteredCount} completed items`); - } catch (error) { console.error('[HomeScreen] Error refreshing continue watching:', error); setHasContinueWatching(false); } - } else { - console.log('[HomeScreen] Continue watching ref is null'); } }, []); @@ -617,11 +590,8 @@ const calculatePosterLayout = (screenWidth: number) => { const usableWidth = availableWidth - 8; const posterWidth = (usableWidth - (n - 1) * SPACING) / (n + 0.25); - console.log(`[HomeScreen] Testing ${n} posters: width=${posterWidth.toFixed(1)}px, screen=${screenWidth}px`); - if (posterWidth >= MIN_POSTER_WIDTH && posterWidth <= MAX_POSTER_WIDTH) { bestLayout = { numFullPosters: n, posterWidth }; - console.log(`[HomeScreen] Selected layout: ${n} full posters at ${posterWidth.toFixed(1)}px each`); } } diff --git a/src/services/stremioService.ts b/src/services/stremioService.ts index 6415c14..bec8078 100644 --- a/src/services/stremioService.ts +++ b/src/services/stremioService.ts @@ -535,13 +535,12 @@ class StremioService { if (hasMetaSupport) { try { - logger.log(`HTTP GET: ${wouldBeUrl} (preferred addon: ${preferredAddon.name})`); + const response = await this.retryRequest(async () => { return await axios.get(wouldBeUrl, { timeout: 10000 }); }); if (response.data && response.data.meta) { - logger.log(`✅ Metadata fetched successfully from preferred addon: ${wouldBeUrl}`); return response.data.meta; } } catch (error) { @@ -564,13 +563,12 @@ class StremioService { for (const baseUrl of cinemetaUrls) { try { const url = `${baseUrl}/meta/${type}/${id}.json`; - logger.log(`HTTP GET: ${url}`); + const response = await this.retryRequest(async () => { return await axios.get(url, { timeout: 10000 }); }); if (response.data && response.data.meta) { - logger.log(`✅ Metadata fetched successfully from: ${url}`); return response.data.meta; } } catch (error) { @@ -619,7 +617,6 @@ class StremioService { }); if (response.data && response.data.meta) { - logger.log(`✅ Metadata fetched successfully from: ${url}`); return response.data.meta; } } catch (error) {