mirror of
https://github.com/ngthanhvu/kr-phim.git
synced 2026-08-10 15:07:46 +00:00
feat: add HLS proxy, view tracking, and player improvements
- Add HLS proxy middleware for CORS bypass - Add view tracking API endpoint - Improve HLS player with proxy fallback mechanism - Add custom episode support in admin - Update admin movie list with view count - Add description expand/collapse on movie detail - Fix hydration warnings in watch page
This commit is contained in:
@@ -89,7 +89,7 @@ watch(() => route.path, () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="fixed inset-x-0 top-0 z-50 bg-gradient-to-b from-black/80 via-black/40 to-transparent">
|
||||
<header class="fixed inset-x-0 top-0 z-50 bg-linear-to-b from-black/80 via-black/40 to-transparent">
|
||||
<nav class="mx-auto flex max-w-390 items-center gap-3 px-4 py-3 sm:px-6 lg:gap-6 lg:px-8 xl:px-10">
|
||||
<AppLogo />
|
||||
|
||||
@@ -115,7 +115,8 @@ watch(() => route.path, () => {
|
||||
class="inline-flex h-9 shrink-0 cursor-pointer items-center gap-1.5 rounded-full bg-white px-2.5 pl-1 text-xs font-black text-slate-950 shadow-xl shadow-black/20 transition hover:bg-yellow-100"
|
||||
aria-label="Tài khoản thành viên" @click="handleMemberClick">
|
||||
<template v-if="user">
|
||||
<span class="grid size-7 place-items-center rounded-full bg-yellow-400/20 text-xs font-black text-yellow-400">
|
||||
<span
|
||||
class="grid size-7 place-items-center rounded-full bg-yellow-400/20 text-xs font-black text-yellow-400">
|
||||
{{ displayInitial }}
|
||||
</span>
|
||||
<span class="max-w-24 truncate">{{ displayName }}</span>
|
||||
@@ -171,7 +172,8 @@ watch(() => route.path, () => {
|
||||
</div>
|
||||
|
||||
<div v-if="user" class="flex items-center gap-3 border-b border-white/10 px-4 py-4">
|
||||
<span class="grid size-9 place-items-center rounded-full bg-yellow-400/10 text-sm font-black text-yellow-400">
|
||||
<span
|
||||
class="grid size-9 place-items-center rounded-full bg-yellow-400/10 text-sm font-black text-yellow-400">
|
||||
{{ displayInitial }}
|
||||
</span>
|
||||
<div class="min-w-0">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { Circle, Heart, Play } from 'lucide-vue-next'
|
||||
import { ChevronDown, ChevronUp, Circle, Heart, Play } from 'lucide-vue-next'
|
||||
|
||||
const props = defineProps<{
|
||||
movie: {
|
||||
@@ -21,6 +21,7 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const isPreviewVisible = ref(false)
|
||||
const isDescriptionExpanded = ref(false)
|
||||
const previewStyle = ref<Record<string, string>>({})
|
||||
let hideTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
@@ -62,6 +63,7 @@ function scheduleHide() {
|
||||
if (hideTimer) clearTimeout(hideTimer)
|
||||
hideTimer = setTimeout(() => {
|
||||
isPreviewVisible.value = false
|
||||
isDescriptionExpanded.value = false
|
||||
}, 90)
|
||||
}
|
||||
|
||||
@@ -137,13 +139,25 @@ onBeforeUnmount(() => {
|
||||
movie.episode }}</span>
|
||||
</div>
|
||||
|
||||
<p class="mt-3 line-clamp-2 text-xs font-bold leading-6 text-slate-200">
|
||||
<template v-if="movie.countries?.length">{{ movie.countries.slice(0, 2).join(' • ') }}</template>
|
||||
<template v-if="movie.countries?.length && movie.categories?.length"> • </template>
|
||||
<template v-if="movie.categories?.length">{{ movie.categories.slice(0, 3).join(' • ') }}</template>
|
||||
<template v-if="!movie.countries?.length && !movie.categories?.length">Phim Hàn Quốc Vietsub mới cập
|
||||
nhật</template>
|
||||
</p>
|
||||
<div class="mt-3">
|
||||
<p class="text-xs font-bold leading-6 text-slate-200" :class="isDescriptionExpanded ? '' : 'line-clamp-1'">
|
||||
<template v-if="movie.countries?.length">{{ movie.countries.slice(0, 2).join(' • ') }}</template>
|
||||
<template v-if="movie.countries?.length && movie.categories?.length"> • </template>
|
||||
<template v-if="movie.categories?.length">{{ movie.categories.slice(0, 3).join(' • ') }}</template>
|
||||
<template v-if="!movie.countries?.length && !movie.categories?.length">Phim Hàn Quốc Vietsub mới cập
|
||||
nhật</template>
|
||||
</p>
|
||||
<button type="button"
|
||||
class="mt-1 inline-flex items-center gap-0.5 text-[10px] font-semibold text-yellow-300 transition hover:text-yellow-200"
|
||||
@click.stop="isDescriptionExpanded = !isDescriptionExpanded">
|
||||
<template v-if="isDescriptionExpanded">
|
||||
Thu gọn <ChevronUp class="size-3" />
|
||||
</template>
|
||||
<template v-else>
|
||||
Xem thêm <ChevronDown class="size-3" />
|
||||
</template>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</Transition>
|
||||
|
||||
@@ -134,6 +134,7 @@ const totalPages = computed(() => data.value?.totalPages || 1)
|
||||
<th class="w-12 px-4 py-3 text-center">STT</th>
|
||||
<th class="px-4 py-3 text-center">Phim</th>
|
||||
<th class="px-4 py-3 text-center">Nguồn</th>
|
||||
<th class="px-4 py-3 text-center">Lượt xem</th>
|
||||
<th class="px-4 py-3 text-center">Trạng thái</th>
|
||||
<th class="px-4 py-3 text-center">Chỉnh sửa</th>
|
||||
<th class="px-4 py-3 text-center">Thao tác</th>
|
||||
@@ -155,6 +156,9 @@ const totalPages = computed(() => data.value?.totalPages || 1)
|
||||
{{ movie.source?.toUpperCase() }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-center text-sm text-slate-300">
|
||||
{{ (movie.views || 0).toLocaleString() }}
|
||||
</td>
|
||||
<td class="px-4 py-3 text-center">
|
||||
<span class="rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||
:class="movie.active ? 'bg-green-400/10 text-green-400' : 'bg-slate-400/10 text-slate-400'">
|
||||
@@ -188,7 +192,7 @@ const totalPages = computed(() => data.value?.totalPages || 1)
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!movies.length">
|
||||
<td colspan="6" class="px-4 py-12 text-center text-sm text-slate-400">
|
||||
<td colspan="7" class="px-4 py-12 text-center text-sm text-slate-400">
|
||||
{{ debouncedKeyword ? 'Không tìm thấy phim nào.' : 'Chưa có phim nào. Bấm "Đồng bộ từ API" để lấy phim.' }}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
+3
-2
@@ -96,8 +96,9 @@ function movieUpdateTime(movie: any) {
|
||||
}
|
||||
|
||||
const topTrending = computed(() => [...homeCatalog.value]
|
||||
.sort((a: any, b: any) => (Number(b.rating) || 0) - (Number(a.rating) || 0)
|
||||
|| movieUpdateTime(b) - movieUpdateTime(a))
|
||||
.filter((movie: any) => (movie.views || 0) > 0)
|
||||
.sort((a: any, b: any) => (Number(b.views) || 0) - (Number(a.views) || 0)
|
||||
|| (Number(b.rating) || 0) - (Number(a.rating) || 0))
|
||||
.slice(0, 10))
|
||||
|
||||
const latestMovies = computed(() => withoutMovies(homeCatalog.value, topTrending.value)
|
||||
|
||||
@@ -6,6 +6,7 @@ const requestedSource = computed(() => String(route.query.source || 'nguonc'))
|
||||
const requestedSources = computed(() => typeof route.query.srcs === 'string' ? route.query.srcs : '')
|
||||
const selectedServer = ref(0)
|
||||
const movieInfoOpen = ref(false)
|
||||
const contentExpanded = ref(false)
|
||||
const activeTab = ref<'episodes' | 'actors'>('episodes')
|
||||
const isFavoriteMovie = ref(false)
|
||||
const actionMessage = ref('')
|
||||
@@ -164,6 +165,10 @@ async function shareMovie() {
|
||||
|
||||
onMounted(async () => {
|
||||
await refreshFavoriteState()
|
||||
await $fetch(`/api/movies/${route.params.slug}/view`, {
|
||||
method: 'POST',
|
||||
query: { source: route.query.source },
|
||||
}).catch(() => {})
|
||||
})
|
||||
|
||||
watch(requestedSource, () => {
|
||||
@@ -253,10 +258,16 @@ useHead(() => ({
|
||||
</div>
|
||||
|
||||
<div class="mt-4 hidden space-y-3 text-sm leading-6 text-slate-300 sm:block lg:mt-5">
|
||||
<p v-if="movie.content">
|
||||
<div v-if="movie.content">
|
||||
<span class="block font-black text-white">Giới thiệu:</span>
|
||||
{{ movie.content }}
|
||||
</p>
|
||||
<p class="mt-1" :class="contentExpanded ? '' : 'line-clamp-3'">{{ movie.content }}</p>
|
||||
<button type="button"
|
||||
class="mt-1 inline-flex items-center gap-1 text-xs font-semibold text-yellow-300 transition hover:text-yellow-200"
|
||||
@click="contentExpanded = !contentExpanded">
|
||||
{{ contentExpanded ? 'Thu gọn' : 'Xem thêm' }}
|
||||
<ChevronDown class="size-3 transition" :class="contentExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
</div>
|
||||
<p><span class="font-black text-white">Số tập:</span> {{
|
||||
episodeCount || movie.episode || 'Đang cập nhật'
|
||||
}}</p>
|
||||
@@ -278,10 +289,16 @@ useHead(() => ({
|
||||
|
||||
<div v-if="movieInfoOpen"
|
||||
class="mb-4 space-y-3 border-b border-white/10 pb-4 text-sm leading-6 text-slate-300 sm:hidden">
|
||||
<p v-if="movie.content">
|
||||
<div v-if="movie.content">
|
||||
<span class="block font-black text-white">Giới thiệu:</span>
|
||||
{{ movie.content }}
|
||||
</p>
|
||||
<p class="mt-1" :class="contentExpanded ? '' : 'line-clamp-3'">{{ movie.content }}</p>
|
||||
<button type="button"
|
||||
class="mt-1 inline-flex items-center gap-1 text-xs font-semibold text-yellow-300 transition hover:text-yellow-200"
|
||||
@click="contentExpanded = !contentExpanded">
|
||||
{{ contentExpanded ? 'Thu gọn' : 'Xem thêm' }}
|
||||
<ChevronDown class="size-3 transition" :class="contentExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
</div>
|
||||
<p><span class="font-black text-white">Số tập:</span> {{
|
||||
episodeCount || movie.episode || 'Đang cập nhật'
|
||||
}}</p>
|
||||
|
||||
+103
-49
@@ -97,6 +97,12 @@ const canUseHls = computed(() => Boolean(hlsPlayerUrl.value))
|
||||
const actorSummary = computed(() => (movie.value?.actors ?? []).map((actor: any) => actor.name).filter(Boolean).slice(0, 6).join(', '))
|
||||
const durationSeconds = computed(() => Math.floor(videoDuration.value || parseDurationSeconds(movie.value?.time || '')))
|
||||
const hasNextEpisode = computed(() => Boolean(activeServer.value?.episodes?.[selectedEpisode.value + 1]))
|
||||
|
||||
function getProxyUrl(url: string): string {
|
||||
const encoded = btoa(url)
|
||||
return `/api/proxy-m3u8/${encoded}`
|
||||
}
|
||||
|
||||
const progressPercent = computed(() => {
|
||||
if (!durationSeconds.value || !progressSeconds.value) return 0
|
||||
return Math.min(Math.max((progressSeconds.value / durationSeconds.value) * 100, 0), 100)
|
||||
@@ -365,8 +371,13 @@ function formatPlayerTime(seconds = 0) {
|
||||
return `${minutes}:${String(remainingSeconds).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
async function setupHlsPlayer(autoplay = false) {
|
||||
if (!import.meta.client || !videoRef.value || !hlsPlayerUrl.value) return
|
||||
async function setupHlsPlayer(autoplay = false, tryProxy = true) {
|
||||
console.log('[HLS] Setup called', { tryProxy, hasVideoRef: !!videoRef.value, hlsUrl: hlsPlayerUrl.value })
|
||||
|
||||
if (!import.meta.client || !videoRef.value || !hlsPlayerUrl.value) {
|
||||
console.log('[HLS] Early return - missing requirements')
|
||||
return
|
||||
}
|
||||
|
||||
destroyHlsPlayer()
|
||||
hlsFatalRetryCount = 0
|
||||
@@ -378,59 +389,102 @@ async function setupHlsPlayer(autoplay = false) {
|
||||
video.muted = isVideoMuted.value
|
||||
video.playbackRate = playbackRate.value
|
||||
|
||||
if (video.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
video.src = hlsPlayerUrl.value
|
||||
// Use proxy if tryProxy is true, otherwise use direct URL
|
||||
let sourceUrl = tryProxy ? getProxyUrl(hlsPlayerUrl.value) : hlsPlayerUrl.value
|
||||
console.log('[HLS] Source URL:', sourceUrl)
|
||||
|
||||
// Force use hls.js when using proxy, as native HLS doesn't handle proxy URLs well
|
||||
if (video.canPlayType('application/vnd.apple.mpegurl') && !tryProxy) {
|
||||
console.log('[HLS] Using native HLS (Safari) - direct URL only')
|
||||
// Native HLS (Safari) - only when using direct URL
|
||||
video.src = sourceUrl
|
||||
scheduleHlsFallback()
|
||||
|
||||
// Listen for errors on native HLS
|
||||
const handleError = () => {
|
||||
console.log('[HLS] Native HLS error, falling back to hls.js')
|
||||
video.removeEventListener('error', handleError)
|
||||
// Fall back to hls.js instead of embed
|
||||
tryProxy = false
|
||||
setupHlsPlayer(autoplay, false)
|
||||
}
|
||||
video.addEventListener('error', handleError)
|
||||
} else {
|
||||
const { default: HlsPlayer } = await import('hls.js')
|
||||
console.log('[HLS] Using hls.js library')
|
||||
try {
|
||||
const { default: HlsPlayer } = await import('hls.js')
|
||||
|
||||
if (!HlsPlayer.isSupported()) {
|
||||
fallbackToEmbed('Trình duyệt chưa hỗ trợ HLS, đã chuyển sang chế độ Nhúng.')
|
||||
return
|
||||
}
|
||||
|
||||
if (!HlsPlayer.isSupported()) {
|
||||
hlsErrorMessage.value = 'Trình duyệt chưa hỗ trợ HLS, bạn dùng chế độ Nhúng nhé.'
|
||||
return
|
||||
}
|
||||
|
||||
hlsPlayer = new HlsPlayer({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: true,
|
||||
})
|
||||
hlsPlayer.on(HlsPlayer.Events.MANIFEST_PARSED, () => {
|
||||
clearHlsFallbackTimer()
|
||||
qualityLevels.value = hlsPlayer?.levels
|
||||
.map((level, index) => ({
|
||||
label: level.height ? `${level.height}p` : `${Math.round((level.bitrate || 0) / 1000)}kbps`,
|
||||
level: index,
|
||||
}))
|
||||
.filter((level) => level.label !== '0kbps') ?? []
|
||||
selectedQuality.value = -1
|
||||
applyResumeProgress()
|
||||
})
|
||||
hlsPlayer.on(HlsPlayer.Events.ERROR, (_event, data) => {
|
||||
if (!data.fatal) return
|
||||
|
||||
hlsFatalRetryCount += 1
|
||||
if (hlsFatalRetryCount >= 2) {
|
||||
fallbackToEmbed('HLS tải không ổn định, đã chuyển sang chế độ Nhúng.')
|
||||
if (!HlsPlayer.isSupported()) {
|
||||
console.log('[HLS] hls.js not supported')
|
||||
fallbackToEmbed('Trình duyệt chưa hỗ trợ HLS, đã chuyển sang chế độ Nhúng.')
|
||||
return
|
||||
}
|
||||
|
||||
if (data.type === HlsPlayer.ErrorTypes.NETWORK_ERROR) {
|
||||
hlsErrorMessage.value = 'Mạng đang chập chờn, đang thử tải lại...'
|
||||
hlsPlayer?.startLoad()
|
||||
} else if (data.type === HlsPlayer.ErrorTypes.MEDIA_ERROR) {
|
||||
hlsErrorMessage.value = 'Video bị lỗi giải mã, đang thử khôi phục...'
|
||||
hlsPlayer?.recoverMediaError()
|
||||
} else {
|
||||
hlsErrorMessage.value = 'Link HLS đang lỗi, bạn chuyển sang chế độ Nhúng nhé.'
|
||||
}
|
||||
})
|
||||
hlsPlayer.loadSource(hlsPlayerUrl.value)
|
||||
hlsPlayer.attachMedia(video)
|
||||
scheduleHlsFallback()
|
||||
hlsPlayer = new HlsPlayer({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: true,
|
||||
xhrSetup: (xhr, url) => {
|
||||
xhr.withCredentials = false
|
||||
},
|
||||
})
|
||||
|
||||
hlsPlayer.on(HlsPlayer.Events.MANIFEST_PARSED, () => {
|
||||
console.log('[HLS] Manifest parsed successfully')
|
||||
clearHlsFallbackTimer()
|
||||
qualityLevels.value = hlsPlayer?.levels
|
||||
.map((level, index) => ({
|
||||
label: level.height ? `${level.height}p` : `${Math.round((level.bitrate || 0) / 1000)}kbps`,
|
||||
level: index,
|
||||
}))
|
||||
.filter((level) => level.label !== '0kbps') ?? []
|
||||
selectedQuality.value = -1
|
||||
applyResumeProgress()
|
||||
})
|
||||
|
||||
hlsPlayer.on(HlsPlayer.Events.ERROR, (_event, data) => {
|
||||
console.log('[HLS] Error:', data.type, data.details, data.fatal)
|
||||
if (!data.fatal) return
|
||||
|
||||
// If using proxy and it fails, try direct URL
|
||||
if (tryProxy) {
|
||||
console.log('[HLS] Proxy failed, trying direct URL')
|
||||
hlsErrorMessage.value = 'Proxy lỗi, đang thử trực tiếp...'
|
||||
hlsPlayer?.destroy()
|
||||
|
||||
// Retry with direct URL
|
||||
setTimeout(() => {
|
||||
setupHlsPlayer(autoplay, false)
|
||||
}, 100)
|
||||
return
|
||||
}
|
||||
|
||||
hlsFatalRetryCount += 1
|
||||
if (hlsFatalRetryCount >= 2) {
|
||||
console.log('[HLS] Too many errors, falling back to embed')
|
||||
fallbackToEmbed('HLS tải không ổn định, đã chuyển sang chế độ Nhúng.')
|
||||
return
|
||||
}
|
||||
|
||||
if (data.type === HlsPlayer.ErrorTypes.NETWORK_ERROR) {
|
||||
hlsErrorMessage.value = 'Mạng đang chập chờn, đang thử tải lại...'
|
||||
hlsPlayer?.startLoad()
|
||||
} else if (data.type === HlsPlayer.ErrorTypes.MEDIA_ERROR) {
|
||||
hlsErrorMessage.value = 'Video bị lỗi giải mã, đang thử khôi phục...'
|
||||
hlsPlayer?.recoverMediaError()
|
||||
} else {
|
||||
hlsErrorMessage.value = 'Link HLS đang lỗi, bạn chuyển sang chế độ Nhúng nhé.'
|
||||
}
|
||||
})
|
||||
|
||||
console.log('[HLS] Loading source and attaching media')
|
||||
hlsPlayer.loadSource(sourceUrl)
|
||||
hlsPlayer.attachMedia(video)
|
||||
scheduleHlsFallback()
|
||||
} catch (error) {
|
||||
console.error('[HLS] Setup error:', error)
|
||||
fallbackToEmbed('Lỗi khởi tạo HLS player, đã chuyển sang chế độ Nhúng.')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (autoplay) {
|
||||
|
||||
Reference in New Issue
Block a user