From 26a267b1116418a2eeae19863592feab1b6f7a16 Mon Sep 17 00:00:00 2001
From: LittleSheep <littlesheep.code@hotmail.com>
Date: Sat, 5 Apr 2025 12:06:11 +0800
Subject: [PATCH] :sparkles: Editable content rating for every community
 moderator

---
 pkg/internal/server/api/attachments_api.go | 32 ++++++++++++++++++++++
 pkg/internal/server/api/index.go           |  1 +
 2 files changed, 33 insertions(+)

diff --git a/pkg/internal/server/api/attachments_api.go b/pkg/internal/server/api/attachments_api.go
index 5467a23..4e1443a 100644
--- a/pkg/internal/server/api/attachments_api.go
+++ b/pkg/internal/server/api/attachments_api.go
@@ -154,6 +154,38 @@ func updateAttachmentMeta(c *fiber.Ctx) error {
 	}
 }
 
+func updateAttachmentRating(c *fiber.Ctx) error {
+	id, _ := c.ParamsInt("id", 0)
+	user := c.Locals("nex_user").(*sec.UserInfo)
+
+	var data struct {
+		ContentRating int `json:"content_rating" validate:"required,min=3,max=21"`
+		QualityRating int `json:"quality_rating" validate:"min=0,max=5"`
+	}
+
+	if err := exts.BindAndValidate(c, &data); err != nil {
+		return err
+	}
+
+	attachment, err := services.GetAttachmentByID(uint(id))
+	if err != nil {
+		return fiber.NewError(fiber.StatusNotFound, err.Error())
+	} else if attachment.AccountID != user.ID {
+		if err = sec.EnsureGrantedPerm(c, "OverrideAttachmentRating", true); err != nil {
+			return err
+		}
+	}
+
+	attachment.ContentRating = data.ContentRating
+	attachment.QualityRating = data.QualityRating
+
+	if attachment, err = services.UpdateAttachment(attachment); err != nil {
+		return fiber.NewError(fiber.StatusBadRequest, err.Error())
+	} else {
+		return c.JSON(attachment)
+	}
+}
+
 func deleteAttachment(c *fiber.Ctx) error {
 	id, _ := c.ParamsInt("id", 0)
 	user := c.Locals("nex_user").(*sec.UserInfo)
diff --git a/pkg/internal/server/api/index.go b/pkg/internal/server/api/index.go
index 4efc084..310c7de 100644
--- a/pkg/internal/server/api/index.go
+++ b/pkg/internal/server/api/index.go
@@ -39,6 +39,7 @@ func MapAPIs(app *fiber.App, baseURL string) {
 			attachments.Post("/", sec.ValidatorMiddleware, createAttachmentDirectly)
 			attachments.Post("/referenced", sec.ValidatorMiddleware, createAttachmentWithURL)
 			attachments.Put("/:id", sec.ValidatorMiddleware, updateAttachmentMeta)
+			attachments.Put("/:id/rating", sec.ValidatorMiddleware, updateAttachmentRating)
 			attachments.Delete("/:id", sec.ValidatorMiddleware, deleteAttachment)
 		}