Skip to content

Commit

Permalink
Enhance watch history management by adding episode information for TV…
Browse files Browse the repository at this point in the history
… shows, improving error handling, and implementing functions to remove and clear watch history.
  • Loading branch information
chintan992 authored Dec 30, 2024
1 parent 0395fd6 commit f8ee4a0
Show file tree
Hide file tree
Showing 3 changed files with 157 additions and 66 deletions.
22 changes: 22 additions & 0 deletions src/components/UserFeatures.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,33 @@ const UserFeatures = () => {
<h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-2 line-clamp-2">
{item.title || item.name}
</h3>

{/* Enhanced TV show episode information */}
{item.media_type === 'tv' && (
<div className="mb-2 text-sm text-gray-600 dark:text-gray-400">
{item.season && item.episode && (
<p>
Season {item.season}, Episode {item.episode}
{item.episodeName && (
<span className="block italic">"{item.episodeName}"</span>
)}
</p>
)}
</div>
)}

{/* Watch date information */}
{item.watchedAt && (
<p className="text-sm text-gray-500 dark:text-gray-400 mb-2">
Watched: {new Date(item.watchedAt.seconds * 1000).toLocaleDateString()}
</p>
)}

{/* Content type indicator */}
<p className="text-sm text-gray-500 dark:text-gray-400 mb-2">
{item.media_type === 'movie' ? 'Movie' : 'TV Series'}
</p>

{removeFunction && (
<button
onClick={(e) => {
Expand Down
37 changes: 36 additions & 1 deletion src/components/WatchPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { getRecommendations } from '../api/tmdbApi';
import { getStoredVideoSource, setStoredVideoSource, saveTVProgress, getTVProgress } from '../utils/storage';
import VideoSection from './VideoSection';
import { VIDEO_SOURCES } from '../api';
import { useAuth } from '../context/AuthContext'; // Add this import

const API_KEY = process.env.REACT_APP_TMDB_API_KEY;
const BASE_URL = process.env.REACT_APP_TMDB_BASE_URL;
Expand Down Expand Up @@ -46,6 +47,7 @@ class ErrorBoundary extends React.Component {
function WatchPage() {
const { type, id } = useParams();
const navigate = useNavigate();
const { currentUser } = useAuth(); // Add this line
const [item, setItem] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
Expand Down Expand Up @@ -326,9 +328,42 @@ function WatchPage() {
}
};

const handleListItemClick = (item) => {
const handleListItemClick = async (item) => {
setShowUserLists(false); // Close the sidebar

// Add to watch history before navigating
try {
if (!currentUser) return; // Add check for currentUser

// Create history item with required fields
const historyItem = {
id: item.id,
title: item.title || item.name,
media_type: item.media_type,
poster_path: item.poster_path,
overview: item.overview
};

// For TV shows, add episode info and use it in addToWatchHistory call
if (item.media_type === 'tv') {
const episodeInfo = {
season: '1',
episode: '1',
name: item.name
};
await addToWatchHistory({...historyItem}, episodeInfo);
} else {
await addToWatchHistory({...historyItem});
}

console.log('Added to watch history from recommendations');
} catch (error) {
console.error('Error adding to watch history:', error);
}

// Navigate to the new item
navigate(`/watch/${item.media_type}/${item.id}`);

// Reload the page if we're already on the same item but with different parameters
if (item.id === Number(id)) {
window.location.reload();
Expand Down
164 changes: 99 additions & 65 deletions src/firebase/userService.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,80 +72,114 @@ export const getFavorites = async (userId) => {
};

// Watch History Functions
export const addToWatchHistory = async (userId, mediaItem, progress = 0) => {
const userRef = doc(db, 'users', userId);
const itemWithType = ensureMediaType(mediaItem);
const historyItem = {
...itemWithType,
watchedAt: new Date(),
progress: progress, // Store progress as percentage (0-100)
lastPlayedAt: new Date()
};

// Get current watch history
const docSnap = await getDoc(userRef);
const currentHistory = docSnap.data()?.watchHistory || [];

// Remove any existing entry for this media item
const filteredHistory = currentHistory.filter(
item => !(item.id === mediaItem.id && item.media_type === mediaItem.media_type)
);

// Add new history item at the beginning
await updateDoc(userRef, {
watchHistory: [historyItem, ...filteredHistory]
});
};
export const addToWatchHistory = async (userId, mediaItem, episodeInfo = null) => {
try {
const userRef = doc(db, 'users', userId);
const itemWithType = ensureMediaType(mediaItem);

// Create a simpler history item structure
const historyItem = {
id: mediaItem.id,
title: mediaItem.title || mediaItem.name,
media_type: itemWithType.media_type,
poster_path: mediaItem.poster_path,
watchedAt: new Date(),
overview: mediaItem.overview || '',
};

// Update watch progress
export const updateWatchProgress = async (userId, mediaItem, progress) => {
const userRef = doc(db, 'users', userId);
const docSnap = await getDoc(userRef);
const currentHistory = docSnap.data()?.watchHistory || [];

const updatedHistory = currentHistory.map(item => {
if (item.id === mediaItem.id && item.media_type === mediaItem.media_type) {
return {
...item,
progress: progress,
lastPlayedAt: new Date()
};
// Add TV show specific information if available
if (episodeInfo && itemWithType.media_type === 'tv') {
historyItem.season = episodeInfo.season;
historyItem.episode = episodeInfo.episode;
historyItem.episodeName = episodeInfo.name;
}
return item;
});

await updateDoc(userRef, {
watchHistory: updatedHistory
});

console.log('Adding to watch history:', historyItem); // Debug log

// Get current history
const docSnap = await getDoc(userRef);
const currentHistory = docSnap.data()?.watchHistory || [];

// Remove duplicate entries
const filteredHistory = currentHistory.filter(
item => item.id !== mediaItem.id ||
(item.media_type === 'tv' &&
(item.season !== episodeInfo?.season ||
item.episode !== episodeInfo?.episode))
);

// Add new item at the beginning
const newHistory = [historyItem, ...filteredHistory].slice(0, 100);

// Update the document
await updateDoc(userRef, {
watchHistory: newHistory
});

console.log('Watch history updated successfully'); // Debug log
return true;
} catch (error) {
console.error('Error adding to watch history:', error);
throw error;
}
};

// Get continue watching list (items with progress < 100%)
export const getContinueWatching = async (userId) => {
const userRef = doc(db, 'users', userId);
const docSnap = await getDoc(userRef);
const history = docSnap.data()?.watchHistory || [];

return history
.filter(item => (item.progress || 0) < 100) // Only include unwatched or partially watched
.sort((a, b) => b.lastPlayedAt - a.lastPlayedAt) // Sort by most recently played
.slice(0, 10); // Limit to 10 items
export const getWatchHistory = async (userId) => {
try {
const userRef = doc(db, 'users', userId);
const docSnap = await getDoc(userRef);
const history = docSnap.data()?.watchHistory || [];

// Ensure all items have required fields
return history.map(item => ({
...item,
title: item.title || item.name || 'Unknown Title',
media_type: item.media_type || 'movie',
watchedAt: item.watchedAt || new Date()
}));
} catch (error) {
console.error('Error getting watch history:', error);
return [];
}
};

// Add these new exports for watch history management
export const removeFromWatchHistory = async (userId, historyItem) => {
const userRef = doc(db, 'users', userId);
await updateDoc(userRef, {
watchHistory: arrayRemove(historyItem)
});
try {
const userRef = doc(db, 'users', userId);
const docSnap = await getDoc(userRef);
const currentHistory = docSnap.data()?.watchHistory || [];

// Filter out the item to remove
const newHistory = currentHistory.filter(item =>
!(item.id === historyItem.id &&
item.media_type === historyItem.media_type &&
item.season === historyItem.season &&
item.episode === historyItem.episode)
);

await updateDoc(userRef, {
watchHistory: newHistory
});

return true;
} catch (error) {
console.error('Error removing from watch history:', error);
throw error;
}
};

export const getWatchHistory = async (userId) => {
const userRef = doc(db, 'users', userId);
const docSnap = await getDoc(userRef);
const history = docSnap.data()?.watchHistory || [];
return history.map(item => ({
...ensureMediaType(item),
watchedAt: item.watchedAt
}));
export const clearWatchHistory = async (userId) => {
try {
const userRef = doc(db, 'users', userId);
await updateDoc(userRef, {
watchHistory: []
});
return true;
} catch (error) {
console.error('Error clearing watch history:', error);
throw error;
}
};

// Ratings and Reviews Functions
Expand Down

0 comments on commit f8ee4a0

Please sign in to comment.