package handlers
|
|
import (
|
"fmt"
|
"io"
|
"net/http"
|
"os"
|
"path/filepath"
|
"strconv"
|
"strings"
|
"time"
|
|
"gamebox-server/config"
|
"gamebox-server/models"
|
"gamebox-server/utils"
|
|
"github.com/gin-gonic/gin"
|
"golang.org/x/crypto/bcrypt"
|
)
|
|
// ---------- 管理员登录 ----------
|
|
func AdminLogin(c *gin.Context) {
|
var req struct {
|
Username string `json:"username"`
|
Password string `json:"password"`
|
}
|
if err := c.ShouldBindJSON(&req); err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
|
return
|
}
|
var admin models.Admin
|
if err := config.DB.Where("username = ?", req.Username).First(&admin).Error; err != nil ||
|
bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(req.Password)) != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户名或密码错误"})
|
return
|
}
|
token, _ := utils.GenerateToken(admin.ID, admin.Username, "admin")
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"token": token}})
|
}
|
|
// ---------- 密钥管理 ----------
|
|
// GenerateKeys 批量生成密钥
|
func GenerateKeys(c *gin.Context) {
|
var req struct {
|
CardType string `json:"card_type"` // day/month/year
|
Count int `json:"count"`
|
}
|
if err := c.ShouldBindJSON(&req); err != nil || !validCardType(req.CardType) {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "卡密类型错误"})
|
return
|
}
|
if req.Count < 1 || req.Count > 100 {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "生成数量需在1-100之间"})
|
return
|
}
|
codes := make([]string, 0, req.Count)
|
for i := 0; i < req.Count; i++ {
|
key := models.MemberKey{Code: utils.GenerateKeyCode(), CardType: req.CardType}
|
if err := config.DB.Create(&key).Error; err == nil {
|
codes = append(codes, key.Code)
|
}
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": fmt.Sprintf("成功生成 %d 个密钥", len(codes)), "data": codes})
|
}
|
|
// ListKeys 密钥列表
|
func ListKeys(c *gin.Context) {
|
keyword := c.Query("keyword")
|
status := c.Query("status") // ""全部 0未使用 1已使用(含永久) 2已过期
|
query := config.DB.Model(&models.MemberKey{})
|
if keyword != "" {
|
// 同时支持按激活码或绑定用户手机号搜索
|
var userIDs []uint
|
config.DB.Model(&models.User{}).Where("phone LIKE ?", "%"+keyword+"%").Pluck("id", &userIDs)
|
if len(userIDs) > 0 {
|
query = query.Where("code LIKE ? OR user_id IN ?", "%"+keyword+"%", userIDs)
|
} else {
|
query = query.Where("code LIKE ?", "%"+keyword+"%")
|
}
|
}
|
switch status {
|
case "0":
|
query = query.Where("status = ?", 0)
|
case "1":
|
// 已使用且未过期(永久卡 expired_at 为 NULL)
|
query = query.Where("status = ? AND (expired_at IS NULL OR expired_at > ?)", 1, time.Now())
|
case "2":
|
query = query.Where("status = ? AND expired_at <= ?", 1, time.Now())
|
}
|
var total int64
|
query.Count(&total)
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
if page < 1 {
|
page = 1
|
}
|
var keys []models.MemberKey
|
query.Order("id DESC").Offset((page - 1) * 20).Limit(20).Find(&keys)
|
// 附带用户手机号
|
userIDs := make([]uint, 0)
|
for _, k := range keys {
|
if k.UserID > 0 {
|
userIDs = append(userIDs, k.UserID)
|
}
|
}
|
phoneMap := map[uint]string{}
|
if len(userIDs) > 0 {
|
var users []models.User
|
config.DB.Where("id IN ?", userIDs).Find(&users)
|
for _, u := range users {
|
phoneMap[u.ID] = u.Phone
|
}
|
}
|
type keyVO struct {
|
models.MemberKey
|
CardName string `json:"card_name"`
|
Phone string `json:"phone"`
|
Expired bool `json:"expired"`
|
ExpiredAtStr *string `json:"expired_at_str"`
|
}
|
list := make([]keyVO, 0, len(keys))
|
for _, k := range keys {
|
vo := keyVO{MemberKey: k, CardName: k.CardName(), Phone: phoneMap[k.UserID]}
|
if k.ExpiredAt != nil {
|
vo.Expired = k.ExpiredAt.Before(time.Now())
|
s := k.ExpiredAt.Format("2006-01-02 15:04:05")
|
vo.ExpiredAtStr = &s
|
} else if k.Status == 1 {
|
// 已使用的永久卡
|
s := "永久"
|
vo.ExpiredAtStr = &s
|
}
|
list = append(list, vo)
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"list": list, "total": total, "page": page}})
|
}
|
|
// ResetKey 管理员重置密钥(解绑机器,可再次使用)
|
func ResetKey(c *gin.Context) {
|
id := c.Param("id")
|
var key models.MemberKey
|
if err := config.DB.First(&key, id).Error; err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "密钥不存在"})
|
return
|
}
|
config.DB.Model(&key).Updates(map[string]interface{}{
|
"status": 0,
|
"user_id": 0,
|
"machine_code": "",
|
"activated_at": nil,
|
"expired_at": nil,
|
})
|
config.DB.Model(&key).UpdateColumn("reset_count", key.ResetCount+1)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密钥已重置,可重新使用"})
|
}
|
|
// DeleteKey 删除密钥
|
func DeleteKey(c *gin.Context) {
|
config.DB.Delete(&models.MemberKey{}, c.Param("id"))
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
|
}
|
|
// FreezeKey 冻结/解冻密钥(冻结后无法激活使用)
|
func FreezeKey(c *gin.Context) {
|
id := c.Param("id")
|
var key models.MemberKey
|
if err := config.DB.First(&key, id).Error; err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "密钥不存在"})
|
return
|
}
|
target := !key.Frozen
|
config.DB.Model(&key).Update("frozen", target)
|
msg := "密钥已冻结,无法使用"
|
if !target {
|
msg = "密钥已解冻,可正常使用"
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": msg})
|
}
|
|
// ---------- 工具管理 ----------
|
|
// AdminListTools 工具列表
|
func AdminListTools(c *gin.Context) {
|
var tools []models.Tool
|
config.DB.Order("id DESC").Find(&tools)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": tools})
|
}
|
|
// AdminSaveTool 新增/编辑工具
|
func AdminSaveTool(c *gin.Context) {
|
var req struct {
|
ID uint `json:"id"`
|
Name string `json:"name"`
|
Size string `json:"size"`
|
Cover string `json:"cover"`
|
Description string `json:"description"`
|
FileURL string `json:"file_url"`
|
LaunchExe string `json:"launch_exe"`
|
}
|
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Name) == "" {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写工具名称"})
|
return
|
}
|
var tool models.Tool
|
if req.ID > 0 {
|
if err := config.DB.First(&tool, req.ID).Error; err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "工具不存在"})
|
return
|
}
|
} else {
|
tool = models.Tool{}
|
}
|
tool.Name = req.Name
|
tool.Size = req.Size
|
tool.Cover = req.Cover
|
tool.Description = req.Description
|
tool.FileURL = req.FileURL
|
tool.LaunchExe = req.LaunchExe
|
if req.ID > 0 {
|
config.DB.Save(&tool)
|
} else {
|
config.DB.Create(&tool)
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已保存"})
|
}
|
|
// AdminDeleteTool 删除工具
|
func AdminDeleteTool(c *gin.Context) {
|
config.DB.Delete(&models.Tool{}, c.Param("id"))
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
|
}
|
|
// ---------- 游戏管理 ----------
|
|
func AdminListGames(c *gin.Context) {
|
var games []models.Game
|
config.DB.Order("id DESC").Find(&games)
|
fillCategoryName(&games)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": games})
|
}
|
|
func AdminSaveGame(c *gin.Context) {
|
var game models.Game
|
if err := c.ShouldBindJSON(&game); err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误: " + err.Error()})
|
return
|
}
|
if game.Title == "" {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写游戏名称"})
|
return
|
}
|
if game.Screenshots == "" {
|
game.Screenshots = "[]"
|
}
|
if game.Files == "" {
|
game.Files = "[]"
|
}
|
if game.ID == 0 {
|
config.DB.Create(&game)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "添加成功", "data": game})
|
} else {
|
config.DB.Model(&models.Game{}).Where("id = ?", game.ID).Updates(map[string]interface{}{
|
"title": game.Title, "category_id": game.CategoryID, "platform": game.Platform,
|
"tags": game.Tags, "size": game.Size, "install_size": game.InstallSize,
|
"os_req": game.OSReq, "cpu_req": game.CPUReq, "gpu_req": game.GPUReq, "ram_req": game.RAMReq,
|
"version_note": game.VersionNote, "launch_exe": game.LaunchExe, "cover": game.Cover, "video": game.Video,
|
"screenshots": game.Screenshots, "description": game.Description, "files": game.Files,
|
"is_banner": game.IsBanner,
|
})
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "修改成功"})
|
}
|
}
|
|
func AdminDeleteGame(c *gin.Context) {
|
config.DB.Delete(&models.Game{}, c.Param("id"))
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
|
}
|
|
// ---------- 类别管理 ----------
|
|
func AdminListCategories(c *gin.Context) {
|
var cats []models.Category
|
config.DB.Order("sort ASC").Find(&cats)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": cats})
|
}
|
|
func AdminSaveCategory(c *gin.Context) {
|
var cat models.Category
|
if err := c.ShouldBindJSON(&cat); err != nil || cat.Name == "" {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写类别名称"})
|
return
|
}
|
if cat.ID == 0 {
|
if err := config.DB.Create(&cat).Error; err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该类别已存在"})
|
return
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "添加成功"})
|
} else {
|
config.DB.Model(&models.Category{}).Where("id = ?", cat.ID).Update("name", cat.Name)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "修改成功"})
|
}
|
}
|
|
func AdminDeleteCategory(c *gin.Context) {
|
id := c.Param("id")
|
var count int64
|
config.DB.Model(&models.Game{}).Where("category_id = ?", id).Count(&count)
|
if count > 0 {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": fmt.Sprintf("该类别下还有 %d 个游戏,请先移出或删除", count)})
|
return
|
}
|
config.DB.Delete(&models.Category{}, id)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
|
}
|
|
// ---------- 上传 ----------
|
|
var allowedExts = map[string]bool{
|
".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true,
|
".mp4": true, ".mkv": true, ".avi": true, ".webm": true,
|
".zip": true, ".rar": true, ".7z": true, ".exe": true, ".iso": true, ".torrent": true,
|
}
|
|
// UploadFile 通用文件上传 type: cover/video/image/file
|
func UploadFile(c *gin.Context) {
|
file, err := c.FormFile("file")
|
if err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请选择文件"})
|
return
|
}
|
ext := strings.ToLower(filepath.Ext(file.Filename))
|
if !allowedExts[ext] {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "不支持的文件类型: " + ext})
|
return
|
}
|
fType := c.DefaultPostForm("type", "file")
|
dir := filepath.Join("uploads", fType)
|
os.MkdirAll(dir, 0755)
|
filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
|
dst := filepath.Join(dir, filename)
|
if err := c.SaveUploadedFile(file, dst); err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "保存文件失败"})
|
return
|
}
|
sizeStr := formatSize(file.Size)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
|
"url": "/static/" + fType + "/" + filename,
|
"name": file.Filename,
|
"size": sizeStr,
|
}})
|
}
|
|
func formatSize(n int64) string {
|
f := float64(n)
|
if f > 1024*1024*1024 {
|
return fmt.Sprintf("%.2f GB", f/1024/1024/1024)
|
}
|
if f > 1024*1024 {
|
return fmt.Sprintf("%.2f MB", f/1024/1024)
|
}
|
return fmt.Sprintf("%.2f KB", f/1024)
|
}
|
|
// ---------- 统计 ----------
|
|
func AdminStats(c *gin.Context) {
|
var users, games, keys, unusedKeys, usedKeys int64
|
config.DB.Model(&models.User{}).Count(&users)
|
config.DB.Model(&models.Game{}).Count(&games)
|
config.DB.Model(&models.MemberKey{}).Count(&keys)
|
config.DB.Model(&models.MemberKey{}).Where("status = ?", 0).Count(&unusedKeys)
|
config.DB.Model(&models.MemberKey{}).Where("status = ?", 1).Count(&usedKeys)
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
|
"users": users, "games": games, "keys": keys,
|
"unused_keys": unusedKeys, "used_keys": usedKeys,
|
}})
|
}
|
|
// ---------- 公告管理 ----------
|
|
// AdminGetAnnouncement 获取当前首页公告(最新一条,无则返回空内容)
|
func AdminGetAnnouncement(c *gin.Context) {
|
var ann models.Announcement
|
if err := config.DB.Order("id DESC").First(&ann).Error; err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"content": ""}})
|
return
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": ann})
|
}
|
|
// AdminSaveAnnouncement 保存首页公告(更新最新一条,无则新建;内容为空表示不弹出)
|
func AdminSaveAnnouncement(c *gin.Context) {
|
var req struct {
|
Content string `json:"content"`
|
}
|
if err := c.ShouldBindJSON(&req); err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
|
return
|
}
|
var ann models.Announcement
|
if err := config.DB.Order("id DESC").First(&ann).Error; err == nil {
|
config.DB.Model(&ann).Update("content", req.Content)
|
} else {
|
config.DB.Create(&models.Announcement{Content: req.Content})
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "公告已保存"})
|
}
|
|
var _ = io.Discard
|