feat: 易支付积分充值 + 站内公告 + OpenAI 视频修复 + grok/adobe 失败处理

充值/订单(易支付 mapi):
- 订单表 + 30 分钟自动取消;支付弹窗(二维码/跳转监控、倒计时、轮询、5s 倒计时关闭)
- 系统设置可配:开关/商户ID/密钥/支付地址(根地址拼 /mapi)/支付方式/最低额/积分比例(默认 1元=100积分)
- 异步通知 MD5 验签、幂等到账;用户累计充值;前台/后台订单页(筛选+搜索+分页,前后台分风格);用户管理累计充值列

站内公告:
- Markdown 公告,登录用户首次访问/刷新弹出;内容哈希做版本,改了就重新推;管理员不弹;空内容=下线

OpenAI 视频(/v1/videos)修复:
- /content 拿不到视频:grok 资源 URL 需鉴权,改为用生成账号 token 取流;adobe/runway 公开 URL 直代理(不存 RustFS)
- size→分辨率用短边判定(1280x720 = 720p,之前误判 1080p 被拒)

失败处理:
- grok 429「Too many requests」/403 anti-bot 改判临时错误(不再误封号),真额度耗尽才算 quota
- adobe 视频 408 / system under load 归为临时错误 → tempAsDead 封号

其它:
- 充值默认关闭;签到格子浅色可见;登录验证码按钮浅色可读;并发/账户信息展示
- 创作记录/画图台只显示画图台作品(排除 API);日志页 API 视频预览显示 —
- 视频去画中画/下载/投屏(全局);图片缩略图改背景图规避 Edge 视觉搜索
- 订单/兑换码/配置/日志菜单文案与图标;充值版块样式

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-01 01:32:33 +08:00
co-authored by Claude Opus 4.8
parent 5cf6206ee9
commit 8ec4562f81
39 changed files with 2237 additions and 68 deletions
+6 -1
View File
@@ -104,6 +104,9 @@ func NewApp(ctx context.Context) (*App, error) {
}
concSvc := service.NewConcurrencyService(rdb)
cgroupSvc := service.NewConcurrencyGroupService(cgroupRepo, concSvc)
announcementSvc := service.NewAnnouncementService(siteRepo, userRepo)
orderRepo := repo.NewOrderRepository(db)
paymentSvc := service.NewPaymentService(orderRepo, userRepo, siteRepo)
sessionSvc := service.NewSessionService(rdb, cfg.SessionTTL, cfg.SessionSlideAfter)
emailCodeSvc := service.NewEmailCodeService(rdb)
smtpSvc := service.NewSMTPService()
@@ -150,11 +153,13 @@ func NewApp(ctx context.Context) (*App, error) {
UserGen: handler.NewUserGenerationHandler(userGenSvc, adminReadSvc),
ProviderAdmin: handler.NewProviderAdminHandler(tokenSvc, refreshSvc),
ConcGroups: handler.NewConcurrencyGroupHandler(cgroupSvc),
Announcement: handler.NewAnnouncementHandler(announcementSvc),
Payment: handler.NewPaymentHandler(paymentSvc),
})
// Background self-healing sweep (quota recovery, cookie refresh, stale-pending
// cleanup, log retention) — the Go equivalent of the Python daemon thread.
maintenanceSvc := service.NewMaintenanceService(tokenRepo, tokenSvc, eventRepo, userRepo, refreshSvc, siteRepo, rustfsClient, v1Svc.Inflight(), showcaseRepo)
maintenanceSvc := service.NewMaintenanceService(tokenRepo, tokenSvc, eventRepo, userRepo, refreshSvc, siteRepo, rustfsClient, v1Svc.Inflight(), showcaseRepo, orderRepo)
loopCtx, loopCancel := context.WithCancel(context.Background())
go maintenanceSvc.Run(loopCtx)
+5
View File
@@ -35,6 +35,11 @@ func seedDefaults(ctx context.Context, db *gorm.DB) error {
{Key: "credits.invite_enabled", Value: "true"},
{Key: "credits.invite_reward", Value: "3"},
{Key: "credits.cdk_redeem_enabled", Value: "true"},
{Key: "pay.enabled", Value: "false"},
{Key: "pay.api_base", Value: "https://pay.v8jisu.cn/api/pay"},
{Key: "pay.methods", Value: "wxpay,alipay"},
{Key: "pay.min_amount", Value: "1"},
{Key: "pay.points_ratio", Value: "100"},
{Key: "logs.retention_days", Value: "30"},
{Key: "media.retention_days", Value: "30"},
}
@@ -182,6 +182,7 @@ func userPublic(user model.User) gin.H {
"status": user.Status,
"credits": user.Credits,
"notes": user.Notes,
"recharge_total": user.RechargeTotal,
"concurrency_group_id": user.ConcurrencyGroupID,
"created_at": unixSec(user.CreatedAt),
"last_login_at": unixSecPtr(user.LastLoginAt),
@@ -0,0 +1,65 @@
package handler
import (
"net/http"
"backend/internal/service"
"github.com/gin-gonic/gin"
)
type AnnouncementHandler struct {
svc *service.AnnouncementService
}
func NewAnnouncementHandler(svc *service.AnnouncementService) *AnnouncementHandler {
return &AnnouncementHandler{svc: svc}
}
// Get — logged-in user: the current announcement + whether THIS user has seen it.
func (h *AnnouncementHandler) Get(c *gin.Context) {
user := currentUser(c)
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
return
}
c.JSON(http.StatusOK, h.svc.ForUser(c.Request.Context(), user))
}
// MarkSeen — user dismissed the announcement of the given version.
func (h *AnnouncementHandler) MarkSeen(c *gin.Context) {
user := currentUser(c)
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
return
}
var body struct {
Version string `json:"version"`
}
_ = c.ShouldBindJSON(&body)
if err := h.svc.MarkSeen(c.Request.Context(), user.ID, body.Version); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save"})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
// AdminGet — admin editor: the raw markdown.
func (h *AnnouncementHandler) AdminGet(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"content": h.svc.Content(c.Request.Context())})
}
// AdminPut — admin saves new markdown (re-pops for everyone who hasn't seen it).
func (h *AnnouncementHandler) AdminPut(c *gin.Context) {
var body struct {
Content string `json:"content"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
return
}
if err := h.svc.Save(c.Request.Context(), body.Content); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save"})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
+190
View File
@@ -0,0 +1,190 @@
package handler
import (
"errors"
"net/http"
"strings"
"time"
"backend/internal/model"
"backend/internal/service"
"github.com/gin-gonic/gin"
)
type PaymentHandler struct {
pay *service.PaymentService
}
func NewPaymentHandler(pay *service.PaymentService) *PaymentHandler {
return &PaymentHandler{pay: pay}
}
func orderJSON(o *model.Order) gin.H {
h := gin.H{
"id": o.ID,
"amount": o.Amount,
"points": o.Points,
"pay_type": o.PayType,
"status": o.Status,
"pay_info": o.PayInfo,
"pay_info_type": o.PayInfoType,
"created_at": o.CreatedAt.Unix(),
"expires_at": o.ExpiresAt.Unix(),
"server_now": time.Now().Unix(), // lets the popup count down on server time
}
if o.PaidAt != nil {
h["paid_at"] = o.PaidAt.Unix()
}
return h
}
// ---- user ----
// Config returns the recharge config for the user UI (enabled, methods, min, ratio).
func (h *PaymentHandler) Config(c *gin.Context) {
c.JSON(http.StatusOK, h.pay.Public(c.Request.Context()))
}
func (h *PaymentHandler) Recharge(c *gin.Context) {
user := currentUser(c)
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
return
}
var body struct {
Amount float64 `json:"amount"`
Method string `json:"method"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
return
}
order, err := h.pay.CreateOrder(c.Request.Context(), user, body.Amount, body.Method, requestBaseURL(c), clientIP(c))
if err != nil {
h.writeErr(c, err)
return
}
c.JSON(http.StatusOK, orderJSON(order))
}
func (h *PaymentHandler) MyOrders(c *gin.Context) {
user := currentUser(c)
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
return
}
limit := parseInt(c.Query("limit"), 20)
offset := parseInt(c.Query("offset"), 0)
orders, total, err := h.pay.ListByUser(c.Request.Context(), user.ID, c.Query("status"), limit, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load orders"})
return
}
out := make([]gin.H, 0, len(orders))
for i := range orders {
out = append(out, orderJSON(&orders[i]))
}
c.JSON(http.StatusOK, gin.H{"data": out, "total": total})
}
func (h *PaymentHandler) OrderStatus(c *gin.Context) {
user := currentUser(c)
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
return
}
order, err := h.pay.GetForUser(c.Request.Context(), user.ID, c.Param("id"))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"detail": "订单不存在"})
return
}
c.JSON(http.StatusOK, orderJSON(order))
}
func (h *PaymentHandler) ContinueOrder(c *gin.Context) {
user := currentUser(c)
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"detail": "未登录或会话已过期"})
return
}
order, err := h.pay.Continue(c.Request.Context(), user, c.Param("id"), requestBaseURL(c), clientIP(c))
if err != nil {
h.writeErr(c, err)
return
}
c.JSON(http.StatusOK, orderJSON(order))
}
// ---- admin ----
func (h *PaymentHandler) AdminOrders(c *gin.Context) {
status := c.Query("status")
limit := parseInt(c.Query("limit"), 100)
offset := parseInt(c.Query("offset"), 0)
orders, total, err := h.pay.ListAll(c.Request.Context(), status, limit, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load orders"})
return
}
names := h.pay.UserNames(c.Request.Context())
out := make([]gin.H, 0, len(orders))
for i := range orders {
row := orderJSON(&orders[i])
row["user_name"] = names[orders[i].UserID]
out = append(out, row)
}
c.JSON(http.StatusOK, gin.H{"data": out, "total": total})
}
func (h *PaymentHandler) SettingsGet(c *gin.Context) {
c.JSON(http.StatusOK, h.pay.Settings(c.Request.Context()))
}
func (h *PaymentHandler) SettingsSave(c *gin.Context) {
var in service.PaySettings
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
return
}
if err := h.pay.SaveSettings(c.Request.Context(), in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"detail": strings.TrimSpace(err.Error())})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
// ---- public async notify (no auth — called by the 易支付 server) ----
func (h *PaymentHandler) Notify(c *gin.Context) {
params := map[string]string{}
for k, v := range c.Request.URL.Query() {
if len(v) > 0 {
params[k] = v[0]
}
}
if _, err := h.pay.HandleNotify(c.Request.Context(), params); err != nil {
c.String(http.StatusOK, "fail")
return
}
// 易支付 expects the literal string "success" to stop re-notifying.
c.String(http.StatusOK, "success")
}
func (h *PaymentHandler) writeErr(c *gin.Context, err error) {
switch {
case errors.Is(err, service.ErrPayDisabled):
c.JSON(http.StatusForbidden, gin.H{"detail": "充值已关闭"})
case errors.Is(err, service.ErrPayNotConfig):
c.JSON(http.StatusServiceUnavailable, gin.H{"detail": "支付未配置"})
case errors.Is(err, service.ErrPayMethod):
c.JSON(http.StatusBadRequest, gin.H{"detail": "不支持的支付方式"})
case errors.Is(err, service.ErrPayAmount):
c.JSON(http.StatusBadRequest, gin.H{"detail": "金额低于最低充值额"})
case errors.Is(err, service.ErrOrderNotFound):
c.JSON(http.StatusNotFound, gin.H{"detail": "订单不存在"})
case errors.Is(err, service.ErrOrderPaid):
c.JSON(http.StatusBadRequest, gin.H{"detail": "订单已支付"})
default:
c.JSON(http.StatusBadGateway, gin.H{"detail": strings.TrimSpace(err.Error())})
}
}
+3 -5
View File
@@ -259,12 +259,10 @@ func videoSizeToInternal(size string) (ratio, resolution string) {
if w == 0 || h == 0 {
return "16:9", "720p"
}
long := w
if h > long {
long = h
}
// The "p" resolution is the SHORT edge (720p = 1280×720, 1080p = 1920×1080),
// so a standard 1280×720 must read as 720p — not 1080p off the long edge.
resolution = "720p"
if long >= 1080 {
if min(w, h) >= 1080 {
resolution = "1080p"
}
return guessRatioWH(w, h), resolution
+17
View File
@@ -26,6 +26,8 @@ type Handlers struct {
UserGen *handler.UserGenerationHandler
ProviderAdmin *handler.ProviderAdminHandler
ConcGroups *handler.ConcurrencyGroupHandler
Announcement *handler.AnnouncementHandler
Payment *handler.PaymentHandler
}
func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.Engine {
@@ -62,6 +64,9 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
publicAdmin.GET("/video-presets", handlers.UserGen.VideoPresets)
publicAdmin.GET("/catalog", handlers.UserGen.Catalog)
publicAdmin.GET("/models", handlers.UserGen.Models)
// 易支付 async notify — called server-to-server by the pay platform, no auth.
publicAdmin.GET("/pay/notify", handlers.Payment.Notify)
publicAdmin.POST("/pay/notify", handlers.Payment.Notify)
}
authGroup := engine.Group("/admin/api/auth")
@@ -82,6 +87,13 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
userAuthed.POST("/test", handlers.UserGen.Test)
userAuthed.GET("/jobs/mine", handlers.UserGen.MyJobs)
userAuthed.GET("/my-images", handlers.UserGen.MyImages)
userAuthed.GET("/announcement", handlers.Announcement.Get)
userAuthed.POST("/announcement/seen", handlers.Announcement.MarkSeen)
userAuthed.GET("/pay/config", handlers.Payment.Config)
userAuthed.POST("/pay/recharge", handlers.Payment.Recharge)
userAuthed.GET("/pay/orders", handlers.Payment.MyOrders)
userAuthed.GET("/pay/orders/:id", handlers.Payment.OrderStatus)
userAuthed.POST("/pay/orders/:id/continue", handlers.Payment.ContinueOrder)
}
authed := engine.Group("/admin/api")
@@ -102,6 +114,7 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
authed.PATCH("/concurrency-groups/:id", handlers.ConcGroups.Update)
authed.POST("/concurrency-groups/:id/default", handlers.ConcGroups.SetDefault)
authed.DELETE("/concurrency-groups/:id", handlers.ConcGroups.Delete)
authed.GET("/pay/admin/orders", handlers.Payment.AdminOrders)
authed.GET("/cdks", handlers.CDK.List)
authed.POST("/cdks", handlers.CDK.Create)
authed.POST("/cdks/delete-bulk", handlers.CDK.DeleteBulk)
@@ -158,6 +171,10 @@ func New(cfg *config.Config, auth *service.AuthService, handlers Handlers) *gin.
settings.PUT("/logs", handlers.AppSettings.LogsPut)
settings.GET("/media", handlers.AppSettings.MediaGet)
settings.PUT("/media", handlers.AppSettings.MediaPut)
settings.GET("/announcement", handlers.Announcement.AdminGet)
settings.PUT("/announcement", handlers.Announcement.AdminPut)
settings.GET("/pay", handlers.Payment.SettingsGet)
settings.PUT("/pay", handlers.Payment.SettingsSave)
}
}
+22
View File
@@ -16,6 +16,8 @@ type User struct {
Credits float64 `gorm:"not null;default:0"`
Notes string `gorm:"type:text"`
ConcurrencyGroupID string `gorm:"size:32;index"`
AnnouncementSeen string `gorm:"size:32"` // version hash of the last announcement this user dismissed
RechargeTotal float64 `gorm:"not null;default:0"` // 累计充值金额(元)
InviteCode string `gorm:"size:32;uniqueIndex"`
InvitedBy *string `gorm:"size:32;index"`
InviteRewardDone bool `gorm:"not null;default:false"`
@@ -205,9 +207,29 @@ func AutoMigrateModels() []any {
&SiteSetting{},
&StatCounter{},
&ConcurrencyGroup{},
&Order{},
}
}
// Order is a points-recharge order paid via 易支付 (epay). ID is our merchant
// order number (out_trade_no). Status: pending | paid | cancelled. Unpaid orders
// auto-cancel 30 min after creation (ExpiresAt).
type Order struct {
ID string `gorm:"primaryKey;size:40"`
UserID string `gorm:"size:32;index;not null"`
Amount float64 `gorm:"not null"` // 充值金额(元)
Points int `gorm:"not null"` // 到账积分
PayType string `gorm:"size:16"` // wxpay | alipay
Status string `gorm:"size:16;index;not null"` // pending | paid | cancelled
TradeNo string `gorm:"size:64;index"` // 易支付平台订单号
PayInfo string `gorm:"type:text"` // 二维码 url / 跳转 url
PayInfoType string `gorm:"size:16"` // qrcode | jump | html | ...
ExpiresAt time.Time `gorm:"index"`
PaidAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
// ConcurrencyGroup caps how many generations a member user may run AT ONCE
// (across their API key + 画图台). MaxConcurrency 0 = unlimited. Exactly one
// group is IsDefault — new users are bound to it and it can't be deleted.
+6 -1
View File
@@ -604,7 +604,12 @@ func (c *Client) submitVideo(ctx context.Context, client tlsclient.HttpClient, t
// it's a bad token, a missing scope, or a WAF/fingerprint block.
return respBody, "", fmt.Errorf("%w (%d %s: %s)", ErrAuth, resp.StatusCode, resp.Header.Get("x-access-error"), clip(respBody, 300))
}
if resp.StatusCode == 429 || resp.StatusCode == 451 || resp.StatusCode >= 500 {
if resp.StatusCode == 408 || resp.StatusCode == 429 || resp.StatusCode == 451 || resp.StatusCode >= 500 {
return respBody, "", ErrTemporaryUpstream
}
// "system under load" / timeout_error = adobe overload — treat as a temporary
// error so the tempAsDead policy retires the account (same as the image path).
if b := string(respBody); strings.Contains(b, "system under load") || strings.Contains(b, "timeout_error") {
return respBody, "", ErrTemporaryUpstream
}
if resp.StatusCode != 200 {
+142
View File
@@ -0,0 +1,142 @@
// Package epay implements the 易支付 mapi (API 下单) interface with MD5 signing.
// POST {api_base}/mapi → JSON {code, msg, trade_no, payurl, qrcode}.
// Docs: 请求字段 pid/type/out_trade_no/notify_url/name/money/sign/sign_type.
package epay
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
type Config struct {
APIBase string // 易支付 API 根地址,如 https://pay.v8jisu.cn/api/pay(自动拼 /mapi)
PID string // 商户ID
Key string // 商户密钥
}
type CreateRequest struct {
OutTradeNo string
Type string // wxpay | alipay | unionpay
Name string
Money string // "10.00"
NotifyURL string
ReturnURL string
ClientIP string // unused by mapi; kept for caller convenience
}
type CreateResult struct {
TradeNo string // 平台订单号
PayType string // qrcode | jump
PayInfo string // 二维码内容 或 跳转 url
}
// mapiResp is the raw mapi response. code: 1 成功, -1 失败.
type mapiResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
TradeNo string `json:"trade_no"`
PayURL string `json:"payurl"`
QRCode string `json:"qrcode"`
}
var httpClient = &http.Client{Timeout: 20 * time.Second}
// sign builds the MD5 signature: take all params except sign/sign_type and empty
// values, sort keys ASCII-ascending, join as k=v&k=v (raw values), append the
// merchant key, MD5, lowercase hex.
func sign(params map[string]string, key string) string {
keys := make([]string, 0, len(params))
for k, v := range params {
if k == "sign" || k == "sign_type" || v == "" {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
var b strings.Builder
for i, k := range keys {
if i > 0 {
b.WriteByte('&')
}
b.WriteString(k)
b.WriteByte('=')
b.WriteString(params[k])
}
b.WriteString(key)
sum := md5.Sum([]byte(b.String()))
return hex.EncodeToString(sum[:])
}
// Create places a mapi order and returns the payment info (qrcode preferred).
func (c *Config) Create(ctx context.Context, req CreateRequest) (*CreateResult, error) {
params := map[string]string{
"pid": c.PID,
"type": req.Type,
"out_trade_no": req.OutTradeNo,
"notify_url": req.NotifyURL,
"name": req.Name,
"money": req.Money,
"sign_type": "MD5",
}
if req.ReturnURL != "" {
params["return_url"] = req.ReturnURL
}
params["sign"] = sign(params, c.Key)
form := url.Values{}
for k, v := range params {
form.Set(k, v)
}
endpoint := strings.TrimRight(c.APIBase, "/") + "/mapi"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := httpClient.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var out mapiResp
if err := json.Unmarshal(body, &out); err != nil {
return nil, fmt.Errorf("epay: bad response: %s", strings.TrimSpace(string(body)))
}
if out.Code != 1 {
msg := out.Msg
if msg == "" {
msg = "下单失败"
}
return nil, fmt.Errorf("epay: %s", msg)
}
result := &CreateResult{TradeNo: out.TradeNo}
if out.QRCode != "" {
result.PayType = "qrcode"
result.PayInfo = out.QRCode
} else if out.PayURL != "" {
result.PayType = "jump"
result.PayInfo = out.PayURL
} else {
return nil, fmt.Errorf("epay: 响应缺少 qrcode/payurl")
}
return result, nil
}
// VerifyNotify validates an async-notify callback's MD5 signature.
func (c *Config) VerifyNotify(params map[string]string) bool {
got := strings.TrimSpace(params["sign"])
if got == "" {
return false
}
return strings.EqualFold(got, sign(params, c.Key))
}
+51 -1
View File
@@ -224,6 +224,46 @@ func (c *Client) doPost(ctx context.Context, client tlsclient.HttpClient, token,
return raw, resp.StatusCode, nil
}
// OpenAsset streams a grok asset (e.g. a generated video) authenticated with the
// account token — used by the async /v1/videos /content proxy. The caller MUST
// close the returned ReadCloser.
func (c *Client) OpenAsset(ctx context.Context, token, url string) (io.ReadCloser, string, error) {
token = strings.TrimSpace(strings.TrimPrefix(token, "Bearer "))
if token == "" {
return nil, "", ErrAuth
}
client, err := c.newTLSClient()
if err != nil {
return nil, "", err
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, "", err
}
req = req.WithContext(ctx)
req.Header = http.Header{
"user-agent": {userAgent},
"referer": {origin + "/"},
"cookie": {"sso=" + token + "; sso-rw=" + token},
}
resp, err := client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("%w: %v", ErrTemporaryUpstream, err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
resp.Body.Close()
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, "", fmt.Errorf("%w: asset %d", ErrAuth, resp.StatusCode)
}
return nil, "", fmt.Errorf("%w: asset %d", ErrTemporaryUpstream, resp.StatusCode)
}
ct := resp.Header.Get("Content-Type")
if ct == "" {
ct = "video/mp4"
}
return resp.Body, ct, nil
}
func (c *Client) download(ctx context.Context, client tlsclient.HttpClient, token, url string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
@@ -258,10 +298,20 @@ func mapStatus(path string, status int, raw []byte) error {
switch {
case status == 200:
return nil
case status == 403 && strings.Contains(strings.ToLower(string(raw)), "anti-bot"):
// grok bot-detection (proxy/TLS fingerprint), NOT a dead token — transient,
// so a good account isn't killed by an IP/anti-bot hiccup.
return fmt.Errorf("%w: %s 403 %s", ErrTemporaryUpstream, path, clip(raw, 160))
case status == 401 || status == 403:
return fmt.Errorf("%w: %s %d %s", ErrAuth, path, status, clip(raw, 160))
case status == 429:
return fmt.Errorf("%w: %s 429 %s", ErrQuotaExhausted, path, clip(raw, 160))
// 429 is grok RATE-LIMITING ("Too many requests") — a transient error that
// must NOT kill the account. Only a body that names a credit/usage-pool
// exhaustion is a real quota wall.
if isCreditError(string(raw)) {
return fmt.Errorf("%w: %s 429 %s", ErrQuotaExhausted, path, clip(raw, 160))
}
return fmt.Errorf("%w: %s 429 %s", ErrTemporaryUpstream, path, clip(raw, 160))
case status >= 500:
return fmt.Errorf("%w: %s %d %s", ErrTemporaryUpstream, path, status, clip(raw, 160))
default:
+83
View File
@@ -0,0 +1,83 @@
package repo
import (
"context"
"time"
"backend/internal/model"
"gorm.io/gorm"
)
type OrderRepository struct{ db *gorm.DB }
func NewOrderRepository(db *gorm.DB) *OrderRepository { return &OrderRepository{db: db} }
func (r *OrderRepository) Create(ctx context.Context, o *model.Order) error {
return r.db.WithContext(ctx).Create(o).Error
}
func (r *OrderRepository) Get(ctx context.Context, id string) (*model.Order, error) {
var o model.Order
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&o).Error; err != nil {
return nil, err
}
return &o, nil
}
func (r *OrderRepository) Update(ctx context.Context, id string, patch map[string]any) error {
return r.db.WithContext(ctx).Model(&model.Order{}).Where("id = ?", id).Updates(patch).Error
}
// ListByUser returns a user's own orders, newest first, with pagination + total.
func (r *OrderRepository) ListByUser(ctx context.Context, userID, status string, limit, offset int) ([]model.Order, int64, error) {
var out []model.Order
var total int64
q := r.db.WithContext(ctx).Model(&model.Order{}).Where("user_id = ?", userID)
if status != "" {
q = q.Where("status = ?", status)
}
if err := q.Count(&total).Error; err != nil {
return nil, 0, err
}
if limit <= 0 {
limit = 20
}
err := q.Order("created_at desc").Limit(limit).Offset(offset).Find(&out).Error
return out, total, err
}
// List returns all orders (admin) with optional status filter + pagination.
func (r *OrderRepository) List(ctx context.Context, status string, limit, offset int) ([]model.Order, int64, error) {
var out []model.Order
var total int64
q := r.db.WithContext(ctx).Model(&model.Order{})
if status != "" {
q = q.Where("status = ?", status)
}
if err := q.Count(&total).Error; err != nil {
return nil, 0, err
}
if limit <= 0 {
limit = 50
}
err := q.Order("created_at desc").Limit(limit).Offset(offset).Find(&out).Error
return out, total, err
}
// MarkPaid flips a pending order to paid atomically. Returns true only on the
// transition pending→paid, so a duplicate notify can never double-credit.
func (r *OrderRepository) MarkPaid(ctx context.Context, id, tradeNo string, paidAt time.Time) (bool, error) {
res := r.db.WithContext(ctx).Model(&model.Order{}).
Where("id = ? AND status = ?", id, "pending").
Updates(map[string]any{"status": "paid", "paid_at": paidAt, "trade_no": tradeNo})
return res.RowsAffected > 0, res.Error
}
// ExpirePending cancels every still-pending order whose ExpiresAt has passed and
// returns how many it cancelled.
func (r *OrderRepository) ExpirePending(ctx context.Context, now time.Time) (int64, error) {
res := r.db.WithContext(ctx).Model(&model.Order{}).
Where("status = ? AND expires_at < ?", "pending", now).
Updates(map[string]any{"status": "cancelled"})
return res.RowsAffected, res.Error
}
+62
View File
@@ -0,0 +1,62 @@
package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"strings"
"backend/internal/model"
"backend/internal/repo"
)
// AnnouncementService serves the site-wide 公告 (markdown). It tracks, per user,
// the version they last dismissed so an updated announcement re-pops for everyone
// who hasn't seen the new text. The "version" is a hash of the content, so saving
// identical text doesn't re-notify; any edit does.
type AnnouncementService struct {
settings *repo.SiteSettingRepository
users *repo.UserRepository
}
func NewAnnouncementService(settings *repo.SiteSettingRepository, users *repo.UserRepository) *AnnouncementService {
return &AnnouncementService{settings: settings, users: users}
}
func announcementVersion(content string) string {
if strings.TrimSpace(content) == "" {
return ""
}
sum := sha256.Sum256([]byte(strings.TrimSpace(content)))
return hex.EncodeToString(sum[:8]) // 16 hex chars — plenty to detect a change
}
// Content returns the raw markdown (admin editor).
func (s *AnnouncementService) Content(ctx context.Context) string {
v, _ := s.settings.GetValue(ctx, "announcement.content")
return v
}
// ForUser returns {content, version, seen} for the logged-in user.
func (s *AnnouncementService) ForUser(ctx context.Context, user *model.User) map[string]any {
content := s.Content(ctx)
version := announcementVersion(content)
// Admins never get the popup — they author/preview it in 系统设置 instead.
seen := version == "" || (user != nil && (user.Role == "admin" || user.AnnouncementSeen == version))
return map[string]any{
"content": content,
"version": version,
"seen": seen,
}
}
// MarkSeen records that the user has dismissed the given version.
func (s *AnnouncementService) MarkSeen(ctx context.Context, userID, version string) error {
_, err := s.users.Update(ctx, userID, map[string]any{"announcement_seen": version})
return err
}
// Save persists new announcement markdown (admin). An empty string clears it.
func (s *AnnouncementService) Save(ctx context.Context, content string) error {
return s.settings.UpsertValue(ctx, "announcement.content", content)
}
+1
View File
@@ -456,6 +456,7 @@ func (s *AuthService) PublicUser(ctx context.Context, user *model.User) (map[str
"role": user.Role,
"status": user.Status,
"credits": user.Credits,
"recharge_total": user.RechargeTotal,
"concurrency_group": concName,
"concurrency_limit": concMax,
"checkin_last": user.CheckinLast,
+12 -1
View File
@@ -28,13 +28,14 @@ type MaintenanceService struct {
store *storage.Client
inflight *InflightRegistry
showcase *repo.ShowcaseRepository
orders *repo.OrderRepository
interval time.Duration
stalePending time.Duration
mediaPruneEvery time.Duration
lastMediaPrune time.Time
}
func NewMaintenanceService(tokens *repo.TokenRepository, tokenSvc *TokenService, events *repo.EventRepository, users *repo.UserRepository, refresh *RefreshProfileService, settings *repo.SiteSettingRepository, store *storage.Client, inflight *InflightRegistry, showcase *repo.ShowcaseRepository) *MaintenanceService {
func NewMaintenanceService(tokens *repo.TokenRepository, tokenSvc *TokenService, events *repo.EventRepository, users *repo.UserRepository, refresh *RefreshProfileService, settings *repo.SiteSettingRepository, store *storage.Client, inflight *InflightRegistry, showcase *repo.ShowcaseRepository, orders *repo.OrderRepository) *MaintenanceService {
return &MaintenanceService{
tokens: tokens,
tokenSvc: tokenSvc,
@@ -45,6 +46,7 @@ func NewMaintenanceService(tokens *repo.TokenRepository, tokenSvc *TokenService,
store: store,
inflight: inflight,
showcase: showcase,
orders: orders,
interval: 60 * time.Second,
stalePending: 600 * time.Second,
mediaPruneEvery: 60 * time.Second,
@@ -99,6 +101,15 @@ func (m *MaintenanceService) syncRecoveredQuota(accs []model.TokenAccount) {
}
func (m *MaintenanceService) tick(ctx context.Context) {
// 0. Auto-cancel unpaid recharge orders past their 30-min TTL.
if m.orders != nil {
if n, err := m.orders.ExpirePending(ctx, time.Now()); err != nil {
log.Printf("maintenance: expire orders: %v", err)
} else if n > 0 {
log.Printf("maintenance: cancelled %d expired order(s)", n)
}
}
// 1. Re-activate quota-exhausted tokens whose reset time has passed, then
// auto-sync their real balance — these providers only refresh quota when
// accessed, so recovery alone would leave a stale 0/—. For krea the sync
+285
View File
@@ -0,0 +1,285 @@
package service
import (
"context"
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"backend/internal/model"
"backend/internal/provider/epay"
"backend/internal/repo"
"gorm.io/gorm"
)
const orderTTL = 30 * time.Minute
var (
ErrPayDisabled = errors.New("recharge is currently disabled")
ErrPayNotConfig = errors.New("payment is not configured")
ErrPayMethod = errors.New("unsupported payment method")
ErrPayAmount = errors.New("amount below the minimum")
ErrOrderNotFound = errors.New("order not found")
ErrOrderPaid = errors.New("order already paid")
)
// PaymentService drives 易支付 recharge orders: create → pay → async-notify →
// credit points. Config lives in site settings (pay.*).
type PaymentService struct {
orders *repo.OrderRepository
users *repo.UserRepository
settings *repo.SiteSettingRepository
}
func NewPaymentService(orders *repo.OrderRepository, users *repo.UserRepository, settings *repo.SiteSettingRepository) *PaymentService {
return &PaymentService{orders: orders, users: users, settings: settings}
}
type PaySettings struct {
Enabled bool `json:"enabled"`
PID string `json:"pid"`
Key string `json:"key"`
APIBase string `json:"api_base"` // 易支付站点根地址,代码自动拼 /api/pay/create
Methods []string `json:"methods"` // wxpay, alipay
MinAmount float64 `json:"min_amount"`
PointsRatio int `json:"points_ratio"` // 积分 per 元
}
func (s *PaymentService) get(ctx context.Context, key string) string {
v, _ := s.settings.GetValue(ctx, key)
return v
}
func (s *PaymentService) Settings(ctx context.Context) PaySettings {
api := strings.TrimRight(strings.TrimSpace(s.get(ctx, "pay.api_base")), "/")
if api == "" {
api = "https://pay.v8jisu.cn/api/pay"
}
ratio, _ := strconv.Atoi(s.get(ctx, "pay.points_ratio"))
if ratio <= 0 {
ratio = 100
}
minAmt, _ := strconv.ParseFloat(s.get(ctx, "pay.min_amount"), 64)
var methods []string
for _, m := range strings.Split(s.get(ctx, "pay.methods"), ",") {
if m = strings.TrimSpace(m); m != "" {
methods = append(methods, m)
}
}
if len(methods) == 0 {
methods = []string{"wxpay", "alipay"}
}
return PaySettings{
Enabled: s.get(ctx, "pay.enabled") == "true",
PID: s.get(ctx, "pay.pid"),
Key: s.get(ctx, "pay.key"),
APIBase: api,
Methods: methods,
MinAmount: minAmt,
PointsRatio: ratio,
}
}
// Public returns the recharge config for the user UI (no merchant secrets).
func (s *PaymentService) Public(ctx context.Context) map[string]any {
c := s.Settings(ctx)
return map[string]any{
"enabled": c.Enabled,
"methods": c.Methods,
"min_amount": c.MinAmount,
"points_ratio": c.PointsRatio,
}
}
func (s *PaymentService) SaveSettings(ctx context.Context, in PaySettings) error {
api := strings.TrimRight(strings.TrimSpace(in.APIBase), "/")
pid := strings.TrimSpace(in.PID)
key := strings.TrimSpace(in.Key)
if api == "" {
return errors.New("支付地址不能为空")
}
if pid == "" {
return errors.New("商户ID不能为空")
}
if key == "" {
return errors.New("商户密钥不能为空")
}
if in.PointsRatio <= 0 {
in.PointsRatio = 100
}
if in.MinAmount < 0 {
in.MinAmount = 0
}
return s.settings.UpsertValues(ctx, map[string]string{
"pay.enabled": strconv.FormatBool(in.Enabled),
"pay.pid": pid,
"pay.key": key,
"pay.api_base": api,
"pay.methods": strings.Join(in.Methods, ","),
"pay.min_amount": strconv.FormatFloat(in.MinAmount, 'f', -1, 64),
"pay.points_ratio": strconv.Itoa(in.PointsRatio),
})
}
func (c PaySettings) allows(method string) bool {
for _, m := range c.Methods {
if m == method {
return true
}
}
return false
}
func (s *PaymentService) client(c PaySettings) *epay.Config {
return &epay.Config{APIBase: c.APIBase, PID: c.PID, Key: c.Key}
}
// CreateOrder validates the request, persists a pending order, and places the
// 易支付 order. notifyBase is the public site origin (e.g. https://vividai.run).
func (s *PaymentService) CreateOrder(ctx context.Context, user *model.User, amount float64, method, notifyBase, clientIP string) (*model.Order, error) {
cfg := s.Settings(ctx)
if !cfg.Enabled {
return nil, ErrPayDisabled
}
if cfg.PID == "" || cfg.Key == "" {
return nil, ErrPayNotConfig
}
if !cfg.allows(method) {
return nil, ErrPayMethod
}
amount = math.Round(amount*100) / 100
if amount <= 0 || amount < cfg.MinAmount {
return nil, ErrPayAmount
}
points := int(math.Round(amount * float64(cfg.PointsRatio)))
now := time.Now()
order := &model.Order{
ID: "P" + strconv.FormatInt(now.Unix(), 10) + randomUpper(6),
UserID: user.ID,
Amount: amount,
Points: points,
PayType: method,
Status: "pending",
ExpiresAt: now.Add(orderTTL),
}
if err := s.orders.Create(ctx, order); err != nil {
return nil, err
}
res, err := s.client(cfg).Create(ctx, epay.CreateRequest{
OutTradeNo: order.ID,
Type: method,
Name: fmt.Sprintf("积分充值 %d", points),
Money: strconv.FormatFloat(amount, 'f', 2, 64),
NotifyURL: strings.TrimRight(notifyBase, "/") + "/admin/api/pay/notify",
ClientIP: clientIP,
})
if err != nil {
_ = s.orders.Update(ctx, order.ID, map[string]any{"status": "cancelled"})
return nil, err
}
order.TradeNo = res.TradeNo
order.PayInfo = res.PayInfo
order.PayInfoType = res.PayType
_ = s.orders.Update(ctx, order.ID, map[string]any{
"trade_no": res.TradeNo, "pay_info": res.PayInfo, "pay_info_type": res.PayType,
})
return order, nil
}
// Continue re-creates payment for an unpaid order (clones its amount/method into
// a fresh order — keeps the old one as history). Used by 订单管理 "继续支付".
func (s *PaymentService) Continue(ctx context.Context, user *model.User, orderID, notifyBase, clientIP string) (*model.Order, error) {
old, err := s.orders.Get(ctx, orderID)
if err != nil || old == nil || old.UserID != user.ID {
return nil, ErrOrderNotFound
}
if old.Status == "paid" {
return nil, ErrOrderPaid
}
// Reuse a still-valid pending order — return its saved qrcode/payurl directly,
// no new upstream order (and the countdown keeps its original expiry).
if old.Status == "pending" && old.PayInfo != "" && time.Now().Before(old.ExpiresAt) {
return old, nil
}
// Expired / cancelled (or never got a pay_info) → place a fresh order.
return s.CreateOrder(ctx, user, old.Amount, old.PayType, notifyBase, clientIP)
}
// HandleNotify processes an 易支付 async callback. Returns true when this call is
// the one that credited the user (first successful notify for the order).
func (s *PaymentService) HandleNotify(ctx context.Context, params map[string]string) (bool, error) {
cfg := s.Settings(ctx)
if cfg.Key == "" {
return false, ErrPayNotConfig
}
if !s.client(cfg).VerifyNotify(params) {
return false, errors.New("bad sign")
}
if params["trade_status"] != "TRADE_SUCCESS" {
return false, nil
}
orderID := params["out_trade_no"]
order, err := s.orders.Get(ctx, orderID)
if err != nil || order == nil {
return false, ErrOrderNotFound
}
credited, err := s.orders.MarkPaid(ctx, order.ID, params["trade_no"], time.Now())
if err != nil {
return false, err
}
if !credited {
return false, nil // duplicate / already handled
}
// Credit points + bump the user's cumulative recharge total, atomically.
_, err = s.users.Update(ctx, order.UserID, map[string]any{
"credits": gorm.Expr("credits + ?", order.Points),
"recharge_total": gorm.Expr("recharge_total + ?", order.Amount),
})
return err == nil, err
}
func (s *PaymentService) GetForUser(ctx context.Context, userID, orderID string) (*model.Order, error) {
o, err := s.orders.Get(ctx, orderID)
if err != nil || o == nil || o.UserID != userID {
return nil, ErrOrderNotFound
}
return o, nil
}
func (s *PaymentService) ListByUser(ctx context.Context, userID, status string, limit, offset int) ([]model.Order, int64, error) {
return s.orders.ListByUser(ctx, userID, status, limit, offset)
}
func (s *PaymentService) ListAll(ctx context.Context, status string, limit, offset int) ([]model.Order, int64, error) {
return s.orders.List(ctx, status, limit, offset)
}
// UserNames maps user id → display name (name, else email, else id) so the admin
// 订单管理 list can show 用户名.
func (s *PaymentService) UserNames(ctx context.Context) map[string]string {
out := map[string]string{}
users, err := s.users.List(ctx)
if err != nil {
return out
}
for _, u := range users {
n := u.Name
if n == "" {
n = u.Email
}
if n == "" {
n = u.ID
}
out[u.ID] = n
}
return out
}
// ExpireStale cancels pending orders past their TTL (called by the maintenance
// sweep). Returns how many were cancelled.
func (s *PaymentService) ExpireStale(ctx context.Context) (int64, error) {
return s.orders.ExpirePending(ctx, time.Now())
}
+33 -8
View File
@@ -722,6 +722,8 @@ func (s *V1Service) runVideoJob(ctx context.Context, principal *APIPrincipal, in
defer s.cleanupReferenceImages(ctx, eventID, refFiles)
startedAt := time.Now()
// No-store: capture only the UPSTREAM video URL. /content streams it on demand
// (grok URLs are auth-gated → fetched with the generating account's token).
var videoURL string
var execErr error
switch s.effectiveProvider(genCtx, modelItem) {
@@ -748,7 +750,7 @@ func (s *V1Service) runVideoJob(ctx context.Context, principal *APIPrincipal, in
_ = s.events.UpdateStatus(ctx, eventID, "failed", "upstream returned no video url", 0)
return
}
// Store the upstream URL as the event's "file"; /content proxies it.
// Store the upstream URL as the event's "file"; /content fetches it on demand.
if err := s.events.MarkVideoReady(ctx, eventID, videoURL, int(time.Since(startedAt).Milliseconds())); err != nil {
return
}
@@ -787,6 +789,22 @@ func (s *V1Service) OpenVideoContent(ctx context.Context, principal *APIPrincipa
if ev.Status != "success" || strings.TrimSpace(ev.File) == "" {
return nil, "", ErrVideoNotReady
}
// grok asset URLs (assets.grok.com) are auth-gated — a plain GET 403s. Stream
// them through the SAME account that generated the clip, using its token. If
// that account is gone (grok pools churn often), the clip is unrecoverable.
if ev.Provider == "grok" && s.grok != nil {
if s.settings != nil {
if proxy, perr := s.settings.GetValue(ctx, "proxy.url"); perr == nil {
s.grok.SetProxy(proxy)
}
}
acct, _ := s.tokens.Get(ctx, "grok", ev.AccountID)
if acct == nil || strings.TrimSpace(acct.Value) == "" {
return nil, "", fmt.Errorf("%w: grok account no longer available for this video", ErrProviderTemporary)
}
return s.grok.OpenAsset(ctx, acct.Value, ev.File)
}
// Other providers return publicly-fetchable URLs — proxy directly.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ev.File, nil)
if err != nil {
return nil, "", err
@@ -1251,9 +1269,9 @@ const maxTempDeadAccounts = 3
// • tempAsDead=false (default): retry the SAME account up to
// maxSameAccountAttempts times (not counted); if still failing, STOP
// (no fan-out — an upstream-wide blip fails identically everywhere).
// • tempAsDead=true (adobe): treat the temporary error as a DEAD account —
// mark it like a 401 and fail over to the next account, capped at
// maxTempDeadAccounts accounts so a pool-wide blip can't kill everything.
// • tempAsDead=true (adobe): BAN the account (mark dead/disabled) and fail
// over to the next account, capped at maxTempDeadAccounts accounts so a
// pool-wide blip can't kill everything. Dead accounts don't auto-recover.
// - 参数错 / request-level (anything else) → return immediately, no retry, no
// account penalty (the account isn't at fault).
//
@@ -1356,10 +1374,17 @@ func (s *V1Service) tryAccount(ctx context.Context, eventID, pool string, token
if isTemp {
if tempAsDead {
// Ops policy (adobe): a temporary upstream error ("system under
// load" etc.) means this account is effectively dead — mark it
// like a 401 and fail over to the next account. The pool driver
// caps how many accounts this is allowed to burn.
s.markTokenFailure(ctx, pool, token, kind, true, false)
// load" etc.) BANS this account — mark it dead/disabled and fail
// over to the next account. The pool driver caps how many accounts
// this is allowed to burn per request (maxTempDeadAccounts). Note:
// dead accounts do NOT auto-recover — they need a manual re-enable.
_, _ = s.tokens.Update(ctx, pool, token.ID, map[string]any{
"status": "disabled",
"dead": true,
"last_used_at": time.Now(),
"fail_total": gorm.Expr("fail_total + 1"),
"fails": gorm.Expr("fails + 1"),
})
return nil, err, true, true
}
tempAttempts++