mirror of
https://github.com/wgh136/nysoure.git
synced 2025-09-27 12:17:24 +00:00
Enhance comment functionality with image support and validation.
This commit is contained in:
53
frontend/src/components/image.tsx
Normal file
53
frontend/src/components/image.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import { Image } from "../network/models.ts";
|
||||
import { network } from "../network/network.ts";
|
||||
|
||||
export function SquareImage({ image }: { image: Image }) {
|
||||
let cover = false;
|
||||
const imgAspectRatio = image.width / image.height;
|
||||
if (imgAspectRatio > 0.8 && imgAspectRatio < 1.2) {
|
||||
cover = true;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="aspect-square bg-base-200 rounded-lg cursor-pointer"
|
||||
onClick={() => {
|
||||
const dialog = document.getElementById(
|
||||
`image-dialog-${image.id}`,
|
||||
) as HTMLDialogElement;
|
||||
dialog.showModal();
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={network.getImageUrl(image.id)}
|
||||
alt={"image"}
|
||||
className={`w-full h-full rounded-lg ${cover ? "object-cover" : "object-contain"}`}
|
||||
/>
|
||||
</div>
|
||||
<dialog id={`image-dialog-${image.id}`} className="modal">
|
||||
<div
|
||||
className={"w-screen h-screen flex items-center justify-center"}
|
||||
onClick={() => {
|
||||
const dialog = document.getElementById(
|
||||
`image-dialog-${image.id}`,
|
||||
) as HTMLDialogElement;
|
||||
dialog.close();
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={network.getImageUrl(image.id)}
|
||||
alt={"image"}
|
||||
className={`object-contain max-w-screen max-h-screen modal-box`}
|
||||
style={{
|
||||
padding: 0,
|
||||
margin: 0,
|
||||
backgroundColor: "transparent",
|
||||
boxShadow: "none",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</dialog>
|
||||
</>
|
||||
);
|
||||
}
|
@@ -1,9 +1,11 @@
|
||||
export default function showToast({
|
||||
message,
|
||||
type,
|
||||
parent,
|
||||
}: {
|
||||
message: string;
|
||||
type?: "success" | "error" | "warning" | "info";
|
||||
parent?: HTMLElement | null;
|
||||
}) {
|
||||
type = type || "info";
|
||||
const div = document.createElement("div");
|
||||
@@ -13,7 +15,11 @@ export default function showToast({
|
||||
<span>${message}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
document.body.appendChild(div);
|
||||
if (parent) {
|
||||
parent.appendChild(div);
|
||||
} else {
|
||||
document.body.appendChild(div);
|
||||
}
|
||||
setTimeout(() => {
|
||||
div.remove();
|
||||
}, 3000);
|
||||
|
@@ -111,6 +111,7 @@ export interface Comment {
|
||||
content: string;
|
||||
created_at: string;
|
||||
user: User;
|
||||
images: Image[];
|
||||
}
|
||||
|
||||
export interface CommentWithResource {
|
||||
|
@@ -925,11 +925,12 @@ class Network {
|
||||
async createComment(
|
||||
resourceID: number,
|
||||
content: string,
|
||||
images: number[],
|
||||
): Promise<Response<any>> {
|
||||
try {
|
||||
const response = await axios.postForm(
|
||||
const response = await axios.post(
|
||||
`${this.apiBaseUrl}/comments/${resourceID}`,
|
||||
{ content },
|
||||
{ content, images },
|
||||
);
|
||||
return response.data;
|
||||
} catch (e: any) {
|
||||
@@ -941,11 +942,12 @@ class Network {
|
||||
async updateComment(
|
||||
commentID: number,
|
||||
content: string,
|
||||
images: number[],
|
||||
): Promise<Response<any>> {
|
||||
try {
|
||||
const response = await axios.putForm(
|
||||
const response = await axios.put(
|
||||
`${this.apiBaseUrl}/comments/${commentID}`,
|
||||
{ content },
|
||||
{ content, images },
|
||||
);
|
||||
return response.data;
|
||||
} catch (e: any) {
|
||||
|
@@ -26,12 +26,14 @@ import {
|
||||
MdAdd,
|
||||
MdArrowDownward,
|
||||
MdArrowUpward,
|
||||
MdClose,
|
||||
MdOutlineArticle,
|
||||
MdOutlineComment,
|
||||
MdOutlineDataset,
|
||||
MdOutlineDelete,
|
||||
MdOutlineDownload,
|
||||
MdOutlineEdit,
|
||||
MdOutlineImage,
|
||||
MdOutlineOpenInNew,
|
||||
} from "react-icons/md";
|
||||
import { app } from "../app.ts";
|
||||
@@ -45,6 +47,7 @@ import Button from "../components/button.tsx";
|
||||
import Badge, { BadgeAccent } from "../components/badge.tsx";
|
||||
import Input, { TextArea } from "../components/input.tsx";
|
||||
import { useAppContext } from "../components/AppContext.tsx";
|
||||
import { SquareImage } from "../components/image.tsx";
|
||||
|
||||
export default function ResourcePage() {
|
||||
const params = useParams();
|
||||
@@ -1131,23 +1134,45 @@ function UpdateFileInfoDialog({ file }: { file: RFile }) {
|
||||
|
||||
function Comments({ resourceId }: { resourceId: number }) {
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const [maxPage, setMaxPage] = useState(0);
|
||||
|
||||
const [listKey, setListKey] = useState(0);
|
||||
|
||||
const [commentContent, setCommentContent] = useState("");
|
||||
|
||||
const [isLoading, setLoading] = useState(false);
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const reload = useCallback(() => {
|
||||
setPage(1);
|
||||
setMaxPage(0);
|
||||
setListKey((prev) => prev + 1);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<CommentInput resourceId={resourceId} reload={reload} />
|
||||
<CommentsList
|
||||
resourceId={resourceId}
|
||||
page={page}
|
||||
maxPageCallback={setMaxPage}
|
||||
key={listKey}
|
||||
/>
|
||||
{maxPage ? (
|
||||
<div className={"w-full flex justify-center"}>
|
||||
<Pagination page={page} setPage={setPage} totalPages={maxPage} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CommentInput({
|
||||
resourceId,
|
||||
reload,
|
||||
}: {
|
||||
resourceId: number;
|
||||
reload: () => void;
|
||||
}) {
|
||||
const [commentContent, setCommentContent] = useState("");
|
||||
const [isLoading, setLoading] = useState(false);
|
||||
const [images, setImages] = useState<File[]>([]);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const sendComment = async () => {
|
||||
if (isLoading) {
|
||||
return;
|
||||
@@ -1160,9 +1185,25 @@ function Comments({ resourceId }: { resourceId: number }) {
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
const res = await network.createComment(resourceId, commentContent);
|
||||
const imageIds: number[] = [];
|
||||
for (const image of images) {
|
||||
const res = await network.uploadImage(image);
|
||||
if (res.success) {
|
||||
imageIds.push(res.data!);
|
||||
} else {
|
||||
showToast({ message: res.message, type: "error" });
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const res = await network.createComment(
|
||||
resourceId,
|
||||
commentContent,
|
||||
imageIds,
|
||||
);
|
||||
if (res.success) {
|
||||
setCommentContent("");
|
||||
setImages([]);
|
||||
showToast({
|
||||
message: t("Comment created successfully"),
|
||||
type: "success",
|
||||
@@ -1174,45 +1215,89 @@ function Comments({ resourceId }: { resourceId: number }) {
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{app.isLoggedIn() ? (
|
||||
<div className={"mt-4 mb-6 textarea w-full p-4 h-40 flex flex-col"}>
|
||||
<textarea
|
||||
placeholder={t("Write down your comment")}
|
||||
className={"w-full resize-none grow"}
|
||||
value={commentContent}
|
||||
onChange={(e) => setCommentContent(e.target.value)}
|
||||
/>
|
||||
<div className={"flex flex-row-reverse"}>
|
||||
<button
|
||||
onClick={sendComment}
|
||||
className={`btn btn-primary h-8 text-sm mx-2 ${commentContent === "" && "btn-disabled"}`}
|
||||
>
|
||||
{isLoading ? (
|
||||
<span className={"loading loading-spinner loading-sm"}></span>
|
||||
) : null}
|
||||
Submit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<InfoAlert
|
||||
message={t("You need to log in to comment")}
|
||||
className={"my-4 alert-info"}
|
||||
/>
|
||||
)}
|
||||
<CommentsList
|
||||
resourceId={resourceId}
|
||||
page={page}
|
||||
maxPageCallback={setMaxPage}
|
||||
key={listKey}
|
||||
const handleAddImage = () => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.multiple = true;
|
||||
input.onchange = (e) => {
|
||||
const files = (e.target as HTMLInputElement).files;
|
||||
if ((files?.length ?? 0) + images.length > 9) {
|
||||
showToast({
|
||||
message: t("You can only upload up to 9 images"),
|
||||
type: "error",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (files) {
|
||||
setImages((prev) => [...prev, ...Array.from(files)]);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
if (!app.isLoggedIn()) {
|
||||
return (
|
||||
<InfoAlert
|
||||
message={t("You need to log in to comment")}
|
||||
className={"my-4 alert-info"}
|
||||
/>
|
||||
{maxPage ? (
|
||||
<div className={"w-full flex justify-center"}>
|
||||
<Pagination page={page} setPage={setPage} totalPages={maxPage} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={"mt-4 mb-6 textarea w-full p-4 flex flex-col"}>
|
||||
<textarea
|
||||
placeholder={t("Write down your comment")}
|
||||
className={"w-full resize-none grow h-40"}
|
||||
value={commentContent}
|
||||
onChange={(e) => setCommentContent(e.target.value)}
|
||||
/>
|
||||
{images.length > 0 && (
|
||||
<div
|
||||
className={
|
||||
"grid grid-cols-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8 gap-2 my-2"
|
||||
}
|
||||
>
|
||||
{images.map((image, index) => (
|
||||
<div key={index} className={"relative"}>
|
||||
<img
|
||||
src={URL.createObjectURL(image)}
|
||||
alt={`comment-image-${index}`}
|
||||
className={"rounded-lg aspect-square object-cover"}
|
||||
/>
|
||||
<button
|
||||
className={
|
||||
"btn btn-xs btn-circle btn-error absolute top-1 right-1"
|
||||
}
|
||||
onClick={() => {
|
||||
setImages((prev) => prev.filter((_, i) => i !== index));
|
||||
}}
|
||||
>
|
||||
<MdClose size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
)}
|
||||
<div className={"flex"}>
|
||||
<button
|
||||
className={"btn btn-ghost btn-sm btn-circle"}
|
||||
onClick={handleAddImage}
|
||||
>
|
||||
<MdOutlineImage size={18} />
|
||||
</button>
|
||||
<span className={"grow"} />
|
||||
<button
|
||||
onClick={sendComment}
|
||||
className={`btn btn-primary h-8 text-sm mx-2 ${commentContent === "" && "btn-disabled"}`}
|
||||
>
|
||||
{isLoading ? (
|
||||
<span className={"loading loading-spinner loading-sm"}></span>
|
||||
) : null}
|
||||
{t("Submit")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1313,6 +1398,15 @@ function CommentTile({ comment }: { comment: Comment }) {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={
|
||||
"grid grid-cols-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8 gap-2 p-2"
|
||||
}
|
||||
>
|
||||
{comment.images.map((image) => (
|
||||
<SquareImage key={image.id} image={image} />
|
||||
))}
|
||||
</div>
|
||||
{app.user?.id === comment.user.id && (
|
||||
<div className={"flex flex-row-reverse"}>
|
||||
<DeleteCommentDialog commentId={comment.id} />
|
||||
@@ -1397,13 +1491,33 @@ function EditCommentDialog({ comment }: { comment: Comment }) {
|
||||
const [content, setContent] = useState(comment.content);
|
||||
const { t } = useTranslation();
|
||||
const reload = useContext(context);
|
||||
const [existingImages, setExistingImages] = useState(comment.images);
|
||||
const [newImages, setNewImages] = useState<File[]>([]);
|
||||
|
||||
const handleUpdate = async () => {
|
||||
if (isLoading) {
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
const res = await network.updateComment(comment.id, content);
|
||||
const imageIds: number[] = [];
|
||||
for (const existingImage of existingImages) {
|
||||
imageIds.push(existingImage.id);
|
||||
}
|
||||
for (const newImage of newImages) {
|
||||
const res = await network.uploadImage(newImage);
|
||||
if (res.success) {
|
||||
imageIds.push(res.data!);
|
||||
} else {
|
||||
showToast({
|
||||
message: res.message,
|
||||
type: "error",
|
||||
parent: document.getElementById(`dialog_box`),
|
||||
});
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const res = await network.updateComment(comment.id, content, imageIds);
|
||||
const dialog = document.getElementById(
|
||||
`edit_comment_dialog_${comment.id}`,
|
||||
) as HTMLDialogElement;
|
||||
@@ -1415,7 +1529,11 @@ function EditCommentDialog({ comment }: { comment: Comment }) {
|
||||
});
|
||||
reload();
|
||||
} else {
|
||||
showToast({ message: res.message, type: "error" });
|
||||
showToast({
|
||||
message: res.message,
|
||||
type: "error",
|
||||
parent: document.getElementById(`dialog_box`),
|
||||
});
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
@@ -1435,13 +1553,90 @@ function EditCommentDialog({ comment }: { comment: Comment }) {
|
||||
{t("Edit")}
|
||||
</button>
|
||||
<dialog id={`edit_comment_dialog_${comment.id}`} className="modal">
|
||||
<div className="modal-box">
|
||||
<div className="modal-box" id={"dialog_box"}>
|
||||
<h3 className="font-bold text-lg">{t("Edit Comment")}</h3>
|
||||
<TextArea
|
||||
label={t("Content")}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
<div className={"flex flex-col my-2"}>
|
||||
<p className={"text-sm font-bold mb-2"}>{t("Images")}</p>
|
||||
<div className={"grid grid-cols-4 sm:grid-cols-5 gap-2"}>
|
||||
{existingImages.map((image) => (
|
||||
<div key={image.id} className={"relative"}>
|
||||
<SquareImage image={image} />
|
||||
<button
|
||||
className={
|
||||
"btn btn-xs btn-circle btn-error absolute top-1 right-1"
|
||||
}
|
||||
onClick={() => {
|
||||
setExistingImages((prev) =>
|
||||
prev.filter((i) => i.id !== image.id),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MdClose size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{newImages.map((image, index) => (
|
||||
<div key={index} className={"relative"}>
|
||||
<img
|
||||
src={URL.createObjectURL(image)}
|
||||
alt={`comment-image-${index}`}
|
||||
className={"rounded-lg aspect-square object-cover"}
|
||||
/>
|
||||
<button
|
||||
className={
|
||||
"btn btn-xs btn-circle btn-error absolute top-1 right-1"
|
||||
}
|
||||
onClick={() => {
|
||||
setNewImages((prev) =>
|
||||
prev.filter((_, i) => i !== index),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MdClose size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className={"flex"}>
|
||||
<button
|
||||
className={"btn btn-sm mt-2"}
|
||||
onClick={() => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.multiple = true;
|
||||
input.onchange = (e) => {
|
||||
const files = (e.target as HTMLInputElement).files;
|
||||
if (
|
||||
(files?.length ?? 0) +
|
||||
existingImages.length +
|
||||
newImages.length >
|
||||
9
|
||||
) {
|
||||
showToast({
|
||||
message: t("You can only upload up to 9 images"),
|
||||
type: "error",
|
||||
parent: document.getElementById(`dialog_box`),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (files) {
|
||||
setNewImages((prev) => [...prev, ...Array.from(files)]);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
}}
|
||||
>
|
||||
<MdAdd size={18} />
|
||||
{t("Add")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-action">
|
||||
<form method="dialog">
|
||||
<button className="btn btn-ghost">{t("Close")}</button>
|
||||
@@ -1450,7 +1645,7 @@ function EditCommentDialog({ comment }: { comment: Comment }) {
|
||||
{isLoading ? (
|
||||
<span className={"loading loading-spinner loading-sm"}></span>
|
||||
) : null}
|
||||
{t("Update")}
|
||||
{t("Submit")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
@@ -28,11 +28,17 @@ func createComment(c fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return model.NewRequestError("Invalid resource ID")
|
||||
}
|
||||
content := c.FormValue("content")
|
||||
if content == "" {
|
||||
|
||||
var req service.CommentRequest
|
||||
if err := c.Bind().JSON(&req); err != nil {
|
||||
return model.NewRequestError("Invalid request format")
|
||||
}
|
||||
|
||||
if req.Content == "" {
|
||||
return model.NewRequestError("Content cannot be empty")
|
||||
}
|
||||
comment, err := service.CreateComment(content, userID, uint(resourceID))
|
||||
|
||||
comment, err := service.CreateComment(req, userID, uint(resourceID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -102,11 +108,17 @@ func updateComment(c fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return model.NewRequestError("Invalid comment ID")
|
||||
}
|
||||
content := c.FormValue("content")
|
||||
if content == "" {
|
||||
|
||||
var req service.CommentRequest
|
||||
if err := c.Bind().JSON(&req); err != nil {
|
||||
return model.NewRequestError("Invalid request format")
|
||||
}
|
||||
|
||||
if req.Content == "" {
|
||||
return model.NewRequestError("Content cannot be empty")
|
||||
}
|
||||
comment, err := service.UpdateComment(uint(commentID), userID, content)
|
||||
|
||||
comment, err := service.UpdateComment(uint(commentID), userID, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@@ -19,7 +19,8 @@ func handleUploadImage(c fiber.Ctx) error {
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
return model.NewRequestError("Invalid image format")
|
||||
}
|
||||
id, err := service.CreateImage(uid, data)
|
||||
ip := c.IP()
|
||||
id, err := service.CreateImage(uid, ip, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@@ -6,7 +6,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CreateComment(content string, userID uint, resourceID uint) (model.Comment, error) {
|
||||
func CreateComment(content string, userID uint, resourceID uint, imageIDs []uint) (model.Comment, error) {
|
||||
var comment model.Comment
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
comment = model.Comment{
|
||||
@@ -17,6 +17,20 @@ func CreateComment(content string, userID uint, resourceID uint) (model.Comment,
|
||||
if err := tx.Create(&comment).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 关联图片
|
||||
if len(imageIDs) > 0 {
|
||||
// 查找所有指定的图片
|
||||
var images []model.Image
|
||||
if err := tx.Where("id IN ?", imageIDs).Find(&images).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 建立关联关系
|
||||
if err := tx.Model(&comment).Association("Images").Replace(images); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Model(&model.User{}).Where("id = ?", userID).Update("comments_count", gorm.Expr("comments_count + 1")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -25,6 +39,9 @@ func CreateComment(content string, userID uint, resourceID uint) (model.Comment,
|
||||
if err != nil {
|
||||
return model.Comment{}, err
|
||||
}
|
||||
|
||||
// 重新加载评论以获取关联的图片
|
||||
db.Preload("Images").Where("id = ?", comment.ID).First(&comment)
|
||||
return comment, nil
|
||||
}
|
||||
|
||||
@@ -36,7 +53,7 @@ func GetCommentByResourceID(resourceID uint, page, pageSize int) ([]model.Commen
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if err := db.Where("resource_id = ?", resourceID).Offset((page - 1) * pageSize).Limit(pageSize).Preload("User").Order("created_at DESC").Find(&comments).Error; err != nil {
|
||||
if err := db.Where("resource_id = ?", resourceID).Offset((page - 1) * pageSize).Limit(pageSize).Preload("User").Preload("Images").Order("created_at DESC").Find(&comments).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -56,7 +73,7 @@ func GetCommentsWithUser(username string, page, pageSize int) ([]model.Comment,
|
||||
if err := db.Model(&model.Comment{}).Where("user_id = ?", user.ID).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Where("user_id = ?", user.ID).Offset((page - 1) * pageSize).Limit(pageSize).Preload("User").Preload("Resource").Order("created_at DESC").Find(&comments).Error; err != nil {
|
||||
if err := db.Where("user_id = ?", user.ID).Offset((page - 1) * pageSize).Limit(pageSize).Preload("User").Preload("Resource").Preload("Images").Order("created_at DESC").Find(&comments).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
totalPages := (int(total) + pageSize - 1) / pageSize
|
||||
@@ -65,22 +82,43 @@ func GetCommentsWithUser(username string, page, pageSize int) ([]model.Comment,
|
||||
|
||||
func GetCommentByID(commentID uint) (*model.Comment, error) {
|
||||
var comment model.Comment
|
||||
if err := db.Preload("User").Preload("Resource").First(&comment, commentID).Error; err != nil {
|
||||
if err := db.Preload("User").Preload("Resource").Preload("Images").First(&comment, commentID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &comment, nil
|
||||
}
|
||||
|
||||
func UpdateCommentContent(commentID uint, content string) (*model.Comment, error) {
|
||||
func UpdateCommentContent(commentID uint, content string, imageIDs []uint) (*model.Comment, error) {
|
||||
var comment model.Comment
|
||||
if err := db.First(&comment, commentID).Error; err != nil {
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.First(&comment, commentID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
comment.Content = content
|
||||
if err := tx.Save(&comment).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新图片关联
|
||||
if imageIDs != nil {
|
||||
// 查找所有指定的图片
|
||||
var images []model.Image
|
||||
if err := tx.Where("id IN ?", imageIDs).Find(&images).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 替换关联关系
|
||||
if err := tx.Model(&comment).Association("Images").Replace(images); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
comment.Content = content
|
||||
if err := db.Save(&comment).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.Preload("User").First(&comment, commentID)
|
||||
|
||||
// 重新加载评论以获取关联的图片和用户信息
|
||||
db.Preload("User").Preload("Images").First(&comment, commentID)
|
||||
return &comment, nil
|
||||
}
|
||||
|
||||
@@ -90,6 +128,12 @@ func DeleteCommentByID(commentID uint) error {
|
||||
if err := tx.First(&comment, commentID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 清除图片关联
|
||||
if err := tx.Model(&comment).Association("Images").Clear(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Delete(&comment).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
@@ -2,10 +2,8 @@ package dao
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"nysoure/server/model"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"nysoure/server/model"
|
||||
)
|
||||
|
||||
func CreateImage(name string, width, height int) (model.Image, error) {
|
||||
@@ -42,10 +40,11 @@ func DeleteImage(id uint) error {
|
||||
func GetUnusedImages() ([]model.Image, error) {
|
||||
// Retrieve all images that are not used in any post
|
||||
var images []model.Image
|
||||
oneDayAgo := time.Now().Add(-24 * time.Hour)
|
||||
// oneDayAgo := time.Now().Add(-24 * time.Hour)
|
||||
if err := db.
|
||||
Where("NOT EXISTS (SELECT 1 FROM resource_images WHERE image_id = images.id)").
|
||||
Where("created_at < ?", oneDayAgo).
|
||||
Where("NOT EXISTS (SELECT 1 FROM comment_images WHERE image_id = images.id)").
|
||||
// Where("created_at < ?", oneDayAgo).
|
||||
Find(&images).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
|
@@ -13,21 +13,29 @@ type Comment struct {
|
||||
UserID uint `gorm:"not null"`
|
||||
User User `gorm:"foreignKey:UserID"`
|
||||
Resource Resource `gorm:"foreignKey:ResourceID"`
|
||||
Images []Image `gorm:"many2many:comment_images;"`
|
||||
}
|
||||
|
||||
type CommentView struct {
|
||||
ID uint `json:"id"`
|
||||
Content string `json:"content"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
User UserView `json:"user"`
|
||||
ID uint `json:"id"`
|
||||
Content string `json:"content"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
User UserView `json:"user"`
|
||||
Images []ImageView `json:"images"`
|
||||
}
|
||||
|
||||
func (c *Comment) ToView() *CommentView {
|
||||
imageViews := make([]ImageView, 0, len(c.Images))
|
||||
for _, img := range c.Images {
|
||||
imageViews = append(imageViews, img.ToView())
|
||||
}
|
||||
|
||||
return &CommentView{
|
||||
ID: c.ID,
|
||||
Content: c.Content,
|
||||
CreatedAt: c.CreatedAt,
|
||||
User: c.User.ToView(),
|
||||
Images: imageViews,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,14 +45,21 @@ type CommentWithResourceView struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Resource ResourceView `json:"resource"`
|
||||
User UserView `json:"user"`
|
||||
Images []ImageView `json:"images"`
|
||||
}
|
||||
|
||||
func (c *Comment) ToViewWithResource() *CommentWithResourceView {
|
||||
imageViews := make([]ImageView, 0, len(c.Images))
|
||||
for _, img := range c.Images {
|
||||
imageViews = append(imageViews, img.ToView())
|
||||
}
|
||||
|
||||
return &CommentWithResourceView{
|
||||
ID: c.ID,
|
||||
Content: c.Content,
|
||||
CreatedAt: c.CreatedAt,
|
||||
Resource: c.Resource.ToView(),
|
||||
User: c.User.ToView(),
|
||||
Images: imageViews,
|
||||
}
|
||||
}
|
||||
|
@@ -7,7 +7,19 @@ import (
|
||||
"github.com/gofiber/fiber/v3/log"
|
||||
)
|
||||
|
||||
func CreateComment(content string, userID uint, resourceID uint) (*model.CommentView, error) {
|
||||
const (
|
||||
maxImagePerComment = 9
|
||||
)
|
||||
|
||||
type CommentRequest struct {
|
||||
Content string `json:"content"`
|
||||
Images []uint `json:"images"`
|
||||
}
|
||||
|
||||
func CreateComment(req CommentRequest, userID uint, resourceID uint) (*model.CommentView, error) {
|
||||
if len(req.Images) > maxImagePerComment {
|
||||
return nil, model.NewRequestError("Too many images, maximum is 9")
|
||||
}
|
||||
resourceExists, err := dao.ExistsResource(resourceID)
|
||||
if err != nil {
|
||||
log.Error("Error checking resource existence:", err)
|
||||
@@ -24,7 +36,7 @@ func CreateComment(content string, userID uint, resourceID uint) (*model.Comment
|
||||
if !userExists {
|
||||
return nil, model.NewNotFoundError("User not found")
|
||||
}
|
||||
c, err := dao.CreateComment(content, userID, resourceID)
|
||||
c, err := dao.CreateComment(req.Content, userID, resourceID, req.Images)
|
||||
if err != nil {
|
||||
log.Error("Error creating comment:", err)
|
||||
return nil, model.NewInternalServerError("Error creating comment")
|
||||
@@ -70,7 +82,10 @@ func ListCommentsWithUser(username string, page int) ([]model.CommentWithResourc
|
||||
return res, totalPages, nil
|
||||
}
|
||||
|
||||
func UpdateComment(commentID, userID uint, content string) (*model.CommentView, error) {
|
||||
func UpdateComment(commentID, userID uint, req CommentRequest) (*model.CommentView, error) {
|
||||
if len(req.Images) > maxImagePerComment {
|
||||
return nil, model.NewRequestError("Too many images, maximum is 9")
|
||||
}
|
||||
comment, err := dao.GetCommentByID(commentID)
|
||||
if err != nil {
|
||||
return nil, model.NewNotFoundError("Comment not found")
|
||||
@@ -78,7 +93,7 @@ func UpdateComment(commentID, userID uint, content string) (*model.CommentView,
|
||||
if comment.UserID != userID {
|
||||
return nil, model.NewRequestError("You can only update your own comments")
|
||||
}
|
||||
updated, err := dao.UpdateCommentContent(commentID, content)
|
||||
updated, err := dao.UpdateCommentContent(commentID, req.Content, req.Images)
|
||||
if err != nil {
|
||||
return nil, model.NewInternalServerError("Error updating comment")
|
||||
}
|
||||
|
@@ -11,6 +11,7 @@ import (
|
||||
"nysoure/server/utils"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3/log"
|
||||
@@ -53,14 +54,51 @@ func init() {
|
||||
}()
|
||||
}
|
||||
|
||||
func CreateImage(uid uint, data []byte) (uint, error) {
|
||||
var (
|
||||
imageUploadsByIP = make(map[string]uint)
|
||||
imageUploadsLock = sync.RWMutex{}
|
||||
)
|
||||
|
||||
const maxUploadsPerIP = 100
|
||||
|
||||
func init() {
|
||||
// Initialize the map with a cleanup function to remove old entries
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(24 * time.Hour) // Cleanup every 24 hours
|
||||
imageUploadsLock.Lock()
|
||||
imageUploadsByIP = make(map[string]uint) // Clear the map
|
||||
imageUploadsLock.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func addIpUploadCount(ip string) bool {
|
||||
imageUploadsLock.Lock()
|
||||
defer imageUploadsLock.Unlock()
|
||||
|
||||
count, exists := imageUploadsByIP[ip]
|
||||
if !exists {
|
||||
count = 0
|
||||
}
|
||||
if count >= maxUploadsPerIP {
|
||||
return false // Exceeded upload limit for this IP
|
||||
}
|
||||
imageUploadsByIP[ip] = count + 1
|
||||
return true // Upload count incremented successfully
|
||||
}
|
||||
|
||||
func CreateImage(uid uint, ip string, data []byte) (uint, error) {
|
||||
canUpload, err := checkUserCanUpload(uid)
|
||||
if err != nil {
|
||||
log.Error("Error checking user upload permission:", err)
|
||||
return 0, model.NewInternalServerError("Error checking user upload permission")
|
||||
}
|
||||
if !canUpload {
|
||||
return 0, model.NewUnAuthorizedError("User cannot upload images")
|
||||
// For a normal user, check the IP upload limit
|
||||
if !addIpUploadCount(ip) {
|
||||
return 0, model.NewUnAuthorizedError("You have reached the maximum upload limit")
|
||||
}
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
|
Reference in New Issue
Block a user