mirror of
https://github.com/ngthanhvu/kr-phim.git
synced 2026-08-10 13:27:46 +00:00
feat: thêm cái proxy hình ảnh dùng webp
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { eq, and, isNull, desc, inArray, count } from 'drizzle-orm'
|
||||
import { comments, users, movies } from '../../database/schema'
|
||||
import { proxyImageUrl } from '../../utils/proxy-image'
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
const db = useDb()
|
||||
@@ -132,8 +133,8 @@ export default defineEventHandler(async () => {
|
||||
source: c.source,
|
||||
slug: c.slug,
|
||||
name: c.movieName || '',
|
||||
thumb: c.movieThumb,
|
||||
poster: c.moviePoster,
|
||||
thumb: proxyImageUrl(c.movieThumb || ''),
|
||||
poster: proxyImageUrl(c.moviePoster || ''),
|
||||
}
|
||||
: null,
|
||||
})),
|
||||
@@ -142,8 +143,8 @@ export default defineEventHandler(async () => {
|
||||
slug: m.slug,
|
||||
name: m.name,
|
||||
originName: m.originName,
|
||||
thumb: m.thumb,
|
||||
poster: m.poster,
|
||||
thumb: proxyImageUrl(m.thumb || ''),
|
||||
poster: proxyImageUrl(m.poster || ''),
|
||||
views: m.views,
|
||||
rating: m.rating,
|
||||
})),
|
||||
@@ -152,8 +153,8 @@ export default defineEventHandler(async () => {
|
||||
slug: m.slug,
|
||||
name: m.name,
|
||||
originName: m.originName,
|
||||
thumb: m.thumb,
|
||||
poster: m.poster,
|
||||
thumb: proxyImageUrl(m.thumb || ''),
|
||||
poster: proxyImageUrl(m.poster || ''),
|
||||
views: m.views,
|
||||
rating: m.rating,
|
||||
})),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createHash } from 'crypto'
|
||||
import { useRedis } from '../utils/redis'
|
||||
|
||||
const CACHE_TTL = 604800 // 7 ngày
|
||||
const CACHE_PREFIX = 'img:'
|
||||
const DEFAULT_WIDTH = null
|
||||
const DEFAULT_QUALITY = 85
|
||||
|
||||
async function getCachedWebP(redis: any, key: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const cached = await redis.getBuffer(key)
|
||||
return cached || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function setCachedWebP(redis: any, key: string, data: Buffer): Promise<void> {
|
||||
try {
|
||||
await redis.set(key, data, 'EX', CACHE_TTL)
|
||||
} catch {
|
||||
// Ignore cache write errors
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const url = getQuery(event).url as string
|
||||
|
||||
if (!url) {
|
||||
throw createError({ statusCode: 400, message: 'Missing URL parameter' })
|
||||
}
|
||||
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
throw createError({ statusCode: 400, message: 'Invalid URL protocol' })
|
||||
}
|
||||
|
||||
const width = getQuery(event).w ? parseInt(getQuery(event).w as string) : DEFAULT_WIDTH
|
||||
const quality = getQuery(event).q ? parseInt(getQuery(event).q as string) : DEFAULT_QUALITY
|
||||
const cacheKey = CACHE_PREFIX + createHash('md5').update(`${url}|${width}|${quality}`).digest('hex')
|
||||
|
||||
const redis = useRedis()
|
||||
|
||||
// Check cache
|
||||
const cached = await getCachedWebP(redis, cacheKey)
|
||||
if (cached) {
|
||||
setResponseHeader(event, 'cache-control', 'public, max-age=604800, immutable')
|
||||
setResponseHeader(event, 'content-type', 'image/webp')
|
||||
setResponseHeader(event, 'x-cache', 'HIT')
|
||||
setResponseHeader(event, 'access-control-allow-origin', '*')
|
||||
return cached
|
||||
}
|
||||
|
||||
// Fetch original image
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
|
||||
'Referer': new URL(url).origin,
|
||||
'Origin': new URL(url).origin,
|
||||
},
|
||||
signal: AbortSignal.timeout(15000),
|
||||
})
|
||||
} catch (error: any) {
|
||||
throw createError({ statusCode: 502, message: `Failed to fetch image: ${error.message}` })
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw createError({ statusCode: response.status, message: `Upstream error: ${response.statusText}` })
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type') || ''
|
||||
|
||||
// Skip non-image content types
|
||||
if (!contentType.startsWith('image/')) {
|
||||
throw createError({ statusCode: 400, message: 'Not an image' })
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(await response.arrayBuffer())
|
||||
|
||||
// Convert to WebP with optional resizing (dynamic import to avoid ESM resolution in dev)
|
||||
let webpBuffer: Buffer
|
||||
try {
|
||||
const { default: sharp } = await import('sharp')
|
||||
let transform = sharp(buffer) .webp({ quality, effort: 4 })
|
||||
|
||||
if (width) {
|
||||
transform = transform.resize(width, null, { withoutEnlargement: true })
|
||||
}
|
||||
|
||||
webpBuffer = await transform.toBuffer()
|
||||
} catch (error: any) {
|
||||
// If conversion fails, return original
|
||||
setResponseHeader(event, 'content-type', contentType)
|
||||
setResponseHeader(event, 'cache-control', 'public, max-age=3600')
|
||||
setResponseHeader(event, 'x-cache', 'MISS')
|
||||
setResponseHeader(event, 'access-control-allow-origin', '*')
|
||||
return buffer
|
||||
}
|
||||
|
||||
// Cache in Redis
|
||||
await setCachedWebP(redis, cacheKey, webpBuffer)
|
||||
|
||||
setResponseHeader(event, 'cache-control', 'public, max-age=604800, immutable')
|
||||
setResponseHeader(event, 'content-type', 'image/webp')
|
||||
setResponseHeader(event, 'content-length', webpBuffer.length.toString())
|
||||
setResponseHeader(event, 'x-cache', 'MISS')
|
||||
setResponseHeader(event, 'access-control-allow-origin', '*')
|
||||
|
||||
return webpBuffer
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { movies } from '../database/schema'
|
||||
import { desc, like, and, eq, sql } from 'drizzle-orm'
|
||||
import { proxyImageUrl } from '../utils/proxy-image'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const db = useDb()
|
||||
@@ -67,8 +68,8 @@ function mapMovieToResponse(movie: any) {
|
||||
slug: movie.slug,
|
||||
name: movie.name,
|
||||
originName: movie.originName || '',
|
||||
thumb: movie.customThumb || movie.thumb || '',
|
||||
poster: movie.customPoster || movie.poster || '',
|
||||
thumb: movie.customThumb ? proxyImageUrl(movie.customThumb) : proxyImageUrl(movie.thumb || ''),
|
||||
poster: movie.customPoster ? proxyImageUrl(movie.customPoster) : proxyImageUrl(movie.poster || ''),
|
||||
year: movie.year || undefined,
|
||||
time: movie.time || undefined,
|
||||
episode: movie.episode || undefined,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { movies } from '../../database/schema'
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import type { MovieDetail, NormalizedServer } from '../../utils/movies'
|
||||
import { proxyImageUrl } from '../../utils/proxy-image'
|
||||
|
||||
function mapCustomServers(movie: any): NormalizedServer[] {
|
||||
let raw = movie.customServers ?? movie.custom_servers
|
||||
@@ -30,8 +31,8 @@ function mapMovieToDetail(movie: any): MovieDetail {
|
||||
name: movie.name,
|
||||
originName: movie.originName || '',
|
||||
slug: movie.slug,
|
||||
thumb: movie.customThumb || movie.thumb || '',
|
||||
poster: movie.customPoster || movie.poster || '',
|
||||
thumb: movie.customThumb ? proxyImageUrl(movie.customThumb) : proxyImageUrl(movie.thumb || ''),
|
||||
poster: movie.customPoster ? proxyImageUrl(movie.customPoster) : proxyImageUrl(movie.poster || ''),
|
||||
year: movie.year || undefined,
|
||||
time: movie.time || undefined,
|
||||
episode: movie.episode || undefined,
|
||||
|
||||
+17
-8
@@ -1,3 +1,5 @@
|
||||
import { proxyImageUrl } from './proxy-image'
|
||||
|
||||
type Source = 'ophim' | 'nguonc' | 'kkphim'
|
||||
type SourceFilter = Source | 'all'
|
||||
|
||||
@@ -304,23 +306,26 @@ function normalizeActor(actor: any): NormalizedActor | undefined {
|
||||
const name = text(actor?.name || actor?.actor_name || actor?.title).trim()
|
||||
if (!name) return undefined
|
||||
|
||||
const avatarUrl = joinImage('', actor?.avatar || actor?.image || actor?.thumb_url || actor?.poster_url)
|
||||
return {
|
||||
name,
|
||||
originalName: text(actor?.original_name || actor?.origin_name || actor?.real_name) || undefined,
|
||||
role: text(actor?.role || actor?.character || actor?.as || actor?.cast_name) || undefined,
|
||||
avatar: joinImage('', actor?.avatar || actor?.image || actor?.thumb_url || actor?.poster_url) || undefined,
|
||||
avatar: proxyImageUrl(avatarUrl),
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeOphimMovie(movie: any, pathImage = OPHIM_IMAGE): NormalizedMovie {
|
||||
const thumbUrl = joinOphimImage(pathImage, movie?.thumb_url)
|
||||
const posterUrl = joinOphimImage(pathImage, movie?.poster_url)
|
||||
return {
|
||||
id: `ophim:${movie?._id ?? movie?.slug}`,
|
||||
source: 'ophim',
|
||||
name: text(movie?.name, 'Chưa có tên'),
|
||||
originName: text(movie?.origin_name),
|
||||
slug: text(movie?.slug),
|
||||
thumb: joinOphimImage(pathImage, movie?.thumb_url),
|
||||
poster: joinOphimImage(pathImage, movie?.poster_url),
|
||||
thumb: proxyImageUrl(thumbUrl),
|
||||
poster: proxyImageUrl(posterUrl),
|
||||
year: Number(movie?.year) || undefined,
|
||||
time: text(movie?.time),
|
||||
episode: text(movie?.episode_current),
|
||||
@@ -336,14 +341,16 @@ export function normalizeOphimMovie(movie: any, pathImage = OPHIM_IMAGE): Normal
|
||||
}
|
||||
|
||||
export function normalizeKkphimMovie(movie: any, pathImage = KKPHIM_IMAGE): NormalizedMovie {
|
||||
const thumbUrl = joinKkphimImage(pathImage, movie?.thumb_url)
|
||||
const posterUrl = joinKkphimImage(pathImage, movie?.poster_url)
|
||||
return {
|
||||
id: `kkphim:${movie?._id ?? movie?.slug}`,
|
||||
source: 'kkphim',
|
||||
name: text(movie?.name, 'Chưa có tên'),
|
||||
name: text(movie?.name, 'Chưa có tên'),
|
||||
originName: text(movie?.origin_name),
|
||||
slug: text(movie?.slug),
|
||||
thumb: joinKkphimImage(pathImage, movie?.thumb_url),
|
||||
poster: joinKkphimImage(pathImage, movie?.poster_url),
|
||||
thumb: proxyImageUrl(thumbUrl),
|
||||
poster: proxyImageUrl(posterUrl),
|
||||
year: Number(movie?.year) || undefined,
|
||||
time: text(movie?.time),
|
||||
episode: text(movie?.episode_current),
|
||||
@@ -360,6 +367,8 @@ export function normalizeKkphimMovie(movie: any, pathImage = KKPHIM_IMAGE): Norm
|
||||
|
||||
function normalizeNguoncMovie(movie: any): NormalizedMovie {
|
||||
const image = movie?.thumb_url || movie?.poster_url || movie?.image || movie?.thumbnail
|
||||
const thumbUrl = joinImage('', image)
|
||||
const posterUrl = joinImage('', movie?.poster_url)
|
||||
|
||||
return {
|
||||
id: `nguonc:${movie?._id ?? movie?.slug}`,
|
||||
@@ -367,8 +376,8 @@ function normalizeNguoncMovie(movie: any): NormalizedMovie {
|
||||
name: text(movie?.name || movie?.title, 'Chưa có tên'),
|
||||
originName: text(movie?.original_name || movie?.origin_name),
|
||||
slug: text(movie?.slug),
|
||||
thumb: joinImage('', image),
|
||||
poster: joinImage('', movie?.poster_url),
|
||||
thumb: proxyImageUrl(thumbUrl),
|
||||
poster: proxyImageUrl(posterUrl),
|
||||
year: Number(movie?.year || movie?.release_year) || undefined,
|
||||
time: text(movie?.time || movie?.duration),
|
||||
episode: text(movie?.episode_current || movie?.current_episode),
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Transform image URLs to use the internal image proxy.
|
||||
* This converts remote images to WebP format for faster loading.
|
||||
*/
|
||||
export function proxyImageUrl(url: string): string {
|
||||
if (!url) return ''
|
||||
if (url.startsWith('/api/image-proxy')) return url
|
||||
|
||||
// Nếu đã có sẵn query params
|
||||
const separator = url.includes('?') ? '&' : '?'
|
||||
return `/api/image-proxy?url=${encodeURIComponent(url)}`
|
||||
}
|
||||
|
||||
export function proxyThumbUrl(url: string): string {
|
||||
return proxyImageUrl(url)
|
||||
}
|
||||
|
||||
export function proxyPosterUrl(url: string): string {
|
||||
return proxyImageUrl(url)
|
||||
}
|
||||
Reference in New Issue
Block a user