905086
2026-11-07 6697e53613d5ce562a19795ab41b19803c2bb93d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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