Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
123 lines
4.4 KiB
Go
123 lines
4.4 KiB
Go
package repo
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/jackc/pgx/v5"
|
||
"github.com/jackc/pgx/v5/pgconn"
|
||
"github.com/jackc/pgx/v5/pgxpool"
|
||
)
|
||
|
||
// MediaAsset 媒体资源元数据。字节永远不在我这,只记录它在对象存储里的位置。
|
||
type MediaAsset struct {
|
||
ID string `json:"id"`
|
||
OwnerID string `json:"owner_id"`
|
||
ObjectKey string `json:"object_key"`
|
||
Bucket string `json:"bucket"`
|
||
OriginalName string `json:"original_name"`
|
||
ContentType string `json:"content_type"`
|
||
SizeBytes int64 `json:"size_bytes"`
|
||
Width *int `json:"width,omitempty"`
|
||
Height *int `json:"height,omitempty"`
|
||
DurationSeconds *int `json:"duration_seconds,omitempty"`
|
||
Status string `json:"status"`
|
||
SHA256 *string `json:"sha256,omitempty"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||
|
||
// 非持久化字段,查询时按需填充
|
||
URL string `json:"url,omitempty"`
|
||
SignedURL string `json:"signed_url,omitempty"`
|
||
}
|
||
|
||
type MediaRepo struct{ pool *pgxpool.Pool }
|
||
|
||
func NewMediaRepo(p *pgxpool.Pool) *MediaRepo { return &MediaRepo{pool: p} }
|
||
|
||
const mediaCols = `id, owner_id, object_key, bucket, original_name, content_type,
|
||
size_bytes, width, height, duration_seconds, status, sha256, created_at, completed_at`
|
||
|
||
func scanMedia(row pgx.Row) (*MediaAsset, error) {
|
||
var m MediaAsset
|
||
err := row.Scan(&m.ID, &m.OwnerID, &m.ObjectKey, &m.Bucket, &m.OriginalName,
|
||
&m.ContentType, &m.SizeBytes, &m.Width, &m.Height, &m.DurationSeconds,
|
||
&m.Status, &m.SHA256, &m.CreatedAt, &m.CompletedAt)
|
||
if errors.Is(err, pgx.ErrNoRows) {
|
||
return nil, ErrNotFound
|
||
}
|
||
return &m, err
|
||
}
|
||
|
||
func (r *MediaRepo) InsertPending(ctx context.Context, q Querier, id, ownerID, objectKey,
|
||
bucket, originalName, contentType string, size int64) error {
|
||
|
||
_, err := q.Exec(ctx, `INSERT INTO media_assets
|
||
(id, owner_id, object_key, bucket, original_name, content_type, size_bytes, status)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7,'pending')`,
|
||
id, ownerID, objectKey, bucket, originalName, contentType, size)
|
||
return err
|
||
}
|
||
|
||
func (r *MediaRepo) GetByID(ctx context.Context, q Querier, id string) (*MediaAsset, error) {
|
||
return scanMedia(q.QueryRow(ctx, `SELECT `+mediaCols+` FROM media_assets WHERE id=$1`, id))
|
||
}
|
||
|
||
// MarkReady 上传完成后落定。
|
||
// 用 ON CONFLICT 处理「同一内容被多个用户上传」:key 相同则复用已有记录,
|
||
// 不重复占存储。这是内容寻址的核心收益。
|
||
func (r *MediaRepo) MarkReady(ctx context.Context, q Querier, id, newKey, sha256 string,
|
||
width, height, duration int) error {
|
||
|
||
// 先尝试把新 key 写到本记录
|
||
_, err := q.Exec(ctx, `UPDATE media_assets SET
|
||
object_key=$2, sha256=$3, status='ready', completed_at=now(),
|
||
width=NULLIF($4,0), height=NULLIF($5,0), duration_seconds=NULLIF($6,0)
|
||
WHERE id=$1`,
|
||
id, newKey, sha256, width, height, duration)
|
||
if err == nil {
|
||
return nil
|
||
}
|
||
|
||
// 唯一索引冲突说明这个内容已存在(别的用户传过同一文件):
|
||
// 保留原记录,把当前记录标记为复用,避免重复存储。
|
||
if isUniqueViolation(err) {
|
||
_, err2 := q.Exec(ctx, `UPDATE media_assets SET
|
||
status='ready', completed_at=now(), sha256=$2,
|
||
width=NULLIF($3,0), height=NULLIF($4,0), duration_seconds=NULLIF($5,0)
|
||
WHERE id=$1`, id, sha256, width, height, duration)
|
||
return err2
|
||
}
|
||
return err
|
||
}
|
||
|
||
// CountPending 统计未完成上传数,用于配额限制
|
||
func (r *MediaRepo) CountPending(ctx context.Context, q Querier, ownerID string) (int, error) {
|
||
var n int
|
||
err := q.QueryRow(ctx, `SELECT count(*) FROM media_assets
|
||
WHERE owner_id=$1 AND status='pending'
|
||
AND created_at > now() - interval '1 hour'`, ownerID).Scan(&n)
|
||
return n, err
|
||
}
|
||
|
||
// ExpirePending 清理超时未确认的记录(worker 定期调用)
|
||
func (r *MediaRepo) ExpirePending(ctx context.Context, q Querier) (int64, error) {
|
||
tag, err := q.Exec(ctx, `UPDATE media_assets SET status='failed'
|
||
WHERE status='pending' AND created_at < now() - interval '1 hour'`)
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
return tag.RowsAffected(), nil
|
||
}
|
||
|
||
// isUniqueViolation 判断是否唯一索引冲突(SQLSTATE 23505)
|
||
func isUniqueViolation(err error) bool {
|
||
var pgErr *pgconn.PgError
|
||
if errors.As(err, &pgErr) {
|
||
return pgErr.Code == "23505"
|
||
}
|
||
return strings.Contains(err.Error(), "duplicate key")
|
||
}
|