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.
This commit is contained in:
tapframe 2025-06-21 02:02:46 +05:30
parent 12d625e8d6
commit 7086184eae
6 changed files with 23 additions and 56 deletions

View file

@ -36,11 +36,8 @@ const calculatePosterLayout = (screenWidth: number) => {
const usableWidth = availableWidth - 8; const usableWidth = availableWidth - 8;
const posterWidth = (usableWidth - (n - 1) * SPACING) / (n + 0.25); 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) { if (posterWidth >= MIN_POSTER_WIDTH && posterWidth <= MAX_POSTER_WIDTH) {
bestLayout = { numFullPosters: n, posterWidth }; bestLayout = { numFullPosters: n, posterWidth };
console.log(`[CatalogSection] Selected layout: ${n} full posters at ${posterWidth.toFixed(1)}px each`);
} }
} }

View file

@ -34,11 +34,8 @@ const calculatePosterLayout = (screenWidth: number) => {
const usableWidth = availableWidth - 8; const usableWidth = availableWidth - 8;
const posterWidth = (usableWidth - (n - 1) * SPACING) / (n + 0.25); 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) { if (posterWidth >= MIN_POSTER_WIDTH && posterWidth <= MAX_POSTER_WIDTH) {
bestLayout = { numFullPosters: n, posterWidth }; bestLayout = { numFullPosters: n, posterWidth };
console.log(`[ContentItem] Selected layout: ${n} full posters at ${posterWidth.toFixed(1)}px each`);
} }
} }

View file

@ -355,7 +355,6 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat
})); }));
} else { } else {
setLogoLoadError(true); setLogoLoadError(true);
console.warn(`[FeaturedContent] Logo prefetch failed, falling back to text: ${logoUrl}`);
} }
} }
}; };
@ -363,6 +362,20 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat
loadImages(); loadImages();
}, [featuredContent?.id, logoUrl]); }, [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) { if (!featuredContent) {
return <SkeletonFeatured />; return <SkeletonFeatured />;
} }
@ -412,10 +425,7 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat
contentFit="contain" contentFit="contain"
cachePolicy="memory-disk" cachePolicy="memory-disk"
transition={400} transition={400}
onError={() => { onError={onLogoLoadError}
console.warn(`[FeaturedContent] Logo failed to load: ${logoUrl}`);
setLogoLoadError(true);
}}
/> />
</Animated.View> </Animated.View>
) : ( ) : (
@ -473,14 +483,7 @@ const FeaturedContent = ({ featuredContent, isSaved, handleSaveToLibrary }: Feat
<TouchableOpacity <TouchableOpacity
style={styles.infoButton as ViewStyle} style={styles.infoButton as ViewStyle}
onPress={() => { onPress={handleInfoPress}
if (featuredContent) {
navigation.navigate('Metadata', {
id: featuredContent.id,
type: featuredContent.type
});
}
}}
activeOpacity={0.7} activeOpacity={0.7}
> >
<MaterialIcons name="info-outline" size={24} color={currentTheme.colors.white} /> <MaterialIcons name="info-outline" size={24} color={currentTheme.colors.white} />

View file

@ -215,6 +215,7 @@ export function useTraktAutosync(options: TraktAutosyncOptions) {
// ENHANCED DEDUPLICATION: Check if we've already stopped this session // ENHANCED DEDUPLICATION: Check if we've already stopped this session
// However, allow updates if the new progress is significantly higher (>5% improvement) // However, allow updates if the new progress is significantly higher (>5% improvement)
let isSignificantUpdate = false;
if (hasStopped.current) { if (hasStopped.current) {
const currentProgressPercent = duration > 0 ? (currentTime / duration) * 100 : 0; const currentProgressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;
const progressImprovement = currentProgressPercent - lastSyncProgress.current; 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`); 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 // Reset stopped flag to allow this significant update
hasStopped.current = false; hasStopped.current = false;
isSignificantUpdate = true;
} else { } else {
logger.log(`[TraktAutosync] Already stopped this session, skipping duplicate call (reason: ${reason})`); logger.log(`[TraktAutosync] Already stopped this session, skipping duplicate call (reason: ${reason})`);
return; return;
@ -230,7 +232,8 @@ export function useTraktAutosync(options: TraktAutosyncOptions) {
} }
// ENHANCED DEDUPLICATION: Prevent rapid successive calls (within 5 seconds) // 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})`); logger.log(`[TraktAutosync] Ignoring rapid successive stop call within 5 seconds (reason: ${reason})`);
return; return;
} }

View file

@ -202,8 +202,6 @@ const HomeScreen = () => {
items items
}; };
console.log(`[HomeScreen] Loaded catalog: ${displayName} at position ${currentIndex} (${items.length} items)`);
// Update the catalog at its specific position // Update the catalog at its specific position
setCatalogs(prevCatalogs => { setCatalogs(prevCatalogs => {
const newCatalogs = [...prevCatalogs]; const newCatalogs = [...prevCatalogs];
@ -226,7 +224,6 @@ const HomeScreen = () => {
} }
totalCatalogsRef.current = catalogIndex; totalCatalogsRef.current = catalogIndex;
console.log(`[HomeScreen] Starting to load ${catalogIndex} enabled catalogs progressively...`);
// Initialize catalogs array with proper length // Initialize catalogs array with proper length
setCatalogs(new Array(catalogIndex).fill(null)); setCatalogs(new Array(catalogIndex).fill(null));
@ -234,10 +231,8 @@ const HomeScreen = () => {
// Start all catalog loading promises but don't wait for them // Start all catalog loading promises but don't wait for them
// They will update the state progressively as they complete // They will update the state progressively as they complete
Promise.allSettled(catalogPromises).then(() => { Promise.allSettled(catalogPromises).then(() => {
console.log('[HomeScreen] All catalogs processed');
// Final cleanup: Filter out null values to get only successfully loaded catalogs // 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) { } catch (error) {
@ -388,37 +383,15 @@ const HomeScreen = () => {
}, [featuredContent, navigation]); }, [featuredContent, navigation]);
const refreshContinueWatching = useCallback(async () => { const refreshContinueWatching = useCallback(async () => {
console.log('[HomeScreen] Refreshing continue watching...');
if (continueWatchingRef.current) { if (continueWatchingRef.current) {
try { try {
const hasContent = await continueWatchingRef.current.refresh(); const hasContent = await continueWatchingRef.current.refresh();
console.log(`[HomeScreen] Continue watching has content: ${hasContent}`);
setHasContinueWatching(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) { } catch (error) {
console.error('[HomeScreen] Error refreshing continue watching:', error); console.error('[HomeScreen] Error refreshing continue watching:', error);
setHasContinueWatching(false); setHasContinueWatching(false);
} }
} else {
console.log('[HomeScreen] Continue watching ref is null');
} }
}, []); }, []);
@ -617,11 +590,8 @@ const calculatePosterLayout = (screenWidth: number) => {
const usableWidth = availableWidth - 8; const usableWidth = availableWidth - 8;
const posterWidth = (usableWidth - (n - 1) * SPACING) / (n + 0.25); 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) { if (posterWidth >= MIN_POSTER_WIDTH && posterWidth <= MAX_POSTER_WIDTH) {
bestLayout = { numFullPosters: n, posterWidth }; bestLayout = { numFullPosters: n, posterWidth };
console.log(`[HomeScreen] Selected layout: ${n} full posters at ${posterWidth.toFixed(1)}px each`);
} }
} }

View file

@ -535,13 +535,12 @@ class StremioService {
if (hasMetaSupport) { if (hasMetaSupport) {
try { try {
logger.log(`HTTP GET: ${wouldBeUrl} (preferred addon: ${preferredAddon.name})`);
const response = await this.retryRequest(async () => { const response = await this.retryRequest(async () => {
return await axios.get(wouldBeUrl, { timeout: 10000 }); return await axios.get(wouldBeUrl, { timeout: 10000 });
}); });
if (response.data && response.data.meta) { if (response.data && response.data.meta) {
logger.log(`✅ Metadata fetched successfully from preferred addon: ${wouldBeUrl}`);
return response.data.meta; return response.data.meta;
} }
} catch (error) { } catch (error) {
@ -564,13 +563,12 @@ class StremioService {
for (const baseUrl of cinemetaUrls) { for (const baseUrl of cinemetaUrls) {
try { try {
const url = `${baseUrl}/meta/${type}/${id}.json`; const url = `${baseUrl}/meta/${type}/${id}.json`;
logger.log(`HTTP GET: ${url}`);
const response = await this.retryRequest(async () => { const response = await this.retryRequest(async () => {
return await axios.get(url, { timeout: 10000 }); return await axios.get(url, { timeout: 10000 });
}); });
if (response.data && response.data.meta) { if (response.data && response.data.meta) {
logger.log(`✅ Metadata fetched successfully from: ${url}`);
return response.data.meta; return response.data.meta;
} }
} catch (error) { } catch (error) {
@ -619,7 +617,6 @@ class StremioService {
}); });
if (response.data && response.data.meta) { if (response.data && response.data.meta) {
logger.log(`✅ Metadata fetched successfully from: ${url}`);
return response.data.meta; return response.data.meta;
} }
} catch (error) { } catch (error) {