This commit is contained in:
Li1304553726 2025-02-26 16:38:42 +08:00
commit c284cc637b
32 changed files with 453 additions and 230 deletions

View File

@ -32,7 +32,7 @@ export class AuthService {
return { isValid: false, error: FileValidationErrorType.INVALID_URI }; return { isValid: false, error: FileValidationErrorType.INVALID_URI };
} }
const fileId = extractFileIdFromNginxUrl(params.originalUri); const fileId = extractFileIdFromNginxUrl(params.originalUri);
console.log(params.originalUri, fileId); // console.log(params.originalUri, fileId);
const resource = await db.resource.findFirst({ where: { fileId } }); const resource = await db.resource.findFirst({ where: { fileId } });
// 资源验证 // 资源验证

View File

@ -112,15 +112,12 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
return await db.$transaction(async (tx) => { return await db.$transaction(async (tx) => {
const courseParams = { ...params, tx }; const courseParams = { ...params, tx };
// Create the course first // Create the course first
console.log(courseParams?.staff?.id);
console.log('courseDetail', courseDetail);
const createdCourse = await this.create(courseDetail, courseParams); const createdCourse = await this.create(courseDetail, courseParams);
// If sections are provided, create them // If sections are provided, create them
return createdCourse; return createdCourse;
}); });
} }
// If transaction is provided, use it directly // If transaction is provided, use it directly
console.log('courseDetail', courseDetail);
const createdCourse = await this.create(courseDetail, params); const createdCourse = await this.create(courseDetail, params);
// If sections are provided, create them // If sections are provided, create them
return createdCourse; return createdCourse;
@ -163,7 +160,7 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
await this.setPerms(result, staff); await this.setPerms(result, staff);
await setCourseInfo({ data: result }); await setCourseInfo({ data: result });
} }
// console.log(result);
return result; return result;
}, },
); );

View File

@ -1,6 +1,7 @@
import { import {
db, db,
EnrollmentStatus, EnrollmentStatus,
Lecture,
Post, Post,
PostType, PostType,
SectionDto, SectionDto,
@ -127,7 +128,6 @@ export async function updateCourseEnrollmentStats(courseId: string) {
export async function setCourseInfo({ data }: { data: Post }) { export async function setCourseInfo({ data }: { data: Post }) {
// await db.term // await db.term
if (data?.type === PostType.COURSE) { if (data?.type === PostType.COURSE) {
const ancestries = await db.postAncestry.findMany({ const ancestries = await db.postAncestry.findMany({
where: { where: {
@ -144,28 +144,29 @@ export async function setCourseInfo({ data }: { data: Post }) {
}, },
}); });
const descendants = ancestries.map((ancestry) => ancestry.descendant); const descendants = ancestries.map((ancestry) => ancestry.descendant);
const sections: SectionDto[] = descendants const sections: SectionDto[] = (
.filter((descendant) => { descendants.filter((descendant) => {
return ( return (
descendant.type === PostType.SECTION && descendant.type === PostType.SECTION &&
descendant.parentId === data.id descendant.parentId === data.id
); );
}) }) as any
.map((section) => ({ ).map((section) => ({
...section, ...section,
lectures: [], lectures: [],
})); }));
const lectures = descendants.filter((descendant) => { const lectures = descendants.filter((descendant) => {
return ( return (
descendant.type === PostType.LECTURE && descendant.type === PostType.LECTURE &&
sections.map((section) => section.id).includes(descendant.parentId) sections.map((section) => section.id).includes(descendant.parentId)
); );
}); });
const lectureCount = lectures?.length || 0; const lectureCount = lectures?.length || 0;
sections.forEach((section) => { sections.forEach((section) => {
section.lectures = lectures.filter( section.lectures = lectures.filter(
(lecture) => lecture.parentId === section.id, (lecture) => lecture.parentId === section.id,
); ) as any as Lecture[];
}); });
Object.assign(data, { sections, lectureCount }); Object.assign(data, { sections, lectureCount });
} }

View File

@ -3,7 +3,6 @@ import {
BaseSetting, BaseSetting,
db, db,
PostType, PostType,
TaxonomySlug,
VisitType, VisitType,
} from '@nice/common'; } from '@nice/common';
export async function updateTotalCourseViewCount(type: VisitType) { export async function updateTotalCourseViewCount(type: VisitType) {
@ -24,7 +23,7 @@ export async function updateTotalCourseViewCount(type: VisitType) {
views: true, views: true,
}, },
where: { where: {
postId: { in: courseIds }, postId: { in: lectures.map((lecture) => lecture.id) },
type: type, type: type,
}, },
}); });
@ -67,6 +66,7 @@ export async function updatePostViewCount(id: string, type: VisitType) {
where: { id }, where: { id },
select: { id: true, meta: true }, select: { id: true, meta: true },
}); });
const totalViews = await db.visit.aggregate({ const totalViews = await db.visit.aggregate({
_sum: { _sum: {
views: true, views: true,

View File

@ -10,7 +10,7 @@ const pipeline = new ResourceProcessingPipeline()
.addProcessor(new VideoProcessor()); .addProcessor(new VideoProcessor());
export default async function processJob(job: Job<any, any, QueueJobType>) { export default async function processJob(job: Job<any, any, QueueJobType>) {
if (job.name === QueueJobType.FILE_PROCESS) { if (job.name === QueueJobType.FILE_PROCESS) {
console.log('job', job); // console.log('job', job);
const { resource } = job.data; const { resource } = job.data;
if (!resource) { if (!resource) {
throw new Error('No resource provided in job data'); throw new Error('No resource provided in job data');

View File

@ -89,8 +89,8 @@ export class TusService implements OnModuleInit {
upload: Upload, upload: Upload,
) { ) {
try { try {
console.log('upload.id', upload.id); // console.log('upload.id', upload.id);
console.log('fileId', this.getFileId(upload.id)); // console.log('fileId', this.getFileId(upload.id));
const resource = await this.resourceService.update({ const resource = await this.resourceService.update({
where: { fileId: this.getFileId(upload.id) }, where: { fileId: this.getFileId(upload.id) },
data: { status: ResourceStatus.UPLOADED }, data: { status: ResourceStatus.UPLOADED },

View File

@ -16,8 +16,9 @@ function useGetTaxonomy({ type }): GetTaxonomyProps {
taxonomy: { taxonomy: {
slug: type, slug: type,
}, },
parentId : null
}, },
take: 10, // 只取前10个 take: 11, // 只取前10个
}); });
const categories = useMemo(() => { const categories = useMemo(() => {
const allCategories = isLoading const allCategories = isLoading

View File

@ -30,7 +30,7 @@ interface PlatformStat {
const HeroSection = () => { const HeroSection = () => {
const carouselRef = useRef<CarouselRef>(null); const carouselRef = useRef<CarouselRef>(null);
const { statistics, slides } = useAppConfig(); const { statistics, slides } = useAppConfig();
const [countStatistics, setCountStatistics] = useState<number>(0) const [countStatistics, setCountStatistics] = useState<number>(4)
const platformStats: PlatformStat[] = useMemo(() => { const platformStats: PlatformStat[] = useMemo(() => {
return [ return [
{ icon: <TeamOutlined />, value: statistics.staffs, label: "注册学员" }, { icon: <TeamOutlined />, value: statistics.staffs, label: "注册学员" },
@ -53,7 +53,7 @@ const HeroSection = () => {
useEffect(() => { useEffect(() => {
const count = countNonZeroValues(statistics); const count = countNonZeroValues(statistics);
//console.log(count); console.log(count);
setCountStatistics(count); setCountStatistics(count);
}, [statistics]); }, [statistics]);
return ( return (
@ -111,7 +111,7 @@ const HeroSection = () => {
{ {
countStatistics > 1 && ( countStatistics > 1 && (
<div className="absolute -bottom-20 left-1/2 -translate-x-1/2 w-3/5 max-w-6xl px-4"> <div className="absolute -bottom-20 left-1/2 -translate-x-1/2 w-3/5 max-w-6xl px-4">
<div className={`rounded-2xl grid grid-cols-${countStatistics} md:grid-cols-${countStatistics} gap-4 md:gap-8 p-6 md:p-8 bg-white border duration-500 `}> <div className={`rounded-2xl grid grid-cols-${countStatistics} lg:grid-cols-${countStatistics} md:grid-cols-${countStatistics} gap-4 md:gap-8 p-6 md:p-8 bg-white border shadow-xl hover:shadow-2xl transition-shadow duration-500 will-change-[transform,box-shadow]`}>
{platformStats.map((stat, index) => { {platformStats.map((stat, index) => {
return stat.value return stat.value
? (<div ? (<div

View File

@ -6,39 +6,13 @@ interface CollapsibleContentProps {
maxHeight?: number; maxHeight?: number;
} }
const CollapsibleContent: React.FC<CollapsibleContentProps> = ({ const CollapsibleContent: React.FC<CollapsibleContentProps> = ({ content }) => {
content,
maxHeight = 150,
}) => {
const contentWrapperRef = useRef(null); const contentWrapperRef = useRef(null);
const [isExpanded, setIsExpanded] = useState(false);
const [shouldCollapse, setShouldCollapse] = useState(false);
useEffect(() => {
if (contentWrapperRef.current) {
const shouldCollapse =
contentWrapperRef.current.scrollHeight > maxHeight;
setShouldCollapse(shouldCollapse);
}
}, [content]);
return ( return (
<div className=" text-base "> <div className=" text-base ">
<div className=" flex flex-col gap-4 border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out rounded-xl p-6 "> <div className=" flex flex-col gap-4 border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out rounded-xl p-6 ">
{/* 包装整个内容区域的容器 */} {/* 包装整个内容区域的容器 */}
<div <div ref={contentWrapperRef}>
ref={contentWrapperRef}
style={{
maxHeight:
shouldCollapse && !isExpanded
? maxHeight
: undefined,
}}
className={`duration-300 ${
shouldCollapse && !isExpanded
? ` overflow-hidden relative`
: ""
}`}>
{/* 内容区域 */} {/* 内容区域 */}
<div <div
className="ql-editor p-0 space-y-1 leading-relaxed" className="ql-editor p-0 space-y-1 leading-relaxed"
@ -46,23 +20,7 @@ const CollapsibleContent: React.FC<CollapsibleContentProps> = ({
__html: content || "", __html: content || "",
}} }}
/> />
{/* 渐变遮罩 */}
{shouldCollapse && !isExpanded && (
<div className="absolute bottom-0 left-0 right-0 h-20 bg-gradient-to-t from-white to-transparent" />
)}
</div> </div>
{/* 展开/收起按钮 */}
{shouldCollapse && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="mt-2 text-blue-500 hover:text-blue-700">
{isExpanded ? "收起" : "展开"}
</button>
)}
{/* PostResources 组件 */}
{/* <PostResources post={post} /> */}
</div> </div>
</div> </div>
); );

View File

@ -1,11 +1,11 @@
export const defaultModules = { export const defaultModules = {
toolbar: [ toolbar: [
[{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ header: [1, 2, 3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike'], ["bold", "italic", "underline", "strike"],
[{ 'list': 'ordered' }, { 'list': 'bullet' }], [{ list: "ordered" }, { list: "bullet" }],
[{ 'color': [] }, { 'background': [] }], [{ color: [] }, { background: [] }],
[{ 'align': [] }], [{ align: [] }],
['link', 'image'], ["link"],
['clean'] ["clean"],
] ],
}; };

View File

@ -1,5 +1,4 @@
import { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
// import UncoverAvatarUploader from "../uploader/UncoverAvatarUploader ";
import { Upload, Progress, Button, Image, Form } from "antd"; import { Upload, Progress, Button, Image, Form } from "antd";
import { DeleteOutlined } from "@ant-design/icons"; import { DeleteOutlined } from "@ant-design/icons";
import AvatarUploader from "./AvatarUploader"; import AvatarUploader from "./AvatarUploader";
@ -8,11 +7,17 @@ import { isEqual } from "lodash";
interface MultiAvatarUploaderProps { interface MultiAvatarUploaderProps {
value?: string[]; value?: string[];
onChange?: (value: string[]) => void; onChange?: (value: string[]) => void;
className?: string;
placeholder?: string;
style?: React.CSSProperties;
} }
export function MultiAvatarUploader({ export function MultiAvatarUploader({
value, value,
onChange, onChange,
className,
style,
placeholder = "点击上传",
}: MultiAvatarUploaderProps) { }: MultiAvatarUploaderProps) {
const [imageList, setImageList] = useState<string[]>(value || []); const [imageList, setImageList] = useState<string[]>(value || []);
const [previewImage, setPreviewImage] = useState<string>(""); const [previewImage, setPreviewImage] = useState<string>("");
@ -30,12 +35,21 @@ export function MultiAvatarUploader({
{(imageList || [])?.map((image, index) => { {(imageList || [])?.map((image, index) => {
return ( return (
<div <div
className="mr-2px relative" className={`mr-2px relative ${className}`}
key={index} key={index}
style={{ width: "200px", height: "100px" }}> style={{
width: "100px",
height: "100px",
...style,
}}>
<Image <Image
alt="" alt=""
style={{ width: "200px", height: "100px" }} className={className}
style={{
width: "100px",
height: "100px",
...style,
}}
src={image} src={image}
preview={{ preview={{
visible: previewImage === image, visible: previewImage === image,
@ -70,7 +84,10 @@ export function MultiAvatarUploader({
</div> </div>
<div className="flex"> <div className="flex">
<AvatarUploader <AvatarUploader
style={style}
className={className}
showCover={false} showCover={false}
placeholder={placeholder}
successText={"轮播图上传成功"} successText={"轮播图上传成功"}
onChange={(value) => { onChange={(value) => {
console.log(value); console.log(value);

View File

@ -0,0 +1,135 @@
import React, { useMemo } from "react";
import { Image, Button, Row, Col, Tooltip } from "antd";
import { ResourceDto } from "@nice/common";
import { env } from "@web/src/env";
import { getFileIcon } from "./utils";
import { formatFileSize, getCompressedImageUrl } from "@nice/utils";
export default function ResourcesShower({
resources = [],
}: {
resources: ResourceDto[];
}) {
const { resources: dealedResources } = useMemo(() => {
if (!resources) return { resources: [] };
const isImage = (url: string) =>
/\.(png|jpg|jpeg|gif|webp)$/i.test(url);
const sortedResources = resources
.map((resource) => {
const original = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${resource.url}`;
const isImg = isImage(resource.url);
return {
...resource,
url: isImg ? getCompressedImageUrl(original) : original,
originalUrl: original,
isImage: isImg,
};
})
.sort((a, b) => (a.isImage === b.isImage ? 0 : a.isImage ? -1 : 1));
return { resources: sortedResources };
}, [resources]);
const imageResources = dealedResources.filter((res) => res.isImage);
const fileResources = dealedResources.filter((res) => !res.isImage);
return (
<div className="space-y-6">
{imageResources.length > 0 && (
<Row gutter={[16, 16]} className="mb-6">
<Image.PreviewGroup>
{imageResources.map((resource) => (
<Col
key={resource.url}
xs={12}
sm={8}
md={6}
lg={6}
xl={4}
className="relative">
<div className="relative aspect-square rounded-lg overflow-hidden bg-gray-100">
<div className="w-full h-full">
<Image
src={resource.url}
alt={resource.title}
preview={{
src: resource.originalUrl,
mask: (
<div className="flex items-center justify-center text-white">
</div>
),
}}
style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
objectFit: "cover",
}}
rootClassName="w-full h-full"
/>
</div>
{resource.title && (
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/60 to-transparent text-white text-sm truncate">
{resource.title}
</div>
)}
</div>
</Col>
))}
</Image.PreviewGroup>
</Row>
)}
{fileResources.length > 0 && (
<div className="rounded-xl p-1 border border-gray-100 bg-white">
<div className="flex flex-nowrap overflow-x-auto scrollbar-hide gap-1.5">
{fileResources.map((resource) => {
return (
<a
key={resource.url}
className="flex-shrink-0 relative active:scale-95 transition-transform select-none "
href={resource.originalUrl}
target="_blank"
download={true}
title="点击下载文件">
{/* 超紧凑卡片容器 */}
<div className="w-[120px] h-[80px] p-2 flex flex-col items-center justify-between rounded-xl hover:bg-primary-50/40 cursor-pointer">
{/* 微型文件图标 */}
<div className="text-primary-600 text-base">
{getFileIcon(resource.url)}
</div>
{/* 压缩信息展示 */}
<div className="w-full text-center space-y-0.5">
<p className="text-xs font-medium text-gray-800 truncate">
{resource.title?.slice(0, 12) ||
"未命名"}
</p>
<div className="flex items-center justify-between text-xs text-gray-500">
<span className="bg-gray-100 px-0.5 rounded-sm">
{resource.url
.split(".")
.pop()
?.slice(0, 4)
.toUpperCase()}
</span>
<span>
{resource.meta.size &&
formatFileSize(
resource.meta.size
)}
</span>
</div>
</div>
</div>
</a>
);
})}
</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,48 @@
import {
FilePdfOutlined,
FileWordOutlined,
FileExcelOutlined,
FilePptOutlined,
FileTextOutlined,
FileZipOutlined,
FileImageOutlined,
FileUnknownOutlined,
} from "@ant-design/icons";
export const isContentEmpty = (html: string) => {
// 创建一个临时 div 来解析 HTML 内容
const temp = document.createElement("div");
temp.innerHTML = html;
// 获取纯文本内容并检查是否为空
return !temp.textContent?.trim();
};
export const getFileIcon = (filename: string) => {
const extension = filename.split(".").pop()?.toLowerCase();
switch (extension) {
case "pdf":
return <FilePdfOutlined className="text-red-500" />;
case "doc":
case "docx":
return <FileWordOutlined className="text-blue-500" />;
case "xls":
case "xlsx":
return <FileExcelOutlined className="text-green-600" />;
case "ppt":
case "pptx":
return <FilePptOutlined className="text-orange-500" />;
case "txt":
return <FileTextOutlined className="text-gray-600" />;
case "zip":
case "rar":
case "7z":
return <FileZipOutlined className="text-purple-500" />;
case "png":
case "jpg":
case "jpeg":
case "gif":
case "webp":
return <FileImageOutlined className="text-pink-400" />;
default:
return <FileUnknownOutlined className="text-gray-500" />;
}
};

View File

@ -3,6 +3,7 @@ import {
courseDetailSelect, courseDetailSelect,
CourseDto, CourseDto,
Lecture, Lecture,
lectureDetailSelect,
RolePerms, RolePerms,
VisitType, VisitType,
} from "@nice/common"; } from "@nice/common";
@ -49,10 +50,13 @@ export function CourseDetailProvider({
(api.post as any).findFirst.useQuery( (api.post as any).findFirst.useQuery(
{ {
where: { id: editId }, where: { id: editId },
include: { // include: {
// sections: { include: { lectures: true } }, // // sections: { include: { lectures: true } },
enrollments: true, // enrollments: true,
}, // terms:true
// },
select:courseDetailSelect
}, },
{ enabled: Boolean(editId) } { enabled: Boolean(editId) }
); );
@ -72,16 +76,17 @@ export function CourseDetailProvider({
).findFirst.useQuery( ).findFirst.useQuery(
{ {
where: { id: selectedLectureId }, where: { id: selectedLectureId },
select: lectureDetailSelect,
}, },
{ enabled: Boolean(editId) } { enabled: Boolean(editId) }
); );
useEffect(() => { useEffect(() => {
if (course) { if (lecture?.id) {
read.mutateAsync({ read.mutateAsync({
data: { data: {
visitorId: user?.id || null, visitorId: user?.id || null,
postId: course.id, postId: lecture?.id,
type: VisitType.READED, type: VisitType.READED,
}, },
}); });

View File

@ -1,14 +1,16 @@
import { Course } from "@nice/common"; import { Course, TaxonomySlug } from "@nice/common";
import React, { useContext, useMemo } from "react"; import React, { useContext, useMemo } from "react";
import { Image, Typography, Skeleton } from "antd"; // 引入 antd 组件 import { Image, Typography, Skeleton, Tag } from "antd"; // 引入 antd 组件
import { CourseDetailContext } from "./CourseDetailContext"; import { CourseDetailContext } from "./CourseDetailContext";
import { import {
CalendarOutlined, CalendarOutlined,
EditTwoTone,
EyeOutlined, EyeOutlined,
PlayCircleOutlined, PlayCircleOutlined,
ReloadOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useNavigate } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
export const CourseDetailDescription: React.FC = () => { export const CourseDetailDescription: React.FC = () => {
const { course, isLoading, selectedLectureId, setSelectedLectureId } = const { course, isLoading, selectedLectureId, setSelectedLectureId } =
@ -18,12 +20,14 @@ export const CourseDetailDescription: React.FC = () => {
return course?.sections?.[0]?.lectures?.[0]?.id; return course?.sections?.[0]?.lectures?.[0]?.id;
}, [course]); }, [course]);
const navigate = useNavigate(); const navigate = useNavigate();
const { canEdit } = useContext(CourseDetailContext);
const { id } = useParams();
return ( return (
<div className="w-full bg-white shadow-md rounded-lg border border-gray-200 p-6"> <div className="w-full bg-white shadow-md rounded-lg border border-gray-200 p-5 my-4">
{isLoading || !course ? ( {isLoading || !course ? (
<Skeleton active paragraph={{ rows: 4 }} /> <Skeleton active paragraph={{ rows: 4 }} />
) : ( ) : (
<div className="space-y-4"> <div className="space-y-2">
{!selectedLectureId && ( {!selectedLectureId && (
<> <>
<div className="relative my-4 overflow-hidden flex justify-center items-center"> <div className="relative my-4 overflow-hidden flex justify-center items-center">
@ -43,16 +47,61 @@ export const CourseDetailDescription: React.FC = () => {
</> </>
)} )}
<div className="text-lg font-bold">{"课程简介:"}</div> <div className="text-lg font-bold">{"课程简介:"}</div>
<div className="text-gray-600 flex justify-start gap-4"> <div className="flex gap-2 flex-wrap items-center">
<div>{course?.subTitle}</div> <div>{course?.subTitle}</div>
<div className="flex gap-1"> {
<EyeOutlined></EyeOutlined> course.terms.map((term) => {
<div>{course?.meta?.views || 0}</div> return (
</div> <Tag
key={term.id}
// color={term.taxonomy.slug===TaxonomySlug.CATEGORY? "blue" : "green"}
color={
term?.taxonomy?.slug ===
TaxonomySlug.CATEGORY
? "blue"
: term?.taxonomy?.slug ===
TaxonomySlug.LEVEL
? "green"
: "orange"
}
className="px-3 py-1 rounded-full bg-blue-100 text-blue-600 border-0">
{term.name}
</Tag>
)
})
}
</div>
<div className="text-gray-800 flex justify-start gap-5">
<div className="flex gap-1"> <div className="flex gap-1">
<CalendarOutlined></CalendarOutlined> <CalendarOutlined></CalendarOutlined>
{dayjs(course?.createdAt).format("YYYY年M月D日")} {dayjs(course?.createdAt).format("YYYY年M月D日")}
</div> </div>
<div className="flex gap-1">
<ReloadOutlined></ReloadOutlined>
{dayjs(course?.updatedAt).format("YYYY年M月D日")}
</div>
<div className="flex gap-1">
<EyeOutlined></EyeOutlined>
<div>{course?.meta?.views || 0}</div>
</div>
{
canEdit && (
<div
className="flex gap-1 text-primary hover:cursor-pointer"
onClick={() => {
const url = id
? `/course/${id}/editor`
: "/course/editor";
navigate(url);
}}
>
<EditTwoTone></EditTwoTone>
{"点击编辑课程"}
</div>
)
}
</div> </div>
<Paragraph <Paragraph
className="text-gray-600" className="text-gray-600"

View File

@ -1,67 +0,0 @@
// import { useContext } from "react";
// import { CourseDetailContext } from "../../CourseDetailContext";
// import { CheckCircleIcon } from "@heroicons/react/24/solid";
// export function Overview() {
// const { course } = useContext(CourseDetailContext);
// return (
// <>
// <div className="space-y-8">
// {/* 课程描述 */}
// <div className="prose max-w-none">
// <p>{course?.description}</p>
// </div>
// {/* 学习目标 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">学习目标</h2>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
// {course?.objectives.map((objective, index) => (
// <div key={index} className="flex items-start gap-2">
// <CheckCircleIcon className="w-5 h-5 text-green-500 flex-shrink-0 mt-1" />
// <span>{objective}</span>
// </div>
// ))}
// </div>
// </div>
// {/* 适合人群 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">适合人群</h2>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
// {course?.audiences.map((audience, index) => (
// <div key={index} className="flex items-start gap-2">
// <CheckCircleIcon className="w-5 h-5 text-blue-500 flex-shrink-0 mt-1" />
// <span>{audience}</span>
// </div>
// ))}
// </div>
// </div>
// {/* 课程要求 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">课程要求</h2>
// <ul className="list-disc list-inside space-y-2 text-gray-700">
// {course?.requirements.map((requirement, index) => (
// <li key={index}>{requirement}</li>
// ))}
// </ul>
// </div>
// {/* 可获得技能 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">可获得技能</h2>
// <div className="flex flex-wrap gap-2">
// {course?.skills.map((skill, index) => (
// <span
// key={index}
// className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
// {skill}
// </span>
// ))}
// </div>
// </div>
// </div>
// </>
// );
// }

View File

@ -8,6 +8,7 @@ import { CourseDetailContext } from "./CourseDetailContext";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent"; import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { Skeleton } from "antd"; import { Skeleton } from "antd";
import { CoursePreview } from "./CoursePreview/CoursePreview"; import { CoursePreview } from "./CoursePreview/CoursePreview";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
// interface CourseDetailDisplayAreaProps { // interface CourseDetailDisplayAreaProps {
// // course: Course; // // course: Course;
@ -53,6 +54,12 @@ export const CourseDetailDisplayArea: React.FC = () => {
content={lecture?.content || ""} content={lecture?.content || ""}
maxHeight={500} // Optional, defaults to 150 maxHeight={500} // Optional, defaults to 150
/> />
<div className="px-6">
<ResourcesShower
resources={
lecture?.resources
}></ResourcesShower>
</div>
</div> </div>
</div> </div>
)} )}

View File

@ -24,8 +24,8 @@ export function CourseDetailHeader() {
return ( return (
<Header className="select-none flex items-center justify-center bg-white shadow-md border-b border-gray-100 fixed w-full z-30"> <Header className="select-none flex items-center justify-center bg-white shadow-md border-b border-gray-100 fixed w-full z-30">
<div className="w-full flex items-center justify-between h-full"> <div className="w-full flex items-center justify-between h-full">
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-10">
<HomeOutlined <HomeOutlined
onClick={() => { onClick={() => {
navigate("/"); navigate("/");
@ -33,24 +33,12 @@ export function CourseDetailHeader() {
className="text-2xl text-primary-500 hover:scale-105 cursor-pointer" className="text-2xl text-primary-500 hover:scale-105 cursor-pointer"
/> />
<div className="text-2xl font-bold bg-gradient-to-r from-primary-600 via-primary-500 to-primary-400 bg-clip-text text-transparent transition-transform "> <div className="text-2xl tracking-widest font-bold bg-gradient-to-r from-primary-600 via-primary-500 to-primary-400 bg-clip-text text-transparent transition-transform ">
{course?.title} {course?.title}
</div> </div>
{/* <NavigationMenu /> */} {/* <NavigationMenu /> */}
</div> </div>
<div className="flex items-center space-x-6"> <div className="flex items-center space-x-6">
<div className="group relative">
<Input
size="large"
prefix={
<SearchOutlined className="text-gray-400 group-hover:text-blue-500 transition-colors" />
}
placeholder="搜索课程"
className="w-72 rounded-full"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
</div>
{canEdit && ( {canEdit && (
<> <>
<Button <Button

View File

@ -91,6 +91,7 @@ export function CourseFormProvider({
const formattedValues = { const formattedValues = {
...values, ...values,
type: PostType.COURSE,
meta: { meta: {
...((course?.meta as CourseMeta) || {}), ...((course?.meta as CourseMeta) || {}),
...(values?.meta?.thumbnail !== undefined && { ...(values?.meta?.thumbnail !== undefined && {
@ -111,8 +112,6 @@ export function CourseFormProvider({
delete formattedValues.sections; delete formattedValues.sections;
delete formattedValues.deptIds; delete formattedValues.deptIds;
console.log(course.meta);
console.log(formattedValues?.meta);
try { try {
if (editId) { if (editId) {
const result = await update.mutateAsync({ const result = await update.mutateAsync({
@ -125,7 +124,7 @@ export function CourseFormProvider({
const result = await createCourse.mutateAsync({ const result = await createCourse.mutateAsync({
courseDetail: { courseDetail: {
data: { data: {
title: formattedValues.title || "12345", title: formattedValues.title,
// state: CourseStatus.DRAFT, // state: CourseStatus.DRAFT,
type: PostType.COURSE, type: PostType.COURSE,

View File

@ -33,7 +33,12 @@ import {
useSortable, useSortable,
verticalListSortingStrategy, verticalListSortingStrategy,
} from "@dnd-kit/sortable"; } from "@dnd-kit/sortable";
import { Lecture, LectureType, PostType } from "@nice/common"; import {
Lecture,
lectureDetailSelect,
LectureType,
PostType,
} from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext"; import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client"; import { usePost } from "@nice/client";
import { LectureData, SectionData } from "./interface"; import { LectureData, SectionData } from "./interface";
@ -62,6 +67,7 @@ export const LectureList: React.FC<LectureListProps> = ({
orderBy: { orderBy: {
order: "asc", order: "asc",
}, },
select: lectureDetailSelect,
}, },
{ {
enabled: !!sectionId, enabled: !!sectionId,

View File

@ -15,6 +15,7 @@ import {
LectureType, LectureType,
LessonTypeLabel, LessonTypeLabel,
PostType, PostType,
ResourceStatus,
videoMimeTypes, videoMimeTypes,
} from "@nice/common"; } from "@nice/common";
import { usePost } from "@nice/client"; import { usePost } from "@nice/client";
@ -23,6 +24,8 @@ import toast from "react-hot-toast";
import { env } from "@web/src/env"; import { env } from "@web/src/env";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent"; import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer"; import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer";
import MultiAvatarUploader from "@web/src/components/common/uploader/MultiAvatarUploader";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
interface SortableLectureProps { interface SortableLectureProps {
field: Lecture; field: Lecture;
@ -58,6 +61,7 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
setLoading(true); setLoading(true);
const values = await form.validateFields(); const values = await form.validateFields();
let result; let result;
const fileIds = values?.meta?.fileIds || [];
const videoUrlId = Array.isArray(values?.meta?.videoIds) const videoUrlId = Array.isArray(values?.meta?.videoIds)
? values?.meta?.videoIds[0] ? values?.meta?.videoIds[0]
: typeof values?.meta?.videoIds === "string" : typeof values?.meta?.videoIds === "string"
@ -72,13 +76,14 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
title: values?.title, title: values?.title,
meta: { meta: {
type: values?.meta?.type, type: values?.meta?.type,
fileIds: fileIds,
videoIds: videoUrlId ? [videoUrlId] : [], videoIds: videoUrlId ? [videoUrlId] : [],
videoUrl: videoUrlId videoUrl: videoUrlId
? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8` ? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
: undefined, : undefined,
}, },
resources: { resources: {
connect: [videoUrlId] connect: [videoUrlId, ...fileIds]
.filter(Boolean) .filter(Boolean)
.map((fileId) => ({ .map((fileId) => ({
fileId, fileId,
@ -97,13 +102,14 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
title: values?.title, title: values?.title,
meta: { meta: {
type: values?.meta?.type, type: values?.meta?.type,
fileIds: fileIds,
videoIds: videoUrlId ? [videoUrlId] : [], videoIds: videoUrlId ? [videoUrlId] : [],
videoUrl: videoUrlId videoUrl: videoUrlId
? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8` ? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
: undefined, : undefined,
}, },
resources: { resources: {
connect: [videoUrlId] connect: [videoUrlId, ...fileIds]
.filter(Boolean) .filter(Boolean)
.map((fileId) => ({ .map((fileId) => ({
fileId, fileId,
@ -113,6 +119,7 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
}, },
}); });
} }
setIsContentVisible(false);
toast.success("课时已更新"); toast.success("课时已更新");
field.id = result.id; field.id = result.id;
setEditing(false); setEditing(false);
@ -178,14 +185,30 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
/> />
</Form.Item> </Form.Item>
) : ( ) : (
<Form.Item <div>
name="content" <Form.Item
className="mb-0 flex-1" name="content"
rules={[ className="mb-0 flex-1"
{ required: true, message: "请输入内容" }, rules={[
]}> {
<QuillEditor /> required: true,
</Form.Item> message: "请输入内容",
},
]}>
<QuillEditor />
</Form.Item>
<Form.Item
name={["meta", "fileIds"]}
className="mb-0 flex-1"
rules={[
{
required: true,
message: "请传入文件",
},
]}>
<TusUploader multiple={true} />
</Form.Item>
</div>
)} )}
</div> </div>
@ -237,10 +260,16 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
{isContentVisible && {isContentVisible &&
!editing && // Conditionally render content based on type !editing && // Conditionally render content based on type
(field?.meta?.type === LectureType.ARTICLE ? ( (field?.meta?.type === LectureType.ARTICLE ? (
<CollapsibleContent <div>
maxHeight={200} <CollapsibleContent
content={field?.content} maxHeight={200}
/> content={field?.content}
/>
<div className="px-6 ">
<ResourcesShower
resources={field?.resources}></ResourcesShower>
</div>
</div>
) : ( ) : (
<VideoPlayer src={field?.meta?.videoUrl} /> <VideoPlayer src={field?.meta?.videoUrl} />
))} ))}

View File

@ -48,7 +48,7 @@ export default function TermSelect({
const [listTreeData, setListTreeData] = useState< const [listTreeData, setListTreeData] = useState<
Omit<DefaultOptionType, "label">[] Omit<DefaultOptionType, "label">[]
>([]); >([]);
const fetchParentTerms = useCallback( const fetchParentTerms = useCallback(
async (termIds: string | string[], taxonomyId?: string) => { async (termIds: string | string[], taxonomyId?: string) => {
const idsArray = Array.isArray(termIds) const idsArray = Array.isArray(termIds)

View File

@ -96,7 +96,6 @@ export const Controls = () => {
<div className="flex items-center space-x-4"> <div className="flex items-center space-x-4">
{/* 播放/暂停按钮 */} {/* 播放/暂停按钮 */}
<Play></Play> <Play></Play>
{/* 时间显示 */} {/* 时间显示 */}
{duration && ( {duration && (
<span className="text-white text-xl"> <span className="text-white text-xl">
@ -114,7 +113,7 @@ export const Controls = () => {
{/* 倍速控制 */} {/* 倍速控制 */}
<Speed></Speed> <Speed></Speed>
{/* 设置按钮 */} {/* 设置按钮 */}
<Setting></Setting> {/* <Setting></Setting> */}
{/* 全屏按钮 */} {/* 全屏按钮 */}
<FullScreen></FullScreen> <FullScreen></FullScreen>

View File

@ -14,7 +14,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
onError, onError,
videoRef, videoRef,
setIsReady, setIsReady,
isPlaying,
setIsPlaying, setIsPlaying,
setError, setError,
setBufferingState, setBufferingState,
@ -26,8 +25,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
isDragging, isDragging,
setIsDragging, setIsDragging,
progressRef, progressRef,
resolution,
setResolutions,
} = useContext(VideoPlayerContext); } = useContext(VideoPlayerContext);
// 处理进度条拖拽 // 处理进度条拖拽
@ -40,7 +37,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
); );
videoRef.current.currentTime = percent * videoRef.current.duration; videoRef.current.currentTime = percent * videoRef.current.duration;
}; };
// 添加拖拽事件监听 // 添加拖拽事件监听
useEffect(() => { useEffect(() => {
const handleMouseUp = () => setIsDragging(false); const handleMouseUp = () => setIsDragging(false);
@ -66,15 +62,12 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
setError(null); setError(null);
setLoadingProgress(0); setLoadingProgress(0);
setBufferingState(false); setBufferingState(false);
// Check for native HLS support (Safari) // Check for native HLS support (Safari)
if (videoRef.current.canPlayType("application/vnd.apple.mpegurl")) { if (videoRef.current.canPlayType("application/vnd.apple.mpegurl")) {
videoRef.current.src = src; videoRef.current.src = src;
setIsReady(true); setIsReady(true);
// 设置视频时长 // 设置视频时长
setDuration(videoRef.current.duration); setDuration(videoRef.current.duration);
if (autoPlay) { if (autoPlay) {
try { try {
await videoRef.current.play(); await videoRef.current.play();
@ -85,14 +78,12 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
} }
return; return;
} }
if (!Hls.isSupported()) { if (!Hls.isSupported()) {
const errorMessage = "您的浏览器不支持 HLS 视频播放"; const errorMessage = "您的浏览器不支持 HLS 视频播放";
setError(errorMessage); setError(errorMessage);
onError?.(errorMessage); onError?.(errorMessage);
return; return;
} }
hls = new Hls({ hls = new Hls({
maxBufferLength: 30, maxBufferLength: 30,
maxMaxBufferLength: 600, maxMaxBufferLength: 600,
@ -102,13 +93,10 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
hls.loadSource(src); hls.loadSource(src);
hls.attachMedia(videoRef.current); hls.attachMedia(videoRef.current);
hls.on(Hls.Events.MANIFEST_PARSED, async () => { hls.on(Hls.Events.MANIFEST_PARSED, async () => {
setIsReady(true); setIsReady(true);
// 设置视频时长 // 设置视频时长
setDuration(videoRef.current?.duration || 0); setDuration(videoRef.current?.duration || 0);
if (autoPlay && videoRef.current) { if (autoPlay && videoRef.current) {
try { try {
await videoRef.current.play(); await videoRef.current.play();
@ -118,7 +106,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
} }
} }
}); });
hls.on(Hls.Events.BUFFER_APPENDING, () => { hls.on(Hls.Events.BUFFER_APPENDING, () => {
setBufferingState(true); setBufferingState(true);
}); });

View File

@ -71,7 +71,7 @@ export const routes: CustomRouteObject[] = [
{ {
path: ":id?/editor", path: ":id?/editor",
element: ( element: (
<WithAuth> <WithAuth >
<CourseEditorLayout></CourseEditorLayout> <CourseEditorLayout></CourseEditorLayout>
</WithAuth> </WithAuth>
), ),

View File

@ -5,7 +5,7 @@ export enum PostType {
POST = "post", POST = "post",
POST_COMMENT = "post_comment", POST_COMMENT = "post_comment",
COURSE_REVIEW = "course_review", COURSE_REVIEW = "course_review",
COURSE = "couse", COURSE = "course",
SECTION = "section", SECTION = "section",
LECTURE = "lecture", LECTURE = "lecture",
PATH = "path", PATH = "path",
@ -101,7 +101,6 @@ export enum RolePerms {
} }
export enum AppConfigSlug { export enum AppConfigSlug {
BASE_SETTING = "base_setting", BASE_SETTING = "base_setting",
} }
// 资源类型的枚举,定义了不同类型的资源,以字符串值表示 // 资源类型的枚举,定义了不同类型的资源,以字符串值表示
export enum ResourceType { export enum ResourceType {

View File

@ -1,7 +1,8 @@
export * from "./department" export * from "./department";
export * from "./message" export * from "./message";
export * from "./staff" export * from "./staff";
export * from "./term" export * from "./term";
export * from "./post" export * from "./post";
export * from "./rbac" export * from "./rbac";
export * from "./select" export * from "./select";
export * from "./resource";

View File

@ -8,6 +8,7 @@ import {
} from "@prisma/client"; } from "@prisma/client";
import { StaffDto } from "./staff"; import { StaffDto } from "./staff";
import { TermDto } from "./term"; import { TermDto } from "./term";
import { ResourceDto } from "./resource";
export type PostComment = { export type PostComment = {
id: string; id: string;
@ -44,6 +45,7 @@ export type PostDto = Post & {
export type LectureMeta = { export type LectureMeta = {
type?: string; type?: string;
views?: number;
videoUrl?: string; videoUrl?: string;
videoThumbnail?: string; videoThumbnail?: string;
videoIds?: string[]; videoIds?: string[];
@ -51,6 +53,7 @@ export type LectureMeta = {
}; };
export type Lecture = Post & { export type Lecture = Post & {
resources?: ResourceDto[];
meta?: LectureMeta; meta?: LectureMeta;
}; };
@ -79,5 +82,5 @@ export type CourseDto = Course & {
sections?: SectionDto[]; sections?: SectionDto[];
terms: TermDto[]; terms: TermDto[];
lectureCount?: number; lectureCount?: number;
depts:Department[] depts: Department[];
}; };

View File

@ -0,0 +1,52 @@
import { Resource } from "@prisma/client";
export interface BaseMetadata {
size: number;
filetype: string;
filename: string;
extension: string;
modifiedAt: Date;
}
/**
*
*/
export interface ImageMetadata {
width: number; // 图片宽度(px)
height: number; // 图片高度(px)
compressedUrl?: string;
orientation?: number; // EXIF方向信息
space?: string; // 色彩空间 (如: RGB, CMYK)
hasAlpha?: boolean; // 是否包含透明通道
}
/**
*
*/
export interface VideoMetadata {
width?: number;
height?: number;
duration?: number;
videoCodec?: string;
audioCodec?: string;
coverUrl?: string;
}
/**
*
*/
export interface AudioMetadata {
duration: number; // 音频时长(秒)
bitrate?: number; // 比特率(bps)
sampleRate?: number; // 采样率(Hz)
channels?: number; // 声道数
codec?: string; // 音频编码格式
}
export type FileMetadata = ImageMetadata &
VideoMetadata &
AudioMetadata &
BaseMetadata;
export type ResourceDto = Resource & {
meta: FileMetadata;
};

View File

@ -1,5 +0,0 @@
import { Lecture, Section } from "@prisma/client";
export type SectionDto = Section & {
lectures: Lecture[];
};

View File

@ -69,6 +69,7 @@ export const courseDetailSelect: Prisma.PostSelect = {
id: true, id: true,
title: true, title: true,
subTitle: true, subTitle: true,
type: true,
content: true, content: true,
depts: true, depts: true,
// isFeatured: true, // isFeatured: true,
@ -79,6 +80,7 @@ export const courseDetailSelect: Prisma.PostSelect = {
select: { select: {
id: true, id: true,
name: true, name: true,
taxonomyId: true,
taxonomy: { taxonomy: {
select: { select: {
id: true, id: true,
@ -95,3 +97,15 @@ export const courseDetailSelect: Prisma.PostSelect = {
meta: true, meta: true,
rating: true, rating: true,
}; };
export const lectureDetailSelect: Prisma.PostSelect = {
id: true,
title: true,
subTitle: true,
content: true,
resources: true,
createdAt: true,
updatedAt: true,
// 关联表选择
meta: true,
};