feat: implement core movie streaming features including dashboard, watch history, authentication, and dynamic media pages

This commit is contained in:
thanhvudaynee
2026-05-21 10:15:02 +07:00
parent bc881aee5b
commit 4a91b03678
16 changed files with 2204 additions and 78 deletions
+2
View File
@@ -0,0 +1,2 @@
SUPABASE_URL=
SUPABASE_KEY=
+355 -3
View File
@@ -1,10 +1,44 @@
<script setup lang="ts">
import { Menu, Search, X } from 'lucide-vue-next'
import {
Bell,
Chrome,
Heart,
History,
Loader2,
LockKeyhole,
LogOut,
Mail,
Menu,
Search,
User,
UserRound,
X,
} from 'lucide-vue-next'
const route = useRoute()
const router = useRouter()
const {
user,
loading: authLoading,
initAuth,
signInWithPassword,
signUpWithPassword,
signInWithGoogle,
resetPassword,
signOut,
} = useSupabaseAuth()
const keyword = ref(typeof route.query.q === 'string' ? route.query.q : '')
const mobileMenuOpen = ref(false)
const loginOpen = ref(false)
const memberMenuOpen = ref(false)
const authMode = ref<'login' | 'register'>('login')
const email = ref('')
const password = ref('')
const authMessage = ref('')
const authError = ref('')
const submittingAuth = ref(false)
const submittingProvider = ref(false)
const defaultAvatar = 'https://thumbs.dreamstime.com/b/avatar-vietnam-character-your-project-others-avatar-vietnam-character-274539000.jpg'
const navItems = [
{ label: 'Trang chủ', to: '/' },
@@ -13,6 +47,26 @@ const navItems = [
{ label: 'Phim lẻ', to: '/phim?type=single' },
]
const memberName = computed(() => {
const metadata = user.value?.user_metadata || {}
const name = metadata.name || metadata.full_name || metadata.user_name
if (typeof name === 'string' && name.trim()) return name.trim()
return user.value?.email?.split('@')[0] || 'Thành viên'
})
const memberAvatar = computed(() => {
const metadata = user.value?.user_metadata || {}
return typeof metadata.avatar_url === 'string' && metadata.avatar_url
? metadata.avatar_url
: defaultAvatar
})
const memberMenuItems = [
{ label: 'Trang cá nhân', icon: UserRound, to: '/thanh-vien' },
{ label: 'Yêu thích', icon: Heart, to: '/yeu-thich' },
{ label: 'Lịch sử', icon: History, to: '/lich-su' },
]
function isActive(to: string) {
if (to === '/') return route.path === '/'
return route.fullPath === to || route.path === to.split('?')[0] && route.fullPath.includes(to.split('?')[1] || '')
@@ -30,8 +84,95 @@ function closeMobileMenu() {
mobileMenuOpen.value = false
}
function openLogin() {
authMessage.value = ''
authError.value = ''
email.value = user.value?.email || ''
password.value = ''
authMode.value = 'login'
loginOpen.value = true
}
function handleMemberClick() {
if (!user.value) {
openLogin()
return
}
memberMenuOpen.value = !memberMenuOpen.value
}
async function submitLogin() {
const trimmedEmail = email.value.trim()
if (!trimmedEmail || !password.value) return
submittingAuth.value = true
authMessage.value = ''
authError.value = ''
const { error } = authMode.value === 'login'
? await signInWithPassword(trimmedEmail, password.value)
: await signUpWithPassword(trimmedEmail, password.value)
submittingAuth.value = false
if (error) {
authError.value = error.message
return
}
authMessage.value = authMode.value === 'login'
? 'Đăng nhập thành công.'
: 'Đăng ký thành công. Nếu Supabase yêu cầu xác nhận, bạn mở email để xác nhận nhé.'
if (authMode.value === 'login') loginOpen.value = false
}
async function handleGoogleLogin() {
submittingProvider.value = true
authError.value = ''
const { error } = await signInWithGoogle()
submittingProvider.value = false
if (error) authError.value = error.message
}
async function handleResetPassword() {
const trimmedEmail = email.value.trim()
if (!trimmedEmail) {
authError.value = 'Nhập email trước để lấy lại mật khẩu nhé.'
return
}
submittingAuth.value = true
authMessage.value = ''
authError.value = ''
const { error } = await resetPassword(trimmedEmail)
submittingAuth.value = false
if (error) {
authError.value = error.message
return
}
authMessage.value = 'Đã gửi email đặt lại mật khẩu.'
}
async function handleSignOut() {
await signOut()
loginOpen.value = false
memberMenuOpen.value = false
}
onMounted(() => {
initAuth()
})
watch(() => route.path, () => {
closeMobileMenu()
memberMenuOpen.value = false
})
watch(user, (currentUser) => {
if (currentUser) loginOpen.value = false
})
</script>
@@ -55,8 +196,47 @@ watch(() => route.path, () => {
class="w-full bg-transparent text-sm text-white outline-none placeholder:text-slate-400">
</form>
<div class="group/member relative hidden shrink-0 items-center gap-3 md:flex" @mouseenter="memberMenuOpen = true"
@mouseleave="memberMenuOpen = false">
<button v-if="user" type="button"
class="grid size-10 cursor-pointer place-items-center rounded-full bg-white/10 text-white transition hover:bg-white/16"
aria-label="Thông báo">
<Bell class="size-4 fill-current" />
</button>
<button type="button"
class="grid size-10 shrink-0 place-items-center rounded-lg border border-white/10 bg-white/8 text-white transition hover:bg-white/16 lg:hidden"
class="inline-flex h-11 shrink-0 cursor-pointer items-center gap-2 rounded-full bg-white px-3 pl-1 text-sm font-black text-slate-950 shadow-xl shadow-black/20 transition hover:bg-sky-100"
:aria-label="user ? 'Tài khoản thành viên' : 'Đăng nhập thành viên'" @click="handleMemberClick">
<Loader2 v-if="authLoading" class="mx-1 size-4 animate-spin" />
<template v-else-if="user">
<img :src="memberAvatar" :alt="memberName"
class="size-8 rounded-full object-cover ring-2 ring-sky-200/80">
</template>
<User v-else class="ml-1 size-4 fill-current" />
<span class="max-w-28 truncate">{{ user ? memberName : 'Thành viên' }}</span>
</button>
<Transition name="member-menu">
<div v-if="user && memberMenuOpen"
class="absolute right-0 top-[calc(100%+0.75rem)] w-64 overflow-hidden rounded-lg border border-white/10 bg-[#101116] py-2 text-sm font-semibold text-slate-200 shadow-2xl shadow-black/40">
<NuxtLink v-for="item in memberMenuItems" :key="item.label" :to="item.to"
class="flex h-12 w-full cursor-pointer items-center gap-3 px-5 text-left transition hover:bg-white/8 hover:text-white">
<component :is="item.icon" class="size-4 shrink-0" />
{{ item.label }}
</NuxtLink>
<div class="my-2 border-t border-white/10" />
<button type="button"
class="flex h-12 w-full cursor-pointer items-center gap-3 px-5 text-left font-black text-sky-300 transition hover:bg-white/8 hover:text-white"
@click="handleSignOut">
<LogOut class="size-4 shrink-0" />
Đăng xuất
</button>
</div>
</Transition>
</div>
<button type="button"
class="grid size-10 shrink-0 cursor-pointer place-items-center rounded-lg border border-white/10 bg-white/8 text-white transition hover:bg-white/16 lg:hidden"
aria-label="Mở menu" @click="mobileMenuOpen = true">
<Menu class="size-5" />
</button>
@@ -70,7 +250,7 @@ watch(() => route.path, () => {
<div class="flex items-center justify-between border-b border-white/10 px-4 py-4">
<AppLogo />
<button type="button"
class="grid size-10 place-items-center rounded-lg border border-white/10 bg-white/8 text-white transition hover:bg-white/16"
class="grid size-10 cursor-pointer place-items-center rounded-lg border border-white/10 bg-white/8 text-white transition hover:bg-white/16"
aria-label="Đóng menu" @click="closeMobileMenu">
<X class="size-5" />
</button>
@@ -82,6 +262,132 @@ watch(() => route.path, () => {
{{ item.label }}
</NuxtLink>
</nav>
<div class="border-t border-white/10 p-4">
<button type="button"
class="inline-flex h-11 w-full cursor-pointer items-center justify-center gap-2 rounded-full bg-white px-4 text-sm font-black text-slate-950 transition hover:bg-sky-100"
@click="handleMemberClick">
<img v-if="user" :src="memberAvatar" :alt="memberName"
class="size-7 rounded-full object-cover">
<User v-else class="size-4 fill-current" />
<span>{{ user ? memberName : 'Đăng nhập thành viên' }}</span>
</button>
<div v-if="user" class="mt-3 overflow-hidden rounded-lg border border-white/10 bg-white/5">
<NuxtLink v-for="item in memberMenuItems" :key="item.label" :to="item.to"
class="flex h-11 w-full cursor-pointer items-center gap-3 px-4 text-left text-sm font-semibold text-slate-200 transition hover:bg-white/8 hover:text-white">
<component :is="item.icon" class="size-4 shrink-0" />
{{ item.label }}
</NuxtLink>
<div class="border-t border-white/10" />
<button type="button"
class="flex h-11 w-full cursor-pointer items-center gap-3 px-4 text-left text-sm font-black text-sky-300 transition hover:bg-white/8 hover:text-white"
@click="handleSignOut">
<LogOut class="size-4 shrink-0" />
Đăng xuất
</button>
</div>
</div>
</div>
</div>
</Transition>
<Transition name="auth-modal">
<div v-if="loginOpen" class="fixed inset-0 z-70 grid place-items-center px-3 py-6">
<div class="absolute inset-0 bg-slate-950/80 backdrop-blur-sm" @click="loginOpen = false" />
<div
class="relative grid w-full max-w-5xl overflow-hidden rounded-lg border border-white/10 bg-slate-950 text-white shadow-2xl shadow-black/50 md:grid-cols-[1fr_1fr]">
<button type="button"
class="absolute right-3 top-3 z-10 grid size-9 place-items-center rounded-full text-white transition hover:bg-white/10"
aria-label="Đóng đăng nhập" @click="loginOpen = false">
<X class="size-5" />
</button>
<div class="auth-poster-panel hidden min-h-[32rem] items-end p-8 md:flex">
<div>
<AppLogo />
</div>
</div>
<div class="bg-slate-950 px-5 py-10 sm:px-10 md:px-16 md:py-16">
<div v-if="user">
<p class="text-sm font-bold text-sky-300">Thành viên</p>
<h2 class="mt-2 text-2xl font-black">Tài khoản của bạn</h2>
<p class="mt-6 rounded-md bg-white/8 px-4 py-3 text-sm font-semibold text-slate-100">{{ user.email }}</p>
<button type="button"
class="mt-5 inline-flex h-12 w-full items-center justify-center gap-2 rounded-md bg-sky-300 text-sm font-black text-slate-950 transition hover:bg-white"
@click="handleSignOut">
<LogOut class="size-4" />
Đăng xuất
</button>
</div>
<form v-else @submit.prevent="submitLogin">
<h2 class="text-2xl font-black">{{ authMode === 'login' ? 'Đăng nhập' : 'Đăng ký' }}</h2>
<p class="mt-5 text-sm text-slate-300">
<template v-if="authMode === 'login'">
Nếu bạn chưa tài khoản,
<button type="button" class="font-black text-sky-300 hover:text-white"
@click="authMode = 'register'; authError = ''; authMessage = ''">
đăng ngay
</button>
</template>
<template v-else>
Nếu bạn đã tài khoản,
<button type="button" class="font-black text-sky-300 hover:text-white"
@click="authMode = 'login'; authError = ''; authMessage = ''">
đăng nhập ngay
</button>
</template>
</p>
<div class="mt-8 space-y-3">
<div class="flex h-12 items-center rounded-md border border-white/10 bg-white/8 px-4">
<Mail class="mr-3 size-4 shrink-0 text-slate-400" />
<input v-model="email" type="email" required placeholder="Email"
class="h-full w-full bg-transparent text-sm text-white outline-none placeholder:text-slate-400">
</div>
<div class="flex h-12 items-center rounded-md border border-white/10 bg-white/8 px-4">
<LockKeyhole class="mr-3 size-4 shrink-0 text-slate-400" />
<input v-model="password" type="password" required minlength="6" placeholder="Mật khẩu"
class="h-full w-full bg-transparent text-sm text-white outline-none placeholder:text-slate-400">
</div>
</div>
<button type="button"
class="mt-5 inline-flex h-12 w-full items-center justify-center gap-2 rounded-md border border-white/12 bg-white/8 text-sm font-black text-white transition hover:bg-white/14 disabled:cursor-not-allowed disabled:opacity-70"
:disabled="submittingProvider" @click="handleGoogleLogin">
<Loader2 v-if="submittingProvider" class="size-4 animate-spin" />
<Chrome v-else class="size-4" />
Tiếp tục với Google
</button>
<div class="my-5 flex items-center gap-3 text-xs font-semibold text-slate-400">
<span class="h-px flex-1 bg-white/10" />
hoặc
<span class="h-px flex-1 bg-white/10" />
</div>
<button type="submit"
class="inline-flex h-12 w-full items-center justify-center gap-2 rounded-md bg-sky-300 text-sm font-black text-slate-950 transition hover:bg-white disabled:cursor-not-allowed disabled:opacity-70"
:disabled="submittingAuth">
<Loader2 v-if="submittingAuth" class="size-4 animate-spin" />
<User v-else class="size-4 fill-current" />
{{ authMode === 'login' ? 'Đăng nhập' : 'Đăng ký' }}
</button>
<button v-if="authMode === 'login'" type="button"
class="mt-7 block w-full text-center text-sm font-bold text-white hover:text-sky-300"
@click="handleResetPassword">
Quên mật khẩu?
</button>
<p v-if="authMessage" class="mt-4 rounded-md bg-emerald-400/12 px-3 py-2 text-sm text-emerald-100">
{{ authMessage }}
</p>
<p v-if="authError" class="mt-4 rounded-md bg-red-500/12 px-3 py-2 text-sm text-red-100">
{{ authError }}
</p>
</form>
</div>
</div>
</div>
</Transition>
@@ -109,4 +415,50 @@ watch(() => route.path, () => {
.sidebar-leave-to>div:last-child {
transform: translateX(-100%);
}
.auth-modal-enter-active,
.auth-modal-leave-active {
transition: opacity 0.18s ease;
}
.auth-modal-enter-from,
.auth-modal-leave-to {
opacity: 0;
}
.member-menu-enter-active,
.member-menu-leave-active {
transition: opacity 0.16s ease, transform 0.16s ease;
}
.member-menu-enter-from,
.member-menu-leave-to {
opacity: 0;
transform: translateY(-0.35rem);
}
.auth-poster-panel {
background:
linear-gradient(180deg, rgba(2, 6, 23, 0.45), rgba(2, 6, 23, 0.92)),
linear-gradient(135deg, rgba(125, 211, 252, 0.12) 0 18%, transparent 18% 100%),
radial-gradient(circle at 22% 18%, rgba(56, 189, 248, 0.24), transparent 8rem),
linear-gradient(120deg, #07111f 0%, #0f172a 54%, #020617 100%);
position: relative;
}
.auth-poster-panel::before {
position: absolute;
inset: 0;
background-image:
linear-gradient(115deg, transparent 0 10%, rgba(125, 211, 252, 0.12) 10% 10.6%, transparent 10.6% 100%),
repeating-linear-gradient(105deg, rgba(255, 255, 255, 0.06) 0 7.5rem, transparent 7.5rem 8rem),
repeating-linear-gradient(15deg, rgba(14, 165, 233, 0.08) 0 10rem, transparent 10rem 10.6rem);
content: "";
opacity: 0.75;
}
.auth-poster-panel > div {
position: relative;
z-index: 1;
}
</style>
+149
View File
@@ -0,0 +1,149 @@
export type LibraryMovieItem = {
source: string
slug: string
name: string
originName?: string
thumb?: string
poster?: string
updatedAt?: number
}
const favoriteKey = 'kr-phim-favorites'
const watchLaterKey = 'kr-phim-watch-later'
function normalizeLibraryItem(item: any): LibraryMovieItem | null {
if (!item?.slug || !item?.name) return null
return {
source: String(item.source || ''),
slug: String(item.slug),
name: String(item.name),
originName: item.originName || item.origin_name || undefined,
thumb: item.thumb || undefined,
poster: item.poster || undefined,
updatedAt: typeof item.updatedAt === 'number'
? item.updatedAt
: new Date(item.updated_at || Date.now()).getTime(),
}
}
function readLocalItems(key: string) {
if (!import.meta.client) return []
try {
const raw = window.localStorage.getItem(key)
const items = raw ? JSON.parse(raw) : []
return Array.isArray(items)
? items.map(normalizeLibraryItem).filter(Boolean) as LibraryMovieItem[]
: []
} catch {
return []
}
}
function writeLocalItems(key: string, items: LibraryMovieItem[]) {
if (!import.meta.client) return
window.localStorage.setItem(key, JSON.stringify(items))
}
export function useMovieLibrary() {
const { $supabase } = useNuxtApp()
const { user } = useSupabaseAuth()
async function loadItems(key: string, table: string, limit = 30) {
const localItems = readLocalItems(key)
if (user.value) {
const { data, error } = await $supabase
.from(table)
.select('source, slug, name, origin_name, thumb, poster, updated_at')
.eq('user_id', user.value.id)
.order('updated_at', { ascending: false })
.limit(limit)
if (!error && data) {
return data.map(normalizeLibraryItem).filter(Boolean) as LibraryMovieItem[]
}
}
return localItems
.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
.slice(0, limit)
}
async function saveItem(key: string, table: string, item: LibraryMovieItem) {
const normalizedItem = normalizeLibraryItem({
...item,
updatedAt: Date.now(),
})
if (!normalizedItem) return false
const nextItems = [
normalizedItem,
...readLocalItems(key).filter((savedItem) => !(savedItem.slug === normalizedItem.slug && savedItem.source === normalizedItem.source)),
].slice(0, 50)
writeLocalItems(key, nextItems)
if (user.value) {
await $supabase
.from(table)
.upsert({
user_id: user.value.id,
source: normalizedItem.source,
slug: normalizedItem.slug,
name: normalizedItem.name,
origin_name: normalizedItem.originName || null,
thumb: normalizedItem.thumb || null,
poster: normalizedItem.poster || null,
updated_at: new Date(normalizedItem.updatedAt || Date.now()).toISOString(),
}, {
onConflict: 'user_id,source,slug',
})
}
return true
}
async function removeItem(key: string, table: string, item: LibraryMovieItem) {
const nextItems = readLocalItems(key)
.filter((savedItem) => !(savedItem.slug === item.slug && savedItem.source === item.source))
writeLocalItems(key, nextItems)
if (user.value) {
await $supabase
.from(table)
.delete()
.eq('user_id', user.value.id)
.eq('source', item.source)
.eq('slug', item.slug)
}
}
async function isSaved(key: string, table: string, item: LibraryMovieItem) {
const localSaved = readLocalItems(key)
.some((savedItem) => savedItem.slug === item.slug && savedItem.source === item.source)
if (!user.value) return localSaved
const { data, error } = await $supabase
.from(table)
.select('slug')
.eq('user_id', user.value.id)
.eq('source', item.source)
.eq('slug', item.slug)
.maybeSingle()
return error ? localSaved : Boolean(data)
}
return {
loadFavorites: (limit?: number) => loadItems(favoriteKey, 'favorite_movies', limit),
saveFavorite: (item: LibraryMovieItem) => saveItem(favoriteKey, 'favorite_movies', item),
removeFavorite: (item: LibraryMovieItem) => removeItem(favoriteKey, 'favorite_movies', item),
isFavorite: (item: LibraryMovieItem) => isSaved(favoriteKey, 'favorite_movies', item),
saveWatchLater: (item: LibraryMovieItem) => saveItem(watchLaterKey, 'watch_later_movies', item),
}
}
+86
View File
@@ -0,0 +1,86 @@
import type { User } from '@supabase/supabase-js'
let authListenerStarted = false
export function useSupabaseAuth() {
const { $supabase } = useNuxtApp()
const user = useState<User | null>('supabase-user', () => null)
const loading = useState('supabase-auth-loading', () => false)
async function initAuth() {
if (!import.meta.client || authListenerStarted) return
authListenerStarted = true
loading.value = true
const { data } = await $supabase.auth.getSession()
user.value = data.session?.user ?? null
loading.value = false
$supabase.auth.onAuthStateChange((_event, session) => {
user.value = session?.user ?? null
})
}
function authRedirectUrl() {
const redirectTo = import.meta.client ? window.location.origin : undefined
return redirectTo
}
async function signInWithEmail(email: string) {
return $supabase.auth.signInWithOtp({
email,
options: {
emailRedirectTo: authRedirectUrl(),
},
})
}
async function signInWithPassword(email: string, password: string) {
return $supabase.auth.signInWithPassword({
email,
password,
})
}
async function signUpWithPassword(email: string, password: string) {
return $supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: authRedirectUrl(),
},
})
}
async function signInWithGoogle() {
return $supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: authRedirectUrl(),
},
})
}
async function resetPassword(email: string) {
return $supabase.auth.resetPasswordForEmail(email, {
redirectTo: authRedirectUrl(),
})
}
async function signOut() {
return $supabase.auth.signOut()
}
return {
user,
loading,
initAuth,
signInWithEmail,
signInWithPassword,
signUpWithPassword,
signInWithGoogle,
resetPassword,
signOut,
}
}
+167
View File
@@ -0,0 +1,167 @@
export type WatchHistoryItem = {
source: string
slug: string
name: string
originName?: string
thumb?: string
poster?: string
episodeName?: string
episodeIndex?: number
serverIndex?: number
progressSeconds?: number
durationSeconds?: number
updatedAt?: number
}
const watchHistoryKey = 'kr-phim-watch-history'
function normalizeHistoryItem(item: any): WatchHistoryItem | null {
const slug = item?.slug
const name = item?.name
if (!slug || !name) return null
return {
source: String(item.source || ''),
slug: String(slug),
name: String(name),
originName: item.originName || item.origin_name || undefined,
thumb: item.thumb || undefined,
poster: item.poster || undefined,
episodeName: item.episodeName || item.episode_name || undefined,
episodeIndex: Number(item.episodeIndex ?? item.episode_index ?? 0),
serverIndex: Number(item.serverIndex ?? item.server_index ?? 0),
progressSeconds: Math.max(Number(item.progressSeconds ?? item.progress_seconds ?? 0), 0),
durationSeconds: Math.max(Number(item.durationSeconds ?? item.duration_seconds ?? 0), 0),
updatedAt: typeof item.updatedAt === 'number'
? item.updatedAt
: new Date(item.updated_at || Date.now()).getTime(),
}
}
function readLocalHistory() {
if (!import.meta.client) return []
try {
const raw = window.localStorage.getItem(watchHistoryKey)
const history = raw ? JSON.parse(raw) : []
return Array.isArray(history)
? history
.map(normalizeHistoryItem)
.filter(Boolean) as WatchHistoryItem[]
: []
} catch {
return []
}
}
function writeLocalHistory(items: WatchHistoryItem[]) {
if (!import.meta.client) return
window.localStorage.setItem(watchHistoryKey, JSON.stringify(items))
}
export function useWatchHistory() {
const { $supabase } = useNuxtApp()
const { user } = useSupabaseAuth()
async function loadWatchHistory(limit = 12) {
const localItems = readLocalHistory()
if (user.value) {
if (localItems.length) {
await $supabase
.from('watch_history')
.upsert(localItems.slice(0, 20).map((item) => ({
user_id: user.value?.id,
source: item.source,
slug: item.slug,
name: item.name,
origin_name: item.originName || null,
thumb: item.thumb || null,
poster: item.poster || null,
episode_name: item.episodeName || null,
episode_index: item.episodeIndex || 0,
server_index: item.serverIndex || 0,
progress_seconds: Math.floor(item.progressSeconds || 0),
duration_seconds: Math.floor(item.durationSeconds || 0),
updated_at: new Date(item.updatedAt || Date.now()).toISOString(),
})), {
onConflict: 'user_id,source,slug',
})
}
const { data, error } = await $supabase
.from('watch_history')
.select('source, slug, name, origin_name, thumb, poster, episode_name, episode_index, server_index, progress_seconds, duration_seconds, updated_at')
.eq('user_id', user.value.id)
.order('updated_at', { ascending: false })
.limit(limit)
if (!error && data) {
return data
.map(normalizeHistoryItem)
.filter(Boolean) as WatchHistoryItem[]
}
}
return localItems
.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
.slice(0, limit)
}
async function saveWatchHistory(item: WatchHistoryItem) {
const normalizedItem = normalizeHistoryItem({
...item,
updatedAt: item.updatedAt || Date.now(),
})
if (!normalizedItem) return
const localItems = [
normalizedItem,
...readLocalHistory().filter((historyItem) => !(historyItem.slug === normalizedItem.slug && historyItem.source === normalizedItem.source)),
].slice(0, 20)
writeLocalHistory(localItems)
if (!user.value) return
await $supabase
.from('watch_history')
.upsert({
user_id: user.value.id,
source: normalizedItem.source,
slug: normalizedItem.slug,
name: normalizedItem.name,
origin_name: normalizedItem.originName || null,
thumb: normalizedItem.thumb || null,
poster: normalizedItem.poster || null,
episode_name: normalizedItem.episodeName || null,
episode_index: normalizedItem.episodeIndex || 0,
server_index: normalizedItem.serverIndex || 0,
progress_seconds: Math.floor(normalizedItem.progressSeconds || 0),
duration_seconds: Math.floor(normalizedItem.durationSeconds || 0),
updated_at: new Date(normalizedItem.updatedAt || Date.now()).toISOString(),
}, {
onConflict: 'user_id,source,slug',
})
}
async function clearWatchHistory() {
if (import.meta.client) window.localStorage.removeItem(watchHistoryKey)
if (user.value) {
await $supabase
.from('watch_history')
.delete()
.eq('user_id', user.value.id)
}
}
return {
loadWatchHistory,
saveWatchHistory,
clearWatchHistory,
}
}
+47 -32
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { BookPlus, ChevronLeft, ChevronRight, Heart, Info, Play, Trash2 } from 'lucide-vue-next'
import type { WatchHistoryItem } from '~/composables/useWatchHistory'
const { data, pending, error } = await useFetch('/api/movies', {
query: {
@@ -12,21 +13,12 @@ const heroIndex = ref(0)
const heroSlides = computed(() => movies.value.slice(0, 6))
const hero = computed(() => heroSlides.value[heroIndex.value] ?? movies.value[0])
const sourceStatus = computed(() => data.value?.sources ?? [])
const watchHistoryKey = 'kr-phim-watch-history'
const watchHistory = ref<WatchHistoryItem[]>([])
type WatchHistoryItem = {
source: string
slug: string
name: string
originName?: string
thumb?: string
poster?: string
episodeName?: string
episodeIndex?: number
serverIndex?: number
updatedAt?: number
}
const { user, initAuth } = useSupabaseAuth()
const {
loadWatchHistory: fetchWatchHistory,
clearWatchHistory: removeWatchHistory,
} = useWatchHistory()
let heroTimer: ReturnType<typeof setInterval> | undefined
@@ -51,6 +43,7 @@ watch(heroSlides, (slides) => {
})
onMounted(() => {
initAuth()
heroTimer = setInterval(nextHero, 6500)
loadWatchHistory()
window.addEventListener('storage', loadWatchHistory)
@@ -61,26 +54,14 @@ onBeforeUnmount(() => {
if (import.meta.client) window.removeEventListener('storage', loadWatchHistory)
})
function loadWatchHistory() {
async function loadWatchHistory() {
if (!import.meta.client) return
try {
const raw = window.localStorage.getItem(watchHistoryKey)
const history = raw ? JSON.parse(raw) : []
watchHistory.value = Array.isArray(history)
? history
.filter((item: WatchHistoryItem) => item?.slug && item?.name)
.sort((a: WatchHistoryItem, b: WatchHistoryItem) => (b.updatedAt || 0) - (a.updatedAt || 0))
.slice(0, 12)
: []
} catch {
watchHistory.value = []
}
watchHistory.value = await fetchWatchHistory(12)
}
function clearWatchHistory() {
async function clearWatchHistory() {
if (!import.meta.client) return
window.localStorage.removeItem(watchHistoryKey)
await removeWatchHistory()
watchHistory.value = []
}
@@ -95,6 +76,36 @@ function watchHistoryLink(item: WatchHistoryItem) {
}
}
function formatWatchTime(seconds = 0) {
const totalSeconds = Math.max(Math.floor(seconds), 0)
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const remainingSeconds = totalSeconds % 60
if (hours) {
return `${hours}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}
return `${minutes}:${String(remainingSeconds).padStart(2, '0')}`
}
function watchProgressPercent(item: WatchHistoryItem) {
if (!item.durationSeconds || !item.progressSeconds) return 6
return Math.min(Math.max((item.progressSeconds / item.durationSeconds) * 100, 6), 100)
}
function watchProgressLabel(item: WatchHistoryItem) {
if (item.progressSeconds && item.durationSeconds) {
return `${formatWatchTime(item.progressSeconds)} / ${formatWatchTime(item.durationSeconds)}`
}
if (item.progressSeconds) {
return `${formatWatchTime(item.progressSeconds)} đã xem`
}
return item.episodeName || `Tập ${(item.episodeIndex || 0) + 1}`
}
const rows = computed(() => [
{
title: 'Mới cập nhật',
@@ -113,6 +124,10 @@ const rows = computed(() => [
},
])
watch(user, () => {
loadWatchHistory()
})
useHead({
title: 'KR Phim - Phim Hàn Quốc',
meta: [
@@ -263,7 +278,7 @@ useHead({
<img :src="item.thumb || item.poster" :alt="item.name"
class="h-full w-full object-cover transition duration-500 group-hover:scale-105">
<div class="absolute inset-x-0 bottom-0 h-1 bg-white/18">
<span class="block h-full w-1/3 bg-sky-300" />
<span class="block h-full bg-sky-300" :style="{ width: `${watchProgressPercent(item)}%` }" />
</div>
<span
class="absolute left-2 top-2 rounded bg-sky-400 px-2 py-1 text-xs font-black text-slate-950">
@@ -276,7 +291,7 @@ useHead({
</div>
<h3 class="mt-3 line-clamp-1 text-center text-sm font-black text-white">{{ item.name }}</h3>
<p class="mt-1 truncate text-center text-xs font-semibold text-slate-400">
{{ item.episodeName || `Tập ${(item.episodeIndex || 0) + 1}` }}
{{ watchProgressLabel(item) }}
</p>
</NuxtLink>
</div>
+102
View File
@@ -0,0 +1,102 @@
<script setup lang="ts">
import { Clock3, Trash2 } from 'lucide-vue-next'
import type { WatchHistoryItem } from '~/composables/useWatchHistory'
const { initAuth } = useSupabaseAuth()
const { loadWatchHistory, clearWatchHistory } = useWatchHistory()
const historyItems = ref<WatchHistoryItem[]>([])
const loading = ref(true)
async function refreshHistory() {
loading.value = true
historyItems.value = await loadWatchHistory(30)
loading.value = false
}
function watchHistoryLink(item: WatchHistoryItem) {
return {
path: `/xem/${item.slug}`,
query: {
source: item.source,
server: item.serverIndex || 0,
ep: (item.episodeIndex || 0) + 1,
},
}
}
async function removeHistory() {
await clearWatchHistory()
historyItems.value = []
}
onMounted(async () => {
await initAuth()
await refreshHistory()
})
useHead({
title: 'Lịch sử xem - KR Phim',
})
</script>
<template>
<main class="min-h-screen bg-slate-950 text-white">
<AppHeader />
<section class="mx-auto max-w-390 px-4 pb-16 pt-28 sm:px-6 lg:px-8 lg:pt-32 xl:px-10">
<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div>
<p class="text-sm font-black uppercase text-sky-300">Thành viên</p>
<h1 class="mt-2 text-3xl font-black sm:text-4xl">Lịch sử xem</h1>
</div>
<button v-if="historyItems.length" type="button"
class="inline-flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-white/10 bg-white/8 px-4 text-sm font-black text-white transition hover:bg-white/14"
@click="removeHistory">
<Trash2 class="size-4" />
Xóa lịch sử
</button>
</div>
<div v-if="loading" class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
<div v-for="item in 12" :key="item" class="aspect-2/3 animate-pulse rounded-md bg-white/10" />
</div>
<div v-else-if="historyItems.length" class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
<NuxtLink v-for="item in historyItems" :key="`${item.source}-${item.slug}`" :to="watchHistoryLink(item)"
class="group block min-w-0">
<div
class="relative aspect-2/3 overflow-hidden rounded-md bg-slate-900 shadow-xl shadow-black/25 ring-1 ring-white/10 transition duration-300 group-hover:-translate-y-1 group-hover:ring-sky-300/60">
<img v-if="item.thumb || item.poster" :src="item.thumb || item.poster" :alt="item.name"
class="h-full w-full object-cover transition duration-500 group-hover:scale-105">
<div v-else class="grid h-full w-full place-items-center bg-white/8">
<Clock3 class="size-10 text-sky-300" />
</div>
<div class="absolute inset-x-0 bottom-0 h-1 bg-white/18">
<span class="block h-full w-1/3 bg-sky-300" />
</div>
<span class="absolute left-2 top-2 rounded bg-sky-400 px-2 py-1 text-xs font-black text-slate-950">
{{ item.episodeName || `Tập ${(item.episodeIndex || 0) + 1}` }}
</span>
</div>
<h2 class="mt-3 truncate text-sm font-black">{{ item.name }}</h2>
<p class="mt-1 truncate text-xs font-semibold text-slate-400">
{{ item.episodeName || `Tập ${(item.episodeIndex || 0) + 1}` }}
</p>
</NuxtLink>
</div>
<div v-else
class="flex min-h-80 flex-col items-center justify-center rounded-lg border border-white/10 bg-white/6 p-6 text-center">
<Clock3 class="size-12 text-sky-300" />
<h2 class="mt-4 text-xl font-black">Chưa lịch sử xem</h2>
<p class="mt-2 max-w-md text-sm leading-6 text-slate-300">
Phim bạn đã xem sẽ xuất hiện đây để bạn thể xem tiếp nhanh hơn.
</p>
<NuxtLink to="/phim"
class="mt-5 inline-flex h-11 items-center justify-center rounded-md bg-sky-300 px-5 text-sm font-black text-slate-950 transition hover:bg-white">
Duyệt phim
</NuxtLink>
</div>
</section>
</main>
</template>
+105 -8
View File
@@ -6,6 +6,16 @@ const requestedSource = computed(() => String(route.query.source || 'ophim'))
const selectedServer = ref(0)
const movieInfoOpen = ref(false)
const activeTab = ref<'episodes' | 'actors'>('episodes')
const isFavoriteMovie = ref(false)
const actionMessage = ref('')
const actionBusy = ref(false)
const { user, initAuth } = useSupabaseAuth()
const {
isFavorite,
saveFavorite,
removeFavorite,
saveWatchLater,
} = useMovieLibrary()
const sourceOptions = [
{ label: 'OPhim', value: 'ophim' },
{ label: 'NguonC', value: 'nguonc' },
@@ -32,6 +42,19 @@ const firstWatchLink = computed(() => ({
},
}))
const episodeCount = computed(() => servers.value.reduce((total: number, server: any) => total + (server.episodes?.length || 0), 0))
const libraryItem = computed(() => {
if (!movie.value) return null
return {
source: activeSource.value,
slug: String(route.params.slug),
name: movie.value.name,
originName: movie.value.originName,
thumb: movie.value.thumb,
poster: movie.value.poster,
updatedAt: Date.now(),
}
})
function episodeLink(index: number) {
return {
@@ -60,10 +83,79 @@ function actorInitial(name: string) {
return name.trim().charAt(0).toUpperCase()
}
function flashActionMessage(message: string) {
actionMessage.value = message
window.setTimeout(() => {
if (actionMessage.value === message) actionMessage.value = ''
}, 2200)
}
async function refreshFavoriteState() {
if (!libraryItem.value) return
isFavoriteMovie.value = await isFavorite(libraryItem.value)
}
async function toggleFavorite() {
if (!libraryItem.value || actionBusy.value) return
actionBusy.value = true
if (isFavoriteMovie.value) {
await removeFavorite(libraryItem.value)
isFavoriteMovie.value = false
flashActionMessage('Đã bỏ khỏi yêu thích.')
} else {
await saveFavorite(libraryItem.value)
isFavoriteMovie.value = true
flashActionMessage(user.value ? 'Đã lưu vào yêu thích.' : 'Đã lưu yêu thích trên thiết bị này.')
}
actionBusy.value = false
}
async function addToWatchLater() {
if (!libraryItem.value || actionBusy.value) return
actionBusy.value = true
await saveWatchLater(libraryItem.value)
actionBusy.value = false
flashActionMessage(user.value ? 'Đã thêm vào danh sách xem sau.' : 'Đã thêm vào danh sách xem sau trên thiết bị này.')
}
async function shareMovie() {
if (!import.meta.client || !movie.value) return
const shareUrl = window.location.href
const shareTitle = `${movie.value.name} - KR Phim`
try {
if (navigator.share) {
await navigator.share({
title: shareTitle,
text: movie.value.originName || movie.value.name,
url: shareUrl,
})
return
}
await navigator.clipboard.writeText(shareUrl)
flashActionMessage('Đã copy link phim.')
} catch {
flashActionMessage('Chưa chia sẻ được, bạn thử lại nhé.')
}
}
onMounted(async () => {
await initAuth()
await refreshFavoriteState()
})
watch(requestedSource, () => {
selectedServer.value = 0
})
watch([libraryItem, user], () => {
refreshFavoriteState()
})
useHead(() => ({
title: movie.value ? `${movie.value.name} - KR Phim` : 'Đang tải phim - KR Phim',
meta: [
@@ -196,20 +288,21 @@ useHead(() => ({
<div class="flex items-center justify-between gap-3 px-8 sm:justify-center sm:px-0">
<button type="button"
class="flex flex-col items-center gap-1 text-xs font-bold text-white transition hover:text-sky-200"
aria-label="Yêu thích">
<Heart class="size-5" />
<span>Yêu thích</span>
class="flex cursor-pointer flex-col items-center gap-1 text-xs font-bold transition hover:text-sky-200 disabled:cursor-not-allowed disabled:opacity-70"
:class="isFavoriteMovie ? 'text-sky-300' : 'text-white'" aria-label="Yêu thích"
:disabled="actionBusy" @click="toggleFavorite">
<Heart class="size-5" :class="isFavoriteMovie ? 'fill-current' : ''" />
<span>{{ isFavoriteMovie ? 'Đã thích' : 'Yêu thích' }}</span>
</button>
<button type="button"
class="flex flex-col items-center gap-1 text-xs font-bold text-white transition hover:text-sky-200"
aria-label="Thêm vào">
class="flex cursor-pointer flex-col items-center gap-1 text-xs font-bold text-white transition hover:text-sky-200 disabled:cursor-not-allowed disabled:opacity-70"
aria-label="Thêm vào" :disabled="actionBusy" @click="addToWatchLater">
<Plus class="size-5" />
<span>Thêm vào</span>
</button>
<button type="button"
class="flex flex-col items-center gap-1 text-xs font-bold text-white transition hover:text-sky-200"
aria-label="Chia sẻ">
class="flex cursor-pointer flex-col items-center gap-1 text-xs font-bold text-white transition hover:text-sky-200"
aria-label="Chia sẻ" @click="shareMovie">
<Share2 class="size-5" />
<span>Chia sẻ</span>
</button>
@@ -219,6 +312,10 @@ useHead(() => ({
{{ movie.rating.toFixed(1) }}
</div>
</div>
<p v-if="actionMessage"
class="mt-2 text-center text-xs font-bold text-sky-200 sm:text-right">
{{ actionMessage }}
</p>
</div>
</div>
+93
View File
@@ -0,0 +1,93 @@
<script setup lang="ts">
import { Clock3, Heart, Mail, UserRound } from 'lucide-vue-next'
const { user, loading, initAuth } = useSupabaseAuth()
const defaultAvatar = 'https://thumbs.dreamstime.com/b/avatar-vietnam-character-your-project-others-avatar-vietnam-character-274539000.jpg'
const memberName = computed(() => {
const metadata = user.value?.user_metadata || {}
const name = metadata.name || metadata.full_name || metadata.user_name
if (typeof name === 'string' && name.trim()) return name.trim()
return user.value?.email?.split('@')[0] || 'Thành viên'
})
const memberAvatar = computed(() => {
const metadata = user.value?.user_metadata || {}
return typeof metadata.avatar_url === 'string' && metadata.avatar_url ? metadata.avatar_url : defaultAvatar
})
onMounted(() => {
initAuth()
})
useHead({
title: 'Trang cá nhân - KR Phim',
})
</script>
<template>
<main class="min-h-screen bg-slate-950 text-white">
<AppHeader />
<section class="mx-auto max-w-390 px-4 pb-16 pt-28 sm:px-6 lg:px-8 lg:pt-32 xl:px-10">
<div class="mb-6">
<p class="text-sm font-black uppercase text-sky-300">Thành viên</p>
<h1 class="mt-2 text-3xl font-black sm:text-4xl">Trang nhân</h1>
</div>
<div v-if="loading" class="rounded-lg border border-white/10 bg-white/6 p-5">
<div class="h-24 animate-pulse rounded-md bg-white/10" />
</div>
<div v-else-if="user" class="grid gap-5 lg:grid-cols-[minmax(0,1fr)_22rem]">
<section class="rounded-lg border border-white/10 bg-white/6 p-5 sm:p-6">
<div class="flex flex-col gap-5 sm:flex-row sm:items-center">
<img :src="memberAvatar" :alt="memberName"
class="size-24 shrink-0 rounded-full object-cover ring-4 ring-sky-300/30">
<div class="min-w-0">
<h2 class="truncate text-2xl font-black">{{ memberName }}</h2>
<p class="mt-2 inline-flex items-center gap-2 text-sm font-semibold text-slate-300">
<Mail class="size-4 text-sky-300" />
{{ user.email }}
</p>
<p class="mt-4 max-w-2xl text-sm leading-6 text-slate-400">
Tài khoản này dùng để đồng bộ lịch sử xem các dữ liệu nhân của bạn trên KR Phim.
</p>
</div>
</div>
</section>
<aside class="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
<NuxtLink to="/lich-su"
class="flex items-center gap-3 rounded-lg border border-white/10 bg-white/6 p-4 transition hover:bg-white/10">
<span class="grid size-10 place-items-center rounded-md bg-sky-300 text-slate-950">
<Clock3 class="size-5" />
</span>
<span>
<span class="block font-black">Lịch sử xem</span>
<span class="text-sm text-slate-400">Xem tiếp phim đang dở</span>
</span>
</NuxtLink>
<NuxtLink to="/yeu-thich"
class="flex items-center gap-3 rounded-lg border border-white/10 bg-white/6 p-4 transition hover:bg-white/10">
<span class="grid size-10 place-items-center rounded-md bg-white/10 text-sky-300">
<Heart class="size-5 fill-current" />
</span>
<span>
<span class="block font-black">Yêu thích</span>
<span class="text-sm text-slate-400">Phim bạn đã lưu</span>
</span>
</NuxtLink>
</aside>
</div>
<div v-else class="rounded-lg border border-white/10 bg-white/6 p-6">
<UserRound class="size-10 text-sky-300" />
<h2 class="mt-4 text-xl font-black">Bạn chưa đăng nhập</h2>
<p class="mt-2 text-sm leading-6 text-slate-300">
Bấm nút Thành viên trên header để đăng nhập hoặc đăng tài khoản.
</p>
</div>
</section>
</main>
</template>
+772 -33
View File
@@ -1,11 +1,65 @@
<script setup lang="ts">
import { Heart, Play, Plus, Share2, Star } from 'lucide-vue-next'
import type Hls from 'hls.js'
import {
FastForward,
Heart,
Loader2,
Maximize,
Pause,
PictureInPicture2,
Play,
Plus,
Rewind,
Settings,
Share2,
SkipForward,
Star,
Volume2,
VolumeX,
} from 'lucide-vue-next'
const route = useRoute()
const selectedServer = ref(Math.max(Number(route.query.server || 0), 0))
const selectedEpisode = ref(Math.max(Number(route.query.ep || 1) - 1, 0))
const hasStarted = ref(false)
const watchHistoryKey = 'kr-phim-watch-history'
const isFavoriteMovie = ref(false)
const actionMessage = ref('')
const actionBusy = ref(false)
const progressSeconds = ref(0)
const playerMode = ref<'embed' | 'hls'>('embed')
const playerShellRef = ref<HTMLElement | null>(null)
const videoRef = ref<HTMLVideoElement | null>(null)
const isVideoPlaying = ref(false)
const isVideoBuffering = ref(false)
const videoDuration = ref(0)
const videoCurrentTime = ref(0)
const isVideoMuted = ref(false)
const videoVolume = ref(1)
const playbackRate = ref(1)
const selectedQuality = ref(-1)
const qualityLevels = ref<{ label: string, level: number }[]>([])
const isSettingsOpen = ref(false)
const hlsErrorMessage = ref('')
const controlsVisible = ref(true)
const pendingResumeSeconds = ref(0)
let controlsHideTimer: ReturnType<typeof setTimeout> | undefined
let touchStartX = 0
let touchStartY = 0
let touchStartAt = 0
let hlsPlayer: Hls | undefined
let progressTimer: ReturnType<typeof setInterval> | undefined
let lastSavedProgress = 0
const {
loadWatchHistory: fetchWatchHistory,
saveWatchHistory: persistWatchHistory,
} = useWatchHistory()
const { user, initAuth } = useSupabaseAuth()
const {
isFavorite,
saveFavorite,
removeFavorite,
saveWatchLater,
} = useMovieLibrary()
const { data: movie, pending, error } = await useFetch(`/api/movies/${route.params.slug}`, {
query: {
@@ -16,21 +70,33 @@ const { data: movie, pending, error } = await useFetch(`/api/movies/${route.para
const servers = computed(() => movie.value?.servers ?? [])
const activeServer = computed(() => servers.value[selectedServer.value] ?? servers.value[0])
const activeEpisode = computed(() => activeServer.value?.episodes?.[selectedEpisode.value] ?? activeServer.value?.episodes?.[0])
const playerUrl = computed(() => activeEpisode.value?.linkEmbed || activeEpisode.value?.linkM3u8 || '')
const embedPlayerUrl = computed(() => activeEpisode.value?.linkEmbed || '')
const hlsPlayerUrl = computed(() => activeEpisode.value?.linkM3u8 || '')
const playerUrl = computed(() => playerMode.value === 'hls' ? hlsPlayerUrl.value : (embedPlayerUrl.value || hlsPlayerUrl.value))
const canUseEmbed = computed(() => Boolean(embedPlayerUrl.value))
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]))
const progressPercent = computed(() => {
if (!durationSeconds.value || !progressSeconds.value) return 0
return Math.min(Math.max((progressSeconds.value / durationSeconds.value) * 100, 0), 100)
})
const skipIntroSeconds = 85
const skipOutroSeconds = computed(() => Math.max((durationSeconds.value || 0) - 85, 0))
const libraryItem = computed(() => {
if (!movie.value) return null
type WatchHistoryItem = {
source: string
slug: string
name: string
originName?: string
thumb?: string
poster?: string
episodeName?: string
episodeIndex: number
serverIndex: number
updatedAt: number
}
return {
source: String(route.query.source || movie.value.source || ''),
slug: String(route.params.slug),
name: movie.value.name,
originName: movie.value.originName,
thumb: movie.value.thumb,
poster: movie.value.poster,
updatedAt: Date.now(),
}
})
function episodeLink(index: number) {
return {
@@ -47,19 +113,399 @@ function selectServer(index: number) {
selectedServer.value = index
selectedEpisode.value = 0
hasStarted.value = false
resetProgressTimer()
destroyHlsPlayer()
}
function startPlayer() {
async function startPlayer() {
hasStarted.value = true
await loadResumeProgress()
startProgressTimer()
saveWatchHistory()
if (playerMode.value === 'hls') {
nextTick(() => setupHlsPlayer(true))
}
}
function selectPlayerMode(mode: 'embed' | 'hls') {
if (mode === playerMode.value) return
playerMode.value = mode
isSettingsOpen.value = false
hasStarted.value = false
resetProgressTimer()
destroyHlsPlayer()
}
function parseDurationSeconds(value: string) {
const normalizedValue = value.toLowerCase()
const hourMatch = normalizedValue.match(/(\d+)\s*(?:h|giờ|gio)/)
const minuteMatch = normalizedValue.match(/(\d+)\s*(?:m|min|phút|phut|p)/)
const compactMatch = normalizedValue.match(/^(\d+)$/)
const hours = hourMatch ? Number(hourMatch[1]) : 0
const minutes = minuteMatch ? Number(minuteMatch[1]) : compactMatch ? Number(compactMatch[1]) : 0
return Math.max((hours * 60 + minutes) * 60, 0)
}
function resetProgressTimer() {
progressSeconds.value = 0
videoCurrentTime.value = 0
videoDuration.value = 0
isVideoPlaying.value = false
isVideoBuffering.value = false
hlsErrorMessage.value = ''
pendingResumeSeconds.value = 0
lastSavedProgress = 0
stopProgressTimer()
}
function stopProgressTimer() {
if (!progressTimer) return
clearInterval(progressTimer)
progressTimer = undefined
}
function tickProgress() {
if (!hasStarted.value || (import.meta.client && document.visibilityState === 'hidden')) return
if (playerMode.value === 'hls' && videoRef.value) {
progressSeconds.value = Math.floor(videoRef.value.currentTime || 0)
videoCurrentTime.value = progressSeconds.value
} else {
progressSeconds.value += 1
}
if (durationSeconds.value) {
progressSeconds.value = Math.min(progressSeconds.value, durationSeconds.value)
}
if (progressSeconds.value - lastSavedProgress >= 10) {
lastSavedProgress = progressSeconds.value
saveWatchHistory()
}
}
function startProgressTimer() {
if (!import.meta.client || progressTimer) return
progressTimer = setInterval(tickProgress, 1000)
}
function handleVisibilityChange() {
if (!import.meta.client || document.visibilityState !== 'hidden' || !hasStarted.value) return
saveWatchHistory()
}
function saveWatchHistory() {
function handleKeyboardShortcut(event: KeyboardEvent) {
if (playerMode.value !== 'hls' || !hasStarted.value || !videoRef.value) return
if (['INPUT', 'TEXTAREA', 'SELECT'].includes((event.target as HTMLElement)?.tagName)) return
const key = event.key.toLowerCase()
if (key === ' ') {
event.preventDefault()
toggleHlsPlayback()
} else if (key === 'arrowleft') {
event.preventDefault()
seekBy(-10)
} else if (key === 'arrowright') {
event.preventDefault()
seekBy(10)
} else if (key === 'f') {
event.preventDefault()
toggleFullscreen()
} else if (key === 'm') {
event.preventDefault()
toggleMute()
} else if (key === 'p') {
event.preventDefault()
togglePictureInPicture()
}
}
function showControlsTemporarily() {
controlsVisible.value = true
if (controlsHideTimer) clearTimeout(controlsHideTimer)
if (!isVideoPlaying.value || isSettingsOpen.value) return
controlsHideTimer = setTimeout(() => {
controlsVisible.value = false
}, 2600)
}
function formatPlayerTime(seconds = 0) {
const totalSeconds = Math.max(Math.floor(seconds), 0)
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const remainingSeconds = totalSeconds % 60
if (hours) {
return `${hours}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}
return `${minutes}:${String(remainingSeconds).padStart(2, '0')}`
}
async function setupHlsPlayer(autoplay = false) {
if (!import.meta.client || !videoRef.value || !hlsPlayerUrl.value) return
destroyHlsPlayer()
const video = videoRef.value
isVideoBuffering.value = true
hlsErrorMessage.value = ''
video.volume = videoVolume.value
video.muted = isVideoMuted.value
video.playbackRate = playbackRate.value
if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = hlsPlayerUrl.value
} else {
const { default: HlsPlayer } = await import('hls.js')
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, () => {
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
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)
}
if (autoplay) {
try {
await video.play()
} catch {
isVideoPlaying.value = false
}
}
}
function destroyHlsPlayer() {
if (hlsPlayer) {
hlsPlayer.destroy()
hlsPlayer = undefined
}
if (videoRef.value) {
videoRef.value.removeAttribute('src')
videoRef.value.load()
}
qualityLevels.value = []
selectedQuality.value = -1
}
function updateVideoTime() {
if (!videoRef.value) return
videoCurrentTime.value = Math.floor(videoRef.value.currentTime || 0)
progressSeconds.value = videoCurrentTime.value
if (Number.isFinite(videoRef.value.duration)) {
videoDuration.value = Math.floor(videoRef.value.duration || 0)
}
}
function updateVideoMetadata() {
updateVideoTime()
applyResumeProgress()
isVideoBuffering.value = false
}
async function loadResumeProgress() {
if (!import.meta.client || !movie.value) return
const source = String(route.query.source || movie.value.source || '')
const historyItems = await fetchWatchHistory(30)
const historyItem = historyItems.find((item) => item.slug === String(route.params.slug) && item.source === source)
const savedProgress = Math.floor(historyItem?.progressSeconds || 0)
if (!savedProgress || (historyItem?.episodeIndex ?? 0) !== selectedEpisode.value) return
pendingResumeSeconds.value = savedProgress
progressSeconds.value = savedProgress
videoCurrentTime.value = savedProgress
}
function applyResumeProgress() {
if (!videoRef.value || !pendingResumeSeconds.value) return
const resumeAt = durationSeconds.value
? Math.min(pendingResumeSeconds.value, Math.max(durationSeconds.value - 8, 0))
: pendingResumeSeconds.value
videoRef.value.currentTime = resumeAt
videoCurrentTime.value = Math.floor(resumeAt)
progressSeconds.value = videoCurrentTime.value
pendingResumeSeconds.value = 0
}
function toggleHlsPlayback() {
if (!videoRef.value) return
if (videoRef.value.paused) {
videoRef.value.play()
} else {
videoRef.value.pause()
}
}
function seekBy(seconds: number) {
if (!videoRef.value) return
const nextTime = Math.min(Math.max((videoRef.value.currentTime || 0) + seconds, 0), durationSeconds.value || Number.MAX_SAFE_INTEGER)
videoRef.value.currentTime = nextTime
updateVideoTime()
showControlsTemporarily()
saveWatchHistory()
}
function seekHlsPlayer(event: Event) {
if (!videoRef.value) return
const value = Number((event.target as HTMLInputElement).value)
videoRef.value.currentTime = value
updateVideoTime()
saveWatchHistory()
}
function toggleMute() {
if (!videoRef.value) return
videoRef.value.muted = !videoRef.value.muted
isVideoMuted.value = videoRef.value.muted
}
function changeVolume(event: Event) {
if (!videoRef.value) return
const value = Number((event.target as HTMLInputElement).value)
videoVolume.value = value
videoRef.value.volume = value
videoRef.value.muted = value === 0
isVideoMuted.value = videoRef.value.muted
}
function changePlaybackRate(event: Event) {
if (!videoRef.value) return
playbackRate.value = Number((event.target as HTMLSelectElement).value)
videoRef.value.playbackRate = playbackRate.value
showControlsTemporarily()
}
function changeQuality(event: Event) {
const value = Number((event.target as HTMLSelectElement).value)
selectedQuality.value = value
if (hlsPlayer) hlsPlayer.currentLevel = value
showControlsTemporarily()
}
function toggleFullscreen() {
const target = videoRef.value?.parentElement
if (!target) return
if (document.fullscreenElement) {
document.exitFullscreen()
} else {
target.requestFullscreen()
}
}
async function togglePictureInPicture() {
if (!videoRef.value || !document.pictureInPictureEnabled) return
if (document.pictureInPictureElement) {
await document.exitPictureInPicture()
} else {
await videoRef.value.requestPictureInPicture()
}
}
function skipIntro() {
if (!videoRef.value) return
videoRef.value.currentTime = Math.max(videoRef.value.currentTime, skipIntroSeconds)
updateVideoTime()
}
function skipOutro() {
if (!videoRef.value || !skipOutroSeconds.value) return
videoRef.value.currentTime = skipOutroSeconds.value
updateVideoTime()
}
function playNextEpisode(autoplay = true) {
if (!hasNextEpisode.value) return
selectedEpisode.value += 1
hasStarted.value = false
resetProgressTimer()
destroyHlsPlayer()
navigateTo(episodeLink(selectedEpisode.value), { replace: true })
if (autoplay) {
nextTick(() => startPlayer())
}
}
function handleVideoEnded() {
isVideoPlaying.value = false
saveWatchHistory()
playNextEpisode(true)
}
function handleTouchStart(event: TouchEvent) {
const touch = event.touches[0]
touchStartX = touch.clientX
touchStartY = touch.clientY
touchStartAt = Date.now()
}
function handleTouchEnd(event: TouchEvent) {
if (!videoRef.value) return
const touch = event.changedTouches[0]
const deltaX = touch.clientX - touchStartX
const deltaY = touch.clientY - touchStartY
const elapsed = Date.now() - touchStartAt
if (Math.abs(deltaX) > 48 && Math.abs(deltaX) > Math.abs(deltaY) && elapsed < 700) {
seekBy(deltaX > 0 ? 10 : -10)
return
}
if (Math.abs(deltaY) > 48 && Math.abs(deltaY) > Math.abs(deltaX)) {
const nextVolume = Math.min(Math.max(videoVolume.value + (deltaY < 0 ? 0.1 : -0.1), 0), 1)
videoVolume.value = Number(nextVolume.toFixed(1))
videoRef.value.volume = videoVolume.value
videoRef.value.muted = videoVolume.value === 0
isVideoMuted.value = videoRef.value.muted
}
}
async function saveWatchHistory() {
if (!import.meta.client || !movie.value) return
const source = String(route.query.source || movie.value.source || '')
const slug = String(route.params.slug)
const item: WatchHistoryItem = {
await persistWatchHistory({
source,
slug,
name: movie.value.name,
@@ -69,32 +515,106 @@ function saveWatchHistory() {
episodeName: activeEpisode.value?.name,
episodeIndex: selectedEpisode.value,
serverIndex: selectedServer.value,
progressSeconds: Math.floor(progressSeconds.value),
durationSeconds: Math.floor(durationSeconds.value),
updatedAt: Date.now(),
})
}
function flashActionMessage(message: string) {
actionMessage.value = message
window.setTimeout(() => {
if (actionMessage.value === message) actionMessage.value = ''
}, 2200)
}
async function refreshFavoriteState() {
if (!libraryItem.value) return
isFavoriteMovie.value = await isFavorite(libraryItem.value)
}
async function toggleFavorite() {
if (!libraryItem.value || actionBusy.value) return
actionBusy.value = true
if (isFavoriteMovie.value) {
await removeFavorite(libraryItem.value)
isFavoriteMovie.value = false
flashActionMessage('Đã bỏ khỏi yêu thích.')
} else {
await saveFavorite(libraryItem.value)
isFavoriteMovie.value = true
flashActionMessage(user.value ? 'Đã lưu vào yêu thích.' : 'Đã lưu yêu thích trên thiết bị này.')
}
actionBusy.value = false
}
async function addToWatchLater() {
if (!libraryItem.value || actionBusy.value) return
actionBusy.value = true
await saveWatchLater(libraryItem.value)
actionBusy.value = false
flashActionMessage(user.value ? 'Đã thêm vào danh sách xem sau.' : 'Đã thêm vào danh sách xem sau trên thiết bị này.')
}
async function shareMovie() {
if (!import.meta.client || !movie.value) return
try {
const raw = window.localStorage.getItem(watchHistoryKey)
const history = raw ? JSON.parse(raw) : []
const items = Array.isArray(history) ? history : []
const nextItems = [
item,
...items.filter((historyItem: WatchHistoryItem) => !(historyItem.slug === slug && historyItem.source === source)),
].slice(0, 20)
if (navigator.share) {
await navigator.share({
title: `${movie.value.name} - KR Phim`,
text: activeEpisode.value?.name || movie.value.originName || movie.value.name,
url: window.location.href,
})
return
}
window.localStorage.setItem(watchHistoryKey, JSON.stringify(nextItems))
await navigator.clipboard.writeText(window.location.href)
flashActionMessage('Đã copy link phim.')
} catch {
window.localStorage.setItem(watchHistoryKey, JSON.stringify([item]))
flashActionMessage('Chưa chia sẻ được, bạn thử lại nhé.')
}
}
onMounted(async () => {
await initAuth()
await refreshFavoriteState()
document.addEventListener('visibilitychange', handleVisibilityChange)
document.addEventListener('keydown', handleKeyboardShortcut)
})
onBeforeUnmount(() => {
if (hasStarted.value) saveWatchHistory()
stopProgressTimer()
if (controlsHideTimer) clearTimeout(controlsHideTimer)
destroyHlsPlayer()
if (import.meta.client) document.removeEventListener('visibilitychange', handleVisibilityChange)
if (import.meta.client) document.removeEventListener('keydown', handleKeyboardShortcut)
})
watch(() => route.query, () => {
selectedServer.value = Math.max(Number(route.query.server || 0), 0)
selectedEpisode.value = Math.max(Number(route.query.ep || 1) - 1, 0)
hasStarted.value = false
resetProgressTimer()
destroyHlsPlayer()
})
watch([movie, activeEpisode], () => {
saveWatchHistory()
if (hasStarted.value) saveWatchHistory()
})
watch([canUseEmbed, canUseHls], () => {
if (!canUseHls.value && playerMode.value === 'hls') playerMode.value = 'embed'
if (!canUseEmbed.value && canUseHls.value) playerMode.value = 'hls'
}, {
immediate: true,
})
watch([libraryItem, user], () => {
refreshFavoriteState()
})
useHead(() => ({
@@ -131,11 +651,177 @@ useHead(() => ({
</NuxtLink>
<div class="mt-4 overflow-hidden rounded-md border border-white/10 bg-black shadow-2xl shadow-black/40">
<div class="grid grid-cols-2 gap-2 border-b border-white/10 bg-slate-950/92 p-2 sm:hidden">
<button type="button"
class="rounded-md px-3 py-2 text-sm font-black transition disabled:cursor-not-allowed disabled:opacity-40"
:class="playerMode === 'embed' ? 'bg-sky-400 text-slate-950' : 'bg-white/10 text-slate-100'"
:disabled="!canUseEmbed" @click="selectPlayerMode('embed')">
Nhúng
</button>
<button type="button"
class="rounded-md px-3 py-2 text-sm font-black transition disabled:cursor-not-allowed disabled:opacity-40"
:class="playerMode === 'hls' ? 'bg-sky-400 text-slate-950' : 'bg-white/10 text-slate-100'"
:disabled="!canUseHls" @click="selectPlayerMode('hls')">
HLS
</button>
</div>
<div class="relative aspect-video bg-slate-950">
<iframe v-if="playerUrl && hasStarted" :src="playerUrl"
<div
class="absolute left-3 top-3 z-20 hidden rounded-md border border-white/10 bg-black/65 p-1 text-xs font-black text-white backdrop-blur sm:inline-flex">
<button type="button" class="rounded px-3 py-1.5 transition disabled:cursor-not-allowed disabled:opacity-40"
:class="playerMode === 'embed' ? 'bg-sky-400 text-slate-950' : 'text-slate-200 hover:bg-white/10'"
:disabled="!canUseEmbed" @click="selectPlayerMode('embed')">
Nhúng
</button>
<button type="button" class="rounded px-3 py-1.5 transition disabled:cursor-not-allowed disabled:opacity-40"
:class="playerMode === 'hls' ? 'bg-sky-400 text-slate-950' : 'text-slate-200 hover:bg-white/10'"
:disabled="!canUseHls" @click="selectPlayerMode('hls')">
HLS
</button>
</div>
<iframe v-if="playerMode === 'embed' && playerUrl && hasStarted" :src="playerUrl"
:title="`${movie.name} - ${activeEpisode?.name || 'Tập phim'}`" class="h-full w-full"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen />
<div v-else-if="playerMode === 'hls' && playerUrl && hasStarted" ref="playerShellRef"
class="group relative h-full w-full bg-black" @mousemove="showControlsTemporarily"
@mouseleave="controlsVisible = false" @touchstart.passive="handleTouchStart"
@touchend.passive="handleTouchEnd">
<video ref="videoRef" class="h-full w-full bg-black object-contain" playsinline
@loadedmetadata="updateVideoMetadata" @timeupdate="updateVideoTime"
@canplay="isVideoBuffering = false" @waiting="isVideoBuffering = true"
@playing="isVideoBuffering = false" @play="isVideoPlaying = true; showControlsTemporarily()"
@pause="isVideoPlaying = false; controlsVisible = true" @ended="handleVideoEnded" />
<div class="pointer-events-none absolute inset-0 bg-linear-to-t from-black/70 via-transparent to-black/35" />
<div v-if="isVideoBuffering"
class="pointer-events-none absolute inset-0 z-10 grid place-items-center bg-black/20 text-sky-200">
<Loader2 class="size-10 animate-spin" />
</div>
<div v-if="hlsErrorMessage"
class="absolute left-1/2 top-1/2 z-20 w-[min(90%,28rem)] -translate-x-1/2 -translate-y-1/2 rounded-md border border-red-300/30 bg-red-950/85 p-4 text-center text-sm font-bold text-red-100">
{{ hlsErrorMessage }}
</div>
<button v-if="videoCurrentTime < skipIntroSeconds && durationSeconds > 180" type="button"
class="absolute bottom-24 right-4 z-20 rounded-md bg-sky-400 px-4 py-2 text-xs font-black text-slate-950 shadow-lg transition hover:bg-white"
@click="skipIntro">
Bỏ intro
</button>
<button v-if="skipOutroSeconds && videoCurrentTime > skipOutroSeconds - 45 && hasNextEpisode" type="button"
class="absolute bottom-24 right-4 z-20 inline-flex items-center gap-2 rounded-md bg-sky-400 px-4 py-2 text-xs font-black text-slate-950 shadow-lg transition hover:bg-white"
@click="playNextEpisode(true)">
<SkipForward class="size-4" /> Tập tiếp
</button>
<button type="button"
class="absolute inset-0 grid cursor-pointer place-items-center text-white transition"
:class="isVideoPlaying && !controlsVisible ? 'opacity-0' : 'opacity-100'"
:aria-label="isVideoPlaying ? 'Tạm dừng' : 'Phát phim'" @click="toggleHlsPlayback">
<span
class="grid size-12 place-items-center rounded-full bg-sky-400 text-slate-950 shadow-xl shadow-sky-950/30 sm:size-16">
<Pause v-if="isVideoPlaying" class="size-5 fill-current sm:size-7" />
<Play v-else class="size-5 fill-current sm:size-7" />
</span>
</button>
<div class="absolute inset-x-0 bottom-0 z-10 px-3 pb-3 text-white transition sm:px-4 sm:pb-4"
:class="controlsVisible || !isVideoPlaying ? 'opacity-100' : 'pointer-events-none opacity-0'">
<input class="kr-hls-range w-full cursor-pointer" type="range" min="0" :max="durationSeconds || 0"
:value="videoCurrentTime" step="1" @input="seekHlsPlayer">
<div class="mt-2 flex items-center justify-between gap-2 sm:mt-3 sm:gap-3">
<div class="flex min-w-0 items-center gap-1.5 sm:gap-3">
<button type="button"
class="grid size-8 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:size-9"
:aria-label="isVideoPlaying ? 'Tạm dừng' : 'Phát phim'" @click="toggleHlsPlayback">
<Pause v-if="isVideoPlaying" class="size-3.5 fill-current sm:size-4" />
<Play v-else class="size-3.5 fill-current sm:size-4" />
</button>
<button type="button"
class="grid size-8 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:size-9"
aria-label="Lùi 10 giây" @click="seekBy(-10)">
<Rewind class="size-3.5 sm:size-4" />
</button>
<button type="button"
class="grid size-8 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:size-9"
aria-label="Tua 10 giây" @click="seekBy(10)">
<FastForward class="size-3.5 sm:size-4" />
</button>
<button type="button"
class="grid size-8 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:size-9"
:aria-label="isVideoMuted ? 'Bật âm' : 'Tắt âm'" @click="toggleMute">
<VolumeX v-if="isVideoMuted" class="size-3.5 sm:size-4" />
<Volume2 v-else class="size-3.5 sm:size-4" />
</button>
<input class="kr-volume-range hidden w-20 cursor-pointer sm:block" type="range" min="0" max="1"
step="0.05" :value="videoVolume" @input="changeVolume">
<span class="shrink-0 text-[11px] font-black text-slate-100 sm:text-xs">
{{ formatPlayerTime(videoCurrentTime) }} / {{ formatPlayerTime(durationSeconds) }}
</span>
</div>
<div class="flex shrink-0 items-center gap-1.5 sm:gap-2">
<div class="relative">
<button type="button"
class="grid size-8 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:size-9"
:class="isSettingsOpen ? 'bg-sky-400 text-slate-950' : ''" aria-label="Cài đặt player"
@click="isSettingsOpen = !isSettingsOpen; controlsVisible = true">
<Settings class="size-3.5 sm:size-4" />
</button>
<div v-if="isSettingsOpen"
class="absolute bottom-10 right-0 z-30 w-48 rounded-md border border-white/10 bg-slate-950/95 p-3 text-white shadow-2xl shadow-black/40 backdrop-blur sm:bottom-12 sm:w-56">
<label class="block text-[11px] font-black uppercase text-slate-400">
Tốc độ phát
</label>
<select
class="mt-2 h-10 w-full cursor-pointer rounded-md border border-white/10 bg-white/10 px-3 text-sm font-black text-white outline-none"
:value="playbackRate" aria-label="Tốc độ phát" @change="changePlaybackRate">
<option class="bg-slate-950" value="0.75">0.75x</option>
<option class="bg-slate-950" value="1">1x</option>
<option class="bg-slate-950" value="1.25">1.25x</option>
<option class="bg-slate-950" value="1.5">1.5x</option>
<option class="bg-slate-950" value="2">2x</option>
</select>
<label class="mt-4 block text-[11px] font-black uppercase text-slate-400">
Chất lượng
</label>
<select
class="mt-2 h-10 w-full cursor-pointer rounded-md border border-white/10 bg-white/10 px-3 text-sm font-black text-white outline-none disabled:cursor-not-allowed disabled:opacity-50"
:value="selectedQuality" :disabled="!qualityLevels.length" aria-label="Chất lượng"
@change="changeQuality">
<option class="bg-slate-950" value="-1">Auto</option>
<option v-for="level in qualityLevels" :key="level.level" class="bg-slate-950" :value="level.level">
{{ level.label }}
</option>
</select>
</div>
</div>
<button type="button"
class="hidden size-9 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:grid"
aria-label="Picture in Picture" @click="togglePictureInPicture">
<PictureInPicture2 class="size-4" />
</button>
<button v-if="hasNextEpisode" type="button"
class="hidden size-9 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:grid"
aria-label="Tập tiếp theo" @click="playNextEpisode(true)">
<SkipForward class="size-4" />
</button>
<button type="button"
class="grid size-8 cursor-pointer place-items-center rounded-full bg-white/12 text-white transition hover:bg-sky-400 hover:text-slate-950 sm:size-9"
aria-label="Toàn màn hình" @click="toggleFullscreen">
<Maximize class="size-3.5 sm:size-4" />
</button>
</div>
</div>
</div>
</div>
<button v-else type="button" class="absolute inset-0 text-white" :aria-label="`Phát ${movie.name}`"
@click="startPlayer">
<img :src="movie.poster || movie.thumb" :alt="movie.name" class="h-full w-full object-cover opacity-45">
@@ -145,22 +831,38 @@ useHead(() => ({
class="grid size-16 place-items-center rounded-full bg-sky-400 text-slate-950 shadow-xl shadow-sky-950/30">
<Play class="size-7 fill-current" />
</span>
<span v-if="playerMode === 'hls' && !canUseHls"
class="mt-4 rounded-md bg-black/70 px-4 py-2 text-xs font-black text-slate-100">
Tập này chưa link HLS
</span>
</div>
</button>
</div>
<div
class="flex items-center justify-center gap-7 border-t border-white/10 px-4 py-4 text-xs font-bold text-slate-100 sm:justify-start sm:gap-4 sm:py-3">
<button type="button" class="inline-flex items-center gap-2 hover:text-sky-200">
<Heart class="size-4 sm:size-3" /> Yêu thích
<button type="button"
class="inline-flex cursor-pointer items-center gap-2 hover:text-sky-200 disabled:cursor-not-allowed disabled:opacity-70"
:class="isFavoriteMovie ? 'text-sky-300' : ''" :disabled="actionBusy" @click="toggleFavorite">
<Heart class="size-4 sm:size-3" :class="isFavoriteMovie ? 'fill-current' : ''" />
{{ isFavoriteMovie ? 'Đã thích' : 'Yêu thích' }}
</button>
<button type="button" class="inline-flex items-center gap-2 hover:text-sky-200">
<button type="button"
class="inline-flex cursor-pointer items-center gap-2 hover:text-sky-200 disabled:cursor-not-allowed disabled:opacity-70"
:disabled="actionBusy" @click="addToWatchLater">
<Plus class="size-4 sm:size-3" /> Thêm vào
</button>
<button type="button" class="inline-flex items-center gap-2 hover:text-sky-200">
<button type="button" class="inline-flex cursor-pointer items-center gap-2 hover:text-sky-200"
@click="shareMovie">
<Share2 class="size-4 sm:size-3" /> Chia sẻ
</button>
<span v-if="actionMessage" class="hidden text-xs font-bold text-sky-200 sm:inline">
{{ actionMessage }}
</span>
</div>
<p v-if="actionMessage" class="border-t border-white/10 px-4 pb-3 text-center text-xs font-bold text-sky-200 sm:hidden">
{{ actionMessage }}
</p>
</div>
<div class="mt-5 grid gap-6 lg:grid-cols-[minmax(0,1fr)_24rem]">
@@ -227,3 +929,40 @@ useHead(() => ({
</template>
</main>
</template>
<style scoped>
.kr-hls-range,
.kr-volume-range {
height: 6px;
appearance: none;
border-radius: 999px;
background:
linear-gradient(90deg, rgb(56 189 248) v-bind('`${progressPercent}%`'), rgb(255 255 255 / 0.22) 0);
outline: none;
}
.kr-volume-range {
background:
linear-gradient(90deg, rgb(56 189 248) v-bind('`${videoVolume * 100}%`'), rgb(255 255 255 / 0.22) 0);
}
.kr-hls-range::-webkit-slider-thumb,
.kr-volume-range::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border-radius: 999px;
background: white;
box-shadow: 0 0 0 5px rgb(56 189 248 / 0.22);
}
.kr-hls-range::-moz-range-thumb,
.kr-volume-range::-moz-range-thumb {
width: 14px;
height: 14px;
border: 0;
border-radius: 999px;
background: white;
box-shadow: 0 0 0 5px rgb(56 189 248 / 0.22);
}
</style>
+94
View File
@@ -0,0 +1,94 @@
<script setup lang="ts">
import { Heart, UserRound } from 'lucide-vue-next'
import type { LibraryMovieItem } from '~/composables/useMovieLibrary'
const { user, loading: authLoading, initAuth } = useSupabaseAuth()
const { loadFavorites } = useMovieLibrary()
const favoriteItems = ref<LibraryMovieItem[]>([])
const loading = ref(true)
async function refreshFavorites() {
loading.value = true
favoriteItems.value = await loadFavorites(48)
loading.value = false
}
function movieLink(item: LibraryMovieItem) {
return {
path: `/phim/${item.slug}`,
query: {
source: item.source,
},
}
}
onMounted(async () => {
await initAuth()
await refreshFavorites()
})
watch(user, () => {
refreshFavorites()
})
useHead({
title: 'Yêu thích - KR Phim',
})
</script>
<template>
<main class="min-h-screen bg-slate-950 text-white">
<AppHeader />
<section class="mx-auto max-w-390 px-4 pb-16 pt-28 sm:px-6 lg:px-8 lg:pt-32 xl:px-10">
<div class="mb-6">
<p class="text-sm font-black uppercase text-sky-300">Thư viện</p>
<h1 class="mt-2 text-3xl font-black sm:text-4xl">Yêu thích</h1>
</div>
<div v-if="loading || authLoading" class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
<div v-for="item in 12" :key="item" class="aspect-2/3 animate-pulse rounded-md bg-white/10" />
</div>
<div v-else-if="favoriteItems.length" class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
<NuxtLink v-for="item in favoriteItems" :key="`${item.source}-${item.slug}`" :to="movieLink(item)"
class="group block min-w-0">
<div
class="relative aspect-2/3 overflow-hidden rounded-md bg-slate-900 shadow-xl shadow-black/25 ring-1 ring-white/10 transition duration-300 group-hover:-translate-y-1 group-hover:ring-sky-300/60">
<img v-if="item.thumb || item.poster" :src="item.thumb || item.poster" :alt="item.name"
class="h-full w-full object-cover transition duration-500 group-hover:scale-105">
<div v-else class="grid h-full w-full place-items-center bg-white/8">
<Heart class="size-10 text-sky-300" />
</div>
<span class="absolute left-2 top-2 rounded bg-sky-400 px-2 py-1 text-xs font-black text-slate-950">
Yêu thích
</span>
</div>
<h2 class="mt-3 truncate text-sm font-black">{{ item.name }}</h2>
<p class="mt-1 truncate text-xs font-semibold text-slate-400">{{ item.originName || item.source }}</p>
</NuxtLink>
</div>
<div v-else-if="user"
class="flex min-h-80 flex-col items-center justify-center rounded-lg border border-white/10 bg-white/6 p-6 text-center">
<Heart class="size-12 text-sky-300" />
<h2 class="mt-4 text-xl font-black">Chưa phim yêu thích</h2>
<p class="mt-2 max-w-md text-sm leading-6 text-slate-300">
Bấm nút Yêu thích trang phim để lưu phim vào đây.
</p>
<NuxtLink to="/phim"
class="mt-5 inline-flex h-11 items-center justify-center rounded-md bg-sky-300 px-5 text-sm font-black text-slate-950 transition hover:bg-white">
Duyệt phim
</NuxtLink>
</div>
<div v-else class="rounded-lg border border-white/10 bg-white/6 p-6">
<UserRound class="size-10 text-sky-300" />
<h2 class="mt-4 text-xl font-black">Bạn chưa đăng nhập</h2>
<p class="mt-2 text-sm leading-6 text-slate-300">
Đăng nhập để đồng bộ danh sách yêu thích, hoặc vẫn thể lưu tạm trên thiết bị này.
</p>
</div>
</section>
</main>
</template>
+18
View File
@@ -0,0 +1,18 @@
import { createClient } from '@supabase/supabase-js'
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig()
const supabase = createClient(config.public.supabaseUrl, config.public.supabaseKey, {
auth: {
persistSession: import.meta.client,
autoRefreshToken: import.meta.client,
detectSessionInUrl: import.meta.client,
},
})
return {
provide: {
supabase,
},
}
})
+104
View File
@@ -0,0 +1,104 @@
create table public.watch_history (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users(id) on delete cascade,
source text not null default '',
slug text not null,
name text not null,
origin_name text,
thumb text,
poster text,
episode_name text,
episode_index integer not null default 0,
server_index integer not null default 0,
progress_seconds integer not null default 0,
duration_seconds integer not null default 0,
updated_at timestamptz not null default now(),
unique (user_id, source, slug)
);
alter table public.watch_history
add column if not exists progress_seconds integer not null default 0,
add column if not exists duration_seconds integer not null default 0;
alter table public.watch_history enable row level security;
create policy "Users can read own watch history"
on public.watch_history for select
using (auth.uid() = user_id);
create policy "Users can insert own watch history"
on public.watch_history for insert
with check (auth.uid() = user_id);
create policy "Users can update own watch history"
on public.watch_history for update
using (auth.uid() = user_id)
with check (auth.uid() = user_id);
create policy "Users can delete own watch history"
on public.watch_history for delete
using (auth.uid() = user_id);
create table public.favorite_movies (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users(id) on delete cascade,
source text not null default '',
slug text not null,
name text not null,
origin_name text,
thumb text,
poster text,
updated_at timestamptz not null default now(),
unique (user_id, source, slug)
);
alter table public.favorite_movies enable row level security;
create policy "Users can read own favorite movies"
on public.favorite_movies for select
using (auth.uid() = user_id);
create policy "Users can insert own favorite movies"
on public.favorite_movies for insert
with check (auth.uid() = user_id);
create policy "Users can update own favorite movies"
on public.favorite_movies for update
using (auth.uid() = user_id)
with check (auth.uid() = user_id);
create policy "Users can delete own favorite movies"
on public.favorite_movies for delete
using (auth.uid() = user_id);
create table public.watch_later_movies (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users(id) on delete cascade,
source text not null default '',
slug text not null,
name text not null,
origin_name text,
thumb text,
poster text,
updated_at timestamptz not null default now(),
unique (user_id, source, slug)
);
alter table public.watch_later_movies enable row level security;
create policy "Users can read own watch later movies"
on public.watch_later_movies for select
using (auth.uid() = user_id);
create policy "Users can insert own watch later movies"
on public.watch_later_movies for insert
with check (auth.uid() = user_id);
create policy "Users can update own watch later movies"
on public.watch_later_movies for update
using (auth.uid() = user_id)
with check (auth.uid() = user_id);
create policy "Users can delete own watch later movies"
on public.watch_later_movies for delete
using (auth.uid() = user_id);
+6
View File
@@ -4,6 +4,12 @@ import tailwindcss from '@tailwindcss/vite'
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: { enabled: true },
runtimeConfig: {
public: {
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_KEY,
},
},
devServer: {
host: '0.0.0.0',
port: 3002,
+102 -2
View File
@@ -7,7 +7,9 @@
"name": "kr-phim",
"hasInstallScript": true,
"dependencies": {
"@supabase/supabase-js": "^2.106.0",
"@tailwindcss/vite": "^4.3.0",
"hls.js": "^1.6.16",
"lucide-vue-next": "^1.0.0",
"nuxt": "^4.4.5",
"tailwindcss": "^4.3.0",
@@ -3392,6 +3394,90 @@
"integrity": "sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==",
"license": "CC0-1.0"
},
"node_modules/@supabase/auth-js": {
"version": "2.106.0",
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.106.0.tgz",
"integrity": "sha512-JY7602OvjK2l3BjsQkpePpxR+6P0iG37gCrZNWAMhAuNh1iFnhGRwj/y5EshUG0INMPGFrj0UA9MErQ/kOEKFg==",
"license": "MIT",
"dependencies": {
"tslib": "2.8.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@supabase/functions-js": {
"version": "2.106.0",
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.106.0.tgz",
"integrity": "sha512-ADIkJYH5w7HbnGVAAlCbyKoLF5QdfyezBLfYXpUqhxZOacK6YepOvnP/8p4p+50bhTPWp6VhDxu19KO7e/qU2g==",
"license": "MIT",
"dependencies": {
"tslib": "2.8.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@supabase/phoenix": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.2.tgz",
"integrity": "sha512-YSAGnmDAfuleFCVt3CeurQZAhxRfXWeZIIkwp7NhYzQ1UwW6ePSnzsFAiUm/mbCkfoCf70QQHKW/K6RKh52a4A==",
"license": "MIT"
},
"node_modules/@supabase/postgrest-js": {
"version": "2.106.0",
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.106.0.tgz",
"integrity": "sha512-vNKFAXQrtmUn7J3LbN+uMlt0jciAwRIBpdy6Do4DKrpf1xj0kJhbqXTX4y8ziewWUEEx8G5GPnDmprXXaO9f3w==",
"license": "MIT",
"dependencies": {
"tslib": "2.8.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@supabase/realtime-js": {
"version": "2.106.0",
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.106.0.tgz",
"integrity": "sha512-mYZoaYpkyjlecixbvxCu0h3jw12uHfEcUqNdaRATNI8zQVI5arels+VJzAGcHwNiD+/Juv0OXIuk+M7SHsdI4A==",
"license": "MIT",
"dependencies": {
"@supabase/phoenix": "^0.4.2",
"tslib": "2.8.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@supabase/storage-js": {
"version": "2.106.0",
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.106.0.tgz",
"integrity": "sha512-BHc3nIjD3zfdDxBenphXrLJSoQ+qwo24VD96cVzmjBFbQVk5krvwRNUXrA5ozPplA3Vhlst2d/hy9R9ViqH2lg==",
"license": "MIT",
"dependencies": {
"iceberg-js": "^0.8.1",
"tslib": "2.8.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@supabase/supabase-js": {
"version": "2.106.0",
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.106.0.tgz",
"integrity": "sha512-OOoo3sLj9iVXNp6b+fkyOfFeQrvvNy7nQbaONNf72dOaictUeS39hFDS9argIRTag6M3ZxIypNWcrDAwLgUihQ==",
"license": "MIT",
"dependencies": {
"@supabase/auth-js": "2.106.0",
"@supabase/functions-js": "2.106.0",
"@supabase/postgrest-js": "2.106.0",
"@supabase/realtime-js": "2.106.0",
"@supabase/storage-js": "2.106.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@tailwindcss/node": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.0.tgz",
@@ -5899,6 +5985,12 @@
"node": ">= 0.4"
}
},
"node_modules/hls.js": {
"version": "1.6.16",
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.16.tgz",
"integrity": "sha512-VSIRpLfRwlAAdGL4wiTucx2ScRipo0ed1FBatWkyt832jC4CReKstga6yIhYVwGu9LOBjuX9wzmRMeQdBJtzEA==",
"license": "Apache-2.0"
},
"node_modules/hookable": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.1.tgz",
@@ -5963,6 +6055,15 @@
"node": ">=16.17.0"
}
},
"node_modules/iceberg-js": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
"integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",
"license": "MIT",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
@@ -9198,8 +9299,7 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD",
"optional": true
"license": "0BSD"
},
"node_modules/type-fest": {
"version": "5.6.0",
+2
View File
@@ -11,7 +11,9 @@
"postinstall": "nuxt prepare"
},
"dependencies": {
"@supabase/supabase-js": "^2.106.0",
"@tailwindcss/vite": "^4.3.0",
"hls.js": "^1.6.16",
"lucide-vue-next": "^1.0.0",
"nuxt": "^4.4.5",
"tailwindcss": "^4.3.0",