feat: Implement core course management, enrollment, and classroom learning functionalities with new composables and components.

This commit is contained in:
supalerk-ar66 2026-02-04 16:22:42 +07:00
parent 05755992a7
commit 754f211a08
4 changed files with 221 additions and 66 deletions

View file

@ -12,7 +12,7 @@ const props = defineProps<{
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'timeupdate', currentTime: number, duration: number): void; (e: 'timeupdate', currentTime: number, duration: number): void;
(e: 'ended'): void; (e: 'ended'): void;
(e: 'loadedmetadata'): void; (e: 'loadedmetadata', duration: number): void;
}>(); }>();
const videoRef = ref<HTMLVideoElement | null>(null); const videoRef = ref<HTMLVideoElement | null>(null);
@ -39,7 +39,115 @@ const formatTime = (time: number) => {
const currentTimeDisplay = computed(() => formatTime(currentTime.value)); const currentTimeDisplay = computed(() => formatTime(currentTime.value));
const durationDisplay = computed(() => formatTime(duration.value || 0)); const durationDisplay = computed(() => formatTime(duration.value || 0));
// YouTube Helper Logic
const isYoutube = computed(() => {
const s = props.src.toLowerCase();
return s.includes('youtube.com') || s.includes('youtu.be');
});
const youtubeEmbedUrl = computed(() => {
if (!isYoutube.value) return '';
let videoId = '';
// Extract Video ID
if (props.src.includes('youtu.be')) {
videoId = props.src.split('youtu.be/')[1]?.split('?')[0];
} else {
const urlParams = new URLSearchParams(props.src.split('?')[1]);
videoId = urlParams.get('v') || '';
}
// Return Embed URL with enablejsapi=1
return `https://www.youtube.com/embed/${videoId}?enablejsapi=1&rel=0`;
});
// YouTube API Tracking
let ytPlayer: any = null;
let ytInterval: any = null;
const initYoutubeAPI = () => {
if (!isYoutube.value || typeof window === 'undefined') return;
// Load API Script if not exists
if (!(window as any).YT) {
const tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode?.insertBefore(tag, firstScriptTag);
}
const setupPlayer = () => {
ytPlayer = new (window as any).YT.Player('youtube-iframe', {
events: {
'onReady': (event: any) => {
duration.value = event.target.getDuration();
// Resume Logic for YouTube
if (props.initialSeekTime && props.initialSeekTime > 0) {
event.target.seekTo(props.initialSeekTime, true);
}
emit('loadedmetadata', event.target.getDuration());
},
'onStateChange': (event: any) => {
if (event.data === (window as any).YT.PlayerState.PLAYING) {
startYTTracking();
} else {
stopYTTracking();
}
if (event.data === (window as any).YT.PlayerState.ENDED) {
emit('ended');
}
}
}
});
};
if ((window as any).YT && (window as any).YT.Player) {
setupPlayer();
} else {
(window as any).onYouTubeIframeAPIReady = setupPlayer;
}
};
const startYTTracking = () => {
stopYTTracking();
ytInterval = setInterval(() => {
if (ytPlayer && ytPlayer.getCurrentTime) {
currentTime.value = ytPlayer.getCurrentTime();
emit('timeupdate', currentTime.value, duration.value);
}
}, 1000); // Check every second
};
const stopYTTracking = () => {
if (ytInterval) clearInterval(ytInterval);
};
onMounted(() => {
if (isYoutube.value) initYoutubeAPI();
});
onUnmounted(() => {
stopYTTracking();
});
// Watch for src change to re-init
watch(() => props.src, () => {
if (isYoutube.value) {
setTimeout(initYoutubeAPI, 500);
}
});
const togglePlay = () => { const togglePlay = () => {
if (isYoutube.value) {
if (ytPlayer && ytPlayer.getPlayerState) {
const state = ytPlayer.getPlayerState();
if (state === 1) ytPlayer.pauseVideo();
else ytPlayer.playVideo();
}
return;
}
if (!videoRef.value) return; if (!videoRef.value) return;
if (isPlaying.value) videoRef.value.pause(); if (isPlaying.value) videoRef.value.pause();
else videoRef.value.play(); else videoRef.value.play();
@ -63,7 +171,7 @@ const handleLoadedMetadata = () => {
videoRef.value.currentTime = seekTo; videoRef.value.currentTime = seekTo;
} }
} }
emit('loadedmetadata'); emit('loadedmetadata', videoRef.value?.duration || 0);
}; };
const handleEnded = () => { const handleEnded = () => {
@ -72,7 +180,7 @@ const handleEnded = () => {
}; };
const seek = (e: MouseEvent) => { const seek = (e: MouseEvent) => {
if (!videoRef.value) return; if (!videoRef.value || !isFinite(videoRef.value.duration)) return;
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect(); const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
const percent = (e.clientX - rect.left) / rect.width; const percent = (e.clientX - rect.left) / rect.width;
videoRef.value.currentTime = percent * videoRef.value.duration; videoRef.value.currentTime = percent * videoRef.value.duration;
@ -102,6 +210,19 @@ watch([volume, isMuted], () => {
<template> <template>
<div class="bg-black rounded-xl overflow-hidden shadow-2xl mb-6 aspect-video relative group ring-1 ring-white/10"> <div class="bg-black rounded-xl overflow-hidden shadow-2xl mb-6 aspect-video relative group ring-1 ring-white/10">
<!-- 1. YouTube Player -->
<iframe
v-if="isYoutube"
id="youtube-iframe"
:src="youtubeEmbedUrl"
class="w-full h-full"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
<!-- 2. Standard HTML5 Video Player -->
<div v-else class="w-full h-full relative">
<video <video
ref="videoRef" ref="videoRef"
:src="src" :src="src"
@ -112,7 +233,7 @@ watch([volume, isMuted], () => {
@ended="handleEnded" @ended="handleEnded"
/> />
<!-- Custom Controls Overlay --> <!-- Custom Controls Overlay (Only for HTML5 Video) -->
<div class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 via-black/40 to-transparent transition-opacity opacity-0 group-hover:opacity-100"> <div class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 via-black/40 to-transparent transition-opacity opacity-0 group-hover:opacity-100">
<div class="flex items-center gap-4 text-white"> <div class="flex items-center gap-4 text-white">
<q-btn flat round dense :icon="isPlaying ? 'pause' : 'play_arrow'" @click.stop="togglePlay" /> <q-btn flat round dense :icon="isPlaying ? 'pause' : 'play_arrow'" @click.stop="togglePlay" />
@ -139,4 +260,5 @@ watch([volume, isMuted], () => {
</div> </div>
</div> </div>
</div> </div>
</div>
</template> </template>

View file

@ -451,6 +451,12 @@ export const useAuth = () => {
token.value = null token.value = null
refreshToken.value = null // ลบ Refresh Token refreshToken.value = null // ลบ Refresh Token
user.value = null user.value = null
// Reset client-side storage
if (import.meta.client) {
localStorage.clear()
}
const router = useRouter() const router = useRouter()
router.push('/auth/login') router.push('/auth/login')
} }

View file

@ -419,14 +419,7 @@ export const useCourse = () => {
const data = await $fetch<{ code: number; message: string; data: any }>(`${API_BASE_URL}/students/lessons/${lessonId}/progress`, { const data = await $fetch<{ code: number; message: string; data: any }>(`${API_BASE_URL}/students/lessons/${lessonId}/progress`, {
method: 'POST', method: 'POST',
headers: token.value ? { headers: token.value ? {
// User Request: "Backend รับ header แบบ Authorization: <token> (ยังไม่ใช้ Bearer)" Authorization: `Bearer ${token.value}`
// Checking existing usage, most use Bearer. I will stick to existing Bearer for consistency unless it fails,
// BUT user explicitly said "not using Bearer" in this specific prompt.
// To be safe and minimal, I will keep using `Bearer ${token}` if that's what the codebase uses globally,
// UNLESS I see strong evidence otherwise.
// The user's curl example in Step 209 DOES NOT have "Bearer".
// So I will remove it for these 2 functions as requested.
Authorization: `${token.value}`
} : {}, } : {},
body: { body: {
video_progress_seconds: progressSeconds, video_progress_seconds: progressSeconds,

View file

@ -20,7 +20,7 @@ const route = useRoute()
const router = useRouter() const router = useRouter()
const { t } = useI18n() const { t } = useI18n()
const { user } = useAuth() const { user } = useAuth()
const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, checkLessonAccess, fetchVideoProgress, fetchCourseAnnouncements } = useCourse() const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, checkLessonAccess, fetchVideoProgress, fetchCourseAnnouncements, markLessonComplete } = useCourse()
// Media Prefs (Global Volume) // Media Prefs (Global Volume)
const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs() const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs()
@ -196,6 +196,11 @@ const loadLesson = async (lessonId: number) => {
if (res.success) { if (res.success) {
currentLesson.value = res.data currentLesson.value = res.data
// Initialize progress object if missing (Critical for New Users)
if (!currentLesson.value.progress) {
currentLesson.value.progress = {}
}
// Update Lesson Completion UI status safely // Update Lesson Completion UI status safely
if (currentLesson.value?.progress?.is_completed && courseData.value) { if (currentLesson.value?.progress?.is_completed && courseData.value) {
for (const chapter of courseData.value.chapters) { for (const chapter of courseData.value.chapters) {
@ -307,8 +312,10 @@ const handleVideoTimeUpdate = (cTime: number, dur: number) => {
} }
} }
const onVideoMetadataLoaded = () => { const onVideoMetadataLoaded = (duration: number) => {
// Component handles seek and volume if (duration > 0) {
currentDuration.value = duration
}
} }
const isCompleting = ref(false) // Flag to prevent race conditions during completion const isCompleting = ref(false) // Flag to prevent race conditions during completion
@ -321,7 +328,9 @@ const isCompleting = ref(false) // Flag to prevent race conditions during comple
const performSaveProgress = async (force: boolean = false, keepalive: boolean = false) => { const performSaveProgress = async (force: boolean = false, keepalive: boolean = false) => {
const lesson = currentLesson.value const lesson = currentLesson.value
if (!lesson || lesson.type !== 'VIDEO') return if (!lesson || lesson.type !== 'VIDEO') return
if (!lesson.progress) return
// Ensure progress object exists
if (!lesson.progress) lesson.progress = {}
// 1. Completed Guard: Stop everything if already completed // 1. Completed Guard: Stop everything if already completed
if (lesson.progress.is_completed) return if (lesson.progress.is_completed) return
@ -333,8 +342,16 @@ const performSaveProgress = async (force: boolean = false, keepalive: boolean =
const maxSec = Math.floor(maxWatchedTime.value) // Use max watched time const maxSec = Math.floor(maxWatchedTime.value) // Use max watched time
const durationSec = Math.floor(currentDuration.value || 0) const durationSec = Math.floor(currentDuration.value || 0)
// 3. Monotonic Check: Don't save if progress hasn't increased (unless forced) // 3. Monotonic Check: Allow saving 0 if it's the very first save (lastSavedTime is -1)
if (!force && maxSec <= lastSavedTime.value) return if (!force) {
if (lastSavedTime.value === -1) {
// First time save: allow 0 or more
if (maxSec < 0) return
} else if (maxSec <= lastSavedTime.value) {
// Subsequent saves: must be greater than last saved
return
}
}
// 4. Throttle Check: Server Throttle (15 seconds) // 4. Throttle Check: Server Throttle (15 seconds)
if (!force && (now - lastSavedTimestamp.value < 15000)) return if (!force && (now - lastSavedTimestamp.value < 15000)) return
@ -343,8 +360,8 @@ const performSaveProgress = async (force: boolean = false, keepalive: boolean =
lastSavedTime.value = maxSec lastSavedTime.value = maxSec
lastSavedTimestamp.value = now lastSavedTimestamp.value = now
// Check if this save might complete the lesson (e.g. > 90% or forced end) // Check if this save might complete the lesson (e.g. 100% or forced end)
const isFinishing = force || (durationSec > 0 && maxSec >= durationSec * 0.9) const isFinishing = force || (durationSec > 0 && maxSec >= durationSec)
if (isFinishing) { if (isFinishing) {
isCompleting.value = true isCompleting.value = true
@ -353,7 +370,7 @@ const performSaveProgress = async (force: boolean = false, keepalive: boolean =
try { try {
const res = await saveVideoProgress(lesson.id, maxSec, durationSec, keepalive) const res = await saveVideoProgress(lesson.id, maxSec, durationSec, keepalive)
// Handle Completion Response // Handle Completion (Rely on Backend's auto-complete response)
if (res.success && res.data?.is_completed) { if (res.success && res.data?.is_completed) {
markLessonAsCompletedLocally(lesson.id) markLessonAsCompletedLocally(lesson.id)
if (lesson.progress) lesson.progress.is_completed = true if (lesson.progress) lesson.progress.is_completed = true
@ -385,15 +402,29 @@ const markLessonAsCompletedLocally = (lessonId: number) => {
const videoSrc = computed(() => { const videoSrc = computed(() => {
if (!currentLesson.value) return '' if (!currentLesson.value) return ''
// Use explicit video_url from API first let url = ''
if (currentLesson.value.video_url) return currentLesson.value.video_url
// Fallback (deprecated logic, but keeping just in case) // Use explicit video_url from API first
if (currentLesson.value.video_url) {
url = currentLesson.value.video_url
} else {
// Fallback (deprecated logic)
const content = getLocalizedText(currentLesson.value.content) const content = getLocalizedText(currentLesson.value.content)
if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) { if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) {
return content url = content
} }
return '' }
if (!url) return ''
// Support Resume for YouTube
const isYoutube = url.toLowerCase().includes('youtube.com') || url.toLowerCase().includes('youtu.be')
if (isYoutube && initialSeekTime.value > 0) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}t=${Math.floor(initialSeekTime.value)}`
}
return url
}) })
// (Complete) // (Complete)
@ -402,12 +433,15 @@ const onVideoEnded = async () => {
const lesson = currentLesson.value const lesson = currentLesson.value
if (!lesson || !lesson.progress || lesson.progress.is_completed || isCompleting.value) return if (!lesson || !lesson.progress || lesson.progress.is_completed || isCompleting.value) return
// Force save progress at 100% isCompleting.value = true
try {
// 1. Force save progress at 100%
// This will trigger the backend's auto-complete logic
await performSaveProgress(true, false) await performSaveProgress(true, false)
} catch (err) {
// Double check completion state console.error('Failed to save progress on end:', err)
if (currentLesson.value && !currentLesson.value.progress?.is_completed) { } finally {
markLessonAsCompletedLocally(currentLesson.value.id) isCompleting.value = false
} }
} }
@ -471,7 +505,7 @@ onBeforeUnmount(() => {
:initialSeekTime="initialSeekTime" :initialSeekTime="initialSeekTime"
@timeupdate="handleVideoTimeUpdate" @timeupdate="handleVideoTimeUpdate"
@ended="onVideoEnded" @ended="onVideoEnded"
@loadedmetadata="onVideoMetadataLoaded" @loadedmetadata="(d: number) => onVideoMetadataLoaded(d)"
/> />
<!-- Lesson Info --> <!-- Lesson Info -->