Add optimized tutorial cover images
这个提交包含在:
@@ -16,6 +16,9 @@ FROM node:22-bookworm-slim AS runtime
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
RUN corepack enable
|
RUN corepack enable
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
COPY package.json pnpm-lock.yaml ./
|
COPY package.json pnpm-lock.yaml ./
|
||||||
COPY patches ./patches
|
COPY patches ./patches
|
||||||
RUN pnpm install --prod --frozen-lockfile
|
RUN pnpm install --prod --frozen-lockfile
|
||||||
|
|||||||
@@ -1,306 +1,441 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
import { useAuth } from "@/_core/hooks/useAuth";
|
import { useAuth } from "@/_core/hooks/useAuth";
|
||||||
import { trpc } from "@/lib/trpc";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
|
||||||
import { Progress } from "@/components/ui/progress";
|
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { trpc } from "@/lib/trpc";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useState, useMemo } from "react";
|
|
||||||
import {
|
import {
|
||||||
BookOpen, Play, CheckCircle2, Star, Target,
|
BookOpen,
|
||||||
ChevronRight, Filter, AlertTriangle, Lightbulb,
|
CheckCircle2,
|
||||||
ArrowUpDown, Clock, Dumbbell
|
ChevronRight,
|
||||||
|
Clock3,
|
||||||
|
ExternalLink,
|
||||||
|
Flame,
|
||||||
|
Star,
|
||||||
|
Target,
|
||||||
|
Trophy,
|
||||||
|
type LucideIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
const CATEGORY_LABELS: Record<string, { label: string; icon: React.ReactNode; color: string }> = {
|
type TutorialRecord = Record<string, any>;
|
||||||
forehand: { label: "正手", icon: <Target className="w-4 h-4" />, color: "bg-green-100 text-green-700" },
|
|
||||||
backhand: { label: "反手", icon: <ArrowUpDown className="w-4 h-4" />, color: "bg-blue-100 text-blue-700" },
|
const CATEGORY_META: Record<string, { label: string; icon: LucideIcon; tone: string }> = {
|
||||||
serve: { label: "发球", icon: <Dumbbell className="w-4 h-4" />, color: "bg-purple-100 text-purple-700" },
|
forehand: { label: "正手", icon: Target, tone: "bg-green-500/10 text-green-700" },
|
||||||
volley: { label: "截击", icon: <Target className="w-4 h-4" />, color: "bg-orange-100 text-orange-700" },
|
backhand: { label: "反手", icon: Target, tone: "bg-blue-500/10 text-blue-700" },
|
||||||
footwork: { label: "脚步", icon: <Dumbbell className="w-4 h-4" />, color: "bg-yellow-100 text-yellow-700" },
|
serve: { label: "发球", icon: Target, tone: "bg-violet-500/10 text-violet-700" },
|
||||||
shadow: { label: "影子挥拍", icon: <Play className="w-4 h-4" />, color: "bg-indigo-100 text-indigo-700" },
|
volley: { label: "截击", icon: Target, tone: "bg-orange-500/10 text-orange-700" },
|
||||||
wall: { label: "墙壁练习", icon: <Target className="w-4 h-4" />, color: "bg-pink-100 text-pink-700" },
|
footwork: { label: "脚步", icon: Flame, tone: "bg-yellow-500/10 text-yellow-700" },
|
||||||
fitness: { label: "体能", icon: <Dumbbell className="w-4 h-4" />, color: "bg-red-100 text-red-700" },
|
shadow: { label: "影子挥拍", icon: BookOpen, tone: "bg-indigo-500/10 text-indigo-700" },
|
||||||
strategy: { label: "战术", icon: <Lightbulb className="w-4 h-4" />, color: "bg-teal-100 text-teal-700" },
|
wall: { label: "墙壁练习", icon: Target, tone: "bg-pink-500/10 text-pink-700" },
|
||||||
|
fitness: { label: "体能", icon: Flame, tone: "bg-rose-500/10 text-rose-700" },
|
||||||
|
strategy: { label: "战术", icon: Trophy, tone: "bg-teal-500/10 text-teal-700" },
|
||||||
};
|
};
|
||||||
|
|
||||||
const SKILL_LABELS: Record<string, { label: string; color: string }> = {
|
const SKILL_META: Record<string, { label: string; tone: string }> = {
|
||||||
beginner: { label: "初级", color: "bg-emerald-100 text-emerald-700" },
|
beginner: { label: "初级", tone: "bg-emerald-500/10 text-emerald-700" },
|
||||||
intermediate: { label: "中级", color: "bg-amber-100 text-amber-700" },
|
intermediate: { label: "中级", tone: "bg-amber-500/10 text-amber-700" },
|
||||||
advanced: { label: "高级", color: "bg-rose-100 text-rose-700" },
|
advanced: { label: "高级", tone: "bg-rose-500/10 text-rose-700" },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function parseStringArray(value: unknown) {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.filter((item): item is string => typeof item === "string");
|
||||||
|
}
|
||||||
|
if (typeof value === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(value);
|
||||||
|
return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTutorialCompleted(progress: TutorialRecord | undefined) {
|
||||||
|
return progress?.completed === 1 || progress?.watched === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatEffortMinutes(tutorial: TutorialRecord) {
|
||||||
|
const effort = tutorial.estimatedEffortMinutes || (tutorial.duration ? Math.round(tutorial.duration / 60) : 0);
|
||||||
|
return effort > 0 ? `${effort} 分钟` : "按需学习";
|
||||||
|
}
|
||||||
|
|
||||||
export default function Tutorials() {
|
export default function Tutorials() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [selectedCategory, setSelectedCategory] = useState<string>("all");
|
const utils = trpc.useUtils();
|
||||||
const [selectedSkill, setSelectedSkill] = useState<string>("all");
|
const [selectedCategory, setSelectedCategory] = useState("all");
|
||||||
const [selectedTutorial, setSelectedTutorial] = useState<number | null>(null);
|
const [selectedSkill, setSelectedSkill] = useState("all");
|
||||||
const [notes, setNotes] = useState("");
|
const [draftNotes, setDraftNotes] = useState<Record<number, string>>({});
|
||||||
|
|
||||||
const { data: tutorials, isLoading } = trpc.tutorial.list.useQuery({
|
const tutorialsQuery = trpc.tutorial.list.useQuery({ topicArea: "tennis_skill" });
|
||||||
category: selectedCategory === "all" ? undefined : selectedCategory,
|
const progressQuery = trpc.tutorial.progress.useQuery(undefined, { enabled: !!user });
|
||||||
skillLevel: selectedSkill === "all" ? undefined : selectedSkill,
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: progressData } = trpc.tutorial.progress.useQuery(undefined, { enabled: !!user });
|
|
||||||
|
|
||||||
const updateProgress = trpc.tutorial.updateProgress.useMutation({
|
const updateProgress = trpc.tutorial.updateProgress.useMutation({
|
||||||
onSuccess: () => toast.success("进度已更新"),
|
onSuccess: async () => {
|
||||||
|
await utils.tutorial.progress.invalidate();
|
||||||
|
toast.success("教程进度已更新");
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const tutorials = tutorialsQuery.data ?? [];
|
||||||
const progressMap = useMemo(() => {
|
const progressMap = useMemo(() => {
|
||||||
const map: Record<number, any> = {};
|
const map: Record<number, TutorialRecord> = {};
|
||||||
progressData?.forEach((p: any) => { map[p.tutorialId] = p; });
|
(progressQuery.data ?? []).forEach((item: TutorialRecord) => {
|
||||||
|
map[item.tutorialId] = item;
|
||||||
|
});
|
||||||
return map;
|
return map;
|
||||||
}, [progressData]);
|
}, [progressQuery.data]);
|
||||||
|
|
||||||
const totalTutorials = tutorials?.length || 0;
|
const filteredTutorials = useMemo(
|
||||||
const watchedCount = tutorials?.filter((t: any) => progressMap[t.id]?.watched).length || 0;
|
() => tutorials.filter((tutorial) => {
|
||||||
const progressPercent = totalTutorials > 0 ? Math.round((watchedCount / totalTutorials) * 100) : 0;
|
if (selectedCategory !== "all" && tutorial.category !== selectedCategory) return false;
|
||||||
|
if (selectedSkill !== "all" && tutorial.skillLevel !== selectedSkill) return false;
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
[selectedCategory, selectedSkill, tutorials],
|
||||||
|
);
|
||||||
|
|
||||||
const categories = useMemo(() => {
|
const categories = useMemo(
|
||||||
const cats = new Set<string>();
|
() => Array.from(new Set(tutorials.map((tutorial) => tutorial.category).filter(Boolean))),
|
||||||
tutorials?.forEach((t: any) => cats.add(t.category));
|
[tutorials],
|
||||||
return Array.from(cats);
|
);
|
||||||
}, [tutorials]);
|
|
||||||
|
|
||||||
const handleMarkWatched = (tutorialId: number) => {
|
const completedTutorials = useMemo(
|
||||||
updateProgress.mutate({ tutorialId, watched: 1 });
|
() => tutorials.filter((tutorial) => isTutorialCompleted(progressMap[tutorial.id])),
|
||||||
};
|
[progressMap, tutorials],
|
||||||
|
);
|
||||||
|
|
||||||
const handleSaveNotes = (tutorialId: number) => {
|
const handleSaveNotes = (tutorialId: number) => {
|
||||||
|
const notes = draftNotes[tutorialId] ?? progressMap[tutorialId]?.notes ?? "";
|
||||||
updateProgress.mutate({ tutorialId, notes });
|
updateProgress.mutate({ tutorialId, notes });
|
||||||
setNotes("");
|
};
|
||||||
toast.success("笔记已保存");
|
|
||||||
|
const handleComplete = (tutorialId: number) => {
|
||||||
|
updateProgress.mutate({ tutorialId, completed: 1, watched: 1 });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSelfScore = (tutorialId: number, score: number) => {
|
const handleSelfScore = (tutorialId: number, score: number) => {
|
||||||
updateProgress.mutate({ tutorialId, selfScore: score });
|
updateProgress.mutate({ tutorialId, selfScore: score });
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isLoading) {
|
if (tutorialsQuery.isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center min-h-[60vh]">
|
<div className="flex min-h-[60vh] items-center justify-center">
|
||||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Header */}
|
<section className="overflow-hidden rounded-[30px] border border-border/60 bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.18),_transparent_24%),radial-gradient(circle_at_82%_18%,_rgba(59,130,246,0.14),_transparent_24%),linear-gradient(135deg,rgba(255,255,255,0.98),rgba(248,250,252,0.96))] p-5 shadow-sm md:p-7">
|
||||||
|
<div className="grid gap-4 xl:grid-cols-[minmax(0,1.2fr)_360px]">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold flex items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<BookOpen className="w-6 h-6 text-primary" />
|
<Badge className="bg-emerald-500/10 text-emerald-700">
|
||||||
教程库
|
<BookOpen className="mr-1 h-3 w-3" />
|
||||||
</h1>
|
网球教程库
|
||||||
<p className="text-muted-foreground mt-1">查看动作分解、要点说明和常见错误</p>
|
</Badge>
|
||||||
|
<Badge variant="outline">仅保留网球训练相关内容</Badge>
|
||||||
|
</div>
|
||||||
|
<h1 className="mt-4 text-3xl font-semibold tracking-tight">专注正手、反手、发球、脚步和比赛能力</h1>
|
||||||
|
<p className="mt-3 max-w-3xl text-sm leading-7 text-muted-foreground">
|
||||||
|
这里现在只保留和网球训练直接相关的教程。你可以按动作类别和水平筛选,记录自评与训练笔记,把教程真正沉淀到自己的日常练习里。
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Progress Overview */}
|
<div className="grid gap-3 sm:grid-cols-3 xl:grid-cols-1">
|
||||||
<Card>
|
<Card className="border-0 bg-background/90 shadow-sm">
|
||||||
<CardContent className="pt-6">
|
<CardHeader className="pb-2">
|
||||||
<div className="flex items-center justify-between mb-2">
|
<CardDescription>教程总数</CardDescription>
|
||||||
<span className="text-sm font-medium">学习进度</span>
|
<CardTitle className="text-3xl">{tutorials.length}</CardTitle>
|
||||||
<span className="text-sm text-muted-foreground">{watchedCount}/{totalTutorials} 已学习</span>
|
</CardHeader>
|
||||||
</div>
|
</Card>
|
||||||
<Progress value={progressPercent} className="h-2" />
|
<Card className="border-0 bg-background/90 shadow-sm">
|
||||||
<p className="text-xs text-muted-foreground mt-1">{progressPercent}% 完成</p>
|
<CardHeader className="pb-2">
|
||||||
</CardContent>
|
<CardDescription>已完成</CardDescription>
|
||||||
|
<CardTitle className="text-3xl">{completedTutorials.length}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>
|
||||||
|
<Card className="border-0 bg-background/90 shadow-sm">
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<CardDescription>当前筛选</CardDescription>
|
||||||
|
<CardTitle className="text-base">
|
||||||
|
{selectedCategory === "all" ? "全部分类" : (CATEGORY_META[selectedCategory] || { label: selectedCategory }).label}
|
||||||
|
{" · "}
|
||||||
|
{selectedSkill === "all" ? "全部级别" : (SKILL_META[selectedSkill] || { label: selectedSkill }).label}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Filters */}
|
|
||||||
<div className="flex flex-wrap gap-3">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Filter className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-sm font-medium">分类:</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-1.5">
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-5">
|
||||||
|
<div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-semibold tracking-tight">网球基础教程</h2>
|
||||||
|
<p className="mt-1 text-sm text-muted-foreground">选择一个动作主题,完成学习、自评和训练复盘。</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-border/60 bg-background/85 px-4 py-3 text-sm text-muted-foreground">
|
||||||
|
已完成 {completedTutorials.length}/{tutorials.length}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-3">
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
<Button
|
<Button
|
||||||
variant={selectedCategory === "all" ? "default" : "outline"}
|
variant={selectedCategory === "all" ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setSelectedCategory("all")}
|
onClick={() => setSelectedCategory("all")}
|
||||||
>
|
>
|
||||||
全部
|
全部分类
|
||||||
</Button>
|
</Button>
|
||||||
{Object.entries(CATEGORY_LABELS).map(([key, { label, icon }]) => (
|
{categories.map((category) => (
|
||||||
<Button
|
<Button
|
||||||
key={key}
|
key={category}
|
||||||
variant={selectedCategory === key ? "default" : "outline"}
|
variant={selectedCategory === category ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setSelectedCategory(key)}
|
onClick={() => setSelectedCategory(category)}
|
||||||
className="gap-1"
|
|
||||||
>
|
>
|
||||||
{icon} {label}
|
{(CATEGORY_META[category] || { label: category }).label}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-3">
|
<div className="flex flex-wrap gap-2">
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Star className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-sm font-medium">级别:</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-1.5">
|
|
||||||
<Button
|
<Button
|
||||||
variant={selectedSkill === "all" ? "default" : "outline"}
|
variant={selectedSkill === "all" ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setSelectedSkill("all")}
|
onClick={() => setSelectedSkill("all")}
|
||||||
>
|
>
|
||||||
全部
|
全部级别
|
||||||
</Button>
|
</Button>
|
||||||
{Object.entries(SKILL_LABELS).map(([key, { label }]) => (
|
{Object.entries(SKILL_META).map(([key, meta]) => (
|
||||||
<Button
|
<Button
|
||||||
key={key}
|
key={key}
|
||||||
variant={selectedSkill === key ? "default" : "outline"}
|
variant={selectedSkill === key ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setSelectedSkill(key)}
|
onClick={() => setSelectedSkill(key)}
|
||||||
>
|
>
|
||||||
{label}
|
{meta.label}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tutorial Grid */}
|
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
{filteredTutorials.map((tutorial) => {
|
||||||
{tutorials?.map((tutorial: any) => {
|
|
||||||
const cat = CATEGORY_LABELS[tutorial.category] || { label: tutorial.category, color: "bg-gray-100 text-gray-700" };
|
|
||||||
const skill = SKILL_LABELS[tutorial.skillLevel] || { label: tutorial.skillLevel, color: "bg-gray-100 text-gray-700" };
|
|
||||||
const progress = progressMap[tutorial.id];
|
const progress = progressMap[tutorial.id];
|
||||||
const isWatched = progress?.watched === 1;
|
const completed = isTutorialCompleted(progress);
|
||||||
const keyPoints = typeof tutorial.keyPoints === "string" ? JSON.parse(tutorial.keyPoints) : tutorial.keyPoints || [];
|
const category = CATEGORY_META[tutorial.category || "forehand"] || CATEGORY_META.forehand;
|
||||||
const mistakes = typeof tutorial.commonMistakes === "string" ? JSON.parse(tutorial.commonMistakes) : tutorial.commonMistakes || [];
|
const skill = SKILL_META[tutorial.skillLevel || "beginner"] || SKILL_META.beginner;
|
||||||
|
const keyPoints = parseStringArray(tutorial.keyPoints);
|
||||||
|
const commonMistakes = parseStringArray(tutorial.commonMistakes);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog key={tutorial.id}>
|
<Dialog key={tutorial.id}>
|
||||||
<DialogTrigger asChild>
|
<Card className={cn(
|
||||||
<Card className={`cursor-pointer hover:shadow-md transition-all ${isWatched ? "border-green-300 bg-green-50/30" : ""}`}>
|
"overflow-hidden border-0 shadow-sm transition-shadow hover:shadow-md",
|
||||||
<CardHeader className="pb-3">
|
completed && "ring-1 ring-emerald-200",
|
||||||
<div className="flex items-start justify-between">
|
)}>
|
||||||
<div className="flex gap-2 flex-wrap">
|
<div className="relative h-48 overflow-hidden bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.28),_transparent_30%),radial-gradient(circle_at_bottom_right,_rgba(59,130,246,0.18),_transparent_28%),linear-gradient(135deg,rgba(255,255,255,1),rgba(248,250,252,0.92))] px-5 py-4">
|
||||||
<Badge variant="secondary" className={cat.color}>{cat.label}</Badge>
|
{tutorial.thumbnailUrl ? (
|
||||||
<Badge variant="secondary" className={skill.color}>{skill.label}</Badge>
|
<>
|
||||||
|
<img
|
||||||
|
src={tutorial.thumbnailUrl}
|
||||||
|
alt={`${tutorial.title} 标准配图`}
|
||||||
|
loading="lazy"
|
||||||
|
className="absolute inset-0 h-full w-full object-cover"
|
||||||
|
/>
|
||||||
|
<div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(15,23,42,0.18),rgba(15,23,42,0.58))]" />
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="relative flex items-start justify-between gap-3">
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Badge className={category.tone}>{category.label}</Badge>
|
||||||
|
<Badge className={skill.tone}>{skill.label}</Badge>
|
||||||
</div>
|
</div>
|
||||||
{isWatched && <CheckCircle2 className="w-5 h-5 text-green-600 shrink-0" />}
|
{completed ? <CheckCircle2 className="h-5 w-5 text-emerald-600" /> : null}
|
||||||
</div>
|
</div>
|
||||||
<CardTitle className="text-base mt-2">{tutorial.title}</CardTitle>
|
|
||||||
<CardDescription className="line-clamp-2">{tutorial.description}</CardDescription>
|
<div className="relative mt-6">
|
||||||
</CardHeader>
|
<div className={cn("text-xl font-semibold", tutorial.thumbnailUrl && "text-white drop-shadow-sm")}>{tutorial.title}</div>
|
||||||
<CardContent className="pt-0">
|
<div className={cn(
|
||||||
|
"mt-2 line-clamp-2 text-sm leading-6",
|
||||||
|
tutorial.thumbnailUrl ? "text-white/88 drop-shadow-sm" : "text-muted-foreground",
|
||||||
|
)}>
|
||||||
|
{tutorial.description}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CardContent className="p-5">
|
||||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||||
<span className="flex items-center gap-1">
|
<span className="inline-flex items-center gap-1">
|
||||||
<Clock className="w-3 h-3" />
|
<Clock3 className="h-3.5 w-3.5" />
|
||||||
{Math.round((tutorial.duration || 0) / 60)}分钟
|
{formatEffortMinutes(tutorial)}
|
||||||
</span>
|
|
||||||
<span className="flex items-center gap-1">
|
|
||||||
{keyPoints.length}个要点
|
|
||||||
<ChevronRight className="w-3 h-3" />
|
|
||||||
</span>
|
</span>
|
||||||
|
<span>{keyPoints.length} 个要点</span>
|
||||||
</div>
|
</div>
|
||||||
{progress?.selfScore && (
|
|
||||||
<div className="flex items-center gap-1 mt-2">
|
{progress?.selfScore ? (
|
||||||
{[1, 2, 3, 4, 5].map(s => (
|
<div className="mt-3 flex items-center gap-1">
|
||||||
<Star key={s} className={`w-3 h-3 ${s <= progress.selfScore ? "fill-yellow-400 text-yellow-400" : "text-gray-300"}`} />
|
{[1, 2, 3, 4, 5].map((score) => (
|
||||||
))}
|
<Star
|
||||||
<span className="text-xs text-muted-foreground ml-1">自评</span>
|
key={score}
|
||||||
</div>
|
className={cn(
|
||||||
|
"h-4 w-4",
|
||||||
|
score <= progress.selfScore ? "fill-yellow-400 text-yellow-400" : "text-slate-300",
|
||||||
)}
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button variant="outline" className="mt-4 w-full">查看详情</Button>
|
||||||
|
</DialogTrigger>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</DialogTrigger>
|
|
||||||
|
|
||||||
<DialogContent className="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col">
|
<DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<div className="flex gap-2 mb-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<Badge variant="secondary" className={cat.color}>{cat.label}</Badge>
|
<Badge className={category.tone}>{category.label}</Badge>
|
||||||
<Badge variant="secondary" className={skill.color}>{skill.label}</Badge>
|
<Badge className={skill.tone}>{skill.label}</Badge>
|
||||||
<Badge variant="outline" className="gap-1">
|
|
||||||
<Clock className="w-3 h-3" />
|
|
||||||
{Math.round((tutorial.duration || 0) / 60)}分钟
|
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
<DialogTitle className="text-xl">{tutorial.title}</DialogTitle>
|
<DialogTitle className="text-xl">{tutorial.title}</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<ScrollArea className="flex-1 pr-4">
|
<ScrollArea className="max-h-[68vh] pr-4">
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<p className="text-muted-foreground">{tutorial.description}</p>
|
{tutorial.thumbnailUrl ? (
|
||||||
|
<div className="overflow-hidden rounded-[24px] border border-border/60 bg-muted/20">
|
||||||
|
<img
|
||||||
|
src={tutorial.thumbnailUrl}
|
||||||
|
alt={`${tutorial.title} 标准配图`}
|
||||||
|
loading="lazy"
|
||||||
|
className="h-64 w-full object-cover sm:h-80"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{/* Key Points */}
|
<p className="text-sm leading-7 text-muted-foreground">{tutorial.description}</p>
|
||||||
<div>
|
|
||||||
<h3 className="font-semibold flex items-center gap-2 mb-3">
|
|
||||||
<Lightbulb className="w-4 h-4 text-yellow-500" />
|
|
||||||
技术要点
|
|
||||||
</h3>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{keyPoints.map((point: string, i: number) => (
|
|
||||||
<div key={i} className="flex items-start gap-2 p-2 rounded-lg bg-green-50 border border-green-100">
|
|
||||||
<CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 shrink-0" />
|
|
||||||
<span className="text-sm">{point}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Common Mistakes */}
|
{tutorial.externalUrl ? (
|
||||||
<div>
|
<div className="flex flex-wrap items-center gap-2 rounded-2xl border border-border/60 bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
|
||||||
<h3 className="font-semibold flex items-center gap-2 mb-3">
|
<span>标准配图来源</span>
|
||||||
<AlertTriangle className="w-4 h-4 text-orange-500" />
|
<a
|
||||||
常见错误
|
href={tutorial.externalUrl}
|
||||||
</h3>
|
target="_blank"
|
||||||
<div className="space-y-2">
|
rel="noopener noreferrer"
|
||||||
{mistakes.map((mistake: string, i: number) => (
|
className="inline-flex items-center gap-1 font-medium text-primary underline-offset-4 hover:underline"
|
||||||
<div key={i} className="flex items-start gap-2 p-2 rounded-lg bg-orange-50 border border-orange-100">
|
|
||||||
<AlertTriangle className="w-4 h-4 text-orange-500 mt-0.5 shrink-0" />
|
|
||||||
<span className="text-sm">{mistake}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Self Assessment */}
|
|
||||||
{user && (
|
|
||||||
<div>
|
|
||||||
<h3 className="font-semibold mb-3">自我评估</h3>
|
|
||||||
<div className="flex items-center gap-2 mb-3">
|
|
||||||
<span className="text-sm text-muted-foreground">掌握程度:</span>
|
|
||||||
{[1, 2, 3, 4, 5].map(s => (
|
|
||||||
<button
|
|
||||||
key={s}
|
|
||||||
onClick={() => handleSelfScore(tutorial.id, s)}
|
|
||||||
className="hover:scale-110 transition-transform"
|
|
||||||
>
|
>
|
||||||
<Star className={`w-6 h-6 ${s <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-gray-300 hover:text-yellow-300"}`} />
|
Wikimedia Commons
|
||||||
|
<ExternalLink className="h-3.5 w-3.5" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground">技术要点</h4>
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{keyPoints.map((item) => (
|
||||||
|
<div key={item} className="rounded-2xl border border-emerald-200 bg-emerald-50/70 px-4 py-3 text-sm">
|
||||||
|
{item}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground">常见错误</h4>
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{commonMistakes.map((item) => (
|
||||||
|
<div key={item} className="rounded-2xl border border-amber-200 bg-amber-50/70 px-4 py-3 text-sm">
|
||||||
|
{item}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{user ? (
|
||||||
|
<div className="rounded-[24px] border border-border/60 bg-muted/20 p-5">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-base font-semibold">自我评估与训练笔记</div>
|
||||||
|
<div className="mt-1 text-sm text-muted-foreground">学完后给自己打分,并记录本次训练最需要修正的点。</div>
|
||||||
|
</div>
|
||||||
|
{!completed ? (
|
||||||
|
<Button size="sm" onClick={() => handleComplete(tutorial.id)}>
|
||||||
|
标记已学习
|
||||||
|
<CheckCircle2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Badge className="bg-emerald-500/10 text-emerald-700">
|
||||||
|
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||||
|
已完成
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5">
|
||||||
|
<div className="mb-2 text-sm font-medium">掌握程度</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{[1, 2, 3, 4, 5].map((score) => (
|
||||||
|
<button
|
||||||
|
key={score}
|
||||||
|
onClick={() => handleSelfScore(tutorial.id, score)}
|
||||||
|
className="transition-transform hover:scale-110"
|
||||||
|
>
|
||||||
|
<Star className={cn(
|
||||||
|
"h-6 w-6",
|
||||||
|
score <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-slate-300",
|
||||||
|
)} />
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5">
|
||||||
|
<div className="mb-2 text-sm font-medium">学习笔记</div>
|
||||||
<Textarea
|
<Textarea
|
||||||
placeholder="记录学习笔记和心得..."
|
rows={4}
|
||||||
value={notes || progress?.notes || ""}
|
placeholder="记录今天的挥拍体感、移动节奏、失误原因和下次训练目标。"
|
||||||
onChange={e => setNotes(e.target.value)}
|
value={draftNotes[tutorial.id] ?? progress?.notes ?? ""}
|
||||||
className="mb-2"
|
onChange={(event) => setDraftNotes((current) => ({
|
||||||
rows={3}
|
...current,
|
||||||
|
[tutorial.id]: event.target.value,
|
||||||
|
}))}
|
||||||
/>
|
/>
|
||||||
<div className="flex gap-2">
|
<div className="mt-3 flex gap-2">
|
||||||
<Button size="sm" onClick={() => handleSaveNotes(tutorial.id)}>
|
<Button size="sm" onClick={() => handleSaveNotes(tutorial.id)}>保存笔记</Button>
|
||||||
保存笔记
|
|
||||||
</Button>
|
|
||||||
{!isWatched && (
|
|
||||||
<Button size="sm" variant="outline" onClick={() => handleMarkWatched(tutorial.id)} className="gap-1">
|
|
||||||
<CheckCircle2 className="w-4 h-4" />
|
|
||||||
标记已学习
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{keyPoints.length > 0 ? (
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground">训练建议</h4>
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{keyPoints.slice(0, 3).map((item) => (
|
||||||
|
<div key={item} className="flex items-start gap-2 rounded-2xl bg-muted/20 px-4 py-3 text-sm">
|
||||||
|
<ChevronRight className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
|
||||||
|
<span>下次练习时优先检查:{item}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
@@ -309,12 +444,12 @@ export default function Tutorials() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{tutorials?.length === 0 && (
|
{filteredTutorials.length === 0 ? (
|
||||||
<div className="text-center py-12 text-muted-foreground">
|
<div className="rounded-[26px] border border-dashed border-border/60 px-6 py-14 text-center text-muted-foreground">
|
||||||
<BookOpen className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
当前筛选下暂无匹配教程。
|
||||||
<p>暂无匹配的教程</p>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
) : null}
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Verified Features
|
# Verified Features
|
||||||
|
|
||||||
本文档记录当前已经通过自动化验证或构建验证的项目。更新时间:2026-03-15 11:28 CST。
|
本文档记录当前已经通过自动化验证或构建验证的项目。更新时间:2026-03-15 11:58 CST。
|
||||||
|
|
||||||
## 最新完整验证记录
|
## 最新完整验证记录
|
||||||
|
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
| `https://te.hao.work/` HTTPS 访问 | `curl -I https://te.hao.work/` | 通过 |
|
| `https://te.hao.work/` HTTPS 访问 | `curl -I https://te.hao.work/` | 通过 |
|
||||||
| `https://te.hao.work/checkin` 成就系统路由 | Playwright 登录后检查“成就系统” | 通过 |
|
| `https://te.hao.work/checkin` 成就系统路由 | Playwright 登录后检查“成就系统” | 通过 |
|
||||||
| `https://te.hao.work/tutorials` 教程库清洗 | Playwright smoke + `tutorial.list` 线上接口校验,仅返回 `topicArea=tennis_skill` 的 11 条网球教程 | 通过 |
|
| `https://te.hao.work/tutorials` 教程库清洗 | Playwright smoke + `tutorial.list` 线上接口校验,仅返回 `topicArea=tennis_skill` 的 11 条网球教程 | 通过 |
|
||||||
|
| `https://te.hao.work/tutorials` 教程标准配图 | 登录后 Playwright 检查 11 张压缩配图渲染、首图为 `/uploads/tutorials/forehand-fundamentals.webp`,并验证图片资源 `200 OK` | 通过 |
|
||||||
| `https://te.hao.work/logs` 日志页访问 | `curl -I https://te.hao.work/logs` | 通过 |
|
| `https://te.hao.work/logs` 日志页访问 | `curl -I https://te.hao.work/logs` | 通过 |
|
||||||
| `https://te.hao.work/vision-lab` 视觉测试页访问 | `curl -I https://te.hao.work/vision-lab` | 通过 |
|
| `https://te.hao.work/vision-lab` 视觉测试页访问 | `curl -I https://te.hao.work/vision-lab` | 通过 |
|
||||||
| `http://te.hao.work:8302/` 4 位端口访问 | `curl -I http://te.hao.work:8302/` | 通过 |
|
| `http://te.hao.work:8302/` 4 位端口访问 | `curl -I http://te.hao.work:8302/` | 通过 |
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { registerMediaProxy } from "./mediaProxy";
|
|||||||
import { serveStatic } from "./static";
|
import { serveStatic } from "./static";
|
||||||
import { createBackgroundTask, getAdminUserId, hasRecentBackgroundTaskOfType, seedAchievementDefinitions, seedAppSettings, seedTutorials, seedVisionReferenceImages } from "../db";
|
import { createBackgroundTask, getAdminUserId, hasRecentBackgroundTaskOfType, seedAchievementDefinitions, seedAppSettings, seedTutorials, seedVisionReferenceImages } from "../db";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
|
import { syncTutorialImages } from "../tutorialImages";
|
||||||
|
|
||||||
async function scheduleDailyNtrpRefresh() {
|
async function scheduleDailyNtrpRefresh() {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -64,6 +65,7 @@ async function findAvailablePort(startPort: number = 3000): Promise<number> {
|
|||||||
|
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
await seedTutorials();
|
await seedTutorials();
|
||||||
|
await syncTutorialImages();
|
||||||
await seedVisionReferenceImages();
|
await seedVisionReferenceImages();
|
||||||
await seedAchievementDefinitions();
|
await seedAchievementDefinitions();
|
||||||
await seedAppSettings();
|
await seedAppSettings();
|
||||||
|
|||||||
69
server/tutorialImageCatalog.ts
普通文件
69
server/tutorialImageCatalog.ts
普通文件
@@ -0,0 +1,69 @@
|
|||||||
|
export type TutorialImageSpec = {
|
||||||
|
imageUrl: string;
|
||||||
|
sourcePageUrl: string;
|
||||||
|
sourceLabel: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TUTORIAL_IMAGE_LIBRARY = {
|
||||||
|
forehand: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/0/00/Ray_Dunlop_forehand.jpg",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Ray_Dunlop_forehand.jpg",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
backhand: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/8/8c/Backhand_Federer.jpg",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Backhand_Federer.jpg",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
serve: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/8/85/Serena_Williams_Serves.JPG",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Serena_Williams_Serves.JPG",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
volley: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/a/af/Ernest_w._lewis%2C_volleying.jpg",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Ernest_w._lewis,_volleying.jpg",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
action: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/3/34/Frances_Tiafoe_Backhand.jpg",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Frances_Tiafoe_Backhand.jpg",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
wall: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Tennis_wall.jpg",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Tennis_wall.jpg",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
strategy: {
|
||||||
|
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/f/f3/Court_plan.png",
|
||||||
|
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Court_plan.png",
|
||||||
|
sourceLabel: "Wikimedia Commons",
|
||||||
|
},
|
||||||
|
} satisfies Record<string, TutorialImageSpec>;
|
||||||
|
|
||||||
|
const CATEGORY_TO_IMAGE: Record<string, keyof typeof TUTORIAL_IMAGE_LIBRARY> = {
|
||||||
|
forehand: "forehand",
|
||||||
|
backhand: "backhand",
|
||||||
|
serve: "serve",
|
||||||
|
volley: "volley",
|
||||||
|
footwork: "action",
|
||||||
|
shadow: "forehand",
|
||||||
|
wall: "wall",
|
||||||
|
fitness: "action",
|
||||||
|
strategy: "strategy",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function buildTutorialImageKey(slug: string) {
|
||||||
|
return `tutorials/${slug}.webp`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildTutorialImageUrl(slug: string) {
|
||||||
|
return `/uploads/${buildTutorialImageKey(slug)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTutorialImageSpec(category: string): TutorialImageSpec | null {
|
||||||
|
const imageKey = CATEGORY_TO_IMAGE[category];
|
||||||
|
if (!imageKey) return null;
|
||||||
|
return TUTORIAL_IMAGE_LIBRARY[imageKey];
|
||||||
|
}
|
||||||
43
server/tutorialImages.test.ts
普通文件
43
server/tutorialImages.test.ts
普通文件
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
buildTutorialImageFfmpegArgs,
|
||||||
|
buildTutorialImageKey,
|
||||||
|
buildTutorialImageUrl,
|
||||||
|
getTutorialImageSpec,
|
||||||
|
} from "./tutorialImages";
|
||||||
|
|
||||||
|
describe("tutorialImages", () => {
|
||||||
|
it("maps tennis categories to image specs", () => {
|
||||||
|
expect(getTutorialImageSpec("forehand")?.sourcePageUrl).toContain("Ray_Dunlop_forehand");
|
||||||
|
expect(getTutorialImageSpec("backhand")?.sourcePageUrl).toContain("Backhand_Federer");
|
||||||
|
expect(getTutorialImageSpec("serve")?.sourcePageUrl).toContain("Serena_Williams_Serves");
|
||||||
|
expect(getTutorialImageSpec("wall")?.sourcePageUrl).toContain("Tennis_wall");
|
||||||
|
expect(getTutorialImageSpec("unknown")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("builds stable storage keys and public URLs", () => {
|
||||||
|
expect(buildTutorialImageKey("forehand-fundamentals")).toBe("tutorials/forehand-fundamentals.webp");
|
||||||
|
expect(buildTutorialImageUrl("forehand-fundamentals")).toBe("/uploads/tutorials/forehand-fundamentals.webp");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses a fixed compression pipeline for tutorial images", () => {
|
||||||
|
const args = buildTutorialImageFfmpegArgs("/tmp/input.jpg", "/tmp/output.webp");
|
||||||
|
|
||||||
|
expect(args).toEqual([
|
||||||
|
"-y",
|
||||||
|
"-i",
|
||||||
|
"/tmp/input.jpg",
|
||||||
|
"-vf",
|
||||||
|
"scale=1200:675:force_original_aspect_ratio=increase,crop=1200:675",
|
||||||
|
"-frames:v",
|
||||||
|
"1",
|
||||||
|
"-c:v",
|
||||||
|
"libwebp",
|
||||||
|
"-quality",
|
||||||
|
"78",
|
||||||
|
"-compression_level",
|
||||||
|
"6",
|
||||||
|
"/tmp/output.webp",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
178
server/tutorialImages.ts
普通文件
178
server/tutorialImages.ts
普通文件
@@ -0,0 +1,178 @@
|
|||||||
|
import { execFile } from "node:child_process";
|
||||||
|
import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
import { and, asc, eq } from "drizzle-orm";
|
||||||
|
import { tutorialVideos } from "../drizzle/schema";
|
||||||
|
import { getDb } from "./db";
|
||||||
|
import { ENV } from "./_core/env";
|
||||||
|
import { storagePut } from "./storage";
|
||||||
|
import {
|
||||||
|
buildTutorialImageKey,
|
||||||
|
buildTutorialImageUrl,
|
||||||
|
getTutorialImageSpec,
|
||||||
|
type TutorialImageSpec,
|
||||||
|
} from "./tutorialImageCatalog";
|
||||||
|
|
||||||
|
export { buildTutorialImageKey, buildTutorialImageUrl, getTutorialImageSpec } from "./tutorialImageCatalog";
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
const OUTPUT_WIDTH = 1200;
|
||||||
|
const OUTPUT_HEIGHT = 675;
|
||||||
|
const OUTPUT_QUALITY = 78;
|
||||||
|
const OUTPUT_COMPRESSION_LEVEL = 6;
|
||||||
|
|
||||||
|
type TutorialRow = {
|
||||||
|
id: number;
|
||||||
|
slug: string | null;
|
||||||
|
category: string;
|
||||||
|
title: string;
|
||||||
|
thumbnailUrl: string | null;
|
||||||
|
externalUrl: string | null;
|
||||||
|
sourcePlatform: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeSlug(slug: string | null, tutorialId: number) {
|
||||||
|
return slug?.trim() ? slug.trim() : `tutorial-${tutorialId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildTutorialImageFfmpegArgs(inputPath: string, outputPath: string) {
|
||||||
|
return [
|
||||||
|
"-y",
|
||||||
|
"-i",
|
||||||
|
inputPath,
|
||||||
|
"-vf",
|
||||||
|
`scale=${OUTPUT_WIDTH}:${OUTPUT_HEIGHT}:force_original_aspect_ratio=increase,crop=${OUTPUT_WIDTH}:${OUTPUT_HEIGHT}`,
|
||||||
|
"-frames:v",
|
||||||
|
"1",
|
||||||
|
"-c:v",
|
||||||
|
"libwebp",
|
||||||
|
"-quality",
|
||||||
|
`${OUTPUT_QUALITY}`,
|
||||||
|
"-compression_level",
|
||||||
|
`${OUTPUT_COMPRESSION_LEVEL}`,
|
||||||
|
outputPath,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTutorialImageCurrent(tutorial: TutorialRow, spec: TutorialImageSpec, expectedUrl: string) {
|
||||||
|
return tutorial.thumbnailUrl === expectedUrl
|
||||||
|
&& tutorial.externalUrl === spec.sourcePageUrl
|
||||||
|
&& tutorial.sourcePlatform === "wikimedia";
|
||||||
|
}
|
||||||
|
|
||||||
|
function canUseRemoteStorage() {
|
||||||
|
return Boolean(ENV.forgeApiUrl && ENV.forgeApiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function localAssetExists(slug: string) {
|
||||||
|
const filePath = path.join(ENV.localStorageDir, buildTutorialImageKey(slug));
|
||||||
|
try {
|
||||||
|
await access(filePath);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadSourceImage(url: string) {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
headers: {
|
||||||
|
"accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
|
||||||
|
"user-agent": "tennis-training-hub/1.0 (+https://te.hao.work/)",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Image download failed (${response.status}): ${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = response.headers.get("content-type") || "";
|
||||||
|
if (!contentType.startsWith("image/")) {
|
||||||
|
throw new Error(`Unexpected image content-type: ${contentType || "unknown"}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Buffer.from(await response.arrayBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
async function normalizeTutorialImage(buffer: Buffer) {
|
||||||
|
const tempDir = await mkdtemp(path.join(os.tmpdir(), "tutorial-image-"));
|
||||||
|
const inputPath = path.join(tempDir, "source.input");
|
||||||
|
const outputPath = path.join(tempDir, "tutorial.webp");
|
||||||
|
|
||||||
|
try {
|
||||||
|
await writeFile(inputPath, buffer);
|
||||||
|
await execFileAsync("ffmpeg", buildTutorialImageFfmpegArgs(inputPath, outputPath), {
|
||||||
|
timeout: 30_000,
|
||||||
|
maxBuffer: 8 * 1024 * 1024,
|
||||||
|
});
|
||||||
|
return await readFile(outputPath);
|
||||||
|
} finally {
|
||||||
|
await rm(tempDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncTutorialImages() {
|
||||||
|
const db = await getDb();
|
||||||
|
if (!db) return { updated: 0, skipped: 0, failed: 0 };
|
||||||
|
|
||||||
|
const tutorials = await db.select({
|
||||||
|
id: tutorialVideos.id,
|
||||||
|
slug: tutorialVideos.slug,
|
||||||
|
category: tutorialVideos.category,
|
||||||
|
title: tutorialVideos.title,
|
||||||
|
thumbnailUrl: tutorialVideos.thumbnailUrl,
|
||||||
|
externalUrl: tutorialVideos.externalUrl,
|
||||||
|
sourcePlatform: tutorialVideos.sourcePlatform,
|
||||||
|
}).from(tutorialVideos)
|
||||||
|
.where(and(eq(tutorialVideos.topicArea, "tennis_skill"), eq(tutorialVideos.isPublished, 1)))
|
||||||
|
.orderBy(asc(tutorialVideos.sortOrder), asc(tutorialVideos.id));
|
||||||
|
|
||||||
|
let updated = 0;
|
||||||
|
let skipped = 0;
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
for (const tutorial of tutorials) {
|
||||||
|
const spec = getTutorialImageSpec(tutorial.category);
|
||||||
|
if (!spec) {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const slug = normalizeSlug(tutorial.slug, tutorial.id);
|
||||||
|
const expectedUrl = buildTutorialImageUrl(slug);
|
||||||
|
const assetExists = await localAssetExists(slug);
|
||||||
|
|
||||||
|
if (canUseRemoteStorage() && tutorial.thumbnailUrl && tutorial.externalUrl === spec.sourcePageUrl && tutorial.sourcePlatform === "wikimedia") {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (assetExists && isTutorialImageCurrent(tutorial, spec, expectedUrl)) {
|
||||||
|
skipped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const sourceBuffer = await downloadSourceImage(spec.imageUrl);
|
||||||
|
const webpBuffer = await normalizeTutorialImage(sourceBuffer);
|
||||||
|
const stored = await storagePut(buildTutorialImageKey(slug), webpBuffer, "image/webp");
|
||||||
|
|
||||||
|
await db.update(tutorialVideos).set({
|
||||||
|
thumbnailUrl: stored.url,
|
||||||
|
externalUrl: spec.sourcePageUrl,
|
||||||
|
sourcePlatform: "wikimedia",
|
||||||
|
}).where(eq(tutorialVideos.id, tutorial.id));
|
||||||
|
|
||||||
|
updated += 1;
|
||||||
|
} catch (error) {
|
||||||
|
failed += 1;
|
||||||
|
console.error(`[TutorialImages] Failed to sync ${tutorial.title}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[TutorialImages] sync complete: updated=${updated} skipped=${skipped} failed=${failed}`);
|
||||||
|
return { updated, skipped, failed };
|
||||||
|
}
|
||||||
在新工单中引用
屏蔽一个用户