调整UI
This commit is contained in:
@@ -1,290 +0,0 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
registerPath = "/api/app/auth/register"
|
||||
loginPath = "/api/app/auth/login"
|
||||
resetPath = "/api/app/auth/resetPassword"
|
||||
guestPath = "/api/app/auth/guest"
|
||||
getInfoPath = "/api/app/auth/getInfo"
|
||||
profilePath = "/api/app/auth/profile"
|
||||
uploadPath = "/api/app/upload/image"
|
||||
cookieMaxAge = 7 * 24 * 3600
|
||||
)
|
||||
|
||||
// Register 调用上游注册接口。
|
||||
func Register(c *gin.Context, req RegisterReq) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, registerPath, req, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// ResetPassword 通过账号和邮箱校验后重置密码。
|
||||
func ResetPassword(c *gin.Context, req ResetPasswordReq) (*APIEnvelope, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, resetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// Login 调用上游登录接口。
|
||||
func Login(c *gin.Context, req LoginReq) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, loginPath, req, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// GuestLogin 调用上游游客登录(按设备 ID 创建或找回游客账号)。
|
||||
func GuestLogin(c *gin.Context, req GuestLoginReq) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, guestPath, req, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// GetInfo 通过 token 拉取最新用户信息。
|
||||
func GetInfo(c *gin.Context) (*APIEnvelope, *LoginResp, error) {
|
||||
var env APIEnvelope
|
||||
if err := upstream.GetJSON(c, getInfoPath, &env); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return &env, nil, nil
|
||||
}
|
||||
user, err := decodeLoginData(env.Data)
|
||||
if err != nil {
|
||||
return &env, nil, err
|
||||
}
|
||||
return &env, user, nil
|
||||
}
|
||||
|
||||
// UpdateProfile 修改资料(昵称 / 头像等)。
|
||||
func UpdateProfile(c *gin.Context, req UpdateProfileReq) (*APIEnvelope, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, profilePath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// UploadImage 上传图片;头像场景不加水印。
|
||||
func UploadImage(c *gin.Context, fileName string, r io.Reader) (*ImageUploadResp, error) {
|
||||
var resp ImageUploadResp
|
||||
_, err := upstream.PostMultipart(c, uploadPath, map[string]string{
|
||||
"watermark": "0",
|
||||
}, &upstream.MultipartFile{
|
||||
FieldName: "file",
|
||||
FileName: fileName,
|
||||
Reader: r,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func decodeLoginData(raw json.RawMessage) (*LoginResp, error) {
|
||||
if len(raw) == 0 || string(raw) == "null" || string(raw) == `""` {
|
||||
return nil, fmt.Errorf("empty login data")
|
||||
}
|
||||
var user LoginResp
|
||||
if err := json.Unmarshal(raw, &user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// SetAuthCookies 只持久化 SSR 与前端登录态实际依赖的字段。
|
||||
// 个人简介、邮箱、邀请码、展示卡信息由 getInfo 即时提供,不再随每个页面响应重复写入;
|
||||
// sid 已存在于请求时也无需原样回写。ClearAuthCookies 仍保留这些历史键用于兼容清理。
|
||||
func SetAuthCookies(c *gin.Context, user *LoginResp) {
|
||||
if c == nil || user == nil {
|
||||
return
|
||||
}
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
if strings.TrimSpace(user.Token) != "" {
|
||||
setCookie(c, "token", user.Token, secure)
|
||||
}
|
||||
setCookie(c, "userId", strconv.FormatInt(user.UserID, 10), secure)
|
||||
setCookie(c, "accountNo", user.AccountNo, secure)
|
||||
setCookie(c, "nickName", user.NickName, secure)
|
||||
setCookie(c, "avatar", user.Avatar, secure)
|
||||
setCookie(c, "recharge", strconv.FormatInt(user.Recharge, 10), secure)
|
||||
setCookie(c, "vipType", strconv.Itoa(user.VipType), secure)
|
||||
setCookie(c, "currentVipExpire", user.CurrentVipExpire, secure)
|
||||
setCookie(c, "userType", strconv.Itoa(user.Type), secure)
|
||||
isReg := "0"
|
||||
if user.IsRegister || user.Type == 1 {
|
||||
isReg = "1"
|
||||
}
|
||||
setCookie(c, "isRegister", isReg, secure)
|
||||
// 后续 SSR 服务必须能立即读取本次刚建立/刷新的会话;同时记录为本请求的
|
||||
// 权威结果,避免 HTML 渲染阶段再次调用 getInfo 并重复写整套 Cookie。
|
||||
patchAuthCookiesToRequest(c, user)
|
||||
rememberRequestAuthUser(c, user)
|
||||
}
|
||||
|
||||
func setCookie(c *gin.Context, name, value string, secure bool) {
|
||||
// Cookie Value 仅允许 ASCII;中文昵称等需 URL 编码。
|
||||
// 使用 PathEscape(空格→%20),与前端 encodeURIComponent 一致;
|
||||
// 避免 QueryEscape 的空格→+,否则 JS decodeURIComponent 会留下字面量 "+"。
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: name,
|
||||
Value: url.PathEscape(value),
|
||||
Path: "/",
|
||||
MaxAge: cookieMaxAge,
|
||||
HttpOnly: false,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(7 * 24 * time.Hour),
|
||||
})
|
||||
}
|
||||
|
||||
// writeCookie 对同一响应中同名、同 Path、同 Domain 的 Cookie 做 upsert,避免会话恢复的
|
||||
// 「先清除、再重建」产生两套响应头,同时保留其他作用域下可能存在的同名 Cookie。
|
||||
func writeCookie(c *gin.Context, cookie *http.Cookie) {
|
||||
if c == nil || c.Writer == nil || cookie == nil || cookie.Name == "" {
|
||||
return
|
||||
}
|
||||
header := c.Writer.Header()
|
||||
existing := header.Values("Set-Cookie")
|
||||
if len(existing) > 0 {
|
||||
header.Del("Set-Cookie")
|
||||
for _, raw := range existing {
|
||||
if sameCookieScope(raw, cookie) {
|
||||
continue
|
||||
}
|
||||
header.Add("Set-Cookie", raw)
|
||||
}
|
||||
}
|
||||
http.SetCookie(c.Writer, cookie)
|
||||
}
|
||||
|
||||
func sameCookieScope(raw string, target *http.Cookie) bool {
|
||||
response := &http.Response{Header: http.Header{"Set-Cookie": []string{raw}}}
|
||||
for _, existing := range response.Cookies() {
|
||||
if existing.Name == target.Name && existing.Path == target.Path && strings.EqualFold(existing.Domain, target.Domain) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cookieValue(c *gin.Context, name string) string {
|
||||
ck, err := c.Request.Cookie(name)
|
||||
if err != nil || ck == nil {
|
||||
return ""
|
||||
}
|
||||
raw := strings.TrimSpace(ck.Value)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
// QueryUnescape 同时兼容历史 QueryEscape(+)与 PathEscape(%20)
|
||||
if decoded, err := url.QueryUnescape(raw); err == nil {
|
||||
return strings.TrimSpace(decoded)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
// ClearAuthCookies 清除登录相关 cookie。
|
||||
func ClearAuthCookies(c *gin.Context) {
|
||||
forgetRequestAuthUser(c)
|
||||
for _, name := range authCookieNames() {
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: name,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: false,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func authCookieNames() []string {
|
||||
return []string{
|
||||
"token", "_token_", "sid", "_s_token_",
|
||||
"userId", "accountNo", "nickName", "introduction", "avatar",
|
||||
"email", "inviteCode", "recharge", "vipType", "currentVipExpire", "showCardId", "showCardName",
|
||||
"userType", "isRegister",
|
||||
}
|
||||
}
|
||||
|
||||
// AuthFromCookies 从 cookie 读取登录态,供 SSR 头部 / 个人中心展示。
|
||||
func AuthFromCookies(c *gin.Context) (loggedIn bool, userName, avatar, email string) {
|
||||
token := useragent.TokenFromRequest(c.Request)
|
||||
if token == "" {
|
||||
return false, "", "", ""
|
||||
}
|
||||
userName = cookieValue(c, "nickName")
|
||||
if userName == "" {
|
||||
userName = cookieValue(c, "accountNo")
|
||||
}
|
||||
avatar = usableAvatarURL(cookieValue(c, "avatar"))
|
||||
email = cookieValue(c, "email")
|
||||
return true, userName, avatar, email
|
||||
}
|
||||
|
||||
// IsRegisteredFromCookies 是否正式注册账号(非游客)。
|
||||
func IsRegisteredFromCookies(c *gin.Context) bool {
|
||||
if useragent.TokenFromRequest(c.Request) == "" {
|
||||
return false
|
||||
}
|
||||
if cookieValue(c, "isRegister") == "1" {
|
||||
return true
|
||||
}
|
||||
return cookieValue(c, "userType") == "1"
|
||||
}
|
||||
|
||||
func usableAvatarURL(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") || strings.HasPrefix(raw, "/static/") {
|
||||
return raw
|
||||
}
|
||||
// 无域名的相对路径暂不可用(解密拉取需要完整 URL)
|
||||
return ""
|
||||
}
|
||||
@@ -1,314 +0,0 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"videoweb/pub/common/log"
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const guestDevIDCookie = "guest_dev_id"
|
||||
const guestSkipAutoCookie = "guest_skip_auto"
|
||||
|
||||
// EnsureGuestOnEnter 页面进入时:无 token(未自己登录)则走游客登录并写 cookie。
|
||||
// 对应上游 POST /api/app/auth/guest。成功后会把会话补进当前 Request,便于同一次 SSR 读到登录态。
|
||||
// 手动退出后带 guest_skip_auto 时跳过本次;清掉标记后,下次进页再自动游客。
|
||||
func EnsureGuestOnEnter(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if user := freshRequestAuthUser(c); user != nil {
|
||||
return user
|
||||
}
|
||||
if requestAutoAuthSuppressed(c) {
|
||||
return nil
|
||||
}
|
||||
// 已有任意会话(游客或正式账号)则跳过
|
||||
if useragent.TokenFromRequest(c.Request) != "" {
|
||||
return nil
|
||||
}
|
||||
// 手动退出:本次进页不自动游客,并清除标记,供下次进页恢复
|
||||
if IsGuestSkipAuto(c) {
|
||||
ClearGuestSkipAuto(c)
|
||||
dropRequestCookie(c, guestSkipAutoCookie)
|
||||
suppressRequestAutoAuth(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
devID := ensureGuestDevID(c)
|
||||
env, user, err := GuestLogin(c, GuestLoginReq{
|
||||
DevID: devID,
|
||||
DeviceID: devID,
|
||||
Channel: guestChannel(c),
|
||||
})
|
||||
if err != nil {
|
||||
log.Error("ensure guest on enter failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
if env == nil || env.Code != 200 || user == nil || strings.TrimSpace(user.Token) == "" {
|
||||
tip := ""
|
||||
if env != nil {
|
||||
tip = firstNonEmptyTip(env.Tip, env.Msg)
|
||||
}
|
||||
log.Error("ensure guest on enter rejected", log.E(fmt.Errorf("code=%v tip=%s", envCode(env), tip)))
|
||||
return nil
|
||||
}
|
||||
|
||||
SetAuthCookies(c, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// SyncUserOnEnter 是 SSR 页面统一的会话同步入口。同一请求已经通过游客登录、
|
||||
// getInfo 或其他认证流程取得过最新用户时直接复用,避免再次访问上游和重复写 Cookie。
|
||||
func SyncUserOnEnter(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if user := freshRequestAuthUser(c); user != nil {
|
||||
return user
|
||||
}
|
||||
if requestAutoAuthSuppressed(c) {
|
||||
return nil
|
||||
}
|
||||
if useragent.TokenFromRequest(c.Request) == "" {
|
||||
return EnsureGuestOnEnter(c)
|
||||
}
|
||||
return RefreshUserOnEnter(c)
|
||||
}
|
||||
|
||||
// RefreshUserOnEnter 页面进入时用 GET /api/app/auth/getInfo 刷新用户信息并写回 cookie。
|
||||
// 保证刷新后头部昵称、头像、金币等与上游一致(如解锁后余额变化)。
|
||||
func RefreshUserOnEnter(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if user := freshRequestAuthUser(c); user != nil {
|
||||
return user
|
||||
}
|
||||
if requestAutoAuthSuppressed(c) {
|
||||
return nil
|
||||
}
|
||||
token := useragent.TokenFromRequest(c.Request)
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
env, user, err := GetInfo(c)
|
||||
if err != nil {
|
||||
log.Error("refresh user on enter failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
if env != nil && IsSessionExpiredCode(env.Code) {
|
||||
if retry, _ := OnSessionExpired(c, env.Code); retry {
|
||||
// 游客重建已经返回完整用户并写好 Cookie,无需立刻再 getInfo 一次。
|
||||
if fresh := freshRequestAuthUser(c); fresh != nil {
|
||||
return fresh
|
||||
}
|
||||
env, user, err = GetInfo(c)
|
||||
if err != nil {
|
||||
log.Error("refresh user on enter retry failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if env == nil || env.Code != 200 || user == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(user.Token) == "" {
|
||||
user.Token = useragent.TokenFromRequest(c.Request)
|
||||
if user.Token == "" {
|
||||
user.Token = token
|
||||
}
|
||||
}
|
||||
SetAuthCookies(c, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// RefreshGuestSession 游客会话失效时(如上游 6001 用户不存在)重新游客登录。
|
||||
// 正式注册账号不处理,避免把用户踢成游客。
|
||||
func RefreshGuestSession(c *gin.Context) *LoginResp {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil
|
||||
}
|
||||
if IsRegisteredFromCookies(c) {
|
||||
return nil
|
||||
}
|
||||
forgetRequestAuthUser(c)
|
||||
dropRequestCookie(c, "token")
|
||||
dropRequestCookie(c, "_token_")
|
||||
return EnsureGuestOnEnter(c)
|
||||
}
|
||||
|
||||
func dropRequestCookie(c *gin.Context, name string) {
|
||||
if c == nil || c.Request == nil || name == "" {
|
||||
return
|
||||
}
|
||||
var parts []string
|
||||
for _, ck := range c.Request.Cookies() {
|
||||
if ck == nil || ck.Name == name {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, ck.Name+"="+ck.Value)
|
||||
}
|
||||
c.Request.Header.Set("Cookie", strings.Join(parts, "; "))
|
||||
}
|
||||
|
||||
// MarkGuestSkipAuto 手动退出后标记:跳过紧接着的一次自动游客登录。
|
||||
func MarkGuestSkipAuto(c *gin.Context) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
suppressRequestAutoAuth(c)
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: guestSkipAutoCookie,
|
||||
Value: "1",
|
||||
Path: "/",
|
||||
MaxAge: 0, // session cookie
|
||||
HttpOnly: false,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
// IsGuestSkipAuto 是否处于「手动退出后跳过自动游客」状态。
|
||||
func IsGuestSkipAuto(c *gin.Context) bool {
|
||||
return cookieValue(c, guestSkipAutoCookie) == "1"
|
||||
}
|
||||
|
||||
// ClearGuestSkipAuto 清除手动退出跳过标记。
|
||||
func ClearGuestSkipAuto(c *gin.Context) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
writeCookie(c, &http.Cookie{
|
||||
Name: guestSkipAutoCookie,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: false,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
func ensureGuestDevID(c *gin.Context) string {
|
||||
if id := cookieValue(c, guestDevIDCookie); id != "" {
|
||||
return id
|
||||
}
|
||||
id := newGuestDevID()
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
setCookie(c, guestDevIDCookie, id, secure)
|
||||
patchRequestCookie(c, guestDevIDCookie, id)
|
||||
return id
|
||||
}
|
||||
|
||||
func newGuestDevID() string {
|
||||
b := make([]byte, 8)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("%016X%d", uint64(now.UnixNano()), now.UnixMilli())
|
||||
}
|
||||
return strings.ToUpper(hex.EncodeToString(b)) + strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
}
|
||||
|
||||
// ResolveChannel 统一解析渠道码并按首次归因落盘。
|
||||
// 优先级:已有 channel cookie > 调用方传入值 > dc/ch/pc 查询参数;已有渠道不覆盖。
|
||||
func ResolveChannel(c *gin.Context, candidate string) string {
|
||||
channel := strings.TrimSpace(candidate)
|
||||
if c == nil || c.Request == nil {
|
||||
return channel
|
||||
}
|
||||
if stored := cookieValue(c, "channel"); stored != "" {
|
||||
return stored
|
||||
}
|
||||
if channel == "" {
|
||||
for _, key := range []string{"dc", "ch", "pc"} {
|
||||
if value := strings.TrimSpace(c.Query(key)); value != "" {
|
||||
channel = value
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if channel == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
secure := c.Request.TLS != nil
|
||||
setCookie(c, "channel", channel, secure)
|
||||
patchRequestCookie(c, "channel", channel)
|
||||
return channel
|
||||
}
|
||||
|
||||
// guestChannel 为首屏服务端自动游客登录补渠道;cookie 用于复用前端首次归因结果。
|
||||
func guestChannel(c *gin.Context) string {
|
||||
return ResolveChannel(c, "")
|
||||
}
|
||||
|
||||
func patchAuthCookiesToRequest(c *gin.Context, user *LoginResp) {
|
||||
if c == nil || user == nil {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(user.Token) != "" {
|
||||
patchRequestCookie(c, "token", user.Token)
|
||||
}
|
||||
patchRequestCookie(c, "userId", strconv.FormatInt(user.UserID, 10))
|
||||
patchRequestCookie(c, "accountNo", user.AccountNo)
|
||||
patchRequestCookie(c, "nickName", user.NickName)
|
||||
patchRequestCookie(c, "introduction", user.Introduction)
|
||||
patchRequestCookie(c, "avatar", user.Avatar)
|
||||
patchRequestCookie(c, "email", user.Email)
|
||||
patchRequestCookie(c, "inviteCode", user.InviteCode)
|
||||
patchRequestCookie(c, "recharge", strconv.FormatInt(user.Recharge, 10))
|
||||
patchRequestCookie(c, "vipType", strconv.Itoa(user.VipType))
|
||||
patchRequestCookie(c, "currentVipExpire", user.CurrentVipExpire)
|
||||
patchRequestCookie(c, "showCardId", strconv.FormatInt(user.ShowCardID, 10))
|
||||
patchRequestCookie(c, "showCardName", user.ShowCardName)
|
||||
patchRequestCookie(c, "userType", strconv.Itoa(user.Type))
|
||||
isReg := "0"
|
||||
if user.IsRegister || user.Type == 1 {
|
||||
isReg = "1"
|
||||
}
|
||||
patchRequestCookie(c, "isRegister", isReg)
|
||||
}
|
||||
|
||||
func patchRequestCookie(c *gin.Context, name, value string) {
|
||||
if c == nil || c.Request == nil || name == "" {
|
||||
return
|
||||
}
|
||||
escaped := url.PathEscape(value)
|
||||
var parts []string
|
||||
for _, ck := range c.Request.Cookies() {
|
||||
if ck == nil || ck.Name == name {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, ck.Name+"="+ck.Value)
|
||||
}
|
||||
parts = append(parts, name+"="+escaped)
|
||||
c.Request.Header.Set("Cookie", strings.Join(parts, "; "))
|
||||
}
|
||||
|
||||
func envCode(env *APIEnvelope) int {
|
||||
if env == nil {
|
||||
return 0
|
||||
}
|
||||
return env.Code
|
||||
}
|
||||
|
||||
func firstNonEmptyTip(values ...string) string {
|
||||
for _, v := range values {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"videoweb/app/appg"
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var authCookieNamesWritten = []string{
|
||||
"token",
|
||||
"userId",
|
||||
"accountNo",
|
||||
"nickName",
|
||||
"avatar",
|
||||
"recharge",
|
||||
"vipType",
|
||||
"currentVipExpire",
|
||||
"userType",
|
||||
"isRegister",
|
||||
}
|
||||
|
||||
func TestSyncUserOnEnterCreatesGuestWithoutRefreshingIt(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("guest method = %s, want POST", r.Method)
|
||||
}
|
||||
var request GuestLoginReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Errorf("decode guest request: %v", err)
|
||||
}
|
||||
if request.DevID == "" || request.DeviceID != request.DevID {
|
||||
t.Errorf("guest device ids = %#v, want matching non-empty ids", request)
|
||||
}
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("guest-token", "new-guest"))
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("guest-token", "unexpected-refresh"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext()
|
||||
user := SyncUserOnEnter(c)
|
||||
|
||||
if user == nil || user.Token != "guest-token" {
|
||||
t.Fatalf("SyncUserOnEnter user = %#v, want guest-token", user)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 1 {
|
||||
t.Errorf("guest calls = %d, want 1", got)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 0 {
|
||||
t.Errorf("getInfo calls = %d, want 0", got)
|
||||
}
|
||||
assertRequestToken(t, c, "guest-token")
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestSyncUserOnEnterRefreshesExistingTokenOnlyOnce(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
authorization := make(chan string, 1)
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("unexpected-guest-token", "unexpected-guest"))
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
select {
|
||||
case authorization <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
// getInfo may omit token; the existing request token must be preserved.
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("", "fresh-user"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext(
|
||||
&http.Cookie{Name: "token", Value: "existing-token"},
|
||||
&http.Cookie{Name: "sid", Value: "existing-sid"},
|
||||
)
|
||||
first := SyncUserOnEnter(c)
|
||||
second := SyncUserOnEnter(c)
|
||||
|
||||
if first == nil || first.Token != "existing-token" || first.NickName != "fresh-user" {
|
||||
t.Fatalf("first SyncUserOnEnter user = %#v, want refreshed user with existing token", first)
|
||||
}
|
||||
if second == nil || second.Token != "existing-token" || second.NickName != "fresh-user" {
|
||||
t.Fatalf("second SyncUserOnEnter user = %#v, want memoized refreshed user", second)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 0 {
|
||||
t.Errorf("guest calls = %d, want 0", got)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 1 {
|
||||
t.Errorf("getInfo calls = %d, want 1", got)
|
||||
}
|
||||
select {
|
||||
case got := <-authorization:
|
||||
if got != "existing-token" {
|
||||
t.Errorf("Authorization = %q, want existing-token", got)
|
||||
}
|
||||
default:
|
||||
t.Error("getInfo did not capture Authorization header")
|
||||
}
|
||||
assertRequestToken(t, c, "existing-token")
|
||||
if got := cookieValue(c, "nickName"); got != "fresh-user" {
|
||||
t.Errorf("request nickName cookie = %q, want fresh-user", got)
|
||||
}
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestSyncUserOnEnterReusesGuestCreatedBeforeRender(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("pre-render-token", "pre-render-guest"))
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("pre-render-token", "unexpected-refresh"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext()
|
||||
guest := EnsureGuestOnEnter(c)
|
||||
user := SyncUserOnEnter(c)
|
||||
|
||||
if guest == nil || guest.Token != "pre-render-token" {
|
||||
t.Fatalf("EnsureGuestOnEnter user = %#v, want pre-render guest", guest)
|
||||
}
|
||||
if user == nil || user.Token != "pre-render-token" || user.NickName != "pre-render-guest" {
|
||||
t.Fatalf("SyncUserOnEnter user = %#v, want memoized pre-render guest", user)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 1 {
|
||||
t.Errorf("guest calls = %d, want 1", got)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 0 {
|
||||
t.Errorf("getInfo calls = %d, want 0", got)
|
||||
}
|
||||
assertRequestToken(t, c, "pre-render-token")
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestRefreshUserOnEnterReturnsRebuiltGuestWithoutRefreshingItAgain(t *testing.T) {
|
||||
var guestCalls atomic.Int32
|
||||
var getInfoCalls atomic.Int32
|
||||
getInfoAuthorization := make(chan string, 1)
|
||||
guestAuthorization := make(chan string, 1)
|
||||
|
||||
useAuthTestUpstream(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case getInfoPath:
|
||||
getInfoCalls.Add(1)
|
||||
select {
|
||||
case getInfoAuthorization <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 6001, nil)
|
||||
case guestPath:
|
||||
guestCalls.Add(1)
|
||||
select {
|
||||
case guestAuthorization <- r.Header.Get("Authorization"):
|
||||
default:
|
||||
}
|
||||
writeAuthTestEnvelope(w, http.StatusOK, 200, testLoginUser("rebuilt-guest-token", "rebuilt-guest"))
|
||||
default:
|
||||
t.Errorf("unexpected upstream request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
c, recorder := newAuthTestContext(
|
||||
&http.Cookie{Name: "token", Value: "expired-guest-token"},
|
||||
&http.Cookie{Name: "isRegister", Value: "0"},
|
||||
&http.Cookie{Name: "userType", Value: "0"},
|
||||
)
|
||||
user := RefreshUserOnEnter(c)
|
||||
// The rebuilt guest must also be reusable by the page-level sync call.
|
||||
synced := SyncUserOnEnter(c)
|
||||
|
||||
if user == nil || user.Token != "rebuilt-guest-token" || user.NickName != "rebuilt-guest" {
|
||||
t.Fatalf("RefreshUserOnEnter user = %#v, want rebuilt guest", user)
|
||||
}
|
||||
if synced == nil || synced.Token != "rebuilt-guest-token" {
|
||||
t.Fatalf("SyncUserOnEnter user = %#v, want memoized rebuilt guest", synced)
|
||||
}
|
||||
if got := getInfoCalls.Load(); got != 1 {
|
||||
t.Errorf("getInfo calls = %d, want 1 (no refresh of rebuilt guest)", got)
|
||||
}
|
||||
if got := guestCalls.Load(); got != 1 {
|
||||
t.Errorf("guest calls = %d, want 1", got)
|
||||
}
|
||||
select {
|
||||
case got := <-getInfoAuthorization:
|
||||
if got != "expired-guest-token" {
|
||||
t.Errorf("getInfo Authorization = %q, want expired-guest-token", got)
|
||||
}
|
||||
default:
|
||||
t.Error("getInfo did not capture Authorization header")
|
||||
}
|
||||
select {
|
||||
case got := <-guestAuthorization:
|
||||
if got != "" {
|
||||
t.Errorf("guest Authorization = %q, want empty after expired token is removed", got)
|
||||
}
|
||||
default:
|
||||
t.Error("guest login did not capture Authorization header")
|
||||
}
|
||||
assertRequestToken(t, c, "rebuilt-guest-token")
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
}
|
||||
|
||||
func TestSetAuthCookiesUpsertsSameNameWithinResponse(t *testing.T) {
|
||||
c, recorder := newAuthTestContext()
|
||||
SetAuthCookies(c, testLoginUser("first-token", "first-user"))
|
||||
SetAuthCookies(c, testLoginUser("latest-token", "latest-user"))
|
||||
|
||||
assertSingleAuthCookieSet(t, recorder)
|
||||
assertRequestToken(t, c, "latest-token")
|
||||
if got := cookieValue(c, "nickName"); got != "latest-user" {
|
||||
t.Errorf("request nickName cookie = %q, want latest-user", got)
|
||||
}
|
||||
for _, cookie := range recorder.Result().Cookies() {
|
||||
if cookie.Name == "token" && cookie.Value != "latest-token" {
|
||||
t.Errorf("response token cookie = %q, want latest-token", cookie.Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func useAuthTestUpstream(t *testing.T, handler http.Handler) {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(handler)
|
||||
previousServerAddr := appg.Conf.ServerAddr
|
||||
appg.Conf.ServerAddr = server.URL
|
||||
t.Cleanup(func() {
|
||||
appg.Conf.ServerAddr = previousServerAddr
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func newAuthTestContext(cookies ...*http.Cookie) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "https://site.test/page", nil)
|
||||
for _, cookie := range cookies {
|
||||
c.Request.AddCookie(cookie)
|
||||
}
|
||||
return c, recorder
|
||||
}
|
||||
|
||||
func writeAuthTestEnvelope(w http.ResponseWriter, status, code int, data *LoginResp) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data *LoginResp `json:"data"`
|
||||
}{
|
||||
Code: code,
|
||||
Msg: http.StatusText(status),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
func testLoginUser(token, nickName string) *LoginResp {
|
||||
return &LoginResp{
|
||||
Token: token,
|
||||
UserID: 101,
|
||||
AccountNo: "account-101",
|
||||
Email: "user101@example.test",
|
||||
NickName: nickName,
|
||||
// This field is intentionally large: it must stay out of Set-Cookie headers.
|
||||
Introduction: strings.Repeat("简介", 150),
|
||||
Avatar: "https://cdn.example.test/avatar.png",
|
||||
InviteCode: "INVITE101",
|
||||
VipType: 1,
|
||||
CurrentVipExpire: "2099-01-01T00:00:00Z",
|
||||
ShowCardID: 7,
|
||||
ShowCardName: "monthly",
|
||||
Type: 0,
|
||||
Recharge: 88,
|
||||
}
|
||||
}
|
||||
|
||||
func assertRequestToken(t *testing.T, c *gin.Context, want string) {
|
||||
t.Helper()
|
||||
if got := useragent.TokenFromRequest(c.Request); got != want {
|
||||
t.Errorf("request token = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertSingleAuthCookieSet(t *testing.T, recorder *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
counts := make(map[string]int)
|
||||
for _, cookie := range recorder.Result().Cookies() {
|
||||
counts[cookie.Name]++
|
||||
}
|
||||
for name, count := range counts {
|
||||
if count > 1 {
|
||||
t.Errorf("Set-Cookie %q written %d times, want at most once", name, count)
|
||||
}
|
||||
}
|
||||
for _, name := range authCookieNamesWritten {
|
||||
if got := counts[name]; got != 1 {
|
||||
t.Errorf("auth Set-Cookie %q written %d times, want exactly once", name, got)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"introduction", "email", "inviteCode", "showCardId", "showCardName", "sid"} {
|
||||
if got := counts[name]; got != 0 {
|
||||
t.Errorf("non-session Set-Cookie %q written %d times, want none", name, got)
|
||||
}
|
||||
}
|
||||
var headerBytes int
|
||||
for _, raw := range recorder.Header().Values("Set-Cookie") {
|
||||
headerBytes += len("Set-Cookie: ") + len(raw) + len("\r\n")
|
||||
}
|
||||
if headerBytes >= 4096 {
|
||||
t.Errorf("Set-Cookie response headers = %d bytes, want below 4096", headerBytes)
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package authser
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
const requestAuthStateKey = "authser.request-auth-state"
|
||||
|
||||
// requestAuthState 只在单个 Gin 请求内有效,用来避免多个 SSR 服务重复刷新同一会话。
|
||||
// freshUser 表示本请求已经从上游取得并写回过的最新用户;suppressAutoAuth
|
||||
// 表示本请求明确不应再自动创建游客(例如用户刚退出或正式账号已过期)。
|
||||
type requestAuthState struct {
|
||||
freshUser *LoginResp
|
||||
suppressAutoAuth bool
|
||||
}
|
||||
|
||||
func authState(c *gin.Context) *requestAuthState {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if value, ok := c.Get(requestAuthStateKey); ok {
|
||||
if state, ok := value.(*requestAuthState); ok && state != nil {
|
||||
return state
|
||||
}
|
||||
}
|
||||
state := &requestAuthState{}
|
||||
c.Set(requestAuthStateKey, state)
|
||||
return state
|
||||
}
|
||||
|
||||
func freshRequestAuthUser(c *gin.Context) *LoginResp {
|
||||
state := authState(c)
|
||||
if state == nil {
|
||||
return nil
|
||||
}
|
||||
return state.freshUser
|
||||
}
|
||||
|
||||
func rememberRequestAuthUser(c *gin.Context, user *LoginResp) {
|
||||
state := authState(c)
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
state.freshUser = user
|
||||
state.suppressAutoAuth = false
|
||||
}
|
||||
|
||||
func forgetRequestAuthUser(c *gin.Context) {
|
||||
if state := authState(c); state != nil {
|
||||
state.freshUser = nil
|
||||
}
|
||||
}
|
||||
|
||||
func suppressRequestAutoAuth(c *gin.Context) {
|
||||
if state := authState(c); state != nil {
|
||||
state.suppressAutoAuth = true
|
||||
}
|
||||
}
|
||||
|
||||
func allowRequestAutoAuth(c *gin.Context) {
|
||||
if state := authState(c); state != nil {
|
||||
state.suppressAutoAuth = false
|
||||
}
|
||||
}
|
||||
|
||||
func requestAutoAuthSuppressed(c *gin.Context) bool {
|
||||
state := authState(c)
|
||||
return state != nil && state.suppressAutoAuth
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package authser
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
// TokenExpiredCode 上游约定:token 失效,需重新登录。
|
||||
const TokenExpiredCode = 1000
|
||||
|
||||
// IsSessionExpiredCode 是否为会话失效类业务码。
|
||||
func IsSessionExpiredCode(code int) bool {
|
||||
switch code {
|
||||
case TokenExpiredCode, 1002, 1012, 6001: // InvalidToken / NoToken / InvalidateToken / 用户不存在
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// OnSessionExpired 处理上游会话失效。
|
||||
// retry=true:游客已重新登录,调用方应重试原请求;
|
||||
// needLogin=true:注册账号已清 cookie,调用方应跳转登录弹窗/页。
|
||||
func OnSessionExpired(c *gin.Context, code int) (retry, needLogin bool) {
|
||||
if c == nil || !IsSessionExpiredCode(code) {
|
||||
return false, false
|
||||
}
|
||||
if IsRegisteredFromCookies(c) {
|
||||
ClearAuthCookies(c)
|
||||
dropRequestCookie(c, "token")
|
||||
dropRequestCookie(c, "_token_")
|
||||
// 正式账号失效后,本请求保持退出态,避免后续 HTML 渲染又静默转成游客。
|
||||
suppressRequestAutoAuth(c)
|
||||
return false, true
|
||||
}
|
||||
if RefreshGuestSession(c) != nil {
|
||||
return true, false
|
||||
}
|
||||
ClearAuthCookies(c)
|
||||
dropRequestCookie(c, "token")
|
||||
dropRequestCookie(c, "_token_")
|
||||
return false, false
|
||||
}
|
||||
|
||||
// RecoverContentSession 用于允许游客访问的内容读取接口。
|
||||
// 正式账号或游客 token 失效后,清理旧登录态、重新建立游客会话,调用方随后重试一次原请求。
|
||||
// 写操作仍应使用 OnSessionExpired,避免把用户操作静默降级为游客操作。
|
||||
func RecoverContentSession(c *gin.Context, code int) bool {
|
||||
if c == nil || !IsSessionExpiredCode(code) {
|
||||
return false
|
||||
}
|
||||
ClearAuthCookies(c)
|
||||
for _, name := range authCookieNames() {
|
||||
dropRequestCookie(c, name)
|
||||
}
|
||||
dropRequestCookie(c, guestSkipAutoCookie)
|
||||
ClearGuestSkipAuto(c)
|
||||
// 内容读取接口明确允许降级为游客,因此覆盖本请求可能已有的自动认证抑制。
|
||||
allowRequestAutoAuth(c)
|
||||
return EnsureGuestOnEnter(c) != nil
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package authser
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// RegisterReq 对应 swagger authapi.registerReq
|
||||
type RegisterReq struct {
|
||||
AccountNo string `json:"accountNo"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Password string `json:"password"`
|
||||
AgentInviteCode string `json:"agentInviteCode,omitempty"`
|
||||
DevID string `json:"devID,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// LoginReq 对应 swagger authapi.loginReq
|
||||
type LoginReq struct {
|
||||
Account string `json:"account"`
|
||||
Password string `json:"password"`
|
||||
DevID string `json:"devID,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// ResetPasswordReq 对应 swagger authapi.resetPasswordReq。
|
||||
type ResetPasswordReq struct {
|
||||
AccountNo string `json:"accountNo"`
|
||||
Email string `json:"email"`
|
||||
NewPassword string `json:"newPassword"`
|
||||
}
|
||||
|
||||
// GuestLoginReq 对应 swagger authser.GuestLoginReq
|
||||
// POST /api/app/auth/guest
|
||||
type GuestLoginReq struct {
|
||||
DevID string `json:"devID"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
Mac string `json:"mac,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateProfileReq 对应 swagger authapi.updateProfileReq
|
||||
type UpdateProfileReq struct {
|
||||
Avatar *string `json:"avatar,omitempty"`
|
||||
Introduction *string `json:"introduction,omitempty"`
|
||||
NickName *string `json:"nickName,omitempty"`
|
||||
OldPassword *string `json:"oldPassword,omitempty"`
|
||||
NewPassword *string `json:"newPassword,omitempty"`
|
||||
PrivacyMode *bool `json:"privacyMode,omitempty"`
|
||||
}
|
||||
|
||||
// LoginResp 对应 swagger authser.LoginResp
|
||||
// GET /api/app/auth/getInfo、登录/注册/游客成功 data。
|
||||
type LoginResp struct {
|
||||
Token string `json:"token"`
|
||||
UserID int64 `json:"userId"`
|
||||
AccountNo string `json:"accountNo"`
|
||||
Email string `json:"email"`
|
||||
NickName string `json:"nickName"`
|
||||
Introduction string `json:"introduction"` // 简介
|
||||
Avatar string `json:"avatar"` // 头像
|
||||
InviteCode string `json:"inviteCode"` // 邀请码
|
||||
VipType int `json:"vipType"` // 0没卡 1月卡 2年卡
|
||||
CurrentVipExpire string `json:"currentVipExpire"` // VIP 过期时间,需结合 vipType 判断是否有效
|
||||
ShowCardID int64 `json:"showCardId"` // 最新会员卡 id
|
||||
ShowCardName string `json:"showCardName"` // 最新会员卡名称,如「1个月会员」
|
||||
Status int `json:"status"` // 0正常 1封禁 2禁言
|
||||
Type int `json:"type"` // 身份类型:0游客 1普通用户
|
||||
IsNewUser bool `json:"isNewUser"` // 本次是否新建游客
|
||||
IsRegister bool `json:"isRegister"` // 是否已注册
|
||||
HasPassword *bool `json:"hasPassword,omitempty"` // 是否已设置密码;上游未返回时由账号状态推断
|
||||
LoginType int `json:"loginType"` // 登录方式
|
||||
PrivacyMode bool `json:"privacyMode"` // 隐私模式
|
||||
Score int64 `json:"score"` // 积分
|
||||
Recharge int64 `json:"recharge"` // 金币余额
|
||||
}
|
||||
|
||||
// APIEnvelope 上游统一响应壳。Data 在失败时可能是 string/null。
|
||||
type APIEnvelope struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// ImageUploadData 对应 swagger uploadser.ImageUploadData
|
||||
type ImageUploadData struct {
|
||||
ID string `json:"id"`
|
||||
SourceNameFs string `json:"sourceNameFs"`
|
||||
}
|
||||
|
||||
// ImageUploadResp 对应 swagger uploadser.ImageUploadResp
|
||||
type ImageUploadResp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data *ImageUploadData `json:"data"`
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SettingPageVM 账号设置页展示模型。
|
||||
type SettingPageVM struct {
|
||||
UserID int64
|
||||
AccountNo string
|
||||
HasAccount bool
|
||||
HasPassword bool
|
||||
NickName string
|
||||
Introduction string
|
||||
Email string
|
||||
EmailMasked string
|
||||
EmailBound bool
|
||||
Avatar string // 可用头像 URL;空则模板用默认图
|
||||
InviteCode string
|
||||
PrivacyMode bool
|
||||
VipType int
|
||||
VipExpire string
|
||||
Recharge int64
|
||||
Score int64
|
||||
DisplayName string
|
||||
}
|
||||
|
||||
// BuildSettingVM 由 LoginResp 构建设置页 VM。
|
||||
func BuildSettingVM(user *LoginResp) SettingPageVM {
|
||||
if user == nil {
|
||||
return SettingPageVM{}
|
||||
}
|
||||
nick := strings.TrimSpace(user.NickName)
|
||||
account := strings.TrimSpace(user.AccountNo)
|
||||
registered := user.IsRegister || user.Type == 1
|
||||
hasAccount := registered && account != ""
|
||||
hasPassword := hasAccount
|
||||
if user.HasPassword != nil {
|
||||
hasPassword = *user.HasPassword
|
||||
}
|
||||
email := strings.TrimSpace(user.Email)
|
||||
intro := strings.TrimSpace(user.Introduction)
|
||||
display := nick
|
||||
if display == "" {
|
||||
display = account
|
||||
}
|
||||
if display == "" {
|
||||
display = "用户"
|
||||
}
|
||||
return SettingPageVM{
|
||||
UserID: user.UserID,
|
||||
AccountNo: account,
|
||||
HasAccount: hasAccount,
|
||||
HasPassword: hasPassword,
|
||||
NickName: nick,
|
||||
Introduction: intro,
|
||||
Email: email,
|
||||
EmailMasked: MaskEmail(email),
|
||||
EmailBound: email != "",
|
||||
Avatar: usableAvatarURL(user.Avatar),
|
||||
InviteCode: strings.TrimSpace(user.InviteCode),
|
||||
PrivacyMode: user.PrivacyMode,
|
||||
VipType: user.VipType,
|
||||
VipExpire: strings.TrimSpace(user.CurrentVipExpire),
|
||||
Recharge: user.Recharge,
|
||||
Score: user.Score,
|
||||
DisplayName: display,
|
||||
}
|
||||
}
|
||||
|
||||
// MaskEmail 邮箱脱敏,如 ab***@mail.com。
|
||||
func MaskEmail(email string) string {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" {
|
||||
return ""
|
||||
}
|
||||
at := strings.LastIndex(email, "@")
|
||||
if at <= 0 || at == len(email)-1 {
|
||||
return email
|
||||
}
|
||||
local := email[:at]
|
||||
domain := email[at:]
|
||||
runes := []rune(local)
|
||||
if len(runes) <= 2 {
|
||||
return string(runes[:1]) + "***" + domain
|
||||
}
|
||||
return string(runes[:2]) + "***" + domain
|
||||
}
|
||||
|
||||
// FormatUserID 展示用 ID。
|
||||
func FormatUserID(id int64) string {
|
||||
if id <= 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d", id)
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
package authser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func parseVipExpireMs(raw string) int64 {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0
|
||||
}
|
||||
if n, err := strconv.ParseInt(raw, 10, 64); err == nil {
|
||||
if n > 0 && n < 1e12 {
|
||||
return n * 1000
|
||||
}
|
||||
return n
|
||||
}
|
||||
layouts := []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02T15:04:05Z07:00",
|
||||
"2006-01-02 15:04:05",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.Parse(layout, raw); err == nil {
|
||||
return t.UnixMilli()
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// UserIDFromCookies 读取 cookie userId。
|
||||
func UserIDFromCookies(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(cookieValue(c, "userId")), 10, 64)
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// VipTypeFromCookies 读取 cookie vipType。
|
||||
func VipTypeFromCookies(c *gin.Context) int {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.Atoi(strings.TrimSpace(cookieValue(c, "vipType")))
|
||||
return n
|
||||
}
|
||||
|
||||
// VipTypeLabel vipType 文案:0普通 1月卡 2年卡(与 91ly / 编辑资料注释一致)。
|
||||
func VipTypeLabel(vipType int) string {
|
||||
switch vipType {
|
||||
case 1:
|
||||
return "月卡会员"
|
||||
case 2:
|
||||
return "年卡会员"
|
||||
default:
|
||||
return "普通会员"
|
||||
}
|
||||
}
|
||||
|
||||
// ShowCardNameFromCookies 读取 cookie showCardName。
|
||||
func ShowCardNameFromCookies(c *gin.Context) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(cookieValue(c, "showCardName"))
|
||||
}
|
||||
|
||||
// ShowCardIDFromCookies 读取 cookie showCardId。
|
||||
func ShowCardIDFromCookies(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(cookieValue(c, "showCardId")), 10, 64)
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// VipDisplayLabel 优先使用 getInfo.showCardName,否则回退 vipType 文案。
|
||||
func VipDisplayLabel(showCardName string, vipType int) string {
|
||||
if s := strings.TrimSpace(showCardName); s != "" {
|
||||
return s
|
||||
}
|
||||
return VipTypeLabel(vipType)
|
||||
}
|
||||
|
||||
// VipDisplayLabelFromCookies 从 cookie 组装会员展示名。
|
||||
func VipDisplayLabelFromCookies(c *gin.Context) string {
|
||||
return VipDisplayLabel(ShowCardNameFromCookies(c), VipTypeFromCookies(c))
|
||||
}
|
||||
|
||||
// IsActiveVipUser 根据 vipType + currentVipExpire 判断是否有效会员。
|
||||
func IsActiveVipUser(vipType int, currentVipExpire string) bool {
|
||||
if vipType == 0 {
|
||||
return false
|
||||
}
|
||||
expireMs := parseVipExpireMs(currentVipExpire)
|
||||
if expireMs <= 0 {
|
||||
return false
|
||||
}
|
||||
return expireMs > time.Now().UnixMilli()
|
||||
}
|
||||
|
||||
// FormatVipExpireText 格式化到期时间展示。
|
||||
func FormatVipExpireText(currentVipExpire string) string {
|
||||
ms := parseVipExpireMs(currentVipExpire)
|
||||
if ms <= 0 {
|
||||
return ""
|
||||
}
|
||||
return time.UnixMilli(ms).In(time.Local).Format("有效期至 2006/01/02")
|
||||
}
|
||||
|
||||
// VipExpireTextFromCookies 格式化到期时间展示。
|
||||
func VipExpireTextFromCookies(c *gin.Context) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return FormatVipExpireText(cookieValue(c, "currentVipExpire"))
|
||||
}
|
||||
|
||||
// IsActiveVipFromCookies vipType≠0 且 currentVipExpire 未过期(与 91ly 一致)。
|
||||
func IsActiveVipFromCookies(c *gin.Context) bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
return IsActiveVipUser(VipTypeFromCookies(c), cookieValue(c, "currentVipExpire"))
|
||||
}
|
||||
|
||||
// RechargeFromCookies 读取 cookie recharge(金币余额)。
|
||||
func RechargeFromCookies(c *gin.Context) int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(cookieValue(c, "recharge")), 10, 64)
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// SetRechargeCookie 更新金币余额 cookie(解锁/充值后同步)。
|
||||
func SetRechargeCookie(c *gin.Context, balance int64) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
if balance < 0 {
|
||||
balance = 0
|
||||
}
|
||||
secure := c.Request != nil && c.Request.TLS != nil
|
||||
setCookie(c, "recharge", strconv.FormatInt(balance, 10), secure)
|
||||
}
|
||||
|
||||
// FormatRecharge 金币余额千分位展示。
|
||||
func FormatRecharge(n int64) string {
|
||||
if n < 0 {
|
||||
n = 0
|
||||
}
|
||||
s := strconv.FormatInt(n, 10)
|
||||
if len(s) <= 3 {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
rem := len(s) % 3
|
||||
if rem > 0 {
|
||||
b.WriteString(s[:rem])
|
||||
if len(s) > rem {
|
||||
b.WriteByte(',')
|
||||
}
|
||||
}
|
||||
for i := rem; i < len(s); i += 3 {
|
||||
b.WriteString(s[i : i+3])
|
||||
if i+3 < len(s) {
|
||||
b.WriteByte(',')
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package commentser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const likeSetPath = "/api/app/comment/like/set"
|
||||
|
||||
// LikeSet 设置评论点赞/取消点赞。
|
||||
func LikeSet(c *gin.Context, req CommentLikeSetReq) (*APIEnvelope[CommentLikeSetResp], error) {
|
||||
if req.CommentID <= 0 {
|
||||
return nil, fmt.Errorf("comment like invalid commentId")
|
||||
}
|
||||
var env APIEnvelope[CommentLikeSetResp]
|
||||
if _, err := upstream.PostJSON(c, likeSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
@@ -57,18 +56,11 @@ func FetchList(c *gin.Context, q ListQuery) (*GetCommentListResp, error) {
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
params.Set("sortOrder", strconv.Itoa(q.SortOrder))
|
||||
|
||||
authser.EnsureGuestOnEnter(c)
|
||||
requestPath := listPath + "?" + params.Encode()
|
||||
env, err := fetchListOnce(c, requestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 && authser.IsSessionExpiredCode(env.Code) && authser.RecoverContentSession(c, env.Code) {
|
||||
env, err = fetchListOnce(c, requestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("comment list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package commentser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const sendPath = "/api/app/comment/send"
|
||||
|
||||
// Send 发布评论(一级 / 二级)。
|
||||
func Send(c *gin.Context, req CommentSendReq) (*APIEnvelope[any], error) {
|
||||
req.Text = strings.TrimSpace(req.Text)
|
||||
if req.ObjectID <= 0 {
|
||||
return nil, fmt.Errorf("comment send invalid objectId")
|
||||
}
|
||||
req.ObjectType = NormalizeObjectType(req.ObjectType)
|
||||
if req.Text == "" {
|
||||
return nil, fmt.Errorf("comment send empty text")
|
||||
}
|
||||
if utf8.RuneCountInString(req.Text) > 200 {
|
||||
return nil, fmt.Errorf("comment send text too long")
|
||||
}
|
||||
if req.ParentsID < 0 {
|
||||
req.ParentsID = 0
|
||||
}
|
||||
if req.ReplyCommentID < 0 {
|
||||
req.ReplyCommentID = 0
|
||||
}
|
||||
// 二级评论:未显式指定 replyCommentId 时默认回复父评论
|
||||
if req.ParentsID > 0 && req.ReplyCommentID <= 0 {
|
||||
req.ReplyCommentID = req.ParentsID
|
||||
}
|
||||
|
||||
var env APIEnvelope[any]
|
||||
if _, err := upstream.PostJSON(c, sendPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -47,9 +47,9 @@ func FetchAppConfigVMOrEmpty(c *gin.Context) AppConfigVM {
|
||||
if configCache != nil {
|
||||
return *configCache
|
||||
}
|
||||
return ApplyTrackerFallback(AppConfigVM{})
|
||||
return AppConfigVM{}
|
||||
}
|
||||
vm := ApplyTrackerFallback(BuildAppConfigVM(info))
|
||||
vm := BuildAppConfigVM(info)
|
||||
configCache = &vm
|
||||
configAt = time.Now()
|
||||
return vm
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package configser
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"videoweb/app/appg"
|
||||
)
|
||||
|
||||
// ResolveTrackerAppID 优先 yaml,否则固定 JHA-1045。
|
||||
func ResolveTrackerAppID() string {
|
||||
return appg.TrackerAppID()
|
||||
}
|
||||
|
||||
// ResolveReportSDKConfig 上游 reportSdkConfig 优先,本地 yaml 兜底。
|
||||
func ResolveReportSDKConfig(fromAPI string) string {
|
||||
if v := strings.TrimSpace(fromAPI); v != "" {
|
||||
return v
|
||||
}
|
||||
return strings.TrimSpace(appg.Conf.Tracker.EncryptedConfig)
|
||||
}
|
||||
|
||||
// ApplyTrackerFallback 补齐 AppConfigVM 中的上报密文。
|
||||
func ApplyTrackerFallback(vm AppConfigVM) AppConfigVM {
|
||||
vm.ReportSDKConfig = ResolveReportSDKConfig(vm.ReportSDKConfig)
|
||||
return vm
|
||||
}
|
||||
@@ -52,16 +52,14 @@ type FooterContact struct {
|
||||
|
||||
// ConfigInfoResp 对应 swagger proto.ConfigInfoResp
|
||||
// GET /api/app/config/info
|
||||
// reportSdkConfig 与 proto.ConfigInfo 对齐;上游若尚未下发则为空,可由本地 yaml 兜底。
|
||||
// config 为上游实际下发的完整站点配置(swagger 未完整声明,但含 potaoGroup 等字段)。
|
||||
type ConfigInfoResp struct {
|
||||
NewAddressInfo NewAddressInfo `json:"newAddressInfo"`
|
||||
Config ConfigInfo `json:"config"`
|
||||
Advitise AdvitiseData `json:"advitise"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
SeoNavInfo SeoNavInfo `json:"seoNavInfo"`
|
||||
NavPageList []NavPageItem `json:"navPageList"`
|
||||
ReportSDKConfig string `json:"reportSdkConfig"`
|
||||
NewAddressInfo NewAddressInfo `json:"newAddressInfo"`
|
||||
Config ConfigInfo `json:"config"`
|
||||
Advitise AdvitiseData `json:"advitise"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
SeoNavInfo SeoNavInfo `json:"seoNavInfo"`
|
||||
NavPageList []NavPageItem `json:"navPageList"`
|
||||
}
|
||||
|
||||
// ConfigInfo 对应上游 data.config(proto.ConfigInfo 子集,按页面需要取用)。
|
||||
|
||||
@@ -29,7 +29,6 @@ type AppConfigVM struct {
|
||||
SeoInfo SeoInfo `json:"seoInfo,omitempty"`
|
||||
SeoNavInfo SeoNavInfo `json:"seoNavInfo,omitempty"`
|
||||
NavPageList []NavPageItem `json:"navPageList,omitempty"`
|
||||
ReportSDKConfig string `json:"reportSdkConfig,omitempty"`
|
||||
Advitise AdvitiseData `json:"advitise"`
|
||||
DetailTopList []Advertisement `json:"detailTopList,omitempty"`
|
||||
NineGridList []Advertisement `json:"nineGridList,omitempty"`
|
||||
@@ -64,7 +63,6 @@ func BuildAppConfigVM(info *ConfigInfoResp) AppConfigVM {
|
||||
TwitterAddr: firstNonEmptyURL(cfg.TwitterAddr, addr.TwitterAddr),
|
||||
GitAddr: sanitizeURL(cfg.GitAddr),
|
||||
FreeVPN: sanitizeURL(cfg.FreeVPN),
|
||||
ReportSDKConfig: strings.TrimSpace(info.ReportSDKConfig),
|
||||
NavPageList: buildNavPageList(info.NavPageList),
|
||||
Advitise: info.Advitise,
|
||||
DetailTopList: buildAdvertisementList(info.Advitise.DetailTopList),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package feedbackser
|
||||
|
||||
import (
|
||||
"videoweb/app/service/authser"
|
||||
"io"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -11,9 +11,11 @@ const addPath = "/api/app/feedback/add"
|
||||
|
||||
const contactUsAddPath = "/api/app/contactus/add"
|
||||
|
||||
const uploadPath = "/api/app/upload/image"
|
||||
|
||||
// Add 调用上游提交意见反馈。
|
||||
func Add(c *gin.Context, req FeedbackReq) (*authser.APIEnvelope, error) {
|
||||
var env authser.APIEnvelope
|
||||
func Add(c *gin.Context, req FeedbackReq) (*APIEnvelope, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, addPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -21,10 +23,26 @@ func Add(c *gin.Context, req FeedbackReq) (*authser.APIEnvelope, error) {
|
||||
}
|
||||
|
||||
// AddContactUs 调用上游联系我们接口。
|
||||
func AddContactUs(c *gin.Context, req ContactUsAddReq) (*authser.APIEnvelope, error) {
|
||||
var env authser.APIEnvelope
|
||||
func AddContactUs(c *gin.Context, req ContactUsAddReq) (*APIEnvelope, error) {
|
||||
var env APIEnvelope
|
||||
if _, err := upstream.PostJSON(c, contactUsAddPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// UploadImage 上传反馈截图;不加水印。
|
||||
func UploadImage(c *gin.Context, fileName string, r io.Reader) (*ImageUploadResp, error) {
|
||||
var resp ImageUploadResp
|
||||
_, err := upstream.PostMultipart(c, uploadPath, map[string]string{
|
||||
"watermark": "0",
|
||||
}, &upstream.MultipartFile{
|
||||
FieldName: "file",
|
||||
FileName: fileName,
|
||||
Reader: r,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
package feedbackser
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// APIEnvelope 上游通用响应。
|
||||
type APIEnvelope struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// ImageUploadData 对应 swagger uploadser.ImageUploadData
|
||||
type ImageUploadData struct {
|
||||
ID string `json:"id"`
|
||||
SourceNameFs string `json:"sourceNameFs"`
|
||||
}
|
||||
|
||||
// ImageUploadResp 对应 swagger uploadser.ImageUploadResp
|
||||
type ImageUploadResp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data *ImageUploadData `json:"data"`
|
||||
}
|
||||
|
||||
// FeedbackReq 对应 swagger proto.FeedbackReq。
|
||||
// type(接口说明):1-功能建议、2-播放问题、3-账号问题、4-其他
|
||||
type FeedbackReq struct {
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const boughtListPath = "/api/app/playlet/bought/list"
|
||||
|
||||
// PlayletBoughtData 对应 proto.PlayletBoughtData;只列出页面所需字段。
|
||||
type PlayletBoughtData struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
PlayName string `json:"playName"`
|
||||
Slug string `json:"slug"`
|
||||
Cover string `json:"cover"`
|
||||
ThemeNames []string `json:"themeNames"`
|
||||
TotalEpisode int `json:"totalEpisode"`
|
||||
BoughtChapterCount int `json:"boughtChapterCount"`
|
||||
CostCoins int64 `json:"costCoins"`
|
||||
BoughtAt string `json:"boughtAt"`
|
||||
LastChapterID int64 `json:"lastChapterId"`
|
||||
LastEpisode int `json:"lastEpisode"`
|
||||
WatchedCount int `json:"watchedCount"`
|
||||
}
|
||||
|
||||
type PlayletBoughtListResp struct {
|
||||
List []PlayletBoughtData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
func FetchBoughtList(c *gin.Context, pageNum, pageSize int) (*PlayletBoughtListResp, int, error) {
|
||||
if pageNum < 1 {
|
||||
pageNum = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(pageNum))
|
||||
params.Set("pageSize", strconv.Itoa(pageSize))
|
||||
var env APIEnvelope[PlayletBoughtListResp]
|
||||
if err := upstream.GetJSON(c, boughtListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("playlet bought list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, env.Code, nil
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
@@ -49,18 +48,10 @@ func FetchChapterDetail(c *gin.Context, chapterID, playletID int64, playletSlug
|
||||
} else if playletID > 0 {
|
||||
params.Set("playletId", strconv.FormatInt(playletID, 10))
|
||||
}
|
||||
authser.EnsureGuestOnEnter(c)
|
||||
var env APIEnvelope[PlayletChapterInfoResp]
|
||||
if err := upstream.GetJSON(c, chapterDetailPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 && authser.IsSessionExpiredCode(env.Code) {
|
||||
if authser.RecoverContentSession(c, env.Code) {
|
||||
if err := upstream.GetJSON(c, chapterDetailPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("chapter detail code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
@@ -91,18 +82,10 @@ func FetchChapterList(c *gin.Context, playletID int64, playletSlug string) (*Pla
|
||||
} else {
|
||||
return nil, fmt.Errorf("chapter list missing playletSlug or playletId")
|
||||
}
|
||||
authser.EnsureGuestOnEnter(c)
|
||||
var env APIEnvelope[PlayletChapterListResp]
|
||||
if err := upstream.GetJSON(c, chapterListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 && authser.IsSessionExpiredCode(env.Code) {
|
||||
if authser.RecoverContentSession(c, env.Code) {
|
||||
if err := upstream.GetJSON(c, chapterListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet chapter list code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const chapterCollectListPath = "/api/app/playlet/chapter/collect/list"
|
||||
|
||||
// PlayletChapterCollectData 对应 swagger proto.PlayletChapterCollectData
|
||||
type PlayletChapterCollectData struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
ChapterTitle string `json:"chapterTitle"`
|
||||
PlayletID int64 `json:"playletId"`
|
||||
PlayletSlug string `json:"playletSlug"`
|
||||
PlayletTitle string `json:"playletTitle"`
|
||||
PlayletCover string `json:"playletCover"`
|
||||
CurrentEpisode int `json:"currentEpisode"`
|
||||
TotalEpisode int `json:"totalEpisode"`
|
||||
UpdateStatus int `json:"updateStatus"`
|
||||
CountBrowse int64 `json:"countBrowse"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
CollectedAt string `json:"collectedAt"`
|
||||
MediaTime int `json:"mediaTime"`
|
||||
PayType int `json:"payType"`
|
||||
SingleCoins int `json:"singleCoins"`
|
||||
VideoURL string `json:"videoUrl"`
|
||||
}
|
||||
|
||||
// PlayletChapterCollectListResp 对应 swagger proto.PlayletChapterCollectListResp
|
||||
type PlayletChapterCollectListResp struct {
|
||||
List []PlayletChapterCollectData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// FetchChapterCollectList 拉取当前用户剧集收藏列表。
|
||||
// 第二个返回值为上游业务 code(网络错误时为 0)。
|
||||
func FetchChapterCollectList(c *gin.Context, q CollectListQuery) (*PlayletChapterCollectListResp, int, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
|
||||
var env APIEnvelope[PlayletChapterCollectListResp]
|
||||
if err := upstream.GetJSON(c, chapterCollectListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("playlet chapter collect list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, env.Code, nil
|
||||
}
|
||||
|
||||
// FetchChapterCollectListOrEmpty 失败时返回空列表;游客会话失效时尝试重登后重试一次。
|
||||
func FetchChapterCollectListOrEmpty(c *gin.Context, q CollectListQuery) *PlayletChapterCollectListResp {
|
||||
data, code, err := FetchChapterCollectList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &PlayletChapterCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
if retry, _ := authser.OnSessionExpired(c, code); retry {
|
||||
data, _, err = FetchChapterCollectList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &PlayletChapterCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
log.Error("fetch playlet chapter collect list failed", log.E(err))
|
||||
return &PlayletChapterCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
chapterLikeSetPath = "/api/app/playlet/chapter/like/set"
|
||||
chapterCollectSetPath = "/api/app/playlet/chapter/collect/set"
|
||||
)
|
||||
|
||||
// PlayletChapterLikeSetReq 对应 swagger proto.PlayletChapterLikeSetReq
|
||||
type PlayletChapterLikeSetReq struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
IsLike bool `json:"isLike"`
|
||||
}
|
||||
|
||||
// PlayletChapterLikeSetResp 对应 swagger proto.PlayletChapterLikeSetResp
|
||||
type PlayletChapterLikeSetResp struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
IsLike int `json:"isLike"`
|
||||
}
|
||||
|
||||
// ChapterLikeSet 设置剧集点赞/取消点赞。
|
||||
func ChapterLikeSet(c *gin.Context, req PlayletChapterLikeSetReq) (*APIEnvelope[PlayletChapterLikeSetResp], error) {
|
||||
if req.ChapterID <= 0 {
|
||||
return nil, fmt.Errorf("chapter like invalid chapterId")
|
||||
}
|
||||
var env APIEnvelope[PlayletChapterLikeSetResp]
|
||||
if _, err := upstream.PostJSON(c, chapterLikeSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// PlayletChapterCollectSetReq 对应 swagger proto.PlayletChapterCollectSetReq
|
||||
type PlayletChapterCollectSetReq struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
IsCollect bool `json:"isCollect"`
|
||||
}
|
||||
|
||||
// PlayletChapterCollectSetResp 对应 swagger proto.PlayletChapterCollectSetResp
|
||||
type PlayletChapterCollectSetResp struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
}
|
||||
|
||||
// ChapterCollectSet 设置剧集收藏/取消收藏。
|
||||
func ChapterCollectSet(c *gin.Context, req PlayletChapterCollectSetReq) (*APIEnvelope[PlayletChapterCollectSetResp], error) {
|
||||
if req.ChapterID <= 0 {
|
||||
return nil, fmt.Errorf("chapter collect invalid chapterId")
|
||||
}
|
||||
var env APIEnvelope[PlayletChapterCollectSetResp]
|
||||
if _, err := upstream.PostJSON(c, chapterCollectSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const chapterUnlockPath = "/api/app/playlet/chapter/unlock"
|
||||
|
||||
// PlayletChapterUnlockReq 对应 swagger proto.PlayletChapterUnlockReq
|
||||
// POST /api/app/playlet/chapter/unlock
|
||||
type PlayletChapterUnlockReq struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
PlayletID int64 `json:"playletId"`
|
||||
}
|
||||
|
||||
// PlayletChapterUnlockResp 对应 swagger proto.PlayletChapterUnlockResp
|
||||
type PlayletChapterUnlockResp struct {
|
||||
Balance int64 `json:"balance"`
|
||||
CanWatch bool `json:"canWatch"`
|
||||
ChangeCoin int64 `json:"changeCoin"`
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
CostCoins int64 `json:"costCoins"`
|
||||
PlayletID int64 `json:"playletId"`
|
||||
Unlocked bool `json:"unlocked"`
|
||||
}
|
||||
|
||||
// ChapterUnlock 使用金币解锁剧集(幂等)。
|
||||
func ChapterUnlock(c *gin.Context, req PlayletChapterUnlockReq) (*APIEnvelope[PlayletChapterUnlockResp], error) {
|
||||
if req.ChapterID <= 0 || req.PlayletID <= 0 {
|
||||
return nil, fmt.Errorf("chapter unlock invalid chapterId/playletId")
|
||||
}
|
||||
var env APIEnvelope[PlayletChapterUnlockResp]
|
||||
if _, err := upstream.PostJSON(c, chapterUnlockPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const chapterWatchReportPath = "/api/app/playlet/chapter/watch/report"
|
||||
|
||||
// PlayletChapterWatchReportReq 对应 swagger proto.PlayletChapterWatchReportReq
|
||||
type PlayletChapterWatchReportReq struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
PlayletID int64 `json:"playletId,omitempty"`
|
||||
}
|
||||
|
||||
// PlayletChapterWatchReportResp 对应 swagger proto.PlayletChapterWatchReportResp
|
||||
type PlayletChapterWatchReportResp struct {
|
||||
ChapterID int64 `json:"chapterId"`
|
||||
PlayletID int64 `json:"playletId"`
|
||||
CurrentEpisode int `json:"currentEpisode"`
|
||||
LastChapterID int64 `json:"lastChapterId"`
|
||||
LastEpisode int `json:"lastEpisode"`
|
||||
WatchedCount int `json:"watchedCount"`
|
||||
UnwatchedCount int `json:"unwatchedCount"`
|
||||
}
|
||||
|
||||
// ChapterWatchReport 上报短剧剧集观看。
|
||||
func ChapterWatchReport(c *gin.Context, req PlayletChapterWatchReportReq) (*APIEnvelope[PlayletChapterWatchReportResp], error) {
|
||||
if req.ChapterID <= 0 {
|
||||
return nil, fmt.Errorf("chapter watch report invalid chapterId")
|
||||
}
|
||||
var env APIEnvelope[PlayletChapterWatchReportResp]
|
||||
if _, err := upstream.PostJSON(c, chapterWatchReportPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
collectSetPath = "/api/app/playlet/collect/set"
|
||||
collectListPath = "/api/app/playlet/collect/list"
|
||||
defaultCollectPageSize = 40
|
||||
|
||||
CollectTypePlaylet = "playlet"
|
||||
CollectTypeChapter = "chapter"
|
||||
)
|
||||
|
||||
// PlayletCollectSetReq 对应 swagger proto.PlayletCollectSetReq
|
||||
type PlayletCollectSetReq struct {
|
||||
ID int64 `json:"id"`
|
||||
IsCollect bool `json:"isCollect"`
|
||||
}
|
||||
|
||||
// PlayletCollectSetResp 对应 swagger proto.PlayletCollectSetResp
|
||||
type PlayletCollectSetResp struct {
|
||||
ID int64 `json:"id"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
}
|
||||
|
||||
// PlayletCollectData 对应 swagger proto.PlayletCollectData
|
||||
type PlayletCollectData struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
PlayName string `json:"playName"`
|
||||
Slug string `json:"slug"`
|
||||
Cover string `json:"cover"`
|
||||
Desc string `json:"desc"`
|
||||
TagIDs []int64 `json:"tagIds"`
|
||||
TagNames []string `json:"tagNames"`
|
||||
TagSlugs []string `json:"tagSlugs"`
|
||||
ThemeIDs []int64 `json:"themeIds"`
|
||||
ThemeNames []string `json:"themeNames"`
|
||||
ThemeSlugs []string `json:"themeSlugs"`
|
||||
TotalEpisode int `json:"totalEpisode"`
|
||||
UpdateStatus int `json:"updateStatus"`
|
||||
CountBrowse int64 `json:"countBrowse"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
IsFeatured bool `json:"isFeatured"`
|
||||
IsNew bool `json:"isNew"`
|
||||
IsRecommend bool `json:"isRecommend"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
CollectedAt string `json:"collectedAt"`
|
||||
WatchedCount int `json:"watchedCount"`
|
||||
UnwatchedCount int `json:"unwatchedCount"`
|
||||
LastChapterID int64 `json:"lastChapterId"`
|
||||
LastEpisode int `json:"lastEpisode"`
|
||||
}
|
||||
|
||||
// PlayletCollectListResp 对应 swagger proto.PlayletCollectListResp
|
||||
type PlayletCollectListResp struct {
|
||||
List []PlayletCollectData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// CollectListQuery 收藏列表分页参数。
|
||||
type CollectListQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
WatchStatus int // 0 全部、1 追剧中、2 已看完;仅短剧收藏列表使用
|
||||
Type string // playlet | chapter
|
||||
}
|
||||
|
||||
// NormalizeCollectType 归一化收藏类型。
|
||||
func NormalizeCollectType(raw string) string {
|
||||
switch strings.TrimSpace(strings.ToLower(raw)) {
|
||||
case CollectTypeChapter, "2", "episode", "ep":
|
||||
return CollectTypeChapter
|
||||
default:
|
||||
return CollectTypePlaylet
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *CollectListQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultCollectPageSize
|
||||
}
|
||||
if q.PageSize > 50 {
|
||||
q.PageSize = 50
|
||||
}
|
||||
if q.WatchStatus < 0 || q.WatchStatus > 2 {
|
||||
q.WatchStatus = 0
|
||||
}
|
||||
q.Type = NormalizeCollectType(q.Type)
|
||||
}
|
||||
|
||||
// CollectSet 设置短剧收藏/取消收藏。
|
||||
func CollectSet(c *gin.Context, req PlayletCollectSetReq) (*APIEnvelope[PlayletCollectSetResp], error) {
|
||||
if req.ID <= 0 {
|
||||
return nil, fmt.Errorf("playlet collect invalid id")
|
||||
}
|
||||
var env APIEnvelope[PlayletCollectSetResp]
|
||||
if _, err := upstream.PostJSON(c, collectSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// FetchCollectList 拉取当前用户短剧收藏列表。
|
||||
// 第二个返回值为上游业务 code(网络错误时为 0)。
|
||||
func FetchCollectList(c *gin.Context, q CollectListQuery) (*PlayletCollectListResp, int, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
params.Set("watchStatus", strconv.Itoa(q.WatchStatus))
|
||||
|
||||
var env APIEnvelope[PlayletCollectListResp]
|
||||
if err := upstream.GetJSON(c, collectListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("playlet collect list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, env.Code, nil
|
||||
}
|
||||
|
||||
// FetchCollectListOrEmpty 失败时返回空列表;游客会话失效时尝试重登后重试一次。
|
||||
func FetchCollectListOrEmpty(c *gin.Context, q CollectListQuery) *PlayletCollectListResp {
|
||||
data, code, err := FetchCollectList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &PlayletCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
if retry, _ := authser.OnSessionExpired(c, code); retry {
|
||||
data, _, err = FetchCollectList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &PlayletCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
log.Error("fetch playlet collect list failed", log.E(err))
|
||||
return &PlayletCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func collectPageURL(pageNum int, collectType string) string {
|
||||
collectType = NormalizeCollectType(collectType)
|
||||
path := "/collect"
|
||||
if collectType != CollectTypePlaylet {
|
||||
path += "/" + url.PathEscape(collectType)
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func CollectCanonicalPath(q CollectListQuery) string {
|
||||
q.Normalize()
|
||||
return collectPageURL(q.PageNum, q.Type)
|
||||
}
|
||||
|
||||
// BuildCollectPagination 收藏列表分页。
|
||||
func BuildCollectPagination(q CollectListQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return collectPageURL(p, q.Type)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// ParseCollectListQuery 从 query 解析分页与类型(playlet 短剧 / chapter 剧集)。
|
||||
func ParseCollectListQuery(pageStr, typeStr string) CollectListQuery {
|
||||
q := CollectListQuery{
|
||||
PageSize: defaultCollectPageSize,
|
||||
Type: NormalizeCollectType(typeStr),
|
||||
}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
|
||||
// collectProgressText 进度文案:优先最近观看集,其次未看/已看完。
|
||||
func collectProgressText(item PlayletCollectData) string {
|
||||
if item.LastEpisode > 0 {
|
||||
return fmt.Sprintf("第%d集", item.LastEpisode)
|
||||
}
|
||||
if item.TotalEpisode > 0 && item.UnwatchedCount <= 0 {
|
||||
return "已看完"
|
||||
}
|
||||
if item.UnwatchedCount > 0 {
|
||||
return fmt.Sprintf("%d集未看", item.UnwatchedCount)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// collectTagText 收藏卡片标签:仅展示 TagNames 第一项,无标签时不显示。
|
||||
func collectTagText(item PlayletCollectData) string {
|
||||
return firstName(item.TagNames)
|
||||
}
|
||||
|
||||
// chapterCollectEpisodeLabel 剧集收藏角标:总集数。
|
||||
func chapterCollectEpisodeLabel(item PlayletChapterCollectData) string {
|
||||
return episodeText(item.TotalEpisode)
|
||||
}
|
||||
|
||||
// chapterCollectDesc 剧集收藏副标题。
|
||||
func chapterCollectDesc(item PlayletChapterCollectData) string {
|
||||
if t := strings.TrimSpace(item.ChapterTitle); t != "" {
|
||||
return t
|
||||
}
|
||||
if item.CurrentEpisode > 0 {
|
||||
return fmt.Sprintf("第%d集", item.CurrentEpisode)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// chapterCollectMeta 剧集收藏右侧文案:第 N 集。
|
||||
func chapterCollectMeta(item PlayletChapterCollectData) string {
|
||||
if item.CurrentEpisode > 0 {
|
||||
return fmt.Sprintf("第%d集", item.CurrentEpisode)
|
||||
}
|
||||
return updateStatusText(item.UpdateStatus)
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
@@ -45,19 +44,10 @@ func FetchDetailByKey(c *gin.Context, key string) (*PlayletInfoResp, error) {
|
||||
}
|
||||
|
||||
func fetchDetail(c *gin.Context, queryKey, value string) (*PlayletInfoResp, error) {
|
||||
authser.EnsureGuestOnEnter(c)
|
||||
env, err := fetchDetailOnce(c, queryKey, value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 && authser.IsSessionExpiredCode(env.Code) {
|
||||
if authser.RecoverContentSession(c, env.Code) {
|
||||
env, err = fetchDetailOnce(c, queryKey, value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet detail code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
historyListPath = "/api/app/playlet/history/list"
|
||||
historyClearPath = "/api/app/playlet/history/clear"
|
||||
historyDeletePath = "/api/app/playlet/history/delete"
|
||||
defaultHistoryPageSize = 40
|
||||
)
|
||||
|
||||
// PlayletHistoryData 对应 swagger proto.PlayletHistoryData
|
||||
// GET /api/app/playlet/history/list
|
||||
type PlayletHistoryData struct {
|
||||
ID int64 `json:"id"`
|
||||
Status int `json:"status"`
|
||||
IsFeatured bool `json:"isFeatured"`
|
||||
IsNew bool `json:"isNew"`
|
||||
IsRecommend bool `json:"isRecommend"`
|
||||
ShowOnBanner bool `json:"showOnBanner"`
|
||||
Banner string `json:"banner"`
|
||||
OnlineAt string `json:"onlineAt"`
|
||||
MediaCreatedAt string `json:"mediaCreatedAt"`
|
||||
MediaUpdatedAt string `json:"mediaUpdatedAt"`
|
||||
ThemeIDs []int64 `json:"themeIds"`
|
||||
ThemeNames []string `json:"themeNames"`
|
||||
ThemeSlugs []string `json:"themeSlugs"`
|
||||
Title string `json:"title"`
|
||||
PlayName string `json:"playName"`
|
||||
Slug string `json:"slug"`
|
||||
Desc string `json:"desc"`
|
||||
Anchor string `json:"anchor"`
|
||||
Cover string `json:"cover"`
|
||||
TagIDs []int64 `json:"tagIds"`
|
||||
TagNames []string `json:"tagNames"`
|
||||
TagSlugs []string `json:"tagSlugs"`
|
||||
TotalEpisode int `json:"totalEpisode"`
|
||||
UpdateStatus int `json:"updateStatus"`
|
||||
CountBrowse int64 `json:"countBrowse"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
WatchedCount int `json:"watchedCount"`
|
||||
UnwatchedCount int `json:"unwatchedCount"`
|
||||
LastChapterID int64 `json:"lastChapterId"`
|
||||
LastEpisode int `json:"lastEpisode"`
|
||||
IsFinished bool `json:"isFinished"`
|
||||
HistoryAt string `json:"historyAt"`
|
||||
}
|
||||
|
||||
// PlayletHistoryListResp 对应 swagger proto.PlayletHistoryListResp
|
||||
type PlayletHistoryListResp struct {
|
||||
List []PlayletHistoryData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// PlayletHistoryClearResp 对应 swagger proto.PlayletHistoryClearResp
|
||||
type PlayletHistoryClearResp struct {
|
||||
DeletedCount int `json:"deletedCount"`
|
||||
}
|
||||
|
||||
// PlayletHistoryDeleteReq 对应 swagger proto.PlayletHistoryDeleteReq
|
||||
type PlayletHistoryDeleteReq struct {
|
||||
PlayletID int64 `json:"playletId"`
|
||||
}
|
||||
|
||||
// PlayletHistoryDeleteResp 对应 swagger proto.PlayletHistoryDeleteResp
|
||||
type PlayletHistoryDeleteResp struct {
|
||||
DeletedCount int `json:"deletedCount"`
|
||||
}
|
||||
|
||||
// HistoryListQuery 观看历史分页参数。
|
||||
type HistoryListQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *HistoryListQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultHistoryPageSize
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
}
|
||||
|
||||
// FetchHistoryList 分页查询当前用户观看历史。
|
||||
// 第二个返回值为上游业务 code(网络错误时为 0)。
|
||||
func FetchHistoryList(c *gin.Context, q HistoryListQuery) (*PlayletHistoryListResp, int, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
|
||||
var env APIEnvelope[PlayletHistoryListResp]
|
||||
if err := upstream.GetJSON(c, historyListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("playlet history list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, env.Code, nil
|
||||
}
|
||||
|
||||
// FetchHistoryListOrEmpty 失败时返回空列表;游客会话失效时尝试重登后重试一次。
|
||||
func FetchHistoryListOrEmpty(c *gin.Context, q HistoryListQuery) *PlayletHistoryListResp {
|
||||
data, code, err := FetchHistoryList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &PlayletHistoryListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
if retry, _ := authser.OnSessionExpired(c, code); retry {
|
||||
data, _, err = FetchHistoryList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &PlayletHistoryListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
log.Error("fetch playlet history list failed", log.E(err))
|
||||
return &PlayletHistoryListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
|
||||
// HistoryClear 清空当前用户短剧观看历史。
|
||||
// POST /api/app/playlet/history/clear,无请求体。
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/app短剧相关接口/post_api_app_playlet_history_clear
|
||||
func HistoryClear(c *gin.Context) (*APIEnvelope[PlayletHistoryClearResp], error) {
|
||||
var env APIEnvelope[PlayletHistoryClearResp]
|
||||
if _, err := upstream.PostJSON(c, historyClearPath, nil, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// HistoryDelete 删除单条短剧观看历史。
|
||||
// POST /api/app/playlet/history/delete
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/app短剧相关接口/post_api_app_playlet_history_delete
|
||||
func HistoryDelete(c *gin.Context, req PlayletHistoryDeleteReq) (*APIEnvelope[PlayletHistoryDeleteResp], error) {
|
||||
if req.PlayletID <= 0 {
|
||||
return nil, fmt.Errorf("playlet history delete invalid playletId")
|
||||
}
|
||||
var env APIEnvelope[PlayletHistoryDeleteResp]
|
||||
if _, err := upstream.PostJSON(c, historyDeletePath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func historyPageURL(pageNum int) string {
|
||||
if pageNum <= 1 {
|
||||
return "/history"
|
||||
}
|
||||
return "/history/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
|
||||
func HistoryCanonicalPath(q HistoryListQuery) string {
|
||||
q.Normalize()
|
||||
return historyPageURL(q.PageNum)
|
||||
}
|
||||
|
||||
// BuildHistoryPagination 观看历史分页。
|
||||
func BuildHistoryPagination(q HistoryListQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return historyPageURL(p)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// ParseHistoryListQuery 从 query 解析分页。
|
||||
func ParseHistoryListQuery(pageStr string) HistoryListQuery {
|
||||
q := HistoryListQuery{PageSize: defaultHistoryPageSize}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
|
||||
func historyFinished(item PlayletHistoryData) bool {
|
||||
if item.IsFinished {
|
||||
return true
|
||||
}
|
||||
return item.TotalEpisode > 0 && item.UnwatchedCount <= 0 && item.WatchedCount > 0
|
||||
}
|
||||
|
||||
// historyStatus 卡片筛选状态:finished / unfinished。
|
||||
func historyStatus(item PlayletHistoryData) string {
|
||||
if historyFinished(item) {
|
||||
return "finished"
|
||||
}
|
||||
return "unfinished"
|
||||
}
|
||||
|
||||
// historyProgressText PC 卡片未看文案,使用接口 unwatchedCount / isFinished。
|
||||
func historyProgressText(item PlayletHistoryData) string {
|
||||
if historyFinished(item) {
|
||||
return "已看完"
|
||||
}
|
||||
if item.UnwatchedCount > 0 {
|
||||
return fmt.Sprintf("%d集未看", item.UnwatchedCount)
|
||||
}
|
||||
if item.LastEpisode > 0 {
|
||||
return fmt.Sprintf("看到第%d集", item.LastEpisode)
|
||||
}
|
||||
return "未看完"
|
||||
}
|
||||
|
||||
// historyWatchLine H5 进度行。
|
||||
func historyWatchLine(item PlayletHistoryData) string {
|
||||
if historyFinished(item) {
|
||||
if item.LastEpisode > 0 {
|
||||
return fmt.Sprintf("第%d集 · 已看完", item.LastEpisode)
|
||||
}
|
||||
return "已看完"
|
||||
}
|
||||
ep := "未开始"
|
||||
if item.LastEpisode > 0 {
|
||||
ep = fmt.Sprintf("第%d集", item.LastEpisode)
|
||||
}
|
||||
if item.UnwatchedCount > 0 {
|
||||
return ep + fmt.Sprintf(" · 还有%d集未看", item.UnwatchedCount)
|
||||
}
|
||||
return ep + " · 未看完"
|
||||
}
|
||||
|
||||
// historyTagText 历史卡片标签:仅展示 TagNames 第一项,无标签时不显示。
|
||||
func historyTagText(item PlayletHistoryData) string {
|
||||
return firstName(item.TagNames)
|
||||
}
|
||||
|
||||
// historyPlayURL 继续播放:优先最近观看剧集。
|
||||
func historyPlayURL(item PlayletHistoryData) string {
|
||||
return chapterPlayURL(item.Slug, item.ID, item.LastChapterID)
|
||||
}
|
||||
|
||||
// historyContinueMeta 首页「继续观看」文案:看至第 N 集 / 剩 M 集。
|
||||
func historyContinueMeta(item PlayletHistoryData) string {
|
||||
if item.LastEpisode <= 0 {
|
||||
return "观看记录"
|
||||
}
|
||||
meta := fmt.Sprintf("看至第 %d 集", item.LastEpisode)
|
||||
if item.UnwatchedCount > 0 {
|
||||
meta += fmt.Sprintf(" 剩 %d 集", item.UnwatchedCount)
|
||||
}
|
||||
return meta
|
||||
}
|
||||
|
||||
// historyProgressPct 观看进度百分比,供卡片 --p 使用。
|
||||
func historyProgressPct(item PlayletHistoryData) string {
|
||||
progress := 0
|
||||
if item.TotalEpisode > 0 {
|
||||
progress = item.WatchedCount * 100 / item.TotalEpisode
|
||||
}
|
||||
if progress < 0 {
|
||||
progress = 0
|
||||
}
|
||||
if progress > 100 {
|
||||
progress = 100
|
||||
}
|
||||
return fmt.Sprintf("%d%%", progress)
|
||||
}
|
||||
|
||||
// FormatHistoryAt 最近观看时间展示。
|
||||
func FormatHistoryAt(raw string) string {
|
||||
return formatHistoryAt(raw)
|
||||
}
|
||||
|
||||
// FormatHistoryListTime 观看历史列表时间:今天/昨天带时刻,更早仅日期。
|
||||
func FormatHistoryListTime(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
t, ok := parseHistoryTime(raw)
|
||||
if !ok {
|
||||
return raw
|
||||
}
|
||||
now := time.Now()
|
||||
startToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
startThat := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||
dayDiff := int(startToday.Sub(startThat).Hours() / 24)
|
||||
hm := t.Format("15:04")
|
||||
switch {
|
||||
case dayDiff <= 0:
|
||||
return "今天 " + hm
|
||||
case dayDiff == 1:
|
||||
return "昨天 " + hm
|
||||
default:
|
||||
return fmt.Sprintf("%d 月 %d 日", int(t.Month()), t.Day())
|
||||
}
|
||||
}
|
||||
|
||||
// HistoryDayBucket 列表分组标题:今天 / 昨天 / 更早。
|
||||
func HistoryDayBucket(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
t, ok := parseHistoryTime(raw)
|
||||
if !ok {
|
||||
return "更早"
|
||||
}
|
||||
now := time.Now()
|
||||
startToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
startThat := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||
dayDiff := int(startToday.Sub(startThat).Hours() / 24)
|
||||
switch {
|
||||
case dayDiff <= 0:
|
||||
return "今天"
|
||||
case dayDiff == 1:
|
||||
return "昨天"
|
||||
default:
|
||||
return "更早"
|
||||
}
|
||||
}
|
||||
|
||||
func formatHistoryAt(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
t, ok := parseHistoryTime(raw)
|
||||
if !ok {
|
||||
return raw
|
||||
}
|
||||
now := time.Now()
|
||||
startToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
startThat := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||
dayDiff := int(startToday.Sub(startThat).Hours() / 24)
|
||||
hm := t.Format("15:04")
|
||||
switch {
|
||||
case dayDiff <= 0:
|
||||
return "今天 " + hm
|
||||
case dayDiff == 1:
|
||||
return "昨天 " + hm
|
||||
case dayDiff == 2:
|
||||
return "前天 " + hm
|
||||
case dayDiff < 7:
|
||||
return fmt.Sprintf("%d天前 %s", dayDiff, hm)
|
||||
case dayDiff < 14:
|
||||
return "一周前 " + hm
|
||||
default:
|
||||
return fmt.Sprintf("%d 月 %d 日", int(t.Month()), t.Day())
|
||||
}
|
||||
}
|
||||
|
||||
func parseHistoryTime(raw string) (time.Time, bool) {
|
||||
layouts := []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02T15:04:05Z07:00",
|
||||
"2006-01-02 15:04:05.000",
|
||||
"2006-01-02 15:04:05.999999999",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.ParseInLocation(layout, raw, time.Local); err == nil {
|
||||
return t, true
|
||||
}
|
||||
if t, err := time.Parse(layout, raw); err == nil {
|
||||
return t.In(time.Local), true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
// ParseHistoryTime 解析观看历史时间字符串。
|
||||
func ParseHistoryTime(raw string) (time.Time, bool) {
|
||||
return parseHistoryTime(strings.TrimSpace(raw))
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const likeSetPath = "/api/app/playlet/like/set"
|
||||
|
||||
// PlayletLikeSetReq 对应 swagger proto.PlayletLikeSetReq
|
||||
type PlayletLikeSetReq struct {
|
||||
ID int64 `json:"id"`
|
||||
IsLike bool `json:"isLike"`
|
||||
}
|
||||
|
||||
// PlayletLikeSetResp 对应 swagger proto.PlayletLikeSetResp
|
||||
type PlayletLikeSetResp struct {
|
||||
ID int64 `json:"id"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
IsLike int `json:"isLike"`
|
||||
}
|
||||
|
||||
// LikeSet 设置短剧点赞/取消点赞。
|
||||
func LikeSet(c *gin.Context, req PlayletLikeSetReq) (*APIEnvelope[PlayletLikeSetResp], error) {
|
||||
if req.ID <= 0 {
|
||||
return nil, fmt.Errorf("playlet like invalid id")
|
||||
}
|
||||
var env APIEnvelope[PlayletLikeSetResp]
|
||||
if _, err := upstream.PostJSON(c, likeSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
@@ -46,19 +45,10 @@ func FetchSearch(c *gin.Context, q SearchQuery) (*PlayletSearchResp, error) {
|
||||
if q.Keyword == "" {
|
||||
return nil, fmt.Errorf("playlet search keyword is empty")
|
||||
}
|
||||
authser.EnsureGuestOnEnter(c)
|
||||
env, err := fetchSearchOnce(c, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 && authser.IsSessionExpiredCode(env.Code) {
|
||||
if authser.RecoverContentSession(c, env.Code) {
|
||||
env, err = fetchSearchOnce(c, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet search code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
@@ -98,19 +88,10 @@ func FetchSearchSuggest(c *gin.Context, keyword string) (*PlayletSearchSuggestRe
|
||||
if keyword == "" {
|
||||
return nil, fmt.Errorf("playlet search suggest keyword is empty")
|
||||
}
|
||||
authser.EnsureGuestOnEnter(c)
|
||||
env, err := fetchSearchSuggestOnce(c, keyword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 && authser.IsSessionExpiredCode(env.Code) {
|
||||
if authser.RecoverContentSession(c, env.Code) {
|
||||
env, err = fetchSearchSuggestOnce(c, keyword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet search suggest code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
|
||||
@@ -12,83 +12,70 @@ import (
|
||||
// TemplateFuncs 模板辅助:仅做展示格式化 / URL,不把接口字段映射成另一套名字。
|
||||
func TemplateFuncs() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"detailURL": detailURL,
|
||||
"playURL": playURL,
|
||||
"chapterPlayURL": chapterPlayURL,
|
||||
"categoryURL": categoryURL,
|
||||
"categoryDetailURL": categoryDetailURL,
|
||||
"themeListURL": themeListURLByKey,
|
||||
"tagOptionsURL": tagListURLByKey,
|
||||
"allListURL": AllListURL,
|
||||
"moreListURL": MoreListURL,
|
||||
"moreSeriesListURL": MoreSeriesListURL,
|
||||
"navMegaIcon": NavMegaIcon,
|
||||
"topicListURL": TopicListURL,
|
||||
"topicDetailURL": TopicDetailURL,
|
||||
"topicCoverURLs": TopicCoverURLs,
|
||||
"tagPageURL": TagListURL,
|
||||
"hotRankPageURL": HotRankPageURL,
|
||||
"searchResultsURL": SearchResultsURL,
|
||||
"coverURL": coverURL,
|
||||
"formatHeat": formatHeat,
|
||||
"formatCollect": formatCollectHeat,
|
||||
"formatLikeCount": formatLikeCount,
|
||||
"formatMediaTime": formatMediaTime,
|
||||
"playletDisplayName": playletDisplayName,
|
||||
"rankNo": RankNo,
|
||||
"episodeLabel": episodeText,
|
||||
"displayTag": displayTag,
|
||||
"firstTagName": firstTagName,
|
||||
"themeTagText": themeTagText,
|
||||
"tagListURL": tagListURL,
|
||||
"cardTag": cardTag,
|
||||
"cardTags": cardTags,
|
||||
"namedTags": namedTags,
|
||||
"namedThemeTags": namedThemeTags,
|
||||
"firstName": firstName,
|
||||
"rankClass": rankClass,
|
||||
"add": addInt,
|
||||
"mod": modInt,
|
||||
"contains": strings.Contains,
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
"footerLinkURL": footerLinkURL,
|
||||
"footerLinkIsExternal": footerLinkIsExternal,
|
||||
"externalLinkAttrs": externalLinkAttrs,
|
||||
"footerContactURL": footerContactURL,
|
||||
"footerContactName": footerContactName,
|
||||
"footerContactValue": footerContactValue,
|
||||
"navDisplayURL": navDisplayURL,
|
||||
"urlquery": url.QueryEscape,
|
||||
"pathescape": url.PathEscape,
|
||||
"metaLine": metaLine,
|
||||
"adSlice": AdSlice,
|
||||
"cssCover": cssCover,
|
||||
"cssCoverPlaceholder": cssCoverPlaceholder,
|
||||
"updateStatusText": updateStatusText,
|
||||
"browseText": browseText,
|
||||
"usableAnchor": usableAnchor,
|
||||
"playletYearText": playletYearText,
|
||||
"playletDateText": playletDateText,
|
||||
"isPlayletAllFree": isPlayletAllFree,
|
||||
"collectProgressText": collectProgressText,
|
||||
"collectTagText": collectTagText,
|
||||
"chapterCollectEpisodeLabel": chapterCollectEpisodeLabel,
|
||||
"chapterCollectDesc": chapterCollectDesc,
|
||||
"chapterCollectMeta": chapterCollectMeta,
|
||||
"historyProgressText": historyProgressText,
|
||||
"historyWatchLine": historyWatchLine,
|
||||
"historyTagText": historyTagText,
|
||||
"historyPlayURL": historyPlayURL,
|
||||
"historyContinueMeta": historyContinueMeta,
|
||||
"historyProgressPct": historyProgressPct,
|
||||
"historyStatus": historyStatus,
|
||||
"formatHistoryAt": formatHistoryAt,
|
||||
"formatShortDateTime": formatShortDateTime,
|
||||
"absInt64": absInt64Tpl,
|
||||
"absURL": absURLTpl,
|
||||
"canonicalOr": canonicalOr,
|
||||
"joinStrings": joinStrings,
|
||||
"dict": dict,
|
||||
"detailURL": detailURL,
|
||||
"playURL": playURL,
|
||||
"chapterPlayURL": chapterPlayURL,
|
||||
"categoryURL": categoryURL,
|
||||
"categoryDetailURL": categoryDetailURL,
|
||||
"themeListURL": themeListURLByKey,
|
||||
"tagOptionsURL": tagListURLByKey,
|
||||
"allListURL": AllListURL,
|
||||
"moreListURL": MoreListURL,
|
||||
"moreSeriesListURL": MoreSeriesListURL,
|
||||
"navMegaIcon": NavMegaIcon,
|
||||
"topicListURL": TopicListURL,
|
||||
"topicDetailURL": TopicDetailURL,
|
||||
"topicCoverURLs": TopicCoverURLs,
|
||||
"tagPageURL": TagListURL,
|
||||
"hotRankPageURL": HotRankPageURL,
|
||||
"searchResultsURL": SearchResultsURL,
|
||||
"coverURL": coverURL,
|
||||
"formatHeat": formatHeat,
|
||||
"formatCollect": formatCollectHeat,
|
||||
"formatLikeCount": formatLikeCount,
|
||||
"formatMediaTime": formatMediaTime,
|
||||
"playletDisplayName": playletDisplayName,
|
||||
"rankNo": RankNo,
|
||||
"episodeLabel": episodeText,
|
||||
"displayTag": displayTag,
|
||||
"firstTagName": firstTagName,
|
||||
"themeTagText": themeTagText,
|
||||
"tagListURL": tagListURL,
|
||||
"cardTag": cardTag,
|
||||
"cardTags": cardTags,
|
||||
"namedTags": namedTags,
|
||||
"namedThemeTags": namedThemeTags,
|
||||
"firstName": firstName,
|
||||
"rankClass": rankClass,
|
||||
"add": addInt,
|
||||
"mod": modInt,
|
||||
"contains": strings.Contains,
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
"footerLinkURL": footerLinkURL,
|
||||
"footerLinkIsExternal": footerLinkIsExternal,
|
||||
"externalLinkAttrs": externalLinkAttrs,
|
||||
"footerContactURL": footerContactURL,
|
||||
"footerContactName": footerContactName,
|
||||
"footerContactValue": footerContactValue,
|
||||
"navDisplayURL": navDisplayURL,
|
||||
"urlquery": url.QueryEscape,
|
||||
"pathescape": url.PathEscape,
|
||||
"metaLine": metaLine,
|
||||
"adSlice": AdSlice,
|
||||
"cssCover": cssCover,
|
||||
"cssCoverPlaceholder": cssCoverPlaceholder,
|
||||
"updateStatusText": updateStatusText,
|
||||
"browseText": browseText,
|
||||
"usableAnchor": usableAnchor,
|
||||
"playletYearText": playletYearText,
|
||||
"playletDateText": playletDateText,
|
||||
"isPlayletAllFree": isPlayletAllFree,
|
||||
"formatShortDateTime": formatShortDateTime,
|
||||
"absInt64": absInt64Tpl,
|
||||
"absURL": absURLTpl,
|
||||
"canonicalOr": canonicalOr,
|
||||
"joinStrings": joinStrings,
|
||||
"dict": dict,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,281 +0,0 @@
|
||||
package rechargeser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
packageListPath = "/api/app/recharge/package/list"
|
||||
coinBuyPath = "/api/app/coin/buy"
|
||||
vipPayPath = "/api/app/vip/pay"
|
||||
vipOrdersPath = "/api/app/vip/orders"
|
||||
coinOrdersPath = "/api/app/coin/orders"
|
||||
coinTransPath = "/api/app/coin/trans/list"
|
||||
coinTransExportPath = "/api/app/coin/trans/export"
|
||||
)
|
||||
|
||||
// FetchPackageList 拉取购买套餐列表(会员 + 金币)。
|
||||
func FetchPackageList(c *gin.Context) (*RechargePackageListResp, error) {
|
||||
var env APIEnvelope[RechargePackageListResp]
|
||||
if err := upstream.GetJSON(c, packageListPath, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("recharge package list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchPackageListOrEmpty 失败时返回空列表,保证 SSR 可渲染。
|
||||
func FetchPackageListOrEmpty(c *gin.Context) *RechargePackageListResp {
|
||||
data, err := FetchPackageList(c)
|
||||
if err != nil {
|
||||
log.Error("fetch recharge package list failed", log.E(err))
|
||||
return &RechargePackageListResp{}
|
||||
}
|
||||
if data == nil {
|
||||
return &RechargePackageListResp{}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// BuyCoin 购买金币套餐:POST /api/app/coin/buy
|
||||
func BuyCoin(c *gin.Context, req BuyPayReq) (*APIEnvelope[PayOrderResp], error) {
|
||||
var env APIEnvelope[PayOrderResp]
|
||||
if _, err := upstream.PostJSON(c, coinBuyPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// VipPay 购买会员套餐:POST /api/app/vip/pay
|
||||
func VipPay(c *gin.Context, req BuyPayReq) (*APIEnvelope[PayOrderResp], error) {
|
||||
var env APIEnvelope[PayOrderResp]
|
||||
if _, err := upstream.PostJSON(c, vipPayPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// NormalizePayMode 规范化支付方式。
|
||||
func NormalizePayMode(raw string) string {
|
||||
v := strings.ToLower(strings.TrimSpace(raw))
|
||||
switch v {
|
||||
case "wx", "weixin":
|
||||
return "wechat"
|
||||
case "unionpay":
|
||||
return "union"
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// FetchVipOrders 查询 VIP 充值记录。
|
||||
func FetchVipOrders(c *gin.Context, page, pageSize int) ([]VipOrder, error) {
|
||||
return fetchOrders(c, vipOrdersPath, page, pageSize)
|
||||
}
|
||||
|
||||
// FetchCoinOrders 查询金币购买记录。
|
||||
func FetchCoinOrders(c *gin.Context, page, pageSize int) ([]VipOrder, error) {
|
||||
return fetchOrders(c, coinOrdersPath, page, pageSize)
|
||||
}
|
||||
|
||||
// FetchRecentOrdersOrEmpty 合并 VIP + 金币订单,失败返回空。
|
||||
func FetchRecentOrdersOrEmpty(c *gin.Context, limit int) []VipOrder {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
pageSize := limit
|
||||
vipOrders, err1 := FetchVipOrders(c, 1, pageSize)
|
||||
coinOrders, err2 := FetchCoinOrders(c, 1, pageSize)
|
||||
if err1 != nil {
|
||||
log.Error("fetch vip orders failed", log.E(err1))
|
||||
}
|
||||
if err2 != nil {
|
||||
log.Error("fetch coin orders failed", log.E(err2))
|
||||
}
|
||||
out := make([]VipOrder, 0, len(vipOrders)+len(coinOrders))
|
||||
out = append(out, vipOrders...)
|
||||
out = append(out, coinOrders...)
|
||||
return out
|
||||
}
|
||||
|
||||
// FetchCoinTransList 查询金币余额明细:GET /api/app/coin/trans/list
|
||||
// 第二个返回值为上游业务 code(网络/解码失败时为 0)。
|
||||
func FetchCoinTransList(c *gin.Context, page, pageSize int) ([]CoinTransListItem, int, error) {
|
||||
data, code, err := FetchCoinTransPage(c, page, pageSize, 0)
|
||||
if data == nil {
|
||||
return nil, code, err
|
||||
}
|
||||
return data.List, code, err
|
||||
}
|
||||
|
||||
// FetchCoinTransPage 查询金币余额明细并保留分页信息。
|
||||
// typ: 0全部、1充值、2消费、3奖励。
|
||||
func FetchCoinTransPage(c *gin.Context, page, pageSize, typ int) (*CoinTransPage, int, error) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 10
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
if typ < 0 || typ > 3 {
|
||||
typ = 0
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("page", strconv.Itoa(page))
|
||||
query.Set("pageSize", strconv.Itoa(pageSize))
|
||||
query.Set("type", strconv.Itoa(typ))
|
||||
full := coinTransPath + "?" + query.Encode()
|
||||
var env APIEnvelopeRaw
|
||||
if err := upstream.GetJSON(c, full, &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("%s code=%d msg=%s", coinTransPath, env.Code, env.Msg)
|
||||
}
|
||||
return decodeCoinTransPage(env.Data, page, pageSize), env.Code, nil
|
||||
}
|
||||
|
||||
// FetchCoinTransExport 导出金币流水 CSV:GET /api/app/coin/trans/export?type=
|
||||
// typ: 0全部、1充值、2消费、3奖励。
|
||||
func FetchCoinTransExport(c *gin.Context, typ int) (*upstream.BinaryResult, error) {
|
||||
if typ < 0 || typ > 3 {
|
||||
typ = 0
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("type", strconv.Itoa(typ))
|
||||
full := coinTransExportPath + "?" + query.Encode()
|
||||
result, err := upstream.GetBinary(c, full)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result == nil {
|
||||
return nil, fmt.Errorf("%s empty response", coinTransExportPath)
|
||||
}
|
||||
if result.StatusCode < 200 || result.StatusCode >= 300 {
|
||||
return result, fmt.Errorf("%s status=%d body=%s", coinTransExportPath, result.StatusCode, truncateBytes(result.Body, 200))
|
||||
}
|
||||
// 上游偶发返回 JSON 错误包装
|
||||
ct := strings.ToLower(result.ContentType)
|
||||
if strings.Contains(ct, "json") {
|
||||
var env APIEnvelopeRaw
|
||||
if json.Unmarshal(result.Body, &env) == nil && env.Code != 0 && env.Code != 200 {
|
||||
return result, fmt.Errorf("%s code=%d msg=%s", coinTransExportPath, env.Code, env.Msg)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func truncateBytes(b []byte, n int) string {
|
||||
s := string(b)
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
|
||||
// FetchCoinTransListOrEmpty 失败返回空列表;游客会话失效时会尝试重登后重试一次。
|
||||
func FetchCoinTransListOrEmpty(c *gin.Context, page, pageSize int) []CoinTransListItem {
|
||||
list, code, err := FetchCoinTransList(c, page, pageSize)
|
||||
if err == nil {
|
||||
return list
|
||||
}
|
||||
if retry, _ := authser.OnSessionExpired(c, code); retry {
|
||||
list, _, err = FetchCoinTransList(c, page, pageSize)
|
||||
if err == nil {
|
||||
return list
|
||||
}
|
||||
}
|
||||
log.Error("fetch coin trans list failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeCoinTransList(raw json.RawMessage) []CoinTransListItem {
|
||||
return decodeCoinTransPage(raw, 1, 10).List
|
||||
}
|
||||
|
||||
func decodeCoinTransPage(raw json.RawMessage, page, pageSize int) *CoinTransPage {
|
||||
empty := &CoinTransPage{PageNum: page, PageSize: pageSize}
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return empty
|
||||
}
|
||||
var arr []CoinTransListItem
|
||||
if err := json.Unmarshal(raw, &arr); err == nil {
|
||||
empty.List = arr
|
||||
empty.TotalCount = int64(len(arr))
|
||||
return empty
|
||||
}
|
||||
var obj CoinTransPage
|
||||
if err := json.Unmarshal(raw, &obj); err != nil {
|
||||
return empty
|
||||
}
|
||||
if obj.PageNum <= 0 {
|
||||
obj.PageNum = page
|
||||
}
|
||||
if obj.PageSize <= 0 {
|
||||
obj.PageSize = pageSize
|
||||
}
|
||||
return &obj
|
||||
}
|
||||
|
||||
func fetchOrders(c *gin.Context, path string, page, pageSize int) ([]VipOrder, error) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 10
|
||||
}
|
||||
full := fmt.Sprintf("%s?page=%d&pageSize=%d", path, page, pageSize)
|
||||
var env APIEnvelopeRaw
|
||||
if err := upstream.GetJSON(c, full, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("%s code=%d msg=%s", path, env.Code, env.Msg)
|
||||
}
|
||||
return decodeOrderList(env.Data), nil
|
||||
}
|
||||
|
||||
func decodeOrderList(raw json.RawMessage) []VipOrder {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
var arr []VipOrder
|
||||
if err := json.Unmarshal(raw, &arr); err == nil {
|
||||
return arr
|
||||
}
|
||||
var obj struct {
|
||||
List []VipOrder `json:"list"`
|
||||
Orders []VipOrder `json:"orders"`
|
||||
Records []VipOrder `json:"records"`
|
||||
Items []VipOrder `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &obj); err != nil {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case len(obj.List) > 0:
|
||||
return obj.List
|
||||
case len(obj.Orders) > 0:
|
||||
return obj.Orders
|
||||
case len(obj.Records) > 0:
|
||||
return obj.Records
|
||||
case len(obj.Items) > 0:
|
||||
return obj.Items
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package rechargeser
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// PackageType 对应 rechargepackagemod.PackageType
|
||||
const (
|
||||
PackageTypeVip = 1 // 会员畅享
|
||||
PackageTypeCoin = 2 // 金币充值
|
||||
)
|
||||
|
||||
// PayMethodInfo 对应 swagger proto.PayMethodInfo
|
||||
type PayMethodInfo struct {
|
||||
Type string `json:"type"` // alipay / wechat / union
|
||||
TypeName string `json:"typeName"` // 支付宝 / 微信 / 银联
|
||||
}
|
||||
|
||||
// RechargePackageItem 对应 swagger proto.RechargePackageItem
|
||||
type RechargePackageItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SubTitle string `json:"subTitle"`
|
||||
PackageType int `json:"packageType"`
|
||||
Price int64 `json:"price"` // 售价,分
|
||||
OriginalPrice int64 `json:"originalPrice"` // 原价,分
|
||||
BaseCoin int64 `json:"baseCoin"`
|
||||
GiftCoin int64 `json:"giftCoin"`
|
||||
TotalCoin int64 `json:"totalCoin"`
|
||||
DurationDays int `json:"durationDays"`
|
||||
DurationHours int `json:"durationHours"`
|
||||
Sort int `json:"sort"`
|
||||
PayMethods []PayMethodInfo `json:"payMethods"`
|
||||
}
|
||||
|
||||
// RechargePackageListResp 对应 swagger proto.RechargePackageListResp
|
||||
// GET /api/app/recharge/package/list
|
||||
type RechargePackageListResp struct {
|
||||
VipList []RechargePackageItem `json:"vipList"`
|
||||
CoinList []RechargePackageItem `json:"coinList"`
|
||||
}
|
||||
|
||||
// BuyPayReq 对应 coinapi.buyCoinReq / rechargeapi.submitOrderReq
|
||||
type BuyPayReq struct {
|
||||
PackageID int64 `json:"packageId"`
|
||||
PayMode string `json:"payMode"` // alipay / wechat / union ...
|
||||
}
|
||||
|
||||
// PayOrderResp 对应 coinser.BuyCoinResp / rechargeser.SubmitOrderResp
|
||||
type PayOrderResp struct {
|
||||
IsOpenNewBrowser bool `json:"isOpenNewBrowser"`
|
||||
PayURL string `json:"payUrl"`
|
||||
PayURLMode string `json:"payUrlMode"`
|
||||
TradeNo string `json:"tradeNo"`
|
||||
}
|
||||
|
||||
// VipOrder 对应 swagger vipordermod.VipOrder(会员/金币订单共用结构)
|
||||
type VipOrder struct {
|
||||
ID int64 `json:"id"`
|
||||
UserID int64 `json:"userId"`
|
||||
OrderType int `json:"orderType"` // 1会员 2金币
|
||||
Status int `json:"status"` // 1待支付 2成功 3失败
|
||||
Amount int64 `json:"amount"` // 分
|
||||
Coin int64 `json:"coin"`
|
||||
CardID int64 `json:"cardId"`
|
||||
CardName string `json:"cardName"`
|
||||
CoinCfgID int64 `json:"coinCfgId"`
|
||||
PayMode string `json:"payMode"`
|
||||
TradeNo string `json:"tradeNo"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
FinishedAt string `json:"finishedAt"`
|
||||
}
|
||||
|
||||
// CoinTransListItem 对应 swagger proto.CoinTransListItemResp
|
||||
// GET /api/app/coin/trans/list
|
||||
type CoinTransListItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Remark string `json:"remark"`
|
||||
TranType int `json:"tranType"`
|
||||
TranTypeName string `json:"tranTypeName"`
|
||||
FlowDir int `json:"flowDir"` // 1收入 -1支出
|
||||
FlowDirName string `json:"flowDirName"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChangeAmount int64 `json:"changeAmount"`
|
||||
BalanceBefore int64 `json:"balanceBefore"`
|
||||
BalanceAfter int64 `json:"balanceAfter"`
|
||||
OrderNo string `json:"orderNo"`
|
||||
RelatedID int64 `json:"relatedId"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
// CoinTransPage 对应 response.BasePageResp 与金币流水列表组合。
|
||||
type CoinTransPage struct {
|
||||
List []CoinTransListItem `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
const (
|
||||
OrderTypeVip = 1
|
||||
OrderTypeCoin = 2
|
||||
|
||||
OrderStatusPending = 1
|
||||
OrderStatusSuccess = 2
|
||||
OrderStatusFailed = 3
|
||||
|
||||
FlowDirIn = 1
|
||||
FlowDirOut = -1
|
||||
)
|
||||
|
||||
// APIEnvelope 上游统一响应壳
|
||||
type APIEnvelope[T any] struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
|
||||
// APIEnvelopeRaw Data 形态不固定时使用。
|
||||
type APIEnvelopeRaw struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
@@ -1,496 +0,0 @@
|
||||
package rechargeser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PayMethodVM 支付方式展示。
|
||||
type PayMethodVM struct {
|
||||
Type string
|
||||
TypeName string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// PackageCardVM 充值页套餐卡片(字段来自 package/list)。
|
||||
type PackageCardVM struct {
|
||||
ID int64
|
||||
Name string
|
||||
Hint string // 优先 subTitle
|
||||
BaseCoinText string
|
||||
GiftCoinText string
|
||||
TotalCoinText string
|
||||
PriceText string // 售价(元),不含 ¥
|
||||
OriginalPriceText string // 原价(元),仅当原价>售价时有值
|
||||
PriceFen int64
|
||||
Active bool
|
||||
PayMethods []PayMethodVM
|
||||
PayMethodsJSON string // 供 data-pay-methods 使用
|
||||
}
|
||||
|
||||
// DepositPageVM 充值页模板数据。
|
||||
type DepositPageVM struct {
|
||||
VipList []PackageCardVM
|
||||
CoinList []PackageCardVM
|
||||
PayMethods []PayMethodVM // 当前选中套餐的支付方式(接口 payMethods)
|
||||
// TxList 交易明细:直接透传 /api/app/coin/trans/list 返回的字段
|
||||
//(不再做 Name/TimeText/AmountText 的自定义字段映射)。
|
||||
TxList []CoinTransListItem
|
||||
}
|
||||
|
||||
// TxItemVM 交易明细行(历史遗留:旧逻辑会把 CoinTransListItem 映射到此结构)。
|
||||
// 当前“交易明细调试”需求:DepositPageVM 直接透传 CoinTransListItem,
|
||||
// 但旧函数可能仍被其它页面复用,因此保留结构体定义。
|
||||
type TxItemVM struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Description string `json:"description"`
|
||||
Category string `json:"category"`
|
||||
TimeText string `json:"time"`
|
||||
MobileTime string `json:"mobileTime"`
|
||||
AmountText string `json:"amount"`
|
||||
AmountClass string `json:"amountClass"` // deposit-tx-amount--plus / --minus
|
||||
Credit bool `json:"credit"`
|
||||
StatusText string `json:"status"`
|
||||
}
|
||||
|
||||
var defaultPayMethods = []PayMethodInfo{
|
||||
{Type: "alipay", TypeName: "支付宝"},
|
||||
{Type: "wechat", TypeName: "微信"},
|
||||
{Type: "union", TypeName: "银联"},
|
||||
}
|
||||
|
||||
// BuildDepositPageVM 按接口 vipList / coinList 组装展示数据(支付方式不造假)。
|
||||
// preferTab: "coin" 优先选中金币套餐,其它/空则优先会员。
|
||||
func BuildDepositPageVM(raw *RechargePackageListResp, preferTab string) DepositPageVM {
|
||||
if raw == nil {
|
||||
return DepositPageVM{}
|
||||
}
|
||||
vip := buildCards(raw.VipList, true)
|
||||
coin := buildCards(raw.CoinList, false)
|
||||
activatePreferredPackage(vip, coin, preferTab)
|
||||
|
||||
var activePays []PayMethodVM
|
||||
for _, item := range coin {
|
||||
if item.Active {
|
||||
activePays = item.PayMethods
|
||||
break
|
||||
}
|
||||
}
|
||||
if activePays == nil {
|
||||
for _, item := range vip {
|
||||
if item.Active {
|
||||
activePays = item.PayMethods
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(activePays) > 0 {
|
||||
activePays[0].Active = true
|
||||
}
|
||||
return DepositPageVM{
|
||||
VipList: vip,
|
||||
CoinList: coin,
|
||||
PayMethods: activePays,
|
||||
}
|
||||
}
|
||||
|
||||
// activatePreferredPackage 默认选中:优先有支付方式的套餐,否则选第一项。
|
||||
// preferTab=coin 时优先金币,否则优先会员。
|
||||
func activatePreferredPackage(vip, coin []PackageCardVM, preferTab string) {
|
||||
pick := func(list []PackageCardVM) bool {
|
||||
for i := range list {
|
||||
if len(list[i].PayMethods) > 0 {
|
||||
list[i].Active = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
if len(list) > 0 {
|
||||
list[0].Active = true
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
preferCoin := strings.EqualFold(strings.TrimSpace(preferTab), "coin")
|
||||
if preferCoin {
|
||||
if pick(coin) {
|
||||
return
|
||||
}
|
||||
pick(vip)
|
||||
return
|
||||
}
|
||||
if pick(vip) {
|
||||
return
|
||||
}
|
||||
pick(coin)
|
||||
}
|
||||
|
||||
// AttachTxList 附加交易明细(金币流水)。
|
||||
func (vm *DepositPageVM) AttachTxList(list []CoinTransListItem) {
|
||||
if vm == nil {
|
||||
return
|
||||
}
|
||||
vm.TxList = list
|
||||
}
|
||||
|
||||
// BuildTxListFromCoinTrans 将金币流水转为展示列表。
|
||||
func BuildTxListFromCoinTrans(list []CoinTransListItem, limit int) []TxItemVM {
|
||||
items := append([]CoinTransListItem(nil), list...)
|
||||
if limit > 0 && len(items) > limit {
|
||||
items = items[:limit]
|
||||
}
|
||||
out := make([]TxItemVM, 0, len(items))
|
||||
for _, item := range items {
|
||||
name := strings.TrimSpace(item.Title)
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(item.TranTypeName)
|
||||
}
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(item.Remark)
|
||||
}
|
||||
if name == "" {
|
||||
name = "金币变动"
|
||||
}
|
||||
change := item.ChangeAmount
|
||||
if change == 0 {
|
||||
change = item.Amount
|
||||
if item.FlowDir == FlowDirOut {
|
||||
change = -change
|
||||
}
|
||||
}
|
||||
amountClass := "deposit-tx-amount--plus"
|
||||
amountText := "+" + formatCount(absInt64(change)) + " 金币"
|
||||
if change < 0 || item.FlowDir == FlowDirOut {
|
||||
amountClass = "deposit-tx-amount--minus"
|
||||
amountText = "-" + formatCount(absInt64(change)) + " 金币"
|
||||
}
|
||||
out = append(out, TxItemVM{
|
||||
Name: name,
|
||||
Kind: transactionKind(item),
|
||||
Description: name,
|
||||
Category: transactionCategory(item),
|
||||
TimeText: formatTransTime(item.CreatedAt),
|
||||
MobileTime: formatMobileTransTime(item.CreatedAt),
|
||||
AmountText: amountText,
|
||||
AmountClass: amountClass,
|
||||
Credit: change >= 0 && item.FlowDir != FlowDirOut,
|
||||
StatusText: strings.TrimSpace(item.FlowDirName),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func transactionKind(item CoinTransListItem) string {
|
||||
if name := strings.TrimSpace(item.TranTypeName); name != "" {
|
||||
return name
|
||||
}
|
||||
if item.FlowDir == FlowDirOut {
|
||||
return "消费"
|
||||
}
|
||||
return "收入"
|
||||
}
|
||||
|
||||
func transactionCategory(item CoinTransListItem) string {
|
||||
switch item.TranType {
|
||||
case 1:
|
||||
return "topup"
|
||||
case 2:
|
||||
return "reward"
|
||||
case 4:
|
||||
return "spend"
|
||||
default:
|
||||
if item.FlowDir == FlowDirOut {
|
||||
return "spend"
|
||||
}
|
||||
return "reward"
|
||||
}
|
||||
}
|
||||
|
||||
func formatMobileTransTime(raw string) string {
|
||||
formatted := formatTransTime(raw)
|
||||
if len(formatted) >= 16 {
|
||||
return formatted[5:16]
|
||||
}
|
||||
return formatted
|
||||
}
|
||||
|
||||
func absInt64(n int64) int64 {
|
||||
if n < 0 {
|
||||
return -n
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func formatTransTime(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || strings.HasPrefix(raw, "0001") {
|
||||
return ""
|
||||
}
|
||||
raw = strings.ReplaceAll(raw, "T", " ")
|
||||
if i := strings.Index(raw, "."); i > 0 {
|
||||
raw = raw[:i]
|
||||
}
|
||||
if i := strings.IndexAny(raw, "Z+"); i > 10 {
|
||||
raw = strings.TrimSpace(raw[:i])
|
||||
}
|
||||
if len(raw) > 19 {
|
||||
raw = raw[:19]
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
// BuildTxList 将订单转为展示列表(按时间倒序)。保留供订单场景复用。
|
||||
func BuildTxList(orders []VipOrder, limit int) []TxItemVM {
|
||||
items := append([]VipOrder(nil), orders...)
|
||||
sort.SliceStable(items, func(i, j int) bool {
|
||||
return orderTimeKey(items[i]) > orderTimeKey(items[j])
|
||||
})
|
||||
if limit > 0 && len(items) > limit {
|
||||
items = items[:limit]
|
||||
}
|
||||
out := make([]TxItemVM, 0, len(items))
|
||||
for _, o := range items {
|
||||
name := strings.TrimSpace(o.CardName)
|
||||
if name == "" {
|
||||
if o.OrderType == OrderTypeCoin || o.CoinCfgID > 0 {
|
||||
name = "金币充值"
|
||||
} else {
|
||||
name = "会员充值"
|
||||
}
|
||||
}
|
||||
status := orderStatusText(o.Status)
|
||||
if status != "" {
|
||||
name = name + " · " + status
|
||||
}
|
||||
amountClass := "deposit-tx-amount--minus"
|
||||
amountText := "-¥" + FormatYuan(o.Amount)
|
||||
if o.OrderType == OrderTypeCoin || o.Coin > 0 {
|
||||
if o.Status == OrderStatusSuccess && o.Coin > 0 {
|
||||
amountClass = "deposit-tx-amount--plus"
|
||||
amountText = "+" + formatCount(o.Coin) + " 金币"
|
||||
}
|
||||
}
|
||||
out = append(out, TxItemVM{
|
||||
Name: name,
|
||||
TimeText: formatOrderTime(o),
|
||||
AmountText: amountText,
|
||||
AmountClass: amountClass,
|
||||
StatusText: status,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func orderTimeKey(o VipOrder) string {
|
||||
if t := strings.TrimSpace(o.FinishedAt); t != "" && !strings.HasPrefix(t, "0001") {
|
||||
return t
|
||||
}
|
||||
return strings.TrimSpace(o.CreatedAt)
|
||||
}
|
||||
|
||||
func formatOrderTime(o VipOrder) string {
|
||||
raw := orderTimeKey(o)
|
||||
if raw == "" || strings.HasPrefix(raw, "0001") {
|
||||
return ""
|
||||
}
|
||||
// 常见 RFC3339 / 带 T 的时间,截成可读
|
||||
raw = strings.ReplaceAll(raw, "T", " ")
|
||||
if i := strings.Index(raw, "."); i > 0 {
|
||||
raw = raw[:i]
|
||||
}
|
||||
if i := strings.IndexAny(raw, "Z+"); i > 10 {
|
||||
raw = strings.TrimSpace(raw[:i])
|
||||
}
|
||||
if len(raw) > 19 {
|
||||
raw = raw[:19]
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func orderStatusText(status int) string {
|
||||
switch status {
|
||||
case OrderStatusPending:
|
||||
return "待支付"
|
||||
case OrderStatusSuccess:
|
||||
return "已完成"
|
||||
case OrderStatusFailed:
|
||||
return "失败"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func buildCards(list []RechargePackageItem, isVIP bool) []PackageCardVM {
|
||||
items := append([]RechargePackageItem(nil), list...)
|
||||
// 仅按接口 sort 排序;sort 相同保持接口原顺序
|
||||
sort.SliceStable(items, func(i, j int) bool {
|
||||
return items[i].Sort < items[j].Sort
|
||||
})
|
||||
out := make([]PackageCardVM, 0, len(items))
|
||||
for _, item := range items {
|
||||
name := strings.TrimSpace(item.Name)
|
||||
if name == "" {
|
||||
if isVIP {
|
||||
name = "会员套餐"
|
||||
} else {
|
||||
name = "金币套餐"
|
||||
}
|
||||
}
|
||||
pays := buildPayMethodVMs(item.PayMethods, false)
|
||||
card := PackageCardVM{
|
||||
ID: item.ID,
|
||||
Name: name,
|
||||
Hint: packageHint(item, isVIP),
|
||||
BaseCoinText: formatCount(item.BaseCoin),
|
||||
GiftCoinText: formatCount(item.GiftCoin),
|
||||
TotalCoinText: formatCount(packageTotalCoin(item)),
|
||||
PriceText: FormatYuan(item.Price),
|
||||
PriceFen: item.Price,
|
||||
PayMethods: pays,
|
||||
PayMethodsJSON: marshalPayMethodsJSON(pays),
|
||||
}
|
||||
if item.OriginalPrice > item.Price && item.OriginalPrice > 0 {
|
||||
card.OriginalPriceText = FormatYuan(item.OriginalPrice)
|
||||
}
|
||||
out = append(out, card)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func packageTotalCoin(item RechargePackageItem) int64 {
|
||||
if item.TotalCoin > 0 {
|
||||
return item.TotalCoin
|
||||
}
|
||||
return item.BaseCoin + item.GiftCoin
|
||||
}
|
||||
|
||||
func buildPayMethodVMs(list []PayMethodInfo, withFallback bool) []PayMethodVM {
|
||||
src := list
|
||||
if len(src) == 0 && withFallback {
|
||||
src = defaultPayMethods
|
||||
}
|
||||
out := make([]PayMethodVM, 0, len(src))
|
||||
seen := map[string]struct{}{}
|
||||
for _, item := range src {
|
||||
typ := strings.ToLower(strings.TrimSpace(item.Type))
|
||||
name := strings.TrimSpace(item.TypeName)
|
||||
if typ == "" && name == "" {
|
||||
continue
|
||||
}
|
||||
if typ == "" {
|
||||
typ = strings.ToLower(name)
|
||||
}
|
||||
if name == "" {
|
||||
name = defaultPayTypeName(typ)
|
||||
}
|
||||
if _, ok := seen[typ]; ok {
|
||||
continue
|
||||
}
|
||||
seen[typ] = struct{}{}
|
||||
out = append(out, PayMethodVM{Type: typ, TypeName: name})
|
||||
}
|
||||
if len(out) == 0 && withFallback {
|
||||
return buildPayMethodVMs(defaultPayMethods, false)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func defaultPayTypeName(typ string) string {
|
||||
switch typ {
|
||||
case "alipay":
|
||||
return "支付宝"
|
||||
case "wechat", "wx", "weixin":
|
||||
return "微信"
|
||||
case "union", "unionpay":
|
||||
return "银联"
|
||||
case "dcep", "ecny":
|
||||
return "数字人民币"
|
||||
case "usdt":
|
||||
return "USDT"
|
||||
default:
|
||||
if typ == "" {
|
||||
return "支付"
|
||||
}
|
||||
return typ
|
||||
}
|
||||
}
|
||||
|
||||
func marshalPayMethodsJSON(list []PayMethodVM) string {
|
||||
type row struct {
|
||||
Type string `json:"type"`
|
||||
TypeName string `json:"typeName"`
|
||||
}
|
||||
rows := make([]row, 0, len(list))
|
||||
for _, item := range list {
|
||||
rows = append(rows, row{Type: item.Type, TypeName: item.TypeName})
|
||||
}
|
||||
b, err := json.Marshal(rows)
|
||||
if err != nil || len(b) == 0 {
|
||||
return "[]"
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func packageHint(item RechargePackageItem, isVIP bool) string {
|
||||
// 优先接口 subTitle
|
||||
if s := strings.TrimSpace(item.SubTitle); s != "" {
|
||||
return s
|
||||
}
|
||||
if isVIP {
|
||||
if item.DurationDays > 0 {
|
||||
return fmt.Sprintf("%d天会员", item.DurationDays)
|
||||
}
|
||||
if item.DurationHours > 0 {
|
||||
return fmt.Sprintf("%d小时会员", item.DurationHours)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
base := item.BaseCoin
|
||||
gift := item.GiftCoin
|
||||
total := item.TotalCoin
|
||||
if total <= 0 {
|
||||
total = base + gift
|
||||
}
|
||||
if gift > 0 && base > 0 {
|
||||
return fmt.Sprintf("基础 %s + 赠送 %s", formatCount(base), formatCount(gift))
|
||||
}
|
||||
if total > 0 {
|
||||
return formatCount(total) + " 金币"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// FormatYuan 分转元展示(整数不带小数)。
|
||||
func FormatYuan(fen int64) string {
|
||||
if fen < 0 {
|
||||
fen = 0
|
||||
}
|
||||
if fen%100 == 0 {
|
||||
return strconv.FormatInt(fen/100, 10)
|
||||
}
|
||||
return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", float64(fen)/100), "0"), ".")
|
||||
}
|
||||
|
||||
func formatCount(n int64) string {
|
||||
if n < 0 {
|
||||
n = 0
|
||||
}
|
||||
s := strconv.FormatInt(n, 10)
|
||||
if len(s) <= 3 {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
rem := len(s) % 3
|
||||
if rem == 0 {
|
||||
rem = 3
|
||||
}
|
||||
b.WriteString(s[:rem])
|
||||
for i := rem; i < len(s); i += 3 {
|
||||
b.WriteByte(',')
|
||||
b.WriteString(s[i : i+3])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package translationser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"videoweb/app/service/upstream"
|
||||
@@ -67,11 +68,23 @@ func filterHeaderCategories(info *AppTranslationInfo) []TranslationCategory {
|
||||
if cat.Name == "" && cat.URLValue == "" {
|
||||
continue
|
||||
}
|
||||
// 网页版已移除账号体系,后台若仍配置个人中心/已购入口则不展示。
|
||||
if isAccountNavPath(cat.URLValue) {
|
||||
continue
|
||||
}
|
||||
out = append(out, cat)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isAccountNavPath(raw string) bool {
|
||||
switch strings.TrimRight(strings.TrimSpace(raw), "/") {
|
||||
case "/user-center", "user-center", "/profile", "profile", "/purchased-series", "purchased-series", "/purchased", "purchased":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DefaultCategoryList 接口失败时的兜底导航(字段与接口一致)。
|
||||
func DefaultCategoryList() []TranslationCategory {
|
||||
return []TranslationCategory{
|
||||
|
||||
@@ -290,10 +290,6 @@ func rewriteNavPath(path string) string {
|
||||
return "/popular-recommend"
|
||||
case "/tag", "/tag-list":
|
||||
return "/tags"
|
||||
case "/user-center":
|
||||
return "/profile"
|
||||
case "/purchased-series":
|
||||
return "/purchased"
|
||||
case "/search-results":
|
||||
return "/search"
|
||||
case "/more":
|
||||
@@ -455,8 +451,6 @@ func navActiveKey(href, name string, download bool) string {
|
||||
return "aiSeries"
|
||||
case "/home-road":
|
||||
return "homeRoad"
|
||||
case "/profile":
|
||||
return "userCenter"
|
||||
case "/download-app":
|
||||
return "downloadApp"
|
||||
default:
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package usercenterser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const centerDataPath = "/api/app/user/center/data"
|
||||
|
||||
// Data 对应 Swagger proto.UserCenterDataResp。
|
||||
type Data struct {
|
||||
WatchCount int64 `json:"watchCount"`
|
||||
CollectCount int64 `json:"collectCount"`
|
||||
ChasingCount int64 `json:"chasingCount"`
|
||||
BoughtChapterCount int64 `json:"boughtChapterCount"`
|
||||
}
|
||||
|
||||
// Fetch 获取当前用户的个人中心统计。code 为上游业务码,供会话失效重试。
|
||||
func Fetch(c *gin.Context) (*Data, int, error) {
|
||||
var env struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := upstream.GetJSON(c, centerDataPath, &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("user center data code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
var data Data
|
||||
if len(env.Data) == 0 || string(env.Data) == "null" {
|
||||
return nil, env.Code, fmt.Errorf("user center data is empty")
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &data); err != nil {
|
||||
return nil, env.Code, fmt.Errorf("decode user center data: %w", err)
|
||||
}
|
||||
return &data, env.Code, nil
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
package videoser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
collectSetPath = "/api/app/video/collect/set"
|
||||
collectListPath = "/api/app/video/collect/list"
|
||||
defaultCollectPageSize = 40
|
||||
)
|
||||
|
||||
// VideoCollectSetReq 对应 swagger proto.VideoCollectSetReq。
|
||||
// POST /api/app/video/collect/set
|
||||
type VideoCollectSetReq struct {
|
||||
ID int64 `json:"id"`
|
||||
IsCollect bool `json:"isCollect"`
|
||||
}
|
||||
|
||||
// VideoCollectSetResp 对应 swagger proto.VideoCollectSetResp。
|
||||
type VideoCollectSetResp struct {
|
||||
ID int64 `json:"id"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
IsCollect int `json:"isCollect"` // 1-已收藏 2-未收藏
|
||||
}
|
||||
|
||||
// VideoCollectData 对应 swagger proto.VideoCollectData。
|
||||
// GET /api/app/video/collect/list
|
||||
type VideoCollectData struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Slug string `json:"slug"`
|
||||
CoverImg string `json:"coverImg"`
|
||||
Keyworld []string `json:"keyworld"`
|
||||
Tags []int64 `json:"tags"`
|
||||
VideoTime int `json:"videoTime"`
|
||||
WatchTimes int64 `json:"watchTimes"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
CountComment int64 `json:"countComment"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
CollectedAt string `json:"collectedAt"`
|
||||
}
|
||||
|
||||
// VideoCollectListResp 对应 swagger proto.VideoCollectListResp。
|
||||
type VideoCollectListResp struct {
|
||||
List []VideoCollectData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// CollectListQuery 视频收藏列表分页。
|
||||
type CollectListQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *CollectListQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultCollectPageSize
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
}
|
||||
|
||||
// CollectSet 设置视频收藏/取消收藏。
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/视频相关接口/post_api_app_video_collect_set
|
||||
func CollectSet(c *gin.Context, req VideoCollectSetReq) (*APIEnvelope[VideoCollectSetResp], error) {
|
||||
if req.ID <= 0 {
|
||||
return nil, fmt.Errorf("video collect invalid id")
|
||||
}
|
||||
var env APIEnvelope[VideoCollectSetResp]
|
||||
if _, err := upstream.PostJSON(c, collectSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// FetchCollectList 拉取视频收藏列表:GET /api/app/video/collect/list。
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/视频相关接口/get_api_app_video_collect_list
|
||||
func FetchCollectList(c *gin.Context, q CollectListQuery) (*VideoCollectListResp, int, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
|
||||
var env APIEnvelope[VideoCollectListResp]
|
||||
if err := upstream.GetJSON(c, collectListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("video collect list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, env.Code, nil
|
||||
}
|
||||
|
||||
// FetchCollectListOrEmpty 失败返回空列表;游客会话失效时尝试重登后重试一次。
|
||||
func FetchCollectListOrEmpty(c *gin.Context, q CollectListQuery) *VideoCollectListResp {
|
||||
data, code, err := FetchCollectList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &VideoCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
if retry, _ := authser.OnSessionExpired(c, code); retry {
|
||||
data, _, err = FetchCollectList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &VideoCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
log.Error("fetch video collect list failed", log.E(err))
|
||||
return &VideoCollectListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package videoser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/authser"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
videoHistoryListPath = "/api/app/video/history/list"
|
||||
videoHistoryClearPath = "/api/app/video/history/clear"
|
||||
videoHistoryDeletePath = "/api/app/video/history/delete"
|
||||
defaultHistoryPageSize = 40
|
||||
)
|
||||
|
||||
// VideoHistoryData 对应 swagger proto.VideoHistoryData。
|
||||
// GET /api/app/video/history/list
|
||||
type VideoHistoryData struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Slug string `json:"slug"`
|
||||
CoverImg string `json:"coverImg"`
|
||||
Keyworld []string `json:"keyworld"`
|
||||
Tags []int64 `json:"tags"`
|
||||
VideoTime int `json:"videoTime"`
|
||||
WatchTimes int64 `json:"watchTimes"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
CountComment int64 `json:"countComment"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
HistoryAt string `json:"historyAt"`
|
||||
}
|
||||
|
||||
// VideoHistoryListResp 对应 swagger proto.VideoHistoryListResp。
|
||||
type VideoHistoryListResp struct {
|
||||
List []VideoHistoryData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// VideoHistoryClearResp 对应 swagger proto.VideoHistoryClearResp。
|
||||
type VideoHistoryClearResp struct {
|
||||
DeletedCount int `json:"deletedCount"`
|
||||
}
|
||||
|
||||
// VideoHistoryDeleteReq 对应 swagger proto.VideoHistoryDeleteReq。
|
||||
type VideoHistoryDeleteReq struct {
|
||||
VideoID int64 `json:"videoId"`
|
||||
}
|
||||
|
||||
// VideoHistoryDeleteResp 对应 swagger proto.VideoHistoryDeleteResp。
|
||||
type VideoHistoryDeleteResp struct {
|
||||
DeletedCount int `json:"deletedCount"`
|
||||
}
|
||||
|
||||
// HistoryListQuery 视频观看历史分页。
|
||||
type HistoryListQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *HistoryListQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultHistoryPageSize
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
}
|
||||
|
||||
// FetchHistoryList 分页查询视频观看历史:GET /api/app/video/history/list。
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/视频相关接口/get_api_app_video_history_list
|
||||
func FetchHistoryList(c *gin.Context, q HistoryListQuery) (*VideoHistoryListResp, int, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
|
||||
var env APIEnvelope[VideoHistoryListResp]
|
||||
if err := upstream.GetJSON(c, videoHistoryListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, env.Code, fmt.Errorf("video history list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, env.Code, nil
|
||||
}
|
||||
|
||||
// FetchHistoryListOrEmpty 失败返回空列表;游客会话失效时尝试重登后重试一次。
|
||||
func FetchHistoryListOrEmpty(c *gin.Context, q HistoryListQuery) *VideoHistoryListResp {
|
||||
data, code, err := FetchHistoryList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &VideoHistoryListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
if retry, _ := authser.OnSessionExpired(c, code); retry {
|
||||
data, _, err = FetchHistoryList(c, q)
|
||||
if err == nil {
|
||||
if data == nil {
|
||||
return &VideoHistoryListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
log.Error("fetch video history list failed", log.E(err))
|
||||
return &VideoHistoryListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
|
||||
// HistoryClear 清空视频观看历史:POST /api/app/video/history/clear。
|
||||
func HistoryClear(c *gin.Context) (*APIEnvelope[VideoHistoryClearResp], error) {
|
||||
var env APIEnvelope[VideoHistoryClearResp]
|
||||
if _, err := upstream.PostJSON(c, videoHistoryClearPath, nil, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// HistoryDelete 删除单条视频观看历史:POST /api/app/video/history/delete。
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/视频相关接口/post_api_app_video_history_delete
|
||||
func HistoryDelete(c *gin.Context, req VideoHistoryDeleteReq) (*APIEnvelope[VideoHistoryDeleteResp], error) {
|
||||
if req.VideoID <= 0 {
|
||||
return nil, fmt.Errorf("video history delete invalid videoId")
|
||||
}
|
||||
var env APIEnvelope[VideoHistoryDeleteResp]
|
||||
if _, err := upstream.PostJSON(c, videoHistoryDeletePath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package videoser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const likeSetPath = "/api/app/video/like/set"
|
||||
|
||||
// VideoLikeSetReq 对应 swagger proto.VideoLikeSetReq。
|
||||
// POST /api/app/video/like/set
|
||||
type VideoLikeSetReq struct {
|
||||
ID int64 `json:"id"`
|
||||
IsLike bool `json:"isLike"`
|
||||
}
|
||||
|
||||
// VideoLikeSetResp 对应 swagger proto.VideoLikeSetResp。
|
||||
type VideoLikeSetResp struct {
|
||||
ID int64 `json:"id"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
IsLike int `json:"isLike"` // 1-已点赞 2-未点赞
|
||||
}
|
||||
|
||||
// LikeSet 设置视频点赞/取消点赞。
|
||||
// 文档:http://172.104.181.99:25319/swagger/index.html#/视频相关接口/post_api_app_video_like_set
|
||||
func LikeSet(c *gin.Context, req VideoLikeSetReq) (*APIEnvelope[VideoLikeSetResp], error) {
|
||||
if req.ID <= 0 {
|
||||
return nil, fmt.Errorf("video like invalid id")
|
||||
}
|
||||
var env APIEnvelope[VideoLikeSetResp]
|
||||
if _, err := upstream.PostJSON(c, likeSetPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
Reference in New Issue
Block a user