视频播放页面重构

This commit is contained in:
禺狨 2023-04-23 11:43:43 +08:00
parent 89ef2401cf
commit 09707c1fff
9 changed files with 229 additions and 274 deletions

View File

@ -5,6 +5,11 @@ export function detail(id: number) {
return client.get(`/api/v1/course/${id}`, {});
}
// 线上课课时详情
export function play(courseId: number, id: number) {
return client.get(`/api/v1/course/${courseId}/hour/${id}`, {});
}
// 获取播放地址
export function playUrl(courseId: number, hourId: number) {
return client.get(`/api/v1/course/${courseId}/hour/${hourId}/play`, {});

View File

@ -1,8 +1,7 @@
import React, { useState, useEffect } from "react";
import React from "react";
import { useNavigate } from "react-router-dom";
import styles from "./hour.module.scss";
import { durationFormat } from "../../../utils/index";
import { VideoModel } from "./video";
interface PropInterface {
id: number;
@ -11,9 +10,6 @@ interface PropInterface {
duration: number;
record: any;
progress: number;
totalHours: any;
records: any;
onChange: () => void;
}
export const HourCompenent: React.FC<PropInterface> = ({
@ -23,73 +19,14 @@ export const HourCompenent: React.FC<PropInterface> = ({
duration,
record,
progress,
totalHours,
records,
onChange,
}) => {
// const navigate = useNavigate();
const [visible, setVisible] = useState<boolean>(false);
const [currentId, setCurrentId] = useState(id);
const [currentTitle, setCurrentTitle] = useState(title);
const [isLastpage, setIsLastpage] = useState<boolean>(false);
const [lastSeeDuration, setLastSeeDuration] = useState(0);
useEffect(() => {
getData();
}, [totalHours]);
const getData = () => {
const index = totalHours.findIndex((i: any) => i.id === id);
if (index === totalHours.length - 1) {
setIsLastpage(true);
}
if (records[totalHours[index].id]) {
setLastSeeDuration(records[totalHours[index].id].finished_duration);
}
};
const goNextVideo = () => {
const index = totalHours.findIndex((i: any) => i.id === currentId);
if (index === totalHours.length - 1) {
setIsLastpage(true);
} else if (index < totalHours.length - 1) {
setCurrentId(totalHours[index + 1].id);
setCurrentTitle(totalHours[index + 1].title);
if (index + 1 === totalHours.length - 1) {
setIsLastpage(true);
}
if (records[totalHours[index + 1].id]) {
setLastSeeDuration(records[totalHours[index + 1].id].finished_duration);
}
}
setVisible(true);
};
const navigate = useNavigate();
return (
<>
<VideoModel
cid={cid}
id={currentId}
title={currentTitle}
open={visible}
progress={progress}
isLastpage={isLastpage}
lastSeeDuration={lastSeeDuration}
onCancel={() => {
setVisible(false);
onChange();
}}
goNextVideo={() => {
setVisible(false);
goNextVideo();
}}
></VideoModel>
<div
className={styles["item"]}
onClick={() => {
setCurrentId(id);
setCurrentTitle(title);
setVisible(true);
navigate(`/course/${cid}/hour/${id}`);
}}
>
<div className={styles["left-item"]}>

View File

@ -1,169 +0,0 @@
import React, { useState, useRef, useEffect } from "react";
import styles from "./video.module.scss";
import { course } from "../../../api/index";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { useSelector } from "react-redux";
declare const window: any;
interface PropInterface {
id: number;
cid: number;
title: string;
open: boolean;
isLastpage: boolean;
lastSeeDuration: number;
progress: number;
onCancel: () => void;
goNextVideo: () => void;
}
export const VideoModel: React.FC<PropInterface> = ({
id,
cid,
title,
open,
isLastpage,
lastSeeDuration,
progress,
onCancel,
goNextVideo,
}) => {
const systemConfig = useSelector((state: any) => state.systemConfig.value);
const user = useSelector((state: any) => state.loginUser.value.user);
const [playUrl, setPlayUrl] = useState<string>("");
const [playDuration, setPlayDuration] = useState(0);
const [playendedStatus, setPlayendedStatus] = useState<Boolean>(false);
const [lastSeeValue, setLastSeeValue] = useState({});
const [loading, setLoading] = useState<Boolean>(false);
const myRef = useRef(0);
useEffect(() => {
let params = null;
if (open) {
if (lastSeeDuration > 0 && progress < 100) {
params = {
time: 5,
pos: lastSeeDuration,
};
setLastSeeValue(params);
}
setPlayendedStatus(false);
getVideoUrl(params);
}
}, [open, id, cid, lastSeeDuration]);
useEffect(() => {
myRef.current = playDuration;
}, [playDuration]);
const getVideoUrl = (params: any) => {
course.playUrl(cid, id).then((res: any) => {
setPlayUrl(res.data.url);
initDPlayer(res.data.url, 0, params);
});
};
const initDPlayer = (playUrl: string, isTrySee: number, params: any) => {
window.player = new window.DPlayer({
container: document.getElementById("meedu-player-container"),
autoplay: false,
video: {
url: playUrl,
pic: systemConfig.playerPoster,
},
try: isTrySee === 1,
bulletSecret: {
enabled: systemConfig.playerIsEnabledBulletSecret,
text: systemConfig.playerBulletSecretText
.replace("{name}", user.name)
.replace("{email}", user.email)
.replace("{idCard}", user.id_card),
size: "14px",
color: systemConfig.playerBulletSecretColor || "red",
opacity: Number(systemConfig.playerBulletSecretOpacity),
},
ban_drag: false,
last_see_pos: params,
});
// 监听播放进度更新evt
window.player.on("timeupdate", () => {
playTimeUpdate(parseInt(window.player.video.currentTime), false);
});
window.player.on("ended", () => {
setPlayendedStatus(true);
playTimeUpdate(parseInt(window.player.video.currentTime), true);
window.player && window.player.destroy();
});
setLoading(false);
};
const playTimeUpdate = (duration: number, isEnd: boolean) => {
if (duration - myRef.current >= 10 || isEnd === true) {
setPlayDuration(duration);
course.record(cid, id, duration).then((res: any) => {});
course.playPing(cid, id).then((res: any) => {});
}
};
return (
<>
{open && (
<div className={styles["video-mask"]}>
<div className={styles["top-cont"]}>
<div className={styles["box"]}>
<div
className={styles["close-btn"]}
onClick={() => {
window.player && window.player.destroy();
onCancel();
}}
>
<ArrowLeftOutlined />
<span className="ml-14"></span>
</div>
</div>
</div>
<div className={styles["video-body"]}>
<div className={styles["video-title"]}>{title}</div>
<div className={styles["video-box"]}>
<div className="play-box" id="meedu-player-container"></div>
{playendedStatus && (
<div className={styles["alert-message"]}>
{isLastpage && (
<div
className={styles["alert-button"]}
onClick={() => {
window.player && window.player.destroy();
onCancel();
}}
>
</div>
)}
{!isLastpage && (
<div
className={styles["alert-button"]}
onClick={() => {
if (loading) {
return;
}
window.player && window.player.destroy();
setLoading(true);
setLastSeeValue({});
setPlayendedStatus(false);
goNextVideo();
}}
>
</div>
)}
</div>
)}
</div>
</div>
</div>
)}
</>
);
};

View File

@ -15,7 +15,6 @@ const CoursePage = () => {
const [hours, setHours] = useState<any>({});
const [learnRecord, setLearnRecord] = useState<any>({});
const [learnHourRecord, setLearnHourRecord] = useState<any>({});
const [totalHours, setTotalHours] = useState<any>([]);
useEffect(() => {
getDetail();
@ -35,17 +34,6 @@ const CoursePage = () => {
if (res.data.learn_hour_records) {
setLearnHourRecord(res.data.learn_hour_records);
}
if (res.data.chapters.length === 0) {
setTotalHours(res.data.hours[0]);
} else if (res.data.chapters.length > 0) {
const arr: any = [];
for (let key in res.data.hours) {
res.data.hours[key].map((item: any) => {
arr.push(item);
});
}
setTotalHours(arr);
}
setLoading(false);
})
.catch((e) => {
@ -159,14 +147,11 @@ const CoursePage = () => {
cid={item.course_id}
title={item.title}
record={learnHourRecord[item.id]}
records={learnHourRecord}
duration={item.duration}
progress={
(learnHourRecord[item.id].finished_duration * 100) /
learnHourRecord[item.id].total_duration
}
totalHours={totalHours}
onChange={() => getDetail()}
></HourCompenent>
)}
{!learnHourRecord[item.id] && (
@ -175,11 +160,8 @@ const CoursePage = () => {
cid={item.course_id}
title={item.title}
record={null}
records={learnHourRecord}
duration={item.duration}
progress={0}
totalHours={totalHours}
onChange={() => getDetail()}
></HourCompenent>
)}
</div>
@ -199,14 +181,11 @@ const CoursePage = () => {
cid={item.course_id}
title={it.title}
record={learnHourRecord[it.id]}
records={learnHourRecord}
duration={it.duration}
progress={
(learnHourRecord[it.id].finished_duration * 100) /
learnHourRecord[it.id].total_duration
}
onChange={() => getDetail()}
totalHours={totalHours}
></HourCompenent>
)}
{!learnHourRecord[it.id] && (
@ -215,11 +194,8 @@ const CoursePage = () => {
cid={item.course_id}
title={it.title}
record={null}
records={learnHourRecord}
duration={it.duration}
progress={0}
totalHours={totalHours}
onChange={() => getDetail()}
></HourCompenent>
)}
</div>

View File

@ -1,15 +1,10 @@
.video-mask {
width: 100%;
height: 100%;
top: 0;
bottom: 0;
left: 0;
right: 0;
position: fixed;
height: 100vh;
min-height: 100vh;
background-color: #0e0e1e;
display: flex;
justify-content: center;
z-index: 100;
.top-cont {
position: fixed;
top: 0;
@ -18,9 +13,8 @@
width: 100%;
height: 60px;
background: rgba(255, 255, 255, 0.1);
.box {
width: 1200px;
width: 62.5%;
height: 60px;
display: flex;
align-items: center;

206
src/pages/course/video.tsx Normal file
View File

@ -0,0 +1,206 @@
import { useEffect, useRef, useState } from "react";
import styles from "./video.module.scss";
import { useParams, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { course as Course } from "../../api/index";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { message } from "antd";
declare const window: any;
const CoursePalyPage = () => {
const navigate = useNavigate();
const params = useParams();
const systemConfig = useSelector((state: any) => state.systemConfig.value);
const user = useSelector((state: any) => state.loginUser.value.user);
const [playUrl, setPlayUrl] = useState<string>("");
const [playDuration, setPlayDuration] = useState(0);
const [playendedStatus, setPlayendedStatus] = useState<Boolean>(false);
const [lastSeeValue, setLastSeeValue] = useState({});
const [course, setCourse] = useState<any>({});
const [hour, setHour] = useState<any>({});
const [loading, setLoading] = useState<Boolean>(false);
const [isLastpage, setIsLastpage] = useState<Boolean>(false);
const [totalHours, setTotalHours] = useState<any>([]);
const myRef = useRef(0);
useEffect(() => {
getCourse();
getDetail();
}, [params.courseId, params.hourId]);
useEffect(() => {
myRef.current = playDuration;
}, [playDuration]);
const getCourse = () => {
Course.detail(Number(params.courseId)).then((res: any) => {
let totalHours: any = [];
if (res.data.chapters.length === 0) {
setTotalHours(res.data.hours[0]);
totalHours = res.data.hours[0];
} else if (res.data.chapters.length > 0) {
const arr: any = [];
for (let key in res.data.hours) {
res.data.hours[key].map((item: any) => {
arr.push(item);
});
}
setTotalHours(arr);
totalHours = arr;
}
const index = totalHours.findIndex(
(i: any) => i.id === Number(params.hourId)
);
if (index === totalHours.length - 1) {
setIsLastpage(true);
}
});
};
const getDetail = () => {
if (loading) {
return true;
}
setLoading(true);
Course.play(Number(params.courseId), Number(params.hourId))
.then((res: any) => {
setCourse(res.data.course);
setHour(res.data.hour);
document.title = res.data.hour.title;
let record = res.data.user_hour_record;
let params = null;
if (record && record.finished_duration && record.is_finished === 0) {
params = {
time: 5,
pos: record.finished_duration,
};
setLastSeeValue(params);
setLastSeeValue(params);
}
getVideoUrl(params);
setLoading(false);
})
.catch((e) => {
setLoading(false);
});
};
const getVideoUrl = (data: any) => {
Course.playUrl(Number(params.courseId), Number(params.hourId)).then(
(res: any) => {
setPlayUrl(res.data.url);
initDPlayer(res.data.url, 0, data);
}
);
};
const initDPlayer = (playUrl: string, isTrySee: number, params: any) => {
window.player = new window.DPlayer({
container: document.getElementById("meedu-player-container"),
autoplay: false,
video: {
url: playUrl,
pic: systemConfig.playerPoster,
},
try: isTrySee === 1,
bulletSecret: {
enabled: systemConfig.playerIsEnabledBulletSecret,
text: systemConfig.playerBulletSecretText
.replace("{name}", user.name)
.replace("{email}", user.email)
.replace("{idCard}", user.id_card),
size: "14px",
color: systemConfig.playerBulletSecretColor || "red",
opacity: Number(systemConfig.playerBulletSecretOpacity),
},
ban_drag: false,
last_see_pos: params,
});
// 监听播放进度更新evt
window.player.on("timeupdate", () => {
playTimeUpdate(parseInt(window.player.video.currentTime), false);
});
window.player.on("ended", () => {
setPlayendedStatus(true);
playTimeUpdate(parseInt(window.player.video.currentTime), true);
window.player && window.player.destroy();
});
setLoading(false);
};
const playTimeUpdate = (duration: number, isEnd: boolean) => {
if (duration - myRef.current >= 10 || isEnd === true) {
setPlayDuration(duration);
Course.record(
Number(params.courseId),
Number(params.hourId),
duration
).then((res: any) => {});
Course.playPing(Number(params.courseId), Number(params.hourId)).then(
(res: any) => {}
);
}
};
const goNextVideo = () => {
const index = totalHours.findIndex(
(i: any) => i.id === Number(params.hourId)
);
if (index === totalHours.length - 1) {
setIsLastpage(true);
message.error("已经是最后一节了!");
} else if (index < totalHours.length - 1) {
navigate(`/course/${params.courseId}/hour/${totalHours[index + 1].id}`, {
replace: true,
});
}
};
return (
<div className={styles["video-mask"]}>
<div className={styles["top-cont"]}>
<div className={styles["box"]}>
<div
className={styles["close-btn"]}
onClick={() => {
window.player && window.player.destroy();
navigate(-1);
}}
>
<ArrowLeftOutlined />
<span className="ml-14"></span>
</div>
</div>
</div>
<div className={styles["video-body"]}>
<div className={styles["video-title"]}>{hour.title}</div>
<div className={styles["video-box"]}>
<div className="play-box" id="meedu-player-container"></div>
{playendedStatus && (
<div className={styles["alert-message"]}>
{isLastpage && (
<div className={styles["alert-button"]}></div>
)}
{!isLastpage && (
<div
className={styles["alert-button"]}
onClick={() => {
window.player && window.player.destroy();
setLastSeeValue({});
setPlayendedStatus(false);
goNextVideo();
}}
>
</div>
)}
</div>
)}
</div>
</div>
</div>
);
};
export default CoursePalyPage;

View File

@ -7,7 +7,7 @@ import {
} from "../../store/system/systemConfigSlice";
import { loginAction } from "../../store/user/loginUserSlice";
import { Header, NoHeader, Footer } from "../../compenents";
import { useLocation } from "react-router-dom";
import { useParams, useLocation } from "react-router-dom";
interface Props {
loginData?: any;
@ -44,14 +44,15 @@ export const InitPage = (props: Props) => {
}
const pathname = useLocation().pathname;
const params = useParams();
return (
<>
<div>
{pathname === "/login" && <NoHeader></NoHeader>}
{pathname !== "/login" && <Header></Header>}
{pathname !== "/login" && !params.hourId && <Header></Header>}
<Outlet />
{pathname !== "/login" && <Footer></Footer>}
{pathname !== "/login" && !params.hourId && <Footer></Footer>}
</div>
</>
);

View File

@ -45,8 +45,8 @@ const LatestLearnPage = () => {
)}
{!loading &&
courses.length > 0 &&
courses.map((item: any) => (
<div key={item.course.id}>
courses.map((item: any, index: number) => (
<div key={index}>
{item.course && (
<div
className={styles["item"]}

View File

@ -5,7 +5,8 @@ import { SystemConfigStoreInterface } from "../store/system/systemConfigSlice";
import { getToken } from "../utils";
import { InitPage } from "../pages/init";
import CoursePage from "../pages/course";
import CoursePage from "../pages/course/index";
import CoursePlayPage from "../pages/course/video";
import IndexPage from "../pages/index";
import LatestLearnPage from "../pages/latest-learn";
import LoginPage from "../pages/login";
@ -57,6 +58,10 @@ const routes: RouteObject[] = [
path: "/course/:courseId",
element: <CoursePage />,
},
{
path: "/course/:courseId/hour/:hourId",
element: <CoursePlayPage />,
},
{
path: "/latest-learn",
element: <LatestLearnPage />,