Spaces:
Sleeping
Sleeping
File size: 8,532 Bytes
1de7911 |
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 |
package handler
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"zencoder-2api/internal/database"
"zencoder-2api/internal/model"
"zencoder-2api/internal/service"
)
type TokenHandler struct{}
func NewTokenHandler() *TokenHandler {
return &TokenHandler{}
}
// ListTokenRecords 获取所有token记录
func (h *TokenHandler) ListTokenRecords(c *gin.Context) {
records, err := service.GetAllTokenRecords()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// 获取每个token的生成任务统计
var enrichedRecords []map[string]interface{}
for _, record := range records {
// 统计该token的任务信息
var taskStats struct {
TotalTasks int64 `json:"total_tasks"`
TotalSuccess int64 `json:"total_success"`
TotalFail int64 `json:"total_fail"`
RunningTasks int64 `json:"running_tasks"`
}
db := database.GetDB()
db.Model(&model.GenerationTask{}).Where("token_record_id = ?", record.ID).Count(&taskStats.TotalTasks)
db.Model(&model.GenerationTask{}).Where("token_record_id = ?", record.ID).
Select("COALESCE(SUM(success_count), 0)").Scan(&taskStats.TotalSuccess)
db.Model(&model.GenerationTask{}).Where("token_record_id = ?", record.ID).
Select("COALESCE(SUM(fail_count), 0)").Scan(&taskStats.TotalFail)
db.Model(&model.GenerationTask{}).Where("token_record_id = ? AND status = ?", record.ID, "running").
Count(&taskStats.RunningTasks)
// 解析JWT获取用户信息
var email string
var planType string
var subscriptionStartDate time.Time
if record.Token != "" {
if payload, err := service.ParseJWT(record.Token); err == nil {
email = payload.Email
planType = payload.CustomClaims.Plan
if planType != "" {
planType = strings.ToUpper(planType[:1]) + planType[1:]
}
// 获取订阅开始时间
subscriptionStartDate = service.GetSubscriptionDate(payload)
}
}
enrichedRecord := map[string]interface{}{
"id": record.ID,
"description": record.Description,
"generated_count": record.GeneratedCount,
"last_generated_at": record.LastGeneratedAt,
"auto_generate": record.AutoGenerate,
"threshold": record.Threshold,
"generate_batch": record.GenerateBatch,
"is_active": record.IsActive,
"created_at": record.CreatedAt,
"updated_at": record.UpdatedAt,
"token_expiry": record.TokenExpiry,
"status": record.Status,
"ban_reason": record.BanReason,
"email": email,
"plan_type": planType,
"subscription_start_date": subscriptionStartDate,
"has_refresh_token": record.RefreshToken != "",
"total_tasks": taskStats.TotalTasks,
"total_success": taskStats.TotalSuccess,
"total_fail": taskStats.TotalFail,
"running_tasks": taskStats.RunningTasks,
}
enrichedRecords = append(enrichedRecords, enrichedRecord)
}
c.JSON(http.StatusOK, gin.H{
"items": enrichedRecords,
"total": len(enrichedRecords),
})
}
// UpdateTokenRecord 更新token记录配置
func (h *TokenHandler) UpdateTokenRecord(c *gin.Context) {
id := c.Param("id")
tokenID, err := strconv.ParseUint(id, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
var req struct {
AutoGenerate *bool `json:"auto_generate"`
Threshold *int `json:"threshold"`
GenerateBatch *int `json:"generate_batch"`
IsActive *bool `json:"is_active"`
Description string `json:"description"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
updates := make(map[string]interface{})
if req.AutoGenerate != nil {
updates["auto_generate"] = *req.AutoGenerate
}
if req.Threshold != nil {
updates["threshold"] = *req.Threshold
}
if req.GenerateBatch != nil {
updates["generate_batch"] = *req.GenerateBatch
}
if req.IsActive != nil {
updates["is_active"] = *req.IsActive
}
if req.Description != "" {
updates["description"] = req.Description
}
if err := service.UpdateTokenRecord(uint(tokenID), updates); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "updated"})
}
// GetGenerationTasks 获取生成任务历史
func (h *TokenHandler) GetGenerationTasks(c *gin.Context) {
tokenRecordID := c.Query("token_record_id")
var tokenID uint
if tokenRecordID != "" {
id, err := strconv.ParseUint(tokenRecordID, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid token_record_id"})
return
}
tokenID = uint(id)
}
tasks, err := service.GetGenerationTasks(tokenID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"items": tasks,
"total": len(tasks),
})
}
// TriggerGeneration 手动触发生成
func (h *TokenHandler) TriggerGeneration(c *gin.Context) {
id := c.Param("id")
tokenID, err := strconv.ParseUint(id, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
if err := service.ManualTriggerGeneration(uint(tokenID)); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "生成任务已触发"})
}
// GetPoolStatus 获取号池状态
func (h *TokenHandler) GetPoolStatus(c *gin.Context) {
db := database.GetDB()
var stats struct {
TotalAccounts int64 `json:"total_accounts"`
NormalAccounts int64 `json:"normal_accounts"`
CoolingAccounts int64 `json:"cooling_accounts"`
BannedAccounts int64 `json:"banned_accounts"`
ErrorAccounts int64 `json:"error_accounts"`
DisabledAccounts int64 `json:"disabled_accounts"`
ActiveTokens int64 `json:"active_tokens"`
RunningTasks int64 `json:"running_tasks"`
}
// 统计账号状态
db.Model(&model.Account{}).Count(&stats.TotalAccounts)
db.Model(&model.Account{}).Where("status = ?", "normal").Count(&stats.NormalAccounts)
db.Model(&model.Account{}).Where("status = ?", "cooling").Count(&stats.CoolingAccounts)
db.Model(&model.Account{}).Where("status = ?", "banned").Count(&stats.BannedAccounts)
db.Model(&model.Account{}).Where("status = ?", "error").Count(&stats.ErrorAccounts)
db.Model(&model.Account{}).Where("status = ?", "disabled").Count(&stats.DisabledAccounts)
// 统计激活的token
db.Model(&model.TokenRecord{}).Where("is_active = ?", true).Count(&stats.ActiveTokens)
// 统计运行中的任务
db.Model(&model.GenerationTask{}).Where("status = ?", "running").Count(&stats.RunningTasks)
c.JSON(http.StatusOK, stats)
}
// DeleteTokenRecord 删除token记录
func (h *TokenHandler) DeleteTokenRecord(c *gin.Context) {
id := c.Param("id")
tokenID, err := strconv.ParseUint(id, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
// 开启事务,确保删除操作的原子性
db := database.GetDB()
tx := db.Begin()
// 先删除所有关联的生成任务历史记录
if err := tx.Where("token_record_id = ?", tokenID).Delete(&model.GenerationTask{}).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除关联任务失败: " + err.Error()})
return
}
// 删除token记录本身
if err := tx.Delete(&model.TokenRecord{}, tokenID).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除token记录失败: " + err.Error()})
return
}
// 提交事务
if err := tx.Commit().Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "提交事务失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "token及其所有历史记录已删除"})
}
// RefreshTokenRecord 刷新token记录
func (h *TokenHandler) RefreshTokenRecord(c *gin.Context) {
id := c.Param("id")
tokenID, err := strconv.ParseUint(id, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
// 调用service层的刷新函数
if err := service.RefreshTokenAndAccounts(uint(tokenID)); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Token刷新成功,相关账号刷新已启动"})
} |