feat: add episode total handling and display across movie pages

- Implemented `getEpisodeDisplay` function to format episode information for movies.
- Updated movie display components to show episode information using the new function.
- Added `episodeTotal` field to the movies schema and updated related API endpoints to handle this new field.
- Enhanced movie synchronization process to fetch and store episode totals from external sources.
- Created a new error page component for better user experience on 404 errors.
- Added migration scripts to update the database schema for episode totals.
This commit is contained in:
ngthanhvu
2026-07-23 02:56:24 -04:00
parent a35403a5b9
commit f42dff9b0a
19 changed files with 983 additions and 124 deletions
+12 -11
View File
@@ -1,5 +1,5 @@
import { movies } from '../../database/schema'
import { desc, eq, like, sql } from 'drizzle-orm'
import { desc, eq, like, and, sql } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
const db = useDb()
@@ -9,17 +9,18 @@ export default defineEventHandler(async (event) => {
const offset = (page - 1) * limit
const keyword = typeof query.keyword === 'string' ? query.keyword.trim() : ''
const status = typeof query.status === 'string' ? query.status : ''
const source = typeof query.source === 'string' ? query.source : ''
const type = typeof query.type === 'string' ? query.type : ''
let whereClause = undefined
if (keyword && status === 'active') {
whereClause = sql`${like(movies.name, `%${keyword}%`)} AND ${movies.active} = true`
} else if (keyword) {
whereClause = like(movies.name, `%${keyword}%`)
} else if (status === 'active') {
whereClause = eq(movies.active, true)
} else if (status === 'inactive') {
whereClause = eq(movies.active, false)
}
const conditions: any[] = []
if (keyword) conditions.push(like(movies.name, `%${keyword}%`))
if (status === 'active') conditions.push(eq(movies.active, true))
else if (status === 'inactive') conditions.push(eq(movies.active, false))
if (source) conditions.push(eq(movies.source, source))
if (type) conditions.push(eq(movies.type, type))
const whereClause = conditions.length > 0 ? and(...conditions) : undefined
const [items, countResult] = await Promise.all([
db
+24 -1
View File
@@ -1,5 +1,5 @@
import { movies } from '../../database/schema'
import { sql } from 'drizzle-orm'
import { sql, eq } from 'drizzle-orm'
export default defineEventHandler(async () => {
const db = useDb()
@@ -8,11 +8,34 @@ export default defineEventHandler(async () => {
total: sql<number>`count(*)`,
active: sql<number>`SUM(CASE WHEN ${movies.active} = true THEN 1 ELSE 0 END)`,
inactive: sql<number>`SUM(CASE WHEN ${movies.active} = false THEN 1 ELSE 0 END)`,
series: sql<number>`SUM(CASE WHEN ${movies.type} = 'series' THEN 1 ELSE 0 END)`,
single: sql<number>`SUM(CASE WHEN ${movies.type} = 'single' THEN 1 ELSE 0 END)`,
totalViews: sql<number>`COALESCE(SUM(${movies.views}), 0)`,
ophim: sql<number>`SUM(CASE WHEN ${movies.source} = 'ophim' THEN 1 ELSE 0 END)`,
nguonc: sql<number>`SUM(CASE WHEN ${movies.source} = 'nguonc' THEN 1 ELSE 0 END)`,
kkphim: sql<number>`SUM(CASE WHEN ${movies.source} = 'kkphim' THEN 1 ELSE 0 END)`,
}).from(movies)
const topMovies = await db.select({
name: movies.name,
views: movies.views,
slug: movies.slug,
source: movies.source,
}).from(movies)
.where(eq(movies.active, true))
.orderBy(sql`${movies.views} DESC`)
.limit(5)
return {
total: stats?.total ?? 0,
active: stats?.active ?? 0,
inactive: stats?.inactive ?? 0,
series: stats?.series ?? 0,
single: stats?.single ?? 0,
totalViews: stats?.totalViews ?? 0,
ophim: stats?.ophim ?? 0,
nguonc: stats?.nguonc ?? 0,
kkphim: stats?.kkphim ?? 0,
topMovies: topMovies || [],
}
})
+46 -1
View File
@@ -1,9 +1,50 @@
import { movies } from '../../database/schema'
import { eq, and } from 'drizzle-orm'
import { getOphimKoreanMovies, getNguoncKoreanMovies, getKkphimKoreanMovies } from '../../utils/movies'
import {
getOphimKoreanMovies,
getNguoncKoreanMovies,
getKkphimKoreanMovies,
getOphimDetail,
getNguoncDetail,
getKkphimDetail,
} from '../../utils/movies'
const SYNC_PAGES = 10
const ALL_SOURCES = ['ophim', 'nguonc', 'kkphim'] as const
const DETAIL_CONCURRENCY = 5
const detailFetchers = {
ophim: getOphimDetail,
nguonc: getNguoncDetail,
kkphim: getKkphimDetail,
}
async function fetchEpisodeTotal(source: string, slug: string): Promise<string | undefined> {
const fetcher = detailFetchers[source as keyof typeof detailFetchers]
if (!fetcher) return undefined
try {
const detail = await fetcher(slug)
return detail.episodeTotal || undefined
} catch {
return undefined
}
}
async function enrichWithEpisodeTotal(moviesList: any[]): Promise<void> {
const moviesNeedTotal = moviesList.filter((m) => m.type !== 'single' && !m.episodeTotal && m.slug)
for (let i = 0; i < moviesNeedTotal.length; i += DETAIL_CONCURRENCY) {
const batch = moviesNeedTotal.slice(i, i + DETAIL_CONCURRENCY)
const results = await Promise.allSettled(
batch.map((movie) => fetchEpisodeTotal(movie.source, movie.slug)),
)
results.forEach((result, idx) => {
if (result.status === 'fulfilled' && result.value) {
batch[idx].episodeTotal = result.value
}
})
}
}
export default defineEventHandler(async (event) => {
const db = useDb()
@@ -38,6 +79,8 @@ export default defineEventHandler(async (event) => {
}
}
await enrichWithEpisodeTotal(allMovies)
let created = 0
let updated = 0
@@ -59,6 +102,7 @@ export default defineEventHandler(async (event) => {
year: movie.year || null,
time: movie.time || null,
episode: movie.episode || null,
episodeTotal: movie.episodeTotal || null,
quality: movie.quality || null,
lang: movie.lang || null,
type: movie.type || null,
@@ -82,6 +126,7 @@ export default defineEventHandler(async (event) => {
year: movie.year || null,
time: movie.time || null,
episode: movie.episode || null,
episodeTotal: movie.episodeTotal || null,
quality: movie.quality || null,
lang: movie.lang || null,
type: movie.type || null,
+1
View File
@@ -72,6 +72,7 @@ function mapMovieToResponse(movie: any) {
year: movie.year || undefined,
time: movie.time || undefined,
episode: movie.episode || undefined,
episodeTotal: movie.episodeTotal || undefined,
quality: movie.quality || undefined,
lang: movie.lang || undefined,
type: movie.type || undefined,
+17 -2
View File
@@ -19,7 +19,9 @@ export default defineEventHandler(async (event) => {
.where(and(eq(movies.slug, slug), eq(movies.source, source), eq(movies.active, true)))
.limit(1)
if (!existing.length) {
let recordToUpdate = existing.length ? existing[0] : null
if (!recordToUpdate) {
const fallback = await db
.select()
.from(movies)
@@ -29,9 +31,22 @@ export default defineEventHandler(async (event) => {
if (!fallback.length) {
throw createError({ statusCode: 404, statusMessage: 'Phim không tồn tại hoặc đã bị ẩn' })
}
recordToUpdate = fallback[0]
}
const refs = parseSourceRefs(query.sources || query.srcs, query.source, slug)
return await getMovieDetailGroup(refs)
const detail = await getMovieDetailGroup(refs)
if (detail.episodeTotal && recordToUpdate) {
try {
await db
.update(movies)
.set({ episodeTotal: detail.episodeTotal })
.where(eq(movies.id, recordToUpdate.id))
} catch {
}
}
return detail
})
@@ -0,0 +1 @@
ALTER TABLE `movies` ADD `episode_total` varchar(100);
@@ -0,0 +1,336 @@
{
"version": "5",
"dialect": "mysql",
"id": "0c944d62-4add-4bdb-b5cf-764479ba4b22",
"prevId": "12998654-722b-4627-9970-1f407a7d7edd",
"tables": {
"movies": {
"name": "movies",
"columns": {
"id": {
"name": "id",
"type": "int",
"primaryKey": false,
"notNull": true,
"autoincrement": true
},
"source": {
"name": "source",
"type": "varchar(50)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"slug": {
"name": "slug",
"type": "varchar(500)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "varchar(500)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"origin_name": {
"name": "origin_name",
"type": "varchar(500)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"thumb": {
"name": "thumb",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"poster": {
"name": "poster",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"year": {
"name": "year",
"type": "int",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"time": {
"name": "time",
"type": "varchar(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"episode": {
"name": "episode",
"type": "varchar(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"episode_total": {
"name": "episode_total",
"type": "varchar(100)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"quality": {
"name": "quality",
"type": "varchar(50)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lang": {
"name": "lang",
"type": "varchar(50)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"type": {
"name": "type",
"type": "varchar(50)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"rating": {
"name": "rating",
"type": "int",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"views": {
"name": "views",
"type": "int",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"content": {
"name": "content",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"categories": {
"name": "categories",
"type": "json",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"countries": {
"name": "countries",
"type": "json",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"sources": {
"name": "sources",
"type": "json",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"custom_poster": {
"name": "custom_poster",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"custom_thumb": {
"name": "custom_thumb",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"custom_content": {
"name": "custom_content",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"custom_episodes": {
"name": "custom_episodes",
"type": "json",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"active": {
"name": "active",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"api_updated_at": {
"name": "api_updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"synced_at": {
"name": "synced_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(now())"
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(now())"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"onUpdate": true,
"default": "(now())"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {
"movies_id": {
"name": "movies_id",
"columns": [
"id"
]
}
},
"uniqueConstraints": {},
"checkConstraint": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "int",
"primaryKey": false,
"notNull": true,
"autoincrement": true
},
"name": {
"name": "name",
"type": "varchar(200)",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"email": {
"name": "email",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"password": {
"name": "password",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"role": {
"name": "role",
"type": "varchar(50)",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'user'"
},
"avatar": {
"name": "avatar",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"active": {
"name": "active",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(now())"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"onUpdate": true,
"default": "(now())"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {
"users_id": {
"name": "users_id",
"columns": [
"id"
]
}
},
"uniqueConstraints": {
"users_email_unique": {
"name": "users_email_unique",
"columns": [
"email"
]
}
},
"checkConstraint": {}
}
},
"views": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"tables": {},
"indexes": {}
}
}
@@ -43,6 +43,13 @@
"when": 1784709136940,
"tag": "0005_illegal_purple_man",
"breakpoints": true
},
{
"idx": 6,
"version": "5",
"when": 1784780104334,
"tag": "0006_sour_retro_girl",
"breakpoints": true
}
]
}
+1
View File
@@ -23,6 +23,7 @@ export const movies = mysqlTable('movies', {
year: int('year'),
time: varchar('time', { length: 100 }),
episode: varchar('episode', { length: 100 }),
episodeTotal: varchar('episode_total', { length: 100 }),
quality: varchar('quality', { length: 50 }),
lang: varchar('lang', { length: 50 }),
type: varchar('type', { length: 50 }),
+6
View File
@@ -12,6 +12,7 @@ export interface NormalizedMovie {
year?: number
time?: string
episode?: string
episodeTotal?: string
quality?: string
lang?: string
type?: string
@@ -294,6 +295,7 @@ export function normalizeOphimMovie(movie: any, pathImage = OPHIM_IMAGE): Normal
year: Number(movie?.year) || undefined,
time: text(movie?.time),
episode: text(movie?.episode_current),
episodeTotal: movie?.episode_total ? String(movie.episode_total).trim() || undefined : undefined,
quality: text(movie?.quality),
lang: text(movie?.lang),
type: text(movie?.type),
@@ -316,6 +318,7 @@ export function normalizeKkphimMovie(movie: any, pathImage = KKPHIM_IMAGE): Norm
year: Number(movie?.year) || undefined,
time: text(movie?.time),
episode: text(movie?.episode_current),
episodeTotal: movie?.episode_total != null ? String(movie.episode_total).trim() || undefined : undefined,
quality: text(movie?.quality),
lang: text(movie?.lang),
type: text(movie?.type),
@@ -340,6 +343,9 @@ function normalizeNguoncMovie(movie: any): NormalizedMovie {
year: Number(movie?.year || movie?.release_year) || undefined,
time: text(movie?.time || movie?.duration),
episode: text(movie?.episode_current || movie?.current_episode),
episodeTotal: (movie?.episode_total || movie?.total_episodes) != null
? String(movie.episode_total || movie.total_episodes).trim() || undefined
: undefined,
quality: text(movie?.quality),
lang: text(movie?.language || movie?.lang),
type: text(movie?.type),