mirror of
https://github.com/jakejarvis/sofa.git
synced 2026-08-29 01:35:39 -04:00
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:
@@ -0,0 +1,23 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
|
||||
export async function getSession() {
|
||||
return auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function requireAuth(): Promise<string> {
|
||||
const session = await getSession();
|
||||
if (!session?.user?.id) {
|
||||
throw new AuthError();
|
||||
}
|
||||
return session.user.id;
|
||||
}
|
||||
|
||||
export class AuthError extends Error {
|
||||
constructor() {
|
||||
super("Unauthorized");
|
||||
this.name = "AuthError";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export function apiError(message: string, status: number) {
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
export function unauthorized(message = "Unauthorized") {
|
||||
return apiError(message, 401);
|
||||
}
|
||||
|
||||
export function badRequest(message = "Bad request") {
|
||||
return apiError(message, 400);
|
||||
}
|
||||
|
||||
export function notFound(message = "Not found") {
|
||||
return apiError(message, 404);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
|
||||
export const authClient = createAuthClient();
|
||||
|
||||
export const { signIn, signUp, signOut, useSession } = authClient;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { db } from "@/lib/db/client";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "sqlite",
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
},
|
||||
advanced: {
|
||||
database: {
|
||||
generateId: () => uuid(),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
import * as schema from "./schema";
|
||||
|
||||
const globalForDb = globalThis as unknown as {
|
||||
_db: ReturnType<typeof drizzle> | undefined;
|
||||
_sqlite: Database.Database | undefined;
|
||||
};
|
||||
|
||||
if (!globalForDb._sqlite) {
|
||||
globalForDb._sqlite = new Database(process.env.DATABASE_URL ?? "sqlite.db");
|
||||
globalForDb._sqlite.pragma("journal_mode = WAL");
|
||||
globalForDb._sqlite.pragma("foreign_keys = ON");
|
||||
globalForDb._sqlite.pragma("busy_timeout = 5000");
|
||||
}
|
||||
|
||||
if (!globalForDb._db) {
|
||||
globalForDb._db = drizzle(globalForDb._sqlite, { schema });
|
||||
}
|
||||
|
||||
export const db = globalForDb._db;
|
||||
export const sqlite = globalForDb._sqlite;
|
||||
@@ -0,0 +1,279 @@
|
||||
import {
|
||||
index,
|
||||
int,
|
||||
real,
|
||||
sqliteTable,
|
||||
text,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
import { v4 as uuid } from "uuid";
|
||||
|
||||
// Helper for UUID primary keys
|
||||
const uuidPk = () =>
|
||||
text("id")
|
||||
.primaryKey()
|
||||
.$defaultFn(() => uuid());
|
||||
|
||||
// ─── Better Auth tables ──────────────────────────────────────────────
|
||||
|
||||
export const user = sqliteTable("user", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: int("emailVerified", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
image: text("image"),
|
||||
createdAt: int("createdAt", { mode: "timestamp" }).notNull(),
|
||||
updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(),
|
||||
});
|
||||
|
||||
export const session = sqliteTable("session", {
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
token: text("token").notNull().unique(),
|
||||
expiresAt: int("expiresAt", { mode: "timestamp" }).notNull(),
|
||||
ipAddress: text("ipAddress"),
|
||||
userAgent: text("userAgent"),
|
||||
createdAt: int("createdAt", { mode: "timestamp" }).notNull(),
|
||||
updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(),
|
||||
});
|
||||
|
||||
export const account = sqliteTable("account", {
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accountId: text("accountId").notNull(),
|
||||
providerId: text("providerId").notNull(),
|
||||
accessToken: text("accessToken"),
|
||||
refreshToken: text("refreshToken"),
|
||||
accessTokenExpiresAt: int("accessTokenExpiresAt", { mode: "timestamp" }),
|
||||
refreshTokenExpiresAt: int("refreshTokenExpiresAt", { mode: "timestamp" }),
|
||||
scope: text("scope"),
|
||||
password: text("password"),
|
||||
createdAt: int("createdAt", { mode: "timestamp" }).notNull(),
|
||||
updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(),
|
||||
});
|
||||
|
||||
export const verification = sqliteTable("verification", {
|
||||
id: text("id").primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: int("expiresAt", { mode: "timestamp" }).notNull(),
|
||||
createdAt: int("createdAt", { mode: "timestamp" }),
|
||||
updatedAt: int("updatedAt", { mode: "timestamp" }),
|
||||
});
|
||||
|
||||
// ─── App tables ──────────────────────────────────────────────────────
|
||||
|
||||
export const titles = sqliteTable(
|
||||
"titles",
|
||||
{
|
||||
id: uuidPk(),
|
||||
tmdbId: int("tmdbId").notNull(),
|
||||
type: text("type", { enum: ["movie", "tv"] }).notNull(),
|
||||
title: text("title").notNull(),
|
||||
originalTitle: text("originalTitle"),
|
||||
overview: text("overview"),
|
||||
releaseDate: text("releaseDate"),
|
||||
firstAirDate: text("firstAirDate"),
|
||||
posterPath: text("posterPath"),
|
||||
backdropPath: text("backdropPath"),
|
||||
popularity: real("popularity"),
|
||||
voteAverage: real("voteAverage"),
|
||||
voteCount: int("voteCount"),
|
||||
status: text("status"),
|
||||
lastFetchedAt: int("lastFetchedAt", { mode: "timestamp" }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("titles_tmdbId_unique").on(table.tmdbId),
|
||||
index("titles_type_releaseDate").on(table.type, table.releaseDate),
|
||||
index("titles_type_firstAirDate").on(table.type, table.firstAirDate),
|
||||
],
|
||||
);
|
||||
|
||||
export const seasons = sqliteTable(
|
||||
"seasons",
|
||||
{
|
||||
id: uuidPk(),
|
||||
titleId: text("titleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
seasonNumber: int("seasonNumber").notNull(),
|
||||
name: text("name"),
|
||||
overview: text("overview"),
|
||||
posterPath: text("posterPath"),
|
||||
airDate: text("airDate"),
|
||||
lastFetchedAt: int("lastFetchedAt", { mode: "timestamp" }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("seasons_titleId_seasonNumber").on(
|
||||
table.titleId,
|
||||
table.seasonNumber,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const episodes = sqliteTable(
|
||||
"episodes",
|
||||
{
|
||||
id: uuidPk(),
|
||||
seasonId: text("seasonId")
|
||||
.notNull()
|
||||
.references(() => seasons.id, { onDelete: "cascade" }),
|
||||
episodeNumber: int("episodeNumber").notNull(),
|
||||
name: text("name"),
|
||||
overview: text("overview"),
|
||||
stillPath: text("stillPath"),
|
||||
airDate: text("airDate"),
|
||||
runtimeMinutes: int("runtimeMinutes"),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("episodes_seasonId_episodeNumber").on(
|
||||
table.seasonId,
|
||||
table.episodeNumber,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const userTitleStatus = sqliteTable(
|
||||
"userTitleStatus",
|
||||
{
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
titleId: text("titleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
status: text("status", {
|
||||
enum: ["watchlist", "in_progress", "completed"],
|
||||
}).notNull(),
|
||||
addedAt: int("addedAt", { mode: "timestamp" }).notNull(),
|
||||
updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("userTitleStatus_userId_titleId").on(
|
||||
table.userId,
|
||||
table.titleId,
|
||||
),
|
||||
index("userTitleStatus_userId_status").on(table.userId, table.status),
|
||||
],
|
||||
);
|
||||
|
||||
export const userMovieWatches = sqliteTable(
|
||||
"userMovieWatches",
|
||||
{
|
||||
id: uuidPk(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
titleId: text("titleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
watchedAt: int("watchedAt", { mode: "timestamp" }).notNull(),
|
||||
source: text("source", { enum: ["manual", "import"] })
|
||||
.notNull()
|
||||
.default("manual"),
|
||||
},
|
||||
(table) => [
|
||||
index("userMovieWatches_userId_watchedAt").on(
|
||||
table.userId,
|
||||
table.watchedAt,
|
||||
),
|
||||
index("userMovieWatches_titleId").on(table.titleId),
|
||||
],
|
||||
);
|
||||
|
||||
export const userEpisodeWatches = sqliteTable(
|
||||
"userEpisodeWatches",
|
||||
{
|
||||
id: uuidPk(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
episodeId: text("episodeId")
|
||||
.notNull()
|
||||
.references(() => episodes.id, { onDelete: "cascade" }),
|
||||
watchedAt: int("watchedAt", { mode: "timestamp" }).notNull(),
|
||||
source: text("source", { enum: ["manual", "import"] })
|
||||
.notNull()
|
||||
.default("manual"),
|
||||
},
|
||||
(table) => [
|
||||
index("userEpisodeWatches_userId_watchedAt").on(
|
||||
table.userId,
|
||||
table.watchedAt,
|
||||
),
|
||||
index("userEpisodeWatches_episodeId").on(table.episodeId),
|
||||
],
|
||||
);
|
||||
|
||||
export const userRatings = sqliteTable(
|
||||
"userRatings",
|
||||
{
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
titleId: text("titleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
ratingStars: int("ratingStars").notNull(),
|
||||
ratedAt: int("ratedAt", { mode: "timestamp" }).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("userRatings_userId_titleId").on(table.userId, table.titleId),
|
||||
],
|
||||
);
|
||||
|
||||
export const availabilityOffers = sqliteTable(
|
||||
"availabilityOffers",
|
||||
{
|
||||
titleId: text("titleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
region: text("region").notNull().default("US"),
|
||||
providerId: int("providerId").notNull(),
|
||||
providerName: text("providerName").notNull(),
|
||||
logoPath: text("logoPath"),
|
||||
offerType: text("offerType", {
|
||||
enum: ["flatrate", "rent", "buy", "free", "ads"],
|
||||
}).notNull(),
|
||||
link: text("link"),
|
||||
lastFetchedAt: int("lastFetchedAt", { mode: "timestamp" }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("availabilityOffers_unique").on(
|
||||
table.titleId,
|
||||
table.region,
|
||||
table.providerId,
|
||||
table.offerType,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const titleRecommendations = sqliteTable(
|
||||
"titleRecommendations",
|
||||
{
|
||||
titleId: text("titleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
recommendedTitleId: text("recommendedTitleId")
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: "cascade" }),
|
||||
source: text("source", {
|
||||
enum: ["tmdb_similar", "tmdb_recommendations"],
|
||||
}).notNull(),
|
||||
rank: int("rank").notNull(),
|
||||
lastFetchedAt: int("lastFetchedAt", { mode: "timestamp" }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("titleRecommendations_unique").on(
|
||||
table.titleId,
|
||||
table.recommendedTitleId,
|
||||
table.source,
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
import { registerJobs } from "./registry";
|
||||
import { scheduler } from "./scheduler";
|
||||
|
||||
export function initJobs() {
|
||||
registerJobs();
|
||||
scheduler.start();
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { and, eq, isNotNull, lt, or } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import {
|
||||
availabilityOffers,
|
||||
seasons,
|
||||
titles,
|
||||
userTitleStatus,
|
||||
} from "@/lib/db/schema";
|
||||
import { refreshAvailability } from "@/lib/services/availability";
|
||||
import {
|
||||
refreshRecommendations,
|
||||
refreshTitle,
|
||||
refreshTvChildren,
|
||||
} from "@/lib/services/metadata";
|
||||
import { getTvDetails } from "@/lib/tmdb/client";
|
||||
import { scheduler } from "./scheduler";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const DAY = 24 * HOUR;
|
||||
const RATE_LIMIT_MS = 300;
|
||||
|
||||
function delay(ms: number) {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
function getLibraryTitleIds(): string[] {
|
||||
return db
|
||||
.select({ titleId: userTitleStatus.titleId })
|
||||
.from(userTitleStatus)
|
||||
.groupBy(userTitleStatus.titleId)
|
||||
.all()
|
||||
.map((r) => r.titleId);
|
||||
}
|
||||
|
||||
// Refresh titles where lastFetchedAt is stale
|
||||
async function nightlyRefreshLibrary() {
|
||||
const libraryIds = getLibraryTitleIds();
|
||||
const libraryStale = new Date(Date.now() - 7 * DAY);
|
||||
const nonLibraryStale = new Date(Date.now() - 30 * DAY);
|
||||
|
||||
// Library titles: 7 days
|
||||
for (const titleId of libraryIds) {
|
||||
const t = db
|
||||
.select()
|
||||
.from(titles)
|
||||
.where(
|
||||
and(eq(titles.id, titleId), lt(titles.lastFetchedAt, libraryStale)),
|
||||
)
|
||||
.get();
|
||||
if (t) {
|
||||
await refreshTitle(titleId);
|
||||
await delay(RATE_LIMIT_MS);
|
||||
}
|
||||
}
|
||||
|
||||
// Non-library titles: 30 days
|
||||
const nonLibrary = db
|
||||
.select()
|
||||
.from(titles)
|
||||
.where(
|
||||
and(
|
||||
isNotNull(titles.lastFetchedAt),
|
||||
lt(titles.lastFetchedAt, nonLibraryStale),
|
||||
),
|
||||
)
|
||||
.limit(50)
|
||||
.all();
|
||||
|
||||
for (const t of nonLibrary) {
|
||||
if (!libraryIds.includes(t.id)) {
|
||||
await refreshTitle(t.id);
|
||||
await delay(RATE_LIMIT_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh availability for library titles where stale
|
||||
async function refreshAvailabilityJob() {
|
||||
const libraryIds = getLibraryTitleIds();
|
||||
const stale = new Date(Date.now() - DAY);
|
||||
|
||||
for (const titleId of libraryIds) {
|
||||
// Check if any offer is stale
|
||||
const offer = db
|
||||
.select()
|
||||
.from(availabilityOffers)
|
||||
.where(
|
||||
and(
|
||||
eq(availabilityOffers.titleId, titleId),
|
||||
lt(availabilityOffers.lastFetchedAt, stale),
|
||||
),
|
||||
)
|
||||
.get();
|
||||
|
||||
// Also handle titles with no offers yet
|
||||
const anyOffer = db
|
||||
.select()
|
||||
.from(availabilityOffers)
|
||||
.where(eq(availabilityOffers.titleId, titleId))
|
||||
.get();
|
||||
|
||||
if (offer || !anyOffer) {
|
||||
await refreshAvailability(titleId);
|
||||
await delay(RATE_LIMIT_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh recommendations for recently active titles
|
||||
async function refreshRecommendationsJob() {
|
||||
const libraryIds = getLibraryTitleIds();
|
||||
|
||||
for (const titleId of libraryIds) {
|
||||
await refreshRecommendations(titleId);
|
||||
await delay(RATE_LIMIT_MS);
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh TV episodes for returning shows
|
||||
async function refreshTvChildrenJob() {
|
||||
const returningStatuses = ["Returning Series", "In Production"];
|
||||
const stale = new Date(Date.now() - 7 * DAY);
|
||||
|
||||
const tvShows = db
|
||||
.select()
|
||||
.from(titles)
|
||||
.where(
|
||||
and(
|
||||
eq(titles.type, "tv"),
|
||||
isNotNull(titles.lastFetchedAt),
|
||||
or(...returningStatuses.map((s) => eq(titles.status, s))),
|
||||
),
|
||||
)
|
||||
.all();
|
||||
|
||||
for (const show of tvShows) {
|
||||
// Check if seasons are stale
|
||||
const staleSeason = db
|
||||
.select()
|
||||
.from(seasons)
|
||||
.where(
|
||||
and(eq(seasons.titleId, show.id), lt(seasons.lastFetchedAt, stale)),
|
||||
)
|
||||
.get();
|
||||
|
||||
if (staleSeason) {
|
||||
const details = await getTvDetails(show.tmdbId);
|
||||
await refreshTvChildren(show.id, show.tmdbId, details.number_of_seasons);
|
||||
await delay(RATE_LIMIT_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function registerJobs() {
|
||||
scheduler.register("nightlyRefreshLibrary", nightlyRefreshLibrary, 24 * HOUR);
|
||||
scheduler.register("refreshAvailability", refreshAvailabilityJob, 6 * HOUR);
|
||||
scheduler.register(
|
||||
"refreshRecommendations",
|
||||
refreshRecommendationsJob,
|
||||
12 * HOUR,
|
||||
);
|
||||
scheduler.register("refreshTvChildren", refreshTvChildrenJob, 12 * HOUR);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
interface Job {
|
||||
name: string;
|
||||
handler: () => Promise<void>;
|
||||
intervalMs: number;
|
||||
timer?: ReturnType<typeof setInterval>;
|
||||
}
|
||||
|
||||
const globalForScheduler = globalThis as unknown as {
|
||||
_scheduler: Scheduler | undefined;
|
||||
};
|
||||
|
||||
class Scheduler {
|
||||
private jobs = new Map<string, Job>();
|
||||
private running = false;
|
||||
|
||||
register(name: string, handler: () => Promise<void>, intervalMs: number) {
|
||||
this.jobs.set(name, { name, handler, intervalMs });
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
|
||||
for (const job of this.jobs.values()) {
|
||||
job.timer = setInterval(async () => {
|
||||
try {
|
||||
console.log(`[scheduler] Running job: ${job.name}`);
|
||||
await job.handler();
|
||||
console.log(`[scheduler] Completed job: ${job.name}`);
|
||||
} catch (err) {
|
||||
console.error(`[scheduler] Job ${job.name} failed:`, err);
|
||||
}
|
||||
}, job.intervalMs);
|
||||
}
|
||||
|
||||
console.log(`[scheduler] Started ${this.jobs.size} jobs`);
|
||||
}
|
||||
|
||||
stop() {
|
||||
for (const job of this.jobs.values()) {
|
||||
if (job.timer) clearInterval(job.timer);
|
||||
}
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
async runNow(name: string) {
|
||||
const job = this.jobs.get(name);
|
||||
if (!job) throw new Error(`Job not found: ${name}`);
|
||||
await job.handler();
|
||||
}
|
||||
|
||||
getJobNames() {
|
||||
return [...this.jobs.keys()];
|
||||
}
|
||||
}
|
||||
|
||||
if (!globalForScheduler._scheduler) {
|
||||
globalForScheduler._scheduler = new Scheduler();
|
||||
}
|
||||
|
||||
export const scheduler = globalForScheduler._scheduler;
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type {
|
||||
TmdbMovieDetails,
|
||||
TmdbRecommendationResponse,
|
||||
TmdbSearchResponse,
|
||||
TmdbSeasonDetails,
|
||||
TmdbTvDetails,
|
||||
TmdbWatchProviderResponse,
|
||||
} from "./types";
|
||||
|
||||
const BASE_URL = "https://api.themoviedb.org/3";
|
||||
|
||||
function getApiKey() {
|
||||
const key = process.env.TMDB_API_KEY;
|
||||
if (!key) throw new Error("TMDB_API_KEY is not set");
|
||||
return key;
|
||||
}
|
||||
|
||||
async function tmdbFetch<T>(
|
||||
path: string,
|
||||
params?: Record<string, string>,
|
||||
): Promise<T> {
|
||||
const url = new URL(`${BASE_URL}${path}`);
|
||||
if (params) {
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
url.searchParams.set(k, v);
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${getApiKey()}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`TMDB API error: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function searchMulti(query: string, page = 1) {
|
||||
return tmdbFetch<TmdbSearchResponse>("/search/multi", {
|
||||
query,
|
||||
page: String(page),
|
||||
include_adult: "false",
|
||||
});
|
||||
}
|
||||
|
||||
export async function searchMovies(query: string, page = 1) {
|
||||
return tmdbFetch<TmdbSearchResponse>("/search/movie", {
|
||||
query,
|
||||
page: String(page),
|
||||
});
|
||||
}
|
||||
|
||||
export async function searchTv(query: string, page = 1) {
|
||||
return tmdbFetch<TmdbSearchResponse>("/search/tv", {
|
||||
query,
|
||||
page: String(page),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMovieDetails(tmdbId: number) {
|
||||
return tmdbFetch<TmdbMovieDetails>(`/movie/${tmdbId}`);
|
||||
}
|
||||
|
||||
export async function getTvDetails(tmdbId: number) {
|
||||
return tmdbFetch<TmdbTvDetails>(`/tv/${tmdbId}`);
|
||||
}
|
||||
|
||||
export async function getTvSeasonDetails(tmdbId: number, seasonNumber: number) {
|
||||
return tmdbFetch<TmdbSeasonDetails>(`/tv/${tmdbId}/season/${seasonNumber}`);
|
||||
}
|
||||
|
||||
export async function getWatchProviders(tmdbId: number, type: "movie" | "tv") {
|
||||
return tmdbFetch<TmdbWatchProviderResponse>(
|
||||
`/${type}/${tmdbId}/watch/providers`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getRecommendations(tmdbId: number, type: "movie" | "tv") {
|
||||
return tmdbFetch<TmdbRecommendationResponse>(
|
||||
`/${type}/${tmdbId}/recommendations`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSimilar(tmdbId: number, type: "movie" | "tv") {
|
||||
return tmdbFetch<TmdbRecommendationResponse>(`/${type}/${tmdbId}/similar`);
|
||||
}
|
||||
|
||||
export function tmdbImageUrl(path: string | null, size = "w500") {
|
||||
if (!path) return null;
|
||||
return `https://image.tmdb.org/t/p/${size}${path}`;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
export interface TmdbSearchResult {
|
||||
id: number;
|
||||
media_type: "movie" | "tv" | "person";
|
||||
title?: string;
|
||||
name?: string;
|
||||
original_title?: string;
|
||||
original_name?: string;
|
||||
overview: string;
|
||||
release_date?: string;
|
||||
first_air_date?: string;
|
||||
poster_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
popularity: number;
|
||||
vote_average: number;
|
||||
vote_count: number;
|
||||
}
|
||||
|
||||
export interface TmdbSearchResponse {
|
||||
page: number;
|
||||
results: TmdbSearchResult[];
|
||||
total_pages: number;
|
||||
total_results: number;
|
||||
}
|
||||
|
||||
export interface TmdbMovieDetails {
|
||||
id: number;
|
||||
title: string;
|
||||
original_title: string;
|
||||
overview: string;
|
||||
release_date: string;
|
||||
poster_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
popularity: number;
|
||||
vote_average: number;
|
||||
vote_count: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface TmdbTvDetails {
|
||||
id: number;
|
||||
name: string;
|
||||
original_name: string;
|
||||
overview: string;
|
||||
first_air_date: string;
|
||||
poster_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
popularity: number;
|
||||
vote_average: number;
|
||||
vote_count: number;
|
||||
status: string;
|
||||
number_of_seasons: number;
|
||||
seasons: TmdbSeasonSummary[];
|
||||
}
|
||||
|
||||
export interface TmdbSeasonSummary {
|
||||
id: number;
|
||||
season_number: number;
|
||||
name: string;
|
||||
overview: string;
|
||||
poster_path: string | null;
|
||||
air_date: string | null;
|
||||
episode_count: number;
|
||||
}
|
||||
|
||||
export interface TmdbSeasonDetails {
|
||||
id: number;
|
||||
season_number: number;
|
||||
name: string;
|
||||
overview: string;
|
||||
poster_path: string | null;
|
||||
air_date: string | null;
|
||||
episodes: TmdbEpisode[];
|
||||
}
|
||||
|
||||
export interface TmdbEpisode {
|
||||
id: number;
|
||||
episode_number: number;
|
||||
name: string;
|
||||
overview: string;
|
||||
still_path: string | null;
|
||||
air_date: string | null;
|
||||
runtime: number | null;
|
||||
}
|
||||
|
||||
export interface TmdbWatchProviderResponse {
|
||||
id: number;
|
||||
results: Record<
|
||||
string,
|
||||
{
|
||||
link?: string;
|
||||
flatrate?: TmdbProvider[];
|
||||
rent?: TmdbProvider[];
|
||||
buy?: TmdbProvider[];
|
||||
free?: TmdbProvider[];
|
||||
ads?: TmdbProvider[];
|
||||
}
|
||||
>;
|
||||
}
|
||||
|
||||
export interface TmdbProvider {
|
||||
provider_id: number;
|
||||
provider_name: string;
|
||||
logo_path: string;
|
||||
display_priority: number;
|
||||
}
|
||||
|
||||
export interface TmdbRecommendationResponse {
|
||||
page: number;
|
||||
results: TmdbSearchResult[];
|
||||
total_pages: number;
|
||||
total_results: number;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
Reference in New Issue
Block a user