Implement full Couch Potato movie & TV tracking app

Add all 10 milestones: Drizzle ORM + SQLite database with WAL mode,
Better Auth email/password authentication, TMDB API integration for
search and metadata import, TV season/episode caching, user tracking
(watchlist/status/watches/ratings with auto-transitions), discovery
feeds (continue watching, library, recommendations), US streaming
availability via TMDB providers, background job scheduler with
instrumentation hook, and dark cinema-themed frontend with DM Serif
Display + DM Sans typography and amber accent design system.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 14:42:13 -05:00
co-authored by Claude Opus 4.6
parent 1b0ca5431a
commit b02ff1cdc1
65 changed files with 4994 additions and 382 deletions
+55
View File
@@ -0,0 +1,55 @@
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { availabilityOffers, titles } from "@/lib/db/schema";
import { getWatchProviders } from "@/lib/tmdb/client";
export async function refreshAvailability(titleId: string) {
const title = db.select().from(titles).where(eq(titles.id, titleId)).get();
if (!title) return;
const data = await getWatchProviders(title.tmdbId, title.type);
const us = data.results?.US;
if (!us) return;
const now = new Date();
const offerTypes = ["flatrate", "rent", "buy", "free", "ads"] as const;
// Delete existing offers for this title+region
db.delete(availabilityOffers)
.where(
and(
eq(availabilityOffers.titleId, titleId),
eq(availabilityOffers.region, "US"),
),
)
.run();
for (const offerType of offerTypes) {
const providers = us[offerType];
if (!providers) continue;
for (const p of providers) {
db.insert(availabilityOffers)
.values({
titleId,
region: "US",
providerId: p.provider_id,
providerName: p.provider_name,
logoPath: p.logo_path,
offerType,
link: us.link ?? null,
lastFetchedAt: now,
})
.onConflictDoNothing()
.run();
}
}
}
export function getAvailability(titleId: string) {
return db
.select()
.from(availabilityOffers)
.where(eq(availabilityOffers.titleId, titleId))
.all();
}
+242
View File
@@ -0,0 +1,242 @@
import { and, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import {
availabilityOffers,
episodes,
seasons,
titleRecommendations,
titles,
userEpisodeWatches,
userRatings,
userTitleStatus,
} from "@/lib/db/schema";
export interface ContinueWatchingItem {
title: {
id: string;
title: string;
posterPath: string | null;
type: string;
};
nextEpisode: {
id: string;
seasonNumber: number;
episodeNumber: number;
name: string | null;
} | null;
lastWatchedAt: Date | null;
}
export function getContinueWatchingFeed(
userId: string,
): ContinueWatchingItem[] {
// Get in-progress TV shows
const inProgress = db
.select({
titleId: userTitleStatus.titleId,
updatedAt: userTitleStatus.updatedAt,
})
.from(userTitleStatus)
.where(
and(
eq(userTitleStatus.userId, userId),
eq(userTitleStatus.status, "in_progress"),
),
)
.all();
const items: ContinueWatchingItem[] = [];
const today = new Date().toISOString().slice(0, 10);
for (const row of inProgress) {
const title = db
.select()
.from(titles)
.where(and(eq(titles.id, row.titleId), eq(titles.type, "tv")))
.get();
if (!title) continue;
// Get all seasons for this title, ordered
const titleSeasons = db
.select()
.from(seasons)
.where(eq(seasons.titleId, title.id))
.orderBy(seasons.seasonNumber)
.all();
// Find first unwatched episode
let nextEpisode: ContinueWatchingItem["nextEpisode"] = null;
let lastWatchedAt: Date | null = null;
// Get most recent watch for this show
for (const s of titleSeasons) {
const eps = db
.select()
.from(episodes)
.where(eq(episodes.seasonId, s.id))
.orderBy(episodes.episodeNumber)
.all();
for (const ep of eps) {
const watch = db
.select()
.from(userEpisodeWatches)
.where(
and(
eq(userEpisodeWatches.userId, userId),
eq(userEpisodeWatches.episodeId, ep.id),
),
)
.get();
if (watch) {
if (!lastWatchedAt || watch.watchedAt > lastWatchedAt) {
lastWatchedAt = watch.watchedAt;
}
} else if (!nextEpisode) {
// Skip episodes not yet aired
if (ep.airDate && ep.airDate > today) continue;
nextEpisode = {
id: ep.id,
seasonNumber: s.seasonNumber,
episodeNumber: ep.episodeNumber,
name: ep.name,
};
}
}
}
if (nextEpisode) {
items.push({
title: {
id: title.id,
title: title.title,
posterPath: title.posterPath,
type: title.type,
},
nextEpisode,
lastWatchedAt,
});
}
}
// Sort by most recent watch
items.sort((a, b) => {
const aTime = a.lastWatchedAt?.getTime() ?? 0;
const bTime = b.lastWatchedAt?.getTime() ?? 0;
return bTime - aTime;
});
return items;
}
// biome-ignore lint/correctness/noUnusedFunctionParameters: days reserved for future date filtering
export function getNewAvailableFeed(userId: string, days = 14) {
// Get titles the user has in any status that have availability offers
// and recent release/air dates
const results = db
.select({
titleId: titles.id,
title: titles.title,
type: titles.type,
posterPath: titles.posterPath,
releaseDate: titles.releaseDate,
firstAirDate: titles.firstAirDate,
popularity: titles.popularity,
})
.from(titles)
.innerJoin(
userTitleStatus,
and(
eq(userTitleStatus.titleId, titles.id),
eq(userTitleStatus.userId, userId),
),
)
.where(
sql`EXISTS (SELECT 1 FROM ${availabilityOffers} WHERE ${availabilityOffers.titleId} = ${titles.id})`,
)
.orderBy(desc(titles.popularity))
.limit(20)
.all();
return results;
}
export function getRecommendationsFeed(userId: string) {
// Get recommendations from user's highly-rated or completed titles
const userCompletedOrRated = db
.select({ titleId: userTitleStatus.titleId })
.from(userTitleStatus)
.where(
and(
eq(userTitleStatus.userId, userId),
eq(userTitleStatus.status, "completed"),
),
)
.all()
.map((r) => r.titleId);
const ratedIds = db
.select({ titleId: userRatings.titleId })
.from(userRatings)
.where(
and(eq(userRatings.userId, userId), sql`${userRatings.ratingStars} >= 4`),
)
.all()
.map((r) => r.titleId);
const sourceIds = [...new Set([...userCompletedOrRated, ...ratedIds])];
if (sourceIds.length === 0) return [];
// Get all tracked title IDs to exclude
const trackedIds = new Set(
db
.select({ titleId: userTitleStatus.titleId })
.from(userTitleStatus)
.where(eq(userTitleStatus.userId, userId))
.all()
.map((r) => r.titleId),
);
const recs: Map<string, { titleId: string; score: number }> = new Map();
for (const sourceId of sourceIds) {
const recRows = db
.select({
recommendedTitleId: titleRecommendations.recommendedTitleId,
rank: titleRecommendations.rank,
})
.from(titleRecommendations)
.where(eq(titleRecommendations.titleId, sourceId))
.all();
for (const rec of recRows) {
if (trackedIds.has(rec.recommendedTitleId)) continue;
const existing = recs.get(rec.recommendedTitleId);
const score = 100 - rec.rank;
if (existing) {
existing.score += score;
} else {
recs.set(rec.recommendedTitleId, {
titleId: rec.recommendedTitleId,
score,
});
}
}
}
const sorted = [...recs.values()]
.sort((a, b) => b.score - a.score)
.slice(0, 20);
return sorted
.map((r) => {
const title = db
.select()
.from(titles)
.where(eq(titles.id, r.titleId))
.get();
return title;
})
.filter(Boolean);
}
+344
View File
@@ -0,0 +1,344 @@
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import {
episodes,
seasons,
titleRecommendations,
titles,
} from "@/lib/db/schema";
import {
getMovieDetails,
getRecommendations,
getSimilar,
getTvDetails,
getTvSeasonDetails,
} from "@/lib/tmdb/client";
import { refreshAvailability } from "./availability";
export async function importTitle(tmdbId: number, type: "movie" | "tv") {
const existing = db
.select()
.from(titles)
.where(eq(titles.tmdbId, tmdbId))
.get();
if (existing) return existing;
const now = new Date();
if (type === "movie") {
const movie = await getMovieDetails(tmdbId);
const row = db
.insert(titles)
.values({
tmdbId: movie.id,
type: "movie",
title: movie.title,
originalTitle: movie.original_title,
overview: movie.overview,
releaseDate: movie.release_date || null,
posterPath: movie.poster_path,
backdropPath: movie.backdrop_path,
popularity: movie.popularity,
voteAverage: movie.vote_average,
voteCount: movie.vote_count,
status: movie.status,
lastFetchedAt: now,
})
.returning()
.get();
// Fire-and-forget: fetch availability & recommendations
refreshAvailability(row.id).catch(() => {});
refreshRecommendations(row.id).catch(() => {});
return row;
}
const show = await getTvDetails(tmdbId);
const row = db
.insert(titles)
.values({
tmdbId: show.id,
type: "tv",
title: show.name,
originalTitle: show.original_name,
overview: show.overview,
firstAirDate: show.first_air_date || null,
posterPath: show.poster_path,
backdropPath: show.backdrop_path,
popularity: show.popularity,
voteAverage: show.vote_average,
voteCount: show.vote_count,
status: show.status,
lastFetchedAt: now,
})
.returning()
.get();
await refreshTvChildren(row.id, tmdbId, show.number_of_seasons);
// Fire-and-forget: fetch availability & recommendations
refreshAvailability(row.id).catch(() => {});
refreshRecommendations(row.id).catch(() => {});
return row;
}
export async function refreshTitle(titleId: string) {
const title = db.select().from(titles).where(eq(titles.id, titleId)).get();
if (!title) return null;
const now = new Date();
if (title.type === "movie") {
const movie = await getMovieDetails(title.tmdbId);
db.update(titles)
.set({
title: movie.title,
originalTitle: movie.original_title,
overview: movie.overview,
releaseDate: movie.release_date || null,
posterPath: movie.poster_path,
backdropPath: movie.backdrop_path,
popularity: movie.popularity,
voteAverage: movie.vote_average,
voteCount: movie.vote_count,
status: movie.status,
lastFetchedAt: now,
})
.where(eq(titles.id, titleId))
.run();
} else {
const show = await getTvDetails(title.tmdbId);
db.update(titles)
.set({
title: show.name,
originalTitle: show.original_name,
overview: show.overview,
firstAirDate: show.first_air_date || null,
posterPath: show.poster_path,
backdropPath: show.backdrop_path,
popularity: show.popularity,
voteAverage: show.vote_average,
voteCount: show.vote_count,
status: show.status,
lastFetchedAt: now,
})
.where(eq(titles.id, titleId))
.run();
await refreshTvChildren(titleId, title.tmdbId, show.number_of_seasons);
}
return db.select().from(titles).where(eq(titles.id, titleId)).get();
}
export async function refreshTvChildren(
titleId: string,
tmdbId: number,
numberOfSeasons: number,
) {
const now = new Date();
for (let sn = 1; sn <= numberOfSeasons; sn++) {
// Rate-limit: 250ms between TMDB calls
if (sn > 1) await delay(250);
const seasonData = await getTvSeasonDetails(tmdbId, sn);
const seasonRow = db
.insert(seasons)
.values({
titleId,
seasonNumber: seasonData.season_number,
name: seasonData.name,
overview: seasonData.overview,
posterPath: seasonData.poster_path,
airDate: seasonData.air_date,
lastFetchedAt: now,
})
.onConflictDoUpdate({
target: [seasons.titleId, seasons.seasonNumber],
set: {
name: seasonData.name,
overview: seasonData.overview,
posterPath: seasonData.poster_path,
airDate: seasonData.air_date,
lastFetchedAt: now,
},
})
.returning()
.get();
for (const ep of seasonData.episodes) {
db.insert(episodes)
.values({
seasonId: seasonRow.id,
episodeNumber: ep.episode_number,
name: ep.name,
overview: ep.overview,
stillPath: ep.still_path,
airDate: ep.air_date,
runtimeMinutes: ep.runtime,
})
.onConflictDoUpdate({
target: [episodes.seasonId, episodes.episodeNumber],
set: {
name: ep.name,
overview: ep.overview,
stillPath: ep.still_path,
airDate: ep.air_date,
runtimeMinutes: ep.runtime,
},
})
.run();
}
}
}
export async function refreshRecommendations(titleId: string) {
const title = db.select().from(titles).where(eq(titles.id, titleId)).get();
if (!title) return;
const now = new Date();
// Fetch both recommendations and similar
const [recs, similar] = await Promise.all([
getRecommendations(title.tmdbId, title.type),
getSimilar(title.tmdbId, title.type),
]);
// Process recommendations
for (let i = 0; i < recs.results.length && i < 20; i++) {
const r = recs.results[i];
const type = r.media_type ?? title.type;
if (type !== "movie" && type !== "tv") continue;
// Minimal upsert of the recommended title
const existing = db
.select()
.from(titles)
.where(eq(titles.tmdbId, r.id))
.get();
let recTitleId: string;
if (existing) {
recTitleId = existing.id;
} else {
const row = db
.insert(titles)
.values({
tmdbId: r.id,
type,
title: r.title ?? r.name ?? "Unknown",
originalTitle: r.original_title ?? r.original_name,
overview: r.overview,
releaseDate: r.release_date,
firstAirDate: r.first_air_date,
posterPath: r.poster_path,
backdropPath: r.backdrop_path,
popularity: r.popularity,
voteAverage: r.vote_average,
voteCount: r.vote_count,
lastFetchedAt: null,
})
.onConflictDoNothing()
.returning()
.get();
if (!row) {
const found = db
.select()
.from(titles)
.where(eq(titles.tmdbId, r.id))
.get();
if (!found) continue;
recTitleId = found.id;
} else {
recTitleId = row.id;
}
}
db.insert(titleRecommendations)
.values({
titleId,
recommendedTitleId: recTitleId,
source: "tmdb_recommendations",
rank: i + 1,
lastFetchedAt: now,
})
.onConflictDoUpdate({
target: [
titleRecommendations.titleId,
titleRecommendations.recommendedTitleId,
titleRecommendations.source,
],
set: { rank: i + 1, lastFetchedAt: now },
})
.run();
}
// Process similar
for (let i = 0; i < similar.results.length && i < 20; i++) {
const r = similar.results[i];
const type = r.media_type ?? title.type;
if (type !== "movie" && type !== "tv") continue;
const existing = db
.select()
.from(titles)
.where(eq(titles.tmdbId, r.id))
.get();
let recTitleId: string;
if (existing) {
recTitleId = existing.id;
} else {
const row = db
.insert(titles)
.values({
tmdbId: r.id,
type,
title: r.title ?? r.name ?? "Unknown",
originalTitle: r.original_title ?? r.original_name,
overview: r.overview,
releaseDate: r.release_date,
firstAirDate: r.first_air_date,
posterPath: r.poster_path,
backdropPath: r.backdrop_path,
popularity: r.popularity,
voteAverage: r.vote_average,
voteCount: r.vote_count,
lastFetchedAt: null,
})
.onConflictDoNothing()
.returning()
.get();
if (!row) {
const found = db
.select()
.from(titles)
.where(eq(titles.tmdbId, r.id))
.get();
if (!found) continue;
recTitleId = found.id;
} else {
recTitleId = row.id;
}
}
db.insert(titleRecommendations)
.values({
titleId,
recommendedTitleId: recTitleId,
source: "tmdb_similar",
rank: i + 1,
lastFetchedAt: now,
})
.onConflictDoUpdate({
target: [
titleRecommendations.titleId,
titleRecommendations.recommendedTitleId,
titleRecommendations.source,
],
set: { rank: i + 1, lastFetchedAt: now },
})
.run();
}
}
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+215
View File
@@ -0,0 +1,215 @@
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import {
episodes,
seasons,
userEpisodeWatches,
userMovieWatches,
userRatings,
userTitleStatus,
} from "@/lib/db/schema";
export function setTitleStatus(
userId: string,
titleId: string,
status: "watchlist" | "in_progress" | "completed",
) {
const now = new Date();
db.insert(userTitleStatus)
.values({ userId, titleId, status, addedAt: now, updatedAt: now })
.onConflictDoUpdate({
target: [userTitleStatus.userId, userTitleStatus.titleId],
set: { status, updatedAt: now },
})
.run();
}
export function removeTitleStatus(userId: string, titleId: string) {
db.delete(userTitleStatus)
.where(
and(
eq(userTitleStatus.userId, userId),
eq(userTitleStatus.titleId, titleId),
),
)
.run();
}
export function logMovieWatch(userId: string, titleId: string) {
const now = new Date();
db.insert(userMovieWatches)
.values({ userId, titleId, watchedAt: now, source: "manual" })
.run();
// Auto-set status to completed
const existing = db
.select()
.from(userTitleStatus)
.where(
and(
eq(userTitleStatus.userId, userId),
eq(userTitleStatus.titleId, titleId),
),
)
.get();
if (!existing) {
setTitleStatus(userId, titleId, "completed");
} else if (existing.status !== "completed") {
setTitleStatus(userId, titleId, "completed");
}
}
export function logEpisodeWatch(userId: string, episodeId: string) {
const now = new Date();
db.insert(userEpisodeWatches)
.values({ userId, episodeId, watchedAt: now, source: "manual" })
.run();
// Find the title for this episode
const ep = db.select().from(episodes).where(eq(episodes.id, episodeId)).get();
if (!ep) return;
const season = db
.select()
.from(seasons)
.where(eq(seasons.id, ep.seasonId))
.get();
if (!season) return;
const titleId = season.titleId;
// Auto-set status to in_progress if not set
const existing = db
.select()
.from(userTitleStatus)
.where(
and(
eq(userTitleStatus.userId, userId),
eq(userTitleStatus.titleId, titleId),
),
)
.get();
if (!existing) {
setTitleStatus(userId, titleId, "in_progress");
}
// Check if all episodes are watched -> auto-complete
checkAllEpisodesWatched(userId, titleId);
}
function checkAllEpisodesWatched(userId: string, titleId: string) {
const allSeasons = db
.select()
.from(seasons)
.where(eq(seasons.titleId, titleId))
.all();
let totalEpisodes = 0;
let watchedEpisodes = 0;
for (const s of allSeasons) {
const eps = db
.select()
.from(episodes)
.where(eq(episodes.seasonId, s.id))
.all();
totalEpisodes += eps.length;
for (const ep of eps) {
const watch = db
.select()
.from(userEpisodeWatches)
.where(
and(
eq(userEpisodeWatches.userId, userId),
eq(userEpisodeWatches.episodeId, ep.id),
),
)
.get();
if (watch) watchedEpisodes++;
}
}
if (totalEpisodes > 0 && watchedEpisodes >= totalEpisodes) {
setTitleStatus(userId, titleId, "completed");
}
}
export function rateTitleStars(
userId: string,
titleId: string,
ratingStars: number,
) {
const now = new Date();
if (ratingStars === 0) {
db.delete(userRatings)
.where(
and(eq(userRatings.userId, userId), eq(userRatings.titleId, titleId)),
)
.run();
return;
}
db.insert(userRatings)
.values({ userId, titleId, ratingStars, ratedAt: now })
.onConflictDoUpdate({
target: [userRatings.userId, userRatings.titleId],
set: { ratingStars, ratedAt: now },
})
.run();
}
export function getUserTitleInfo(userId: string, titleId: string) {
const status = db
.select()
.from(userTitleStatus)
.where(
and(
eq(userTitleStatus.userId, userId),
eq(userTitleStatus.titleId, titleId),
),
)
.get();
const rating = db
.select()
.from(userRatings)
.where(
and(eq(userRatings.userId, userId), eq(userRatings.titleId, titleId)),
)
.get();
// Get watched episode IDs for this title
const titleSeasons = db
.select()
.from(seasons)
.where(eq(seasons.titleId, titleId))
.all();
const watchedEpisodeIds: string[] = [];
for (const s of titleSeasons) {
const eps = db
.select()
.from(episodes)
.where(eq(episodes.seasonId, s.id))
.all();
for (const ep of eps) {
const watch = db
.select()
.from(userEpisodeWatches)
.where(
and(
eq(userEpisodeWatches.userId, userId),
eq(userEpisodeWatches.episodeId, ep.id),
),
)
.get();
if (watch) watchedEpisodeIds.push(ep.id);
}
}
return {
status: status?.status ?? null,
rating: rating?.ratingStars ?? null,
episodeWatches: watchedEpisodeIds,
};
}