Allow image uploads in lesson comments
Add an image button to the comment toolbar backed by a new upload route (images only, 5 MB, stored under comments/<userId>/), inserted as Markdown. Only images served from our own storage are rendered: a third-party src would be fetched by every reader of the lesson, exposing their address. Such links are shown as plain links instead — this also defuses the external images a few existing comments already carry.
This commit is contained in:
@@ -289,6 +289,7 @@ export default async function LessonPage({ params }: Props) {
|
|||||||
comments={comments}
|
comments={comments}
|
||||||
currentUserId={session.user.id}
|
currentUserId={session.user.id}
|
||||||
currentUserRole={session.user.role ?? "student"}
|
currentUserRole={session.user.role ?? "student"}
|
||||||
|
imageHost={process.env.S3_CDN_URL ?? ""}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { uploadFile } from "@/lib/s3";
|
||||||
|
import { randomUUID } from "crypto";
|
||||||
|
|
||||||
|
// Images only: comments render them inline, and anything else would just be an
|
||||||
|
// unlabelled blob in the middle of a discussion.
|
||||||
|
const ALLOWED_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
|
||||||
|
const ALLOWED_EXTS = new Set(["jpg", "jpeg", "png", "gif", "webp"]);
|
||||||
|
const MAX_BYTES = 5 * 1024 * 1024; // 5 MB — enough for a screenshot
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth.api.getSession({ headers: await headers() });
|
||||||
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
|
||||||
|
const form = await req.formData();
|
||||||
|
const file = form.get("file") as File | null;
|
||||||
|
if (!file) return NextResponse.json({ error: "Missing file" }, { status: 400 });
|
||||||
|
|
||||||
|
if (file.size > MAX_BYTES) {
|
||||||
|
return NextResponse.json({ error: "Изображение слишком большое (макс. 5 МБ)" }, { status: 413 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ALLOWED_TYPES.has(file.type)) {
|
||||||
|
return NextResponse.json({ error: "Разрешены только изображения: jpg, png, gif, webp" }, { status: 415 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const ext = file.name.split(".").pop()?.toLowerCase() ?? "bin";
|
||||||
|
if (!ALLOWED_EXTS.has(ext)) {
|
||||||
|
return NextResponse.json({ error: "Недопустимое расширение файла" }, { status: 415 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = `comments/${session.user.id}/${randomUUID()}.${ext}`;
|
||||||
|
const buffer = Buffer.from(await file.arrayBuffer());
|
||||||
|
const url = await uploadFile(key, buffer, file.type);
|
||||||
|
|
||||||
|
return NextResponse.json({ name: file.name, url, size: file.size });
|
||||||
|
}
|
||||||
@@ -243,6 +243,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Markdown-разметка в комментариях под уроками (react-markdown) */
|
/* Markdown-разметка в комментариях под уроками (react-markdown) */
|
||||||
|
.comment-md img {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
border: 2px solid var(--border);
|
||||||
|
}
|
||||||
.comment-md > :first-child { margin-top: 0; }
|
.comment-md > :first-child { margin-top: 0; }
|
||||||
.comment-md > :last-child { margin-bottom: 0; }
|
.comment-md > :last-child { margin-bottom: 0; }
|
||||||
.comment-md p { margin: 0 0 0.5rem; }
|
.comment-md p { margin: 0 0 0.5rem; }
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useRef, useState, useTransition, type ReactNode } from "react";
|
import { useRef, useState, useTransition, type ReactNode } from "react";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import rehypeSanitize from "rehype-sanitize";
|
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||||
import { addComment, deleteComment, editComment } from "@/lib/actions/student-actions";
|
import { addComment, deleteComment, editComment } from "@/lib/actions/student-actions";
|
||||||
|
|
||||||
const MAX_LEN = 10000;
|
const MAX_LEN = 10000;
|
||||||
@@ -32,6 +32,8 @@ interface Props {
|
|||||||
comments: Comment[];
|
comments: Comment[];
|
||||||
currentUserId: string;
|
currentUserId: string;
|
||||||
currentUserRole: string;
|
currentUserRole: string;
|
||||||
|
/** Public host of our own file storage (S3_CDN_URL) — see CommentBody. */
|
||||||
|
imageHost: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(date: Date) {
|
function formatDate(date: Date) {
|
||||||
@@ -44,15 +46,42 @@ function formatDate(date: Date) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The default schema drops `alt`, so uploaded images would lose their caption.
|
||||||
|
const sanitizeSchema = {
|
||||||
|
...defaultSchema,
|
||||||
|
attributes: {
|
||||||
|
...defaultSchema.attributes,
|
||||||
|
img: [...(defaultSchema.attributes?.img ?? []), "alt"],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
// Renders comment text as sanitized Markdown (no raw HTML, safe links).
|
// Renders comment text as sanitized Markdown (no raw HTML, safe links).
|
||||||
function CommentBody({ text }: { text: string }) {
|
// `imageHost` is our own file storage: images from anywhere else are shown as a
|
||||||
|
// plain link instead of being loaded, since a third-party image would fetch —
|
||||||
|
// and thus expose the address — for every reader of the lesson.
|
||||||
|
function CommentBody({ text, imageHost }: { text: string; imageHost: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="comment-md text-sm leading-relaxed break-words">
|
<div className="comment-md text-sm leading-relaxed break-words">
|
||||||
<ReactMarkdown
|
<ReactMarkdown
|
||||||
rehypePlugins={[rehypeSanitize]}
|
rehypePlugins={[[rehypeSanitize, sanitizeSchema]]}
|
||||||
components={{
|
components={{
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- отбрасываем служебный node от react-markdown, чтобы он не протекал в DOM
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- отбрасываем служебный node от react-markdown, чтобы он не протекал в DOM
|
||||||
a: ({ node, ...props }) => <a {...props} target="_blank" rel="noopener noreferrer" />,
|
a: ({ node, ...props }) => <a {...props} target="_blank" rel="noopener noreferrer" />,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
img: ({ node, src, alt, ...props }) => {
|
||||||
|
const url = typeof src === "string" ? src : "";
|
||||||
|
if (!imageHost || !url.startsWith(`${imageHost}/`)) {
|
||||||
|
return (
|
||||||
|
<a href={url} target="_blank" rel="noopener noreferrer">
|
||||||
|
{alt || url}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element -- пользовательская картинка произвольного размера, next/image здесь не подходит
|
||||||
|
<img {...props} src={url} alt={alt ?? ""} loading="lazy" />
|
||||||
|
);
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{text}
|
{text}
|
||||||
@@ -107,6 +136,44 @@ interface EditorProps {
|
|||||||
// new comment, replies, and inline editing.
|
// new comment, replies, and inline editing.
|
||||||
function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: EditorProps) {
|
function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: EditorProps) {
|
||||||
const ref = useRef<HTMLTextAreaElement>(null);
|
const ref = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Insert text at the caret (used for uploaded images).
|
||||||
|
function insertAtCursor(snippet: string) {
|
||||||
|
const el = ref.current;
|
||||||
|
const at = el ? el.selectionStart : value.length;
|
||||||
|
const next = value.slice(0, at) + snippet + value.slice(at);
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
el?.focus();
|
||||||
|
el?.setSelectionRange(at + snippet.length, at + snippet.length);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
e.target.value = ""; // allow picking the same file twice in a row
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
setUploading(true);
|
||||||
|
setUploadError(null);
|
||||||
|
try {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("file", file);
|
||||||
|
const res = await fetch("/api/student/comment-upload", { method: "POST", body: fd });
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error ?? "Не удалось загрузить изображение");
|
||||||
|
// Square brackets in the filename would break the Markdown link syntax.
|
||||||
|
const caption = file.name.replace(/[[\]]/g, "");
|
||||||
|
insertAtCursor(`\n\n`);
|
||||||
|
} catch (err) {
|
||||||
|
setUploadError(err instanceof Error ? err.message : "Не удалось загрузить изображение");
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Wrap the current selection with before/after markers.
|
// Wrap the current selection with before/after markers.
|
||||||
function wrap(before: string, after: string, placeholderText: string) {
|
function wrap(before: string, after: string, placeholderText: string) {
|
||||||
@@ -152,6 +219,20 @@ function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: Edi
|
|||||||
<ToolbarButton title="Цитата" disabled={disabled} onClick={() => prefixLines("> ")}>»</ToolbarButton>
|
<ToolbarButton title="Цитата" disabled={disabled} onClick={() => prefixLines("> ")}>»</ToolbarButton>
|
||||||
<ToolbarButton title="Код" disabled={disabled} onClick={() => wrap("`", "`", "код")}>{"</>"}</ToolbarButton>
|
<ToolbarButton title="Код" disabled={disabled} onClick={() => wrap("`", "`", "код")}>{"</>"}</ToolbarButton>
|
||||||
<ToolbarButton title="Ссылка" disabled={disabled} onClick={() => wrap("[", "](https://)", "текст")}>🔗</ToolbarButton>
|
<ToolbarButton title="Ссылка" disabled={disabled} onClick={() => wrap("[", "](https://)", "текст")}>🔗</ToolbarButton>
|
||||||
|
<ToolbarButton
|
||||||
|
title="Изображение (jpg, png, gif, webp — до 5 МБ)"
|
||||||
|
disabled={disabled || uploading}
|
||||||
|
onClick={() => fileRef.current?.click()}
|
||||||
|
>
|
||||||
|
{uploading ? "…" : "🖼"}
|
||||||
|
</ToolbarButton>
|
||||||
|
<input
|
||||||
|
ref={fileRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleFile}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<textarea
|
<textarea
|
||||||
ref={ref}
|
ref={ref}
|
||||||
@@ -172,6 +253,11 @@ function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: Edi
|
|||||||
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
||||||
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
||||||
/>
|
/>
|
||||||
|
{uploadError && (
|
||||||
|
<div className="text-xs mt-1" style={{ color: "var(--destructive, #b00)" }}>
|
||||||
|
{uploadError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="text-xs mt-1" style={{ color: "var(--muted-foreground)" }}>
|
<div className="text-xs mt-1" style={{ color: "var(--muted-foreground)" }}>
|
||||||
Поддерживается форматирование Markdown{value.length > 0 ? ` · ${value.length}/${MAX_LEN}` : ""}
|
Поддерживается форматирование Markdown{value.length > 0 ? ` · ${value.length}/${MAX_LEN}` : ""}
|
||||||
</div>
|
</div>
|
||||||
@@ -179,7 +265,7 @@ function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: Edi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole }: Props) {
|
export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole, imageHost }: Props) {
|
||||||
const [text, setText] = useState("");
|
const [text, setText] = useState("");
|
||||||
const [replyToId, setReplyToId] = useState<string | null>(null);
|
const [replyToId, setReplyToId] = useState<string | null>(null);
|
||||||
const [replyText, setReplyText] = useState("");
|
const [replyText, setReplyText] = useState("");
|
||||||
@@ -279,7 +365,7 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<CommentBody text={node.text} />
|
<CommentBody text={node.text} imageHost={imageHost} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!node.deleted && !editing && (
|
{!node.deleted && !editing && (
|
||||||
|
|||||||
Reference in New Issue
Block a user