feat: 画图台并发重构 + 品牌定制 + 用户备注 + provider/UI 多项修复
画图台(并发出图):
- 不再锁定 UI:点「生成」开独立任务,可连续多次并发
- 结果网格一行5个、最多10张,进行中/成功/失败状态回显,刷新保留进行中
- 生图张数 1/2/3/4,各自独立计费出卡
- 点图=参考图(单张替换/多张替换末位);首尾帧模型点视频=抓末帧设为首帧,否则放大
- /logs 新增 statuses=pending,success 服务端过滤(status IN 专用 SQL)
品牌定制(设置→网站):
- 自定义 Logo 图片 + 子标题(公开页头部 + 管理侧栏)
- 邮件验证码标题改用站点名:{title} 邮箱验证码
提示词复制:
- 去掉复制按钮,点提示词文字即复制(预览/后台日志/图片管理/画图记录),统一弹「指令已复制」
- 新增 utils/clipboard.js:execCommand 回退,非安全上下文(http/IP)也能复制
用户管理:列表加「备注」列,新建/编辑可填改备注(默认空)
provider 修复:
- grok 401 正确判死封号(markTokenFailure 漏了 grok 池)
- grok 视频支持 15s
- custom 上游报错去敏感(抹掉上游 URL/IP,改英文短描述)
- custom 去掉额度耗尽锁定:429/欠费当临时错误,账号保持 active
UI/其它:
- 展示位弹窗浅色主题适配(tab 选中高亮、输入框边框)— 主题变量 + 中心补丁
- 自定义模型:时长可填任意秒数 + 15s 预设
- 首页设置/卡密弹窗去固定高度与滚动条
- 顶部菜单「记录」→「图片」
- 下线 Flow provider(代码移除)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,8 @@ import (
|
||||
func seedDefaults(ctx context.Context, db *gorm.DB) error {
|
||||
defaults := []model.SiteSetting{
|
||||
{Key: "site.title", Value: "Vivid"},
|
||||
{Key: "site.logo", Value: ""},
|
||||
{Key: "site.subtitle", Value: ""},
|
||||
{Key: "contact.qq", Value: "1114639355"},
|
||||
{Key: "contact.qq_link", Value: "https://qm.qq.com/q/ItgCcNA7ac"},
|
||||
{Key: "contact.qq_group", Value: "1106849765"},
|
||||
@@ -47,5 +49,35 @@ func seedDefaults(ctx context.Context, db *gorm.DB) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// One-time backfill of the persistent per-model generation counter from
|
||||
// historical success logs, so the admin "次数" keeps its running total when we
|
||||
// switch it off the (retention-pruned) event_log. Only touches models still at
|
||||
// 0, so it never double-counts after the first run; increments take over next.
|
||||
if err := db.WithContext(ctx).Exec(
|
||||
`UPDATE model_configs m SET generation_count = COALESCE(
|
||||
(SELECT COUNT(*) FROM event_logs e WHERE e.model = m.id AND e.status = 'success'), 0)
|
||||
WHERE m.generation_count = 0`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Same one-time backfill for the per-user generation counter.
|
||||
if err := db.WithContext(ctx).Exec(
|
||||
`UPDATE users u SET generation_count = COALESCE(
|
||||
(SELECT COUNT(*) FROM event_logs e WHERE e.user_id = u.id AND e.status = 'success'), 0)
|
||||
WHERE u.generation_count = 0`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Seed the dashboard lifetime counters from logs ONCE (only when empty), so the
|
||||
// all-time cards start from real history then track forward via the hooks.
|
||||
var counterRows int64
|
||||
if err := db.WithContext(ctx).Model(&model.StatCounter{}).Count(&counterRows).Error; err == nil && counterRows == 0 {
|
||||
_ = db.WithContext(ctx).Exec(`INSERT INTO stat_counters (key, value, updated_at)
|
||||
SELECT 'total', COUNT(*), now() FROM event_logs
|
||||
UNION ALL SELECT 'success', COUNT(*) FILTER (WHERE status='success'), now() FROM event_logs
|
||||
UNION ALL SELECT 'failed', COUNT(*) FILTER (WHERE status='failed'), now() FROM event_logs
|
||||
UNION ALL SELECT 'image', COUNT(*) FILTER (WHERE kind='image'), now() FROM event_logs
|
||||
UNION ALL SELECT 'video', COUNT(*) FILTER (WHERE kind='video'), now() FROM event_logs
|
||||
UNION ALL SELECT 'api', COUNT(*) FILTER (WHERE source='v1'), now() FROM event_logs
|
||||
ON CONFLICT (key) DO NOTHING`).Error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -26,16 +26,11 @@ func (h *AdminReadHandler) Users(c *gin.Context) {
|
||||
}
|
||||
|
||||
out := make([]gin.H, 0, len(users))
|
||||
generationCounts := map[string]int64{}
|
||||
if raw, ok := stats["generation_counts"].(map[string]int64); ok {
|
||||
generationCounts = raw
|
||||
}
|
||||
for _, user := range users {
|
||||
row := userPublic(user)
|
||||
row["generation_count"] = generationCounts[user.ID]
|
||||
row["generation_count"] = user.GenerationCount
|
||||
out = append(out, row)
|
||||
}
|
||||
delete(stats, "generation_counts")
|
||||
c.JSON(http.StatusOK, gin.H{"data": out, "stats": stats})
|
||||
}
|
||||
|
||||
@@ -61,7 +56,7 @@ func (h *AdminReadHandler) Logs(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
items, total, stats, err := h.admin.Logs(c.Request.Context(), limit, offset, kind, status, since, "", "", c.Query("source"), false)
|
||||
items, total, stats, err := h.admin.Logs(c.Request.Context(), limit, offset, kind, status, nil, since, "", "", c.Query("source"), false)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load logs"})
|
||||
return
|
||||
|
||||
@@ -21,5 +21,11 @@ func (h *SiteHandler) Public(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load site"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"title": title, "contact": h.site.Contact(c.Request.Context())})
|
||||
ctx := c.Request.Context()
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"title": title,
|
||||
"logo": h.site.Logo(ctx),
|
||||
"subtitle": h.site.Subtitle(ctx),
|
||||
"contact": h.site.Contact(ctx),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -17,18 +17,27 @@ func NewSiteSettingsHandler(site *service.SiteService) *SiteSettingsHandler {
|
||||
}
|
||||
|
||||
func (h *SiteSettingsHandler) Get(c *gin.Context) {
|
||||
title, err := h.site.Title(c.Request.Context())
|
||||
ctx := c.Request.Context()
|
||||
title, err := h.site.Title(ctx)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load site settings"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"title": title, "contact": h.site.Contact(c.Request.Context())})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"title": title,
|
||||
"logo": h.site.Logo(ctx),
|
||||
"subtitle": h.site.Subtitle(ctx),
|
||||
"contact": h.site.Contact(ctx),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SiteSettingsHandler) Put(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
Contact service.Contact `json:"contact"`
|
||||
Title string `json:"title"`
|
||||
Logo string `json:"logo"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
Contact service.Contact `json:"contact"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "invalid request body"})
|
||||
@@ -39,14 +48,21 @@ func (h *SiteSettingsHandler) Put(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "网页主标题不能为空"})
|
||||
return
|
||||
}
|
||||
updated, err := h.site.SetTitle(c.Request.Context(), title)
|
||||
updated, err := h.site.SetTitle(ctx, title)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save site settings"})
|
||||
return
|
||||
}
|
||||
if err := h.site.SetContact(c.Request.Context(), body.Contact); err != nil {
|
||||
if err := h.site.SetBranding(ctx, body.Logo, body.Subtitle); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save branding"})
|
||||
return
|
||||
}
|
||||
if err := h.site.SetContact(ctx, body.Contact); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to save contact info"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true, "data": gin.H{"title": updated, "contact": h.site.Contact(c.Request.Context())}})
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true, "data": gin.H{
|
||||
"title": updated, "logo": h.site.Logo(ctx), "subtitle": h.site.Subtitle(ctx),
|
||||
"contact": h.site.Contact(ctx),
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"backend/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -176,6 +177,16 @@ func (h *UserGenerationHandler) Logs(c *gin.Context) {
|
||||
offset := parseInt(c.Query("offset"), 0)
|
||||
kind := c.Query("kind")
|
||||
status := c.Query("status")
|
||||
// statuses=pending,success → status IN (...). Used by the 画图台 grid so it can
|
||||
// fetch exactly the rows it shows (进行中 + 成功) in one query, server-side.
|
||||
var statuses []string
|
||||
if s := strings.TrimSpace(c.Query("statuses")); s != "" {
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
statuses = append(statuses, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Secure-by-default: always scope to the caller's OWN records. This endpoint
|
||||
// serves the front-end 日志 / 创作记录 pages, so an admin viewing their personal
|
||||
// records must NOT see other users' work. Only an admin who explicitly opts
|
||||
@@ -195,7 +206,7 @@ func (h *UserGenerationHandler) Logs(c *gin.Context) {
|
||||
// rows with real media (success + stored file), not failed/pending events.
|
||||
hasFile := c.Query("has_file") == "1" || c.Query("has_file") == "true"
|
||||
|
||||
items, total, stats, err := h.admin.Logs(c.Request.Context(), limit, offset, kind, status, nil, userID, excludeSource, source, hasFile)
|
||||
items, total, stats, err := h.admin.Logs(c.Request.Context(), limit, offset, kind, status, statuses, nil, userID, excludeSource, source, hasFile)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "failed to load logs"})
|
||||
return
|
||||
@@ -430,7 +441,7 @@ func (h *UserGenerationHandler) catalogEntries(c *gin.Context) ([]gin.H, error)
|
||||
"type": "video",
|
||||
"ratios": []string{"2:3", "3:2", "1:1", "9:16", "16:9"},
|
||||
"resolutions": []string{"720p"},
|
||||
"durations": []string{"6s", "10s"},
|
||||
"durations": []string{"6s", "10s", "15s"},
|
||||
"max_reference_images": 6,
|
||||
"reference_mode": "asset",
|
||||
"description": "Grok Imagine video (文/图生视频)",
|
||||
|
||||
@@ -21,6 +21,7 @@ type User struct {
|
||||
InviteRewardAt *time.Time
|
||||
CheckinLast string `gorm:"size:32"`
|
||||
CheckinStreak int `gorm:"not null;default:0"`
|
||||
GenerationCount int64 `gorm:"not null;default:0"`
|
||||
LastLoginAt *time.Time
|
||||
LastLoginIP string `gorm:"size:128"`
|
||||
CreatedAt time.Time
|
||||
@@ -111,6 +112,10 @@ type ModelConfig struct {
|
||||
// weight floats to the top (matches ShowcaseItem.Weight semantics). Ties fall
|
||||
// back to created_at desc. Default 0.
|
||||
Weight int `gorm:"not null;default:0;index"`
|
||||
// GenerationCount is a persistent success counter, incremented once per
|
||||
// successful generation. Independent of the event_log (which is subject to
|
||||
// retention / manual clearing), so the admin "次数" is a true running total.
|
||||
GenerationCount int64 `gorm:"not null;default:0"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -197,5 +202,15 @@ func AutoMigrateModels() []any {
|
||||
&TokenAccount{},
|
||||
&RefreshProfile{},
|
||||
&SiteSetting{},
|
||||
&StatCounter{},
|
||||
}
|
||||
}
|
||||
|
||||
// StatCounter is a persistent monotonic counter (key → value), independent of the
|
||||
// event_log (which is retention-pruned / clearable). Used for the dashboard
|
||||
// cumulative cards (total/success/failed/image/video/api) so they never reset.
|
||||
type StatCounter struct {
|
||||
Key string `gorm:"primaryKey;size:64"`
|
||||
Value int64 `gorm:"not null;default:0"`
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -29,6 +30,32 @@ type Client struct{}
|
||||
|
||||
func NewClient() *Client { return &Client{} }
|
||||
|
||||
// sanitizeErr strips the upstream URL/host from a network error so a user's
|
||||
// private upstream URL never leaks into the event log / API response.
|
||||
func sanitizeErr(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
s := err.Error()
|
||||
switch {
|
||||
case strings.Contains(s, "context deadline exceeded"), strings.Contains(s, "Client.Timeout"), strings.Contains(s, "timeout"):
|
||||
return "request timeout"
|
||||
case strings.Contains(s, "connection refused"):
|
||||
return "connection refused"
|
||||
case strings.Contains(s, "no such host"), strings.Contains(s, "dial tcp"), strings.Contains(s, "lookup "):
|
||||
return "cannot reach upstream"
|
||||
case strings.Contains(s, "tls"), strings.Contains(s, "TLS"), strings.Contains(s, "certificate"):
|
||||
return "TLS error"
|
||||
case strings.Contains(s, "EOF"), strings.Contains(s, "reset by peer"), strings.Contains(s, "broken pipe"):
|
||||
return "connection reset"
|
||||
}
|
||||
var ue *url.Error
|
||||
if errors.As(err, &ue) {
|
||||
return strings.ToLower(ue.Op) + " upstream failed"
|
||||
}
|
||||
return "upstream request failed"
|
||||
}
|
||||
|
||||
func httpClient() *http.Client { return &http.Client{Timeout: 10 * time.Minute} }
|
||||
|
||||
// GenerateImage calls the upstream OpenAI image API. With reference images it
|
||||
@@ -82,7 +109,7 @@ func (c *Client) GenerateImage(ctx context.Context, baseURL, apiKey, model, prom
|
||||
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrTemporaryUpstream, err)
|
||||
return nil, fmt.Errorf("%w: %s", ErrTemporaryUpstream, sanitizeErr(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
@@ -145,7 +172,7 @@ func (c *Client) GenerateVideo(ctx context.Context, baseURL, apiKey, model, prom
|
||||
case "failed", "error", "canceled", "cancelled":
|
||||
reason := stringValue(job["error"])
|
||||
if isCreditError(reason) {
|
||||
return nil, "", fmt.Errorf("%w: %s", ErrQuotaExhausted, clip([]byte(reason), 160))
|
||||
return nil, "", fmt.Errorf("%w: %s", ErrTemporaryUpstream, clip([]byte(reason), 160))
|
||||
}
|
||||
return nil, "", fmt.Errorf("custom: video %s", clip([]byte(reason), 160))
|
||||
}
|
||||
@@ -171,7 +198,7 @@ func (c *Client) doJSON(ctx context.Context, method, url, apiKey string, body []
|
||||
}
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrTemporaryUpstream, err)
|
||||
return nil, fmt.Errorf("%w: %s", ErrTemporaryUpstream, sanitizeErr(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
@@ -194,7 +221,7 @@ func (c *Client) download(ctx context.Context, url, apiKey string) ([]byte, erro
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrTemporaryUpstream, err)
|
||||
return nil, fmt.Errorf("%w: %s", ErrTemporaryUpstream, sanitizeErr(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
@@ -234,7 +261,7 @@ func imageBytesFromResponse(ctx context.Context, body []byte) ([]byte, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, d.URL, nil)
|
||||
resp, err := httpClient().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrTemporaryUpstream, err)
|
||||
return nil, fmt.Errorf("%w: %s", ErrTemporaryUpstream, sanitizeErr(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return io.ReadAll(resp.Body)
|
||||
@@ -249,12 +276,14 @@ func mapStatus(status int, body []byte) error {
|
||||
case status == 401 || status == 403:
|
||||
return fmt.Errorf("%w: %d %s", ErrAuth, status, clip(body, 160))
|
||||
case status == 429:
|
||||
return fmt.Errorf("%w: 429 %s", ErrQuotaExhausted, clip(body, 160))
|
||||
// Custom upstreams have NO "quota exhausted" lock — a 429 is just rate
|
||||
// limiting, treated as a temporary error (fail over, account stays active).
|
||||
return fmt.Errorf("%w: 429 %s", ErrTemporaryUpstream, clip(body, 160))
|
||||
case status >= 500:
|
||||
return fmt.Errorf("%w: %d %s", ErrTemporaryUpstream, status, clip(body, 160))
|
||||
default:
|
||||
if isCreditError(string(body)) {
|
||||
return fmt.Errorf("%w: %s", ErrQuotaExhausted, clip(body, 160))
|
||||
return fmt.Errorf("%w: %s", ErrTemporaryUpstream, clip(body, 160))
|
||||
}
|
||||
return fmt.Errorf("custom: %d %s", status, clip(body, 160))
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func (c *Client) GenerateVideo(ctx context.Context, token, prompt, aspectRatio,
|
||||
if strings.TrimSpace(resolution) == "" {
|
||||
resolution = "720p"
|
||||
}
|
||||
if seconds != 6 && seconds != 10 {
|
||||
if seconds != 6 && seconds != 10 && seconds != 15 {
|
||||
seconds = 10
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ type EventListFilter struct {
|
||||
Limit int
|
||||
Offset int
|
||||
Kind string
|
||||
Status string
|
||||
Status string // single status (status = ?)
|
||||
Statuses []string // multiple statuses (status IN (?)) — used by the 画图台 grid
|
||||
Since *time.Time
|
||||
UserID string
|
||||
ExcludeSource string // when set, omit rows with this source (e.g. hide API-key "v1" usage from the customer logs page)
|
||||
@@ -47,6 +48,9 @@ func (r *EventRepository) List(ctx context.Context, filter EventListFilter) ([]m
|
||||
if filter.Status != "" {
|
||||
q = q.Where("status = ?", filter.Status)
|
||||
}
|
||||
if len(filter.Statuses) > 0 {
|
||||
q = q.Where("status IN ?", filter.Statuses)
|
||||
}
|
||||
if filter.Since != nil {
|
||||
q = q.Where("ts > ?", *filter.Since)
|
||||
}
|
||||
@@ -443,7 +447,49 @@ func (r *EventRepository) PurgeStale(ctx context.Context, maxAge time.Duration)
|
||||
}
|
||||
|
||||
func (r *EventRepository) Create(ctx context.Context, item *model.EventLog) error {
|
||||
return r.db.WithContext(ctx).Create(item).Error
|
||||
if err := r.db.WithContext(ctx).Create(item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Persistent cumulative counters (survive log retention/clearing): every
|
||||
// created event bumps total + its kind + (api source).
|
||||
deltas := map[string]int64{"total": 1}
|
||||
if item.Kind == "video" {
|
||||
deltas["video"] = 1
|
||||
} else if item.Kind == "image" {
|
||||
deltas["image"] = 1
|
||||
}
|
||||
if item.Source == "v1" {
|
||||
deltas["api"] = 1
|
||||
}
|
||||
r.incrCounters(ctx, deltas)
|
||||
return nil
|
||||
}
|
||||
|
||||
// incrCounters upserts monotonic counters (stat_counters). Best-effort: a counter
|
||||
// failure must never fail the generation, so errors are swallowed.
|
||||
func (r *EventRepository) incrCounters(ctx context.Context, deltas map[string]int64) {
|
||||
for k, n := range deltas {
|
||||
if n == 0 {
|
||||
continue
|
||||
}
|
||||
_ = r.db.WithContext(ctx).Exec(
|
||||
`INSERT INTO stat_counters (key, value, updated_at) VALUES (?, ?, now())
|
||||
ON CONFLICT (key) DO UPDATE SET value = stat_counters.value + EXCLUDED.value, updated_at = now()`,
|
||||
k, n).Error
|
||||
}
|
||||
}
|
||||
|
||||
// Counters returns all persistent counters as key→value.
|
||||
func (r *EventRepository) Counters(ctx context.Context) (map[string]int64, error) {
|
||||
var rows []model.StatCounter
|
||||
if err := r.db.WithContext(ctx).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]int64, len(rows))
|
||||
for _, x := range rows {
|
||||
out[x.Key] = x.Value
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetByID fetches a single event (nil, nil when not found). Used by the async
|
||||
@@ -462,16 +508,22 @@ func (r *EventRepository) GetByID(ctx context.Context, id string) (*model.EventL
|
||||
// MarkVideoReady completes an async video job: status=success, file=upstream URL
|
||||
// (proxied on /content — never persisted), elapsed.
|
||||
func (r *EventRepository) MarkVideoReady(ctx context.Context, eventID, fileURL string, elapsedMS int) error {
|
||||
return r.db.WithContext(ctx).
|
||||
// Guard on a real transition (status <> success) so the success counter is
|
||||
// incremented exactly once even if this fires twice / concurrently.
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&model.EventLog{}).
|
||||
Where("id = ?", eventID).
|
||||
Where("id = ? AND status <> ?", eventID, "success").
|
||||
Updates(map[string]any{
|
||||
"status": "success",
|
||||
"file": fileURL,
|
||||
"error": "",
|
||||
"elapsed_ms": elapsedMS,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
})
|
||||
if res.Error == nil && res.RowsAffected > 0 {
|
||||
r.incrCounters(ctx, map[string]int64{"success": 1})
|
||||
}
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func (r *EventRepository) UpdateStatus(ctx context.Context, eventID, status, errMsg string, elapsedMS int) error {
|
||||
@@ -488,10 +540,20 @@ func (r *EventRepository) UpdateStatus(ctx context.Context, eventID, status, err
|
||||
// "成功 + abandoned" at once.
|
||||
patch["error"] = ""
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
// Guard on a real transition so the success/failed counters increment exactly
|
||||
// once per event even under a duplicate/concurrent terminal status update.
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&model.EventLog{}).
|
||||
Where("id = ?", eventID).
|
||||
Updates(patch).Error
|
||||
Where("id = ? AND status <> ?", eventID, status).
|
||||
Updates(patch)
|
||||
if res.Error == nil && res.RowsAffected > 0 {
|
||||
if status == "success" {
|
||||
r.incrCounters(ctx, map[string]int64{"success": 1})
|
||||
} else if status == "failed" {
|
||||
r.incrCounters(ctx, map[string]int64{"failed": 1})
|
||||
}
|
||||
}
|
||||
return res.Error
|
||||
}
|
||||
|
||||
// MarkRefunded atomically claims the right to refund this event exactly once:
|
||||
|
||||
@@ -18,6 +18,14 @@ func NewModelRepository(db *gorm.DB) *ModelRepository {
|
||||
return &ModelRepository{db: db}
|
||||
}
|
||||
|
||||
// IncrementGenerationCount bumps a model's persistent success counter by 1.
|
||||
// Best-effort: a missing model id is a no-op (0 rows affected, no error).
|
||||
func (r *ModelRepository) IncrementGenerationCount(ctx context.Context, modelID string) error {
|
||||
return r.db.WithContext(ctx).Model(&model.ModelConfig{}).
|
||||
Where("id = ?", modelID).
|
||||
UpdateColumn("generation_count", gorm.Expr("generation_count + 1")).Error
|
||||
}
|
||||
|
||||
func (r *ModelRepository) List(ctx context.Context) ([]model.ModelConfig, error) {
|
||||
var items []model.ModelConfig
|
||||
// Higher weight floats to the top of the dropdown / admin list; ties fall
|
||||
|
||||
@@ -87,6 +87,16 @@ func (r *UserRepository) GetByInviteCode(ctx context.Context, code string) (*mod
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// IncrementGenerationCount bumps a user's persistent success counter by 1.
|
||||
func (r *UserRepository) IncrementGenerationCount(ctx context.Context, userID string) error {
|
||||
if userID == "" {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("id = ?", userID).
|
||||
UpdateColumn("generation_count", gorm.Expr("generation_count + 1")).Error
|
||||
}
|
||||
|
||||
func (r *UserRepository) List(ctx context.Context) ([]model.User, error) {
|
||||
var users []model.User
|
||||
if err := r.db.WithContext(ctx).Preload("APIKeys").Order("created_at desc").Find(&users).Error; err != nil {
|
||||
|
||||
@@ -41,19 +41,12 @@ func (s *AdminReadService) Users(ctx context.Context) ([]model.User, map[string]
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
counts, err := s.events.UserSuccessCounts(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range users {
|
||||
meta := users[i].Notes
|
||||
_ = meta
|
||||
}
|
||||
stats, err := s.users.Stats(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
stats["generation_counts"] = counts
|
||||
// Per-user generation count now comes from the persistent users.generation_count
|
||||
// column (set in the handler from each user object), not a log COUNT.
|
||||
return users, stats, nil
|
||||
}
|
||||
|
||||
@@ -66,10 +59,6 @@ func (s *AdminReadService) ModelsView(ctx context.Context) ([]map[string]any, er
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts, err := s.events.ModelSuccessCounts(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]map[string]any, 0, len(items))
|
||||
for _, item := range items {
|
||||
out = append(out, map[string]any{
|
||||
@@ -89,7 +78,7 @@ func (s *AdminReadService) ModelsView(ctx context.Context) ([]map[string]any, er
|
||||
"max_reference_images": item.MaxReferenceImages,
|
||||
"reference_mode": item.ReferenceMode,
|
||||
"weight": item.Weight,
|
||||
"generation_count": counts[item.ID],
|
||||
"generation_count": item.GenerationCount,
|
||||
"created_at": item.CreatedAt,
|
||||
"updated_at": item.UpdatedAt,
|
||||
})
|
||||
@@ -97,12 +86,13 @@ func (s *AdminReadService) ModelsView(ctx context.Context) ([]map[string]any, er
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *AdminReadService) Logs(ctx context.Context, limit, offset int, kind, status string, since *time.Time, userID, excludeSource, source string, hasFile bool) ([]model.EventLog, int64, *repo.EventStats, error) {
|
||||
func (s *AdminReadService) Logs(ctx context.Context, limit, offset int, kind, status string, statuses []string, since *time.Time, userID, excludeSource, source string, hasFile bool) ([]model.EventLog, int64, *repo.EventStats, error) {
|
||||
items, total, err := s.events.List(ctx, repo.EventListFilter{
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
Kind: kind,
|
||||
Status: status,
|
||||
Statuses: statuses,
|
||||
Since: since,
|
||||
UserID: userID,
|
||||
ExcludeSource: excludeSource,
|
||||
@@ -173,7 +163,7 @@ func (s *AdminReadService) Stats(ctx context.Context) (map[string]any, error) {
|
||||
func (s *AdminReadService) Dashboard(ctx context.Context) (map[string]any, error) {
|
||||
now := time.Now()
|
||||
dayCut := now.Add(-24 * time.Hour)
|
||||
weekCut := now.Add(-7 * 24 * time.Hour)
|
||||
weekCut := now.Add(-3 * 24 * time.Hour) // "week" key = last 3 days (per admin request)
|
||||
|
||||
day, err := s.events.WindowStats(ctx, dayCut)
|
||||
if err != nil {
|
||||
@@ -199,6 +189,12 @@ func (s *AdminReadService) Dashboard(ctx context.Context) (map[string]any, error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// All-time persistent counters (total/success/failed/image/video/api) — these
|
||||
// survive log retention/clearing, unlike the windowed day/week stats.
|
||||
lifetime, err := s.events.Counters(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Per-window top-N analytics so the frontend can toggle 24h / 7d without a
|
||||
// re-fetch (the lists are small — top 6 / top 5).
|
||||
@@ -263,6 +259,7 @@ func (s *AdminReadService) Dashboard(ctx context.Context) (map[string]any, error
|
||||
"dau": dau,
|
||||
"wau": wau,
|
||||
"hourly": hourly,
|
||||
"lifetime": lifetime,
|
||||
"analytics": map[string]any{
|
||||
"day": dayAnalytics,
|
||||
"week": weekAnalytics,
|
||||
|
||||
@@ -358,6 +358,12 @@ func (s *AppSettingsService) loadSMTPConfig(ctx context.Context) (SMTPConfig, er
|
||||
if err != nil {
|
||||
return SMTPConfig{}, err
|
||||
}
|
||||
// The verification-email subject uses the site title, e.g. "<title> 邮箱验证码".
|
||||
title, _ := s.settings.GetValue(ctx, "site.title")
|
||||
title = strings.TrimSpace(title)
|
||||
if title == "" {
|
||||
title = "Vivid"
|
||||
}
|
||||
return SMTPConfig{
|
||||
Host: current.Host,
|
||||
Port: current.Port,
|
||||
@@ -365,6 +371,7 @@ func (s *AppSettingsService) loadSMTPConfig(ctx context.Context) (SMTPConfig, er
|
||||
Password: password,
|
||||
FromAddr: current.FromAddr,
|
||||
UseTLS: current.UseTLS,
|
||||
Subject: title + " 邮箱验证码",
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,28 @@ func (s *SiteService) SetTitle(ctx context.Context, title string) (string, error
|
||||
return title, nil
|
||||
}
|
||||
|
||||
func (s *SiteService) get(ctx context.Context, key string) string {
|
||||
v, _ := s.settings.GetValue(ctx, key)
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
|
||||
// Logo / Subtitle are admin-editable branding shown on the public site.
|
||||
func (s *SiteService) Logo(ctx context.Context) string { return s.get(ctx, "site.logo") }
|
||||
func (s *SiteService) Subtitle(ctx context.Context) string { return s.get(ctx, "site.subtitle") }
|
||||
|
||||
// SetBranding persists logo / subtitle (either may be empty).
|
||||
func (s *SiteService) SetBranding(ctx context.Context, logo, subtitle string) error {
|
||||
for k, v := range map[string]string{
|
||||
"site.logo": strings.TrimSpace(logo),
|
||||
"site.subtitle": strings.TrimSpace(subtitle),
|
||||
} {
|
||||
if err := s.settings.UpsertValue(ctx, k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Contact is the admin-editable "联系我们" info shown in the public 关于 section.
|
||||
type Contact struct {
|
||||
QQ string `json:"qq"`
|
||||
|
||||
@@ -18,6 +18,7 @@ type SMTPConfig struct {
|
||||
Password string
|
||||
FromAddr string
|
||||
UseTLS bool
|
||||
Subject string // verification-code email subject (empty → default)
|
||||
}
|
||||
|
||||
type SMTPService struct{}
|
||||
@@ -35,7 +36,10 @@ func (s *SMTPService) SendCode(ctx context.Context, cfg SMTPConfig, to, code, pu
|
||||
if purpose == "reset" {
|
||||
action = "找回密码"
|
||||
}
|
||||
subject := "Vivid AI 邮箱验证码"
|
||||
subject := strings.TrimSpace(cfg.Subject)
|
||||
if subject == "" {
|
||||
subject = "Vivid AI 邮箱验证码"
|
||||
}
|
||||
body := fmt.Sprintf("你正在进行%s,验证码为:%s\n\n验证码 6 分钟内有效。", action, code)
|
||||
msg := buildSMTPMessage(cfg.FromAddr, to, subject, body)
|
||||
addr := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
|
||||
|
||||
@@ -906,6 +906,7 @@ func (s *TokenService) ImportGrokToken(ctx context.Context, ssoToken, tokenID st
|
||||
return item, nil
|
||||
}
|
||||
|
||||
|
||||
func (s *TokenService) checkPendingGrok(tokenID, ssoToken string) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
|
||||
@@ -495,6 +495,10 @@ func (s *V1Service) prepareImageExecution(ctx context.Context, principal *APIPri
|
||||
if err := s.events.UpdateStatus(ctx, eventID, "success", "", elapsedMS); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = s.models.IncrementGenerationCount(ctx, modelItem.ID)
|
||||
if principal != nil && principal.User != nil {
|
||||
_ = s.users.IncrementGenerationCount(ctx, principal.User.ID)
|
||||
}
|
||||
if charge {
|
||||
_ = s.maybeGrantInviteReward(ctx, principal)
|
||||
}
|
||||
@@ -615,6 +619,10 @@ func (s *V1Service) prepareVideoExecution(ctx context.Context, principal *APIPri
|
||||
if err := s.events.UpdateStatus(ctx, eventID, "success", "", elapsedMS); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = s.models.IncrementGenerationCount(ctx, modelItem.ID)
|
||||
if principal != nil && principal.User != nil {
|
||||
_ = s.users.IncrementGenerationCount(ctx, principal.User.ID)
|
||||
}
|
||||
if charge {
|
||||
_ = s.maybeGrantInviteReward(ctx, principal)
|
||||
}
|
||||
@@ -710,6 +718,10 @@ func (s *V1Service) runVideoJob(ctx context.Context, principal *APIPrincipal, in
|
||||
if err := s.events.MarkVideoReady(ctx, eventID, videoURL, int(time.Since(startedAt).Milliseconds())); err != nil {
|
||||
return
|
||||
}
|
||||
_ = s.models.IncrementGenerationCount(ctx, modelItem.ID)
|
||||
if principal != nil && principal.User != nil {
|
||||
_ = s.users.IncrementGenerationCount(ctx, principal.User.ID)
|
||||
}
|
||||
_ = s.maybeGrantInviteReward(ctx, principal)
|
||||
}
|
||||
|
||||
@@ -2810,7 +2822,7 @@ func (s *V1Service) markTokenFailure(ctx context.Context, pool string, token mod
|
||||
// the cookie. chatgpt/runway/leonardo auth means the stored credential is
|
||||
// dead — a raw JWT (chatgpt/runway) or a cookie whose session no longer
|
||||
// authenticates (leonardo) — there's nothing left to refresh from.
|
||||
if pool == "chatgpt" || pool == "runway" || pool == "leonardo" || pool == "krea" || pool == "imagine" {
|
||||
if pool == "chatgpt" || pool == "runway" || pool == "leonardo" || pool == "krea" || pool == "imagine" || pool == "grok" {
|
||||
patch["status"] = "disabled"
|
||||
patch["dead"] = true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user