Initial commit
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
categoryDetailPath = "/api/app/playlet/recommend/list"
|
||||
defaultCategoryPageSize = 25
|
||||
)
|
||||
|
||||
// CategoryDetailQuery 分类详情分页参数。categorySlug 非空时优先使用 slug。
|
||||
type CategoryDetailQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
CategoryID int64
|
||||
CategorySlug string
|
||||
}
|
||||
|
||||
func (q *CategoryDetailQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultCategoryPageSize
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
if q.CategoryID < 0 {
|
||||
q.CategoryID = 0
|
||||
}
|
||||
q.CategorySlug = strings.TrimSpace(q.CategorySlug)
|
||||
}
|
||||
|
||||
func categoryDetailListURL(q CategoryDetailQuery) string {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
if q.CategorySlug != "" {
|
||||
params.Set("categorySlug", q.CategorySlug)
|
||||
} else if q.CategoryID > 0 {
|
||||
params.Set("categoryId", strconv.FormatInt(q.CategoryID, 10))
|
||||
}
|
||||
return categoryDetailPath + "?" + params.Encode()
|
||||
}
|
||||
|
||||
// FetchCategoryDetail 根据分类 slug 或 ID 获取分类详情列表。
|
||||
func FetchCategoryDetail(c *gin.Context, q CategoryDetailQuery) (*PlayletRecommendListResp, error) {
|
||||
var env APIEnvelope[PlayletRecommendListResp]
|
||||
if err := upstream.GetPublicJSON(c, categoryDetailListURL(q), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet category detail code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchCategoryDetailOrEmpty 保持页面可渲染,接口失败时返回当前分页的空结果。
|
||||
func FetchCategoryDetailOrEmpty(c *gin.Context, q CategoryDetailQuery) *PlayletRecommendListResp {
|
||||
q.Normalize()
|
||||
data, err := FetchCategoryDetail(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet category detail failed", log.E(err))
|
||||
return &PlayletRecommendListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletRecommendListResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
data.SeoInfo.Normalize()
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCategoryDetailListURLUsesSlugBeforeID(t *testing.T) {
|
||||
got := categoryDetailListURL(CategoryDetailQuery{
|
||||
PageNum: 2,
|
||||
CategoryID: 18,
|
||||
CategorySlug: "latest-video",
|
||||
})
|
||||
for _, want := range []string{"/api/app/playlet/recommend/list?", "categorySlug=latest-video", "pageNum=2", "pageSize=25"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("categoryDetailListURL() = %q, missing %q", got, want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, "categoryId=") {
|
||||
t.Fatalf("categoryDetailListURL() = %q, categoryId must be omitted when slug exists", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCategoryDetailQueryAndCanonicalPath(t *testing.T) {
|
||||
slugQuery := ParseCategoryDetailQuery("latest-video", "3")
|
||||
if slugQuery.CategorySlug != "latest-video" || slugQuery.PageNum != 3 || slugQuery.PageSize != 25 {
|
||||
t.Fatalf("ParseCategoryDetailQuery(slug) = %#v", slugQuery)
|
||||
}
|
||||
if got := CategoryDetailCanonicalPath(slugQuery); got != "/category/latest-video/page/3/" {
|
||||
t.Fatalf("CategoryDetailCanonicalPath(slug) = %q", got)
|
||||
}
|
||||
|
||||
idQuery := ParseCategoryDetailQuery("42", "")
|
||||
if idQuery.CategoryID != 42 || idQuery.CategorySlug != "" {
|
||||
t.Fatalf("ParseCategoryDetailQuery(id) = %#v", idQuery)
|
||||
}
|
||||
if got := CategoryDetailCanonicalPath(idQuery); got != "/category/42/" {
|
||||
t.Fatalf("CategoryDetailCanonicalPath(id) = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoryDetailURLPrefersSlugAndFallsBackToID(t *testing.T) {
|
||||
if got := categoryDetailURL("latest-video", 42); got != "/category/latest-video/" {
|
||||
t.Fatalf("categoryDetailURL(slug) = %q", got)
|
||||
}
|
||||
if got := categoryDetailURL("", 42); got != "/category/42/" {
|
||||
t.Fatalf("categoryDetailURL(id) = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func categoryDetailPageURL(categoryID int64, categorySlug string, pageNum int) string {
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
path := "/category"
|
||||
if segment := pathSegment(categorySlug, categoryID); segment != "" {
|
||||
path += "/" + segment
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
func categoryDetailURL(categorySlug string, categoryID int64) string {
|
||||
return categoryDetailPageURL(categoryID, categorySlug, 1)
|
||||
}
|
||||
|
||||
// ParseCategoryDetailQuery 从语义化路由读取分类标识和页码。
|
||||
func ParseCategoryDetailQuery(identifier, pageStr string) CategoryDetailQuery {
|
||||
q := CategoryDetailQuery{PageSize: defaultCategoryPageSize}
|
||||
identifier = strings.TrimSpace(identifier)
|
||||
if id, err := strconv.ParseInt(identifier, 10, 64); err == nil && id > 0 {
|
||||
q.CategoryID = id
|
||||
} else {
|
||||
q.CategorySlug = identifier
|
||||
}
|
||||
if page, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = page
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
|
||||
func CategoryDetailCanonicalPath(q CategoryDetailQuery) string {
|
||||
q.Normalize()
|
||||
return categoryDetailPageURL(q.CategoryID, q.CategorySlug, q.PageNum)
|
||||
}
|
||||
|
||||
func BuildCategoryDetailPagination(q CategoryDetailQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(page int) string {
|
||||
return categoryDetailPageURL(q.CategoryID, q.CategorySlug, page)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
func CategoryDetailPageTitle(categoryName string, pageNum int, seo SeoInfo) string {
|
||||
name := strings.TrimSpace(categoryName)
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(seo.Title)
|
||||
}
|
||||
if name == "" {
|
||||
name = "分类短剧"
|
||||
}
|
||||
return name + PageTitleSuffix(pageNum)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
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 (
|
||||
chapterDetailPath = "/api/app/playlet/chapter/detail"
|
||||
chapterListPath = "/api/app/playlet/chapter/list"
|
||||
)
|
||||
|
||||
// PlayQuery 播放页参数。
|
||||
type PlayQuery struct {
|
||||
PlayletID int64
|
||||
PlayletSlug string
|
||||
ChapterID int64
|
||||
}
|
||||
|
||||
// ParsePlayQuery 解析播放页的路径参数。
|
||||
func ParsePlayQuery(playletKey, chapterIDRaw string) PlayQuery {
|
||||
q := PlayQuery{PlayletSlug: strings.TrimSpace(playletKey)}
|
||||
if n, err := strconv.ParseInt(strings.TrimSpace(playletKey), 10, 64); err == nil && n > 0 {
|
||||
q.PlayletID = n
|
||||
q.PlayletSlug = ""
|
||||
}
|
||||
if n, err := strconv.ParseInt(strings.TrimSpace(chapterIDRaw), 10, 64); err == nil && n > 0 {
|
||||
q.ChapterID = n
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// FetchChapterDetail 查询剧集播放详情。
|
||||
func FetchChapterDetail(c *gin.Context, chapterID, playletID int64, playletSlug string) (*PlayletChapterInfoResp, error) {
|
||||
if chapterID <= 0 {
|
||||
return nil, fmt.Errorf("chapter detail invalid chapterId")
|
||||
}
|
||||
params := url.Values{}
|
||||
params.Set("chapterId", strconv.FormatInt(chapterID, 10))
|
||||
if playletSlug = strings.TrimSpace(playletSlug); playletSlug != "" {
|
||||
params.Set("playletSlug", 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)
|
||||
}
|
||||
env.Data.SeoInfo.Normalize()
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchChapterDetailOrNil 失败返回 nil。
|
||||
func FetchChapterDetailOrNil(c *gin.Context, chapterID, playletID int64, playletSlug string) *PlayletChapterInfoResp {
|
||||
data, err := FetchChapterDetail(c, chapterID, playletID, playletSlug)
|
||||
if err != nil {
|
||||
log.Error("fetch chapter detail failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
if data == nil || data.ID <= 0 {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// FetchChapterList 根据短剧 slug 或 ID 查询选集列表,slug 优先。
|
||||
func FetchChapterList(c *gin.Context, playletID int64, playletSlug string) (*PlayletChapterListResp, error) {
|
||||
params := url.Values{}
|
||||
if playletSlug = strings.TrimSpace(playletSlug); playletSlug != "" {
|
||||
params.Set("playletSlug", playletSlug)
|
||||
} else if playletID > 0 {
|
||||
params.Set("playletId", strconv.FormatInt(playletID, 10))
|
||||
} 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)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// ResolvePlayChapterID 无 chapterId 时取短剧第一章。
|
||||
func ResolvePlayChapterID(playlet *PlayletInfoResp, chapterID int64) int64 {
|
||||
if chapterID > 0 {
|
||||
return chapterID
|
||||
}
|
||||
if playlet == nil {
|
||||
return 0
|
||||
}
|
||||
for _, ch := range playlet.PlayletChapterInfo {
|
||||
if ch.ID > 0 {
|
||||
return ch.ID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// AllowWatch 是否可播放(优先 canWatch;兼容仅返回 videoUrl 的旧数据)。
|
||||
func (c *PlayletChapterInfoResp) AllowWatch() bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
if c.CanWatch {
|
||||
return true
|
||||
}
|
||||
if c.NeedUnlock || c.NeedVip {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(c.VideoURL) != "" && c.PayType == 0
|
||||
}
|
||||
|
||||
// UnlockCost 金币解锁消耗:优先 costCoins。
|
||||
func (c *PlayletChapterInfoResp) UnlockCost() int64 {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
if c.CostCoins > 0 {
|
||||
return c.CostCoins
|
||||
}
|
||||
if c.SingleCoins > 0 {
|
||||
return int64(c.SingleCoins)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// AllowWatch 详情选集是否可直达播放(优先 canWatch)。
|
||||
func (c PlayletChapterData) AllowWatch() bool {
|
||||
if c.CanWatch {
|
||||
return true
|
||||
}
|
||||
if c.NeedUnlock || c.NeedVip {
|
||||
return false
|
||||
}
|
||||
if c.IsUnlocked {
|
||||
return true
|
||||
}
|
||||
return c.PayType == 0
|
||||
}
|
||||
|
||||
// NeedCoinGate 是否弹出金币解锁。
|
||||
func (c PlayletChapterData) NeedCoinGate() bool {
|
||||
if c.AllowWatch() {
|
||||
return false
|
||||
}
|
||||
if c.NeedUnlock {
|
||||
return true
|
||||
}
|
||||
return c.PayType == 1
|
||||
}
|
||||
|
||||
// NeedVipGate 是否弹出 VIP 开通。
|
||||
func (c PlayletChapterData) NeedVipGate() bool {
|
||||
if c.AllowWatch() || c.NeedCoinGate() {
|
||||
return false
|
||||
}
|
||||
if c.NeedVip {
|
||||
return true
|
||||
}
|
||||
return c.PayType == 2
|
||||
}
|
||||
|
||||
// UnlockCost 金币解锁消耗:优先 costCoins。
|
||||
func (c PlayletChapterData) UnlockCost() int {
|
||||
if c.CostCoins > 0 {
|
||||
return int(c.CostCoins)
|
||||
}
|
||||
return c.SingleCoins
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
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"`
|
||||
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
|
||||
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
|
||||
}
|
||||
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))
|
||||
|
||||
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}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
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 (
|
||||
detailPath = "/api/app/playlet/detail"
|
||||
defaultEpisodeRange = 30
|
||||
)
|
||||
|
||||
// EpisodeRange 剧集分段(仅 UI 分页展示,非接口字段映射)。
|
||||
type EpisodeRange struct {
|
||||
Start int
|
||||
End int
|
||||
Label string
|
||||
}
|
||||
|
||||
// FetchDetail 根据短剧 ID 查询详情。
|
||||
func FetchDetail(c *gin.Context, id int64) (*PlayletInfoResp, error) {
|
||||
if id <= 0 {
|
||||
return nil, fmt.Errorf("playlet detail invalid id")
|
||||
}
|
||||
return fetchDetail(c, "id", strconv.FormatInt(id, 10))
|
||||
}
|
||||
|
||||
// FetchDetailByKey 优先按 slug 查询;纯数字路由段按 ID 查询。
|
||||
func FetchDetailByKey(c *gin.Context, key string) (*PlayletInfoResp, error) {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("playlet detail missing route key")
|
||||
}
|
||||
if id := ParseDetailID(key); id > 0 {
|
||||
return FetchDetail(c, id)
|
||||
}
|
||||
return fetchDetail(c, "slug", key)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
env.Data.SeoInfo.Normalize()
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
func fetchDetailOnce(c *gin.Context, queryKey, value string) (*APIEnvelope[PlayletInfoResp], error) {
|
||||
params := url.Values{}
|
||||
params.Set(queryKey, value)
|
||||
var env APIEnvelope[PlayletInfoResp]
|
||||
if err := upstream.GetJSON(c, detailPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// FetchDetailOrNilByKey 失败或无效时返回 nil。
|
||||
func FetchDetailOrNilByKey(c *gin.Context, key string) *PlayletInfoResp {
|
||||
data, err := FetchDetailByKey(c, key)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet detail by route key failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
if data == nil || data.ID <= 0 {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// ParseDetailID 解析纯数字路由段。
|
||||
func ParseDetailID(raw string) int64 {
|
||||
id, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// BuildEpisodeRanges 按集数分段(默认每段 30 集)。
|
||||
func BuildEpisodeRanges(chapters []PlayletChapterData, totalEpisode, size int) []EpisodeRange {
|
||||
if size <= 0 {
|
||||
size = defaultEpisodeRange
|
||||
}
|
||||
maxEp := 0
|
||||
for _, ch := range chapters {
|
||||
if ch.CurrentEpisode > maxEp {
|
||||
maxEp = ch.CurrentEpisode
|
||||
}
|
||||
}
|
||||
if totalEpisode > maxEp {
|
||||
maxEp = totalEpisode
|
||||
}
|
||||
if maxEp <= 0 {
|
||||
maxEp = len(chapters)
|
||||
}
|
||||
if maxEp <= 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]EpisodeRange, 0, (maxEp+size-1)/size)
|
||||
for start := 1; start <= maxEp; start += size {
|
||||
end := start + size - 1
|
||||
if end > maxEp {
|
||||
end = maxEp
|
||||
}
|
||||
out = append(out, EpisodeRange{
|
||||
Start: start,
|
||||
End: end,
|
||||
Label: fmt.Sprintf("%d–%d", start, end),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// UnmarshalJSON 兼容上游 data 为对象、null、空字符串,或二次 JSON 编码的字符串。
|
||||
func (e *APIEnvelope[T]) UnmarshalJSON(raw []byte) error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
raw = bytes.TrimSpace(raw)
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
var aux struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &aux); err != nil {
|
||||
return err
|
||||
}
|
||||
e.Code = aux.Code
|
||||
e.Msg = aux.Msg
|
||||
e.Tip = aux.Tip
|
||||
data, err := unmarshalEnvelopeData[T](aux.Data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e.Data = data
|
||||
return nil
|
||||
}
|
||||
|
||||
func unmarshalEnvelopeData[T any](raw json.RawMessage) (T, error) {
|
||||
var zero T
|
||||
raw = bytes.TrimSpace(raw)
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return zero, nil
|
||||
}
|
||||
if raw[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(raw, &s); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return zero, nil
|
||||
}
|
||||
inner := bytes.TrimSpace([]byte(s))
|
||||
if len(inner) == 0 {
|
||||
return zero, nil
|
||||
}
|
||||
if inner[0] != '{' && inner[0] != '[' {
|
||||
return zero, nil
|
||||
}
|
||||
if err := json.Unmarshal(inner, &zero); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
return zero, nil
|
||||
}
|
||||
if err := json.Unmarshal(raw, &zero); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
return zero, nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package playletser
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFooterLinkURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{name: "关于我们", raw: "/richtext/关于我们", want: "/richtext/关于我们/"},
|
||||
{name: "帮助中心", raw: "/richtext/帮助中心", want: "/richtext/帮助中心/"},
|
||||
{name: "隐私政策", raw: "/richtext/privacy", want: "/richtext/privacy/"},
|
||||
{name: "问题反馈", raw: "/feedback", want: "/feedback/"},
|
||||
{name: "用户中心", raw: "/user-center/", want: "/user-center/"},
|
||||
{name: "合作伙伴", raw: "https://example.com", want: "https://example.com"},
|
||||
{name: "HTTPS外链", raw: "HTTPS://Example.COM", want: "HTTPS://Example.COM"},
|
||||
{name: "关于我们", raw: "", want: ""},
|
||||
{name: "关于我们", raw: "/", want: ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name+" "+tt.raw, func(t *testing.T) {
|
||||
if got := footerLinkURL(tt.name, tt.raw); got != tt.want {
|
||||
t.Fatalf("footerLinkURL(%q, %q) = %q, want %q", tt.name, tt.raw, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFooterLinkIsExternal(t *testing.T) {
|
||||
if !footerLinkIsExternal("http://a.com") || !footerLinkIsExternal("HTTPS://A.COM") {
|
||||
t.Fatal("http(s) URLs should be external")
|
||||
}
|
||||
if footerLinkIsExternal("/richtext/关于我们/") || footerLinkIsExternal("/feedback/") {
|
||||
t.Fatal("internal paths should not be external")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFooterContactURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value string
|
||||
gmail string
|
||||
telegram string
|
||||
customer string
|
||||
want string
|
||||
}{
|
||||
{name: "E-mail", value: "hello@example.com", want: "mailto:hello@example.com"},
|
||||
{name: "邮箱", gmail: "support@example.com", want: "mailto:support@example.com"},
|
||||
{name: "商务合作", value: "立即联系", customer: "service.example.com", want: "https://service.example.com"},
|
||||
{name: "商务合作", value: "business@example.com", want: "mailto:business@example.com"},
|
||||
{name: "官方群", value: "立即加入", telegram: "https://t.me/example", want: "https://t.me/example"},
|
||||
{name: "官方群", value: "t.me/example", want: "https://t.me/example"},
|
||||
{name: "工作时间", value: "10:00-18:00", want: ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name+tt.value, func(t *testing.T) {
|
||||
got := footerContactURL(tt.name, tt.value, tt.gmail, tt.telegram, tt.customer)
|
||||
if got != tt.want {
|
||||
t.Fatalf("footerContactURL(%q, %q) = %q, want %q", tt.name, tt.value, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFooterContactValue(t *testing.T) {
|
||||
for _, value := range []string{"立即联系", "立即加入", " 立即加入 "} {
|
||||
if got := footerContactValue(value); got != "" {
|
||||
t.Fatalf("footerContactValue(%q) = %q, want empty", value, got)
|
||||
}
|
||||
}
|
||||
if got := footerContactValue("hello@example.com"); got != "hello@example.com" {
|
||||
t.Fatalf("footerContactValue(email) = %q", got)
|
||||
}
|
||||
if got := footerContactValue("立即联系:https://t1t1.com"); got != "https://t1t1.com" {
|
||||
t.Fatalf("footerContactValue(business URL) = %q", got)
|
||||
}
|
||||
if got := footerContactValue("立即加入: https://t.me/fuliqun_91sp"); got != "https://t.me/fuliqun_91sp" {
|
||||
t.Fatalf("footerContactValue(group URL) = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFooterContactName(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"商务合作:立即联系": "商务合作",
|
||||
"官方群:立即加入": "官方群",
|
||||
"立即联系:商务合作": "商务合作",
|
||||
" E-mail ": "E-mail",
|
||||
}
|
||||
for input, want := range tests {
|
||||
if got := footerContactName(input); got != want {
|
||||
t.Fatalf("footerContactName(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNavDisplayURL(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"https://91lvmao0000.com/": "91lvmao0000.com",
|
||||
"http://example.com/path/": "example.com/path",
|
||||
"example.com": "example.com",
|
||||
}
|
||||
for input, want := range tests {
|
||||
if got := navDisplayURL(input); got != want {
|
||||
t.Fatalf("navDisplayURL(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const forwardHeatPath = "/api/app/playlet/forward/heat"
|
||||
|
||||
// PlayletForwardHeatReq 对应 swagger proto.PlayletForwardHeatReq
|
||||
type PlayletForwardHeatReq struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
// PlayletForwardHeatResp 对应 swagger proto.PlayletForwardHeatResp
|
||||
type PlayletForwardHeatResp struct {
|
||||
ID int64 `json:"id"`
|
||||
HeatValue int64 `json:"heatValue"`
|
||||
}
|
||||
|
||||
// ForwardHeat 短剧转发增加热度。
|
||||
func ForwardHeat(c *gin.Context, req PlayletForwardHeatReq) (*APIEnvelope[PlayletForwardHeatResp], error) {
|
||||
if req.ID <= 0 {
|
||||
return nil, fmt.Errorf("playlet forward heat invalid id")
|
||||
}
|
||||
var env APIEnvelope[PlayletForwardHeatResp]
|
||||
if _, err := upstream.PostJSON(c, forwardHeatPath, req, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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"
|
||||
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"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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,无请求体。
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
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)
|
||||
}
|
||||
|
||||
// formatHistoryAt 最近观看时间展示。
|
||||
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 t.Format("2006-01-02 15:04")
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const homePath = "/api/app/playlet/home"
|
||||
const homeCacheTTL = 30 * time.Second
|
||||
|
||||
var (
|
||||
homeMu sync.Mutex
|
||||
homeCache *HomePlayletResponse
|
||||
homeAt time.Time
|
||||
)
|
||||
|
||||
// FetchHome 拉取首页短剧聚合数据。
|
||||
func FetchHome(c *gin.Context) (*HomePlayletResponse, error) {
|
||||
var env APIEnvelope[HomePlayletResponse]
|
||||
if err := upstream.GetPublicJSON(c, homePath, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet home code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchHomeOrEmpty 带短缓存;失败时打日志并返回空结构,保证 SSR 页面可渲染。
|
||||
func FetchHomeOrEmpty(c *gin.Context) *HomePlayletResponse {
|
||||
homeMu.Lock()
|
||||
defer homeMu.Unlock()
|
||||
if homeCache != nil && time.Since(homeAt) < homeCacheTTL {
|
||||
return cloneHome(homeCache)
|
||||
}
|
||||
|
||||
data, err := FetchHome(c)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet home failed", log.E(err))
|
||||
if homeCache != nil {
|
||||
return cloneHome(homeCache)
|
||||
}
|
||||
return &HomePlayletResponse{}
|
||||
}
|
||||
if data == nil {
|
||||
if homeCache != nil {
|
||||
return cloneHome(homeCache)
|
||||
}
|
||||
return &HomePlayletResponse{}
|
||||
}
|
||||
data.SeoInfo.Normalize()
|
||||
homeCache = data
|
||||
homeAt = time.Now()
|
||||
return cloneHome(homeCache)
|
||||
}
|
||||
|
||||
func cloneHome(src *HomePlayletResponse) *HomePlayletResponse {
|
||||
if src == nil {
|
||||
return &HomePlayletResponse{}
|
||||
}
|
||||
out := *src
|
||||
if src.Announcements != nil {
|
||||
out.Announcements = append([]AnnouncementItem(nil), src.Announcements...)
|
||||
}
|
||||
if src.HomeBannerData != nil {
|
||||
out.HomeBannerData = append([]HomeBannerData(nil), src.HomeBannerData...)
|
||||
}
|
||||
if src.HomeTodayUpdateData != nil {
|
||||
out.HomeTodayUpdateData = append([]CommonData(nil), src.HomeTodayUpdateData...)
|
||||
}
|
||||
if src.HomeCategoryData != nil {
|
||||
out.HomeCategoryData = make([]HomeCategoryData, len(src.HomeCategoryData))
|
||||
for i, cat := range src.HomeCategoryData {
|
||||
out.HomeCategoryData[i] = cat
|
||||
if cat.List != nil {
|
||||
out.HomeCategoryData[i].List = append([]CommonData(nil), cat.List...)
|
||||
}
|
||||
}
|
||||
}
|
||||
if src.HomeRecommendThemes != nil {
|
||||
out.HomeRecommendThemes = append([]HomeRecommendTheme(nil), src.HomeRecommendThemes...)
|
||||
}
|
||||
if src.SeoInfo.Keywords != nil {
|
||||
out.SeoInfo.Keywords = append([]string(nil), src.SeoInfo.Keywords...)
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
// ActiveHomeBanners 过滤未启用项,保留接口返回顺序。
|
||||
func ActiveHomeBanners(list []HomeBannerData) []HomeBannerData {
|
||||
if len(list) == 0 {
|
||||
return list
|
||||
}
|
||||
out := make([]HomeBannerData, 0, len(list))
|
||||
for _, item := range list {
|
||||
if !item.Status {
|
||||
continue
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"videoweb/app/service/upstream"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const hotLikePath = "/api/app/playlet/hot-like"
|
||||
|
||||
// PlayletHotSearchItem 对应 swagger proto.PlayletHotSearchItem。
|
||||
type PlayletHotSearchItem struct {
|
||||
Keyword string `json:"keyword"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// PlayletHotLikeResp 对应 swagger proto.PlayletHotLikeResp。
|
||||
type PlayletHotLikeResp struct {
|
||||
HotSearch []PlayletHotSearchItem `json:"hotSearch"`
|
||||
GuessLike []CommonData `json:"guessLike"`
|
||||
}
|
||||
|
||||
// FetchHotLike 获取前 10 个热搜词及按收藏量排序的 15 部猜你喜欢短剧。
|
||||
func FetchHotLike(c *gin.Context) (*PlayletHotLikeResp, error) {
|
||||
var env APIEnvelope[PlayletHotLikeResp]
|
||||
if err := upstream.GetPublicJSON(c, hotLikePath, &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet hot-like code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPlayletHotLikeRespMatchesSwaggerFields(t *testing.T) {
|
||||
const raw = `{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"data": {
|
||||
"hotSearch": [{"keyword": "都市", "count": 18}],
|
||||
"guessLike": [{"id": 12, "title": "示例短剧", "slug": "example"}]
|
||||
}
|
||||
}`
|
||||
|
||||
var env APIEnvelope[PlayletHotLikeResp]
|
||||
if err := json.Unmarshal([]byte(raw), &env); err != nil {
|
||||
t.Fatalf("unmarshal hot-like response: %v", err)
|
||||
}
|
||||
if env.Code != 200 || len(env.Data.HotSearch) != 1 || env.Data.HotSearch[0].Keyword != "都市" || env.Data.HotSearch[0].Count != 18 {
|
||||
t.Fatalf("unexpected hot search data: %#v", env)
|
||||
}
|
||||
if len(env.Data.GuessLike) != 1 || env.Data.GuessLike[0].ID != 12 || env.Data.GuessLike[0].Slug != "example" {
|
||||
t.Fatalf("unexpected guess-like data: %#v", env.Data.GuessLike)
|
||||
}
|
||||
if hotLikePath != "/api/app/playlet/hot-like" {
|
||||
t.Fatalf("hotLikePath = %q", hotLikePath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
listPath = "/api/app/playlet/list"
|
||||
themePath = "/api/app/theme/list"
|
||||
|
||||
defaultListPageSize = 25
|
||||
sortHeat = 1 // 热度优先
|
||||
sortTodayUpdate = 2 // 今日更新
|
||||
// 站点统一类型:1-非成人 2-成人(与 themeType 一致)。
|
||||
contentTypeNonAdult = 1
|
||||
contentTypeAdult = 2
|
||||
// playlet/list 上游 type 与站点定义相反:1-成人 2-非成人。
|
||||
upstreamListTypeAdult = 1
|
||||
upstreamListTypeNonAdult = 2
|
||||
)
|
||||
|
||||
// ListQuery 短剧列表查询参数。
|
||||
type ListQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
SortOrder int
|
||||
ThemeID int64
|
||||
ThemeSlug string
|
||||
Type int
|
||||
}
|
||||
|
||||
// Normalize 校正分页与排序默认值。
|
||||
func (q *ListQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultListPageSize
|
||||
}
|
||||
if q.PageSize > 50 {
|
||||
q.PageSize = 50
|
||||
}
|
||||
if q.SortOrder != sortTodayUpdate {
|
||||
q.SortOrder = sortHeat
|
||||
}
|
||||
if q.ThemeID < 0 {
|
||||
q.ThemeID = 0
|
||||
}
|
||||
q.Type = normalizeContentType(q.Type)
|
||||
}
|
||||
|
||||
// FetchList 分页查询已上架短剧。
|
||||
func FetchList(c *gin.Context, q ListQuery) (*PlayletVideoResp, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
params.Set("sortOrder", strconv.Itoa(q.SortOrder))
|
||||
if strings.TrimSpace(q.ThemeSlug) != "" {
|
||||
params.Set("themeSlug", strings.TrimSpace(q.ThemeSlug))
|
||||
} else if q.ThemeID > 0 {
|
||||
params.Set("themeId", strconv.FormatInt(q.ThemeID, 10))
|
||||
} else {
|
||||
params.Set("type", strconv.Itoa(listTypeForUpstream(q.Type)))
|
||||
}
|
||||
|
||||
var env APIEnvelope[PlayletVideoResp]
|
||||
if err := upstream.GetPublicJSON(c, listPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchListOrEmpty 失败时返回空列表。
|
||||
func FetchListOrEmpty(c *gin.Context, q ListQuery) *PlayletVideoResp {
|
||||
data, err := FetchList(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet list failed", log.E(err))
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
data.SeoInfo.Normalize()
|
||||
return data
|
||||
}
|
||||
|
||||
// FetchThemes 拉取题材列表。
|
||||
func FetchThemes(c *gin.Context, contentType int) ([]PlayletThemeItem, error) {
|
||||
contentType = normalizeContentType(contentType)
|
||||
params := url.Values{}
|
||||
params.Set("themeType", strconv.Itoa(contentType))
|
||||
var env APIEnvelope[PlayletThemeListResponse]
|
||||
if err := upstream.GetPublicJSON(c, themePath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("theme list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return env.Data.List, nil
|
||||
}
|
||||
|
||||
// FetchThemesOrEmpty 失败时返回空题材。
|
||||
func FetchThemesOrEmpty(c *gin.Context, contentType int) []PlayletThemeItem {
|
||||
list, err := FetchThemes(c, contentType)
|
||||
if err != nil {
|
||||
log.Error("fetch theme list failed", log.E(err))
|
||||
return nil
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func normalizeContentType(contentType int) int {
|
||||
if contentType == contentTypeAdult {
|
||||
return contentTypeAdult
|
||||
}
|
||||
return contentTypeNonAdult
|
||||
}
|
||||
|
||||
// listTypeForUpstream 将站点统一类型转为 playlet/list 的 type(该接口 1=成人 2=非成人)。
|
||||
func listTypeForUpstream(contentType int) int {
|
||||
if normalizeContentType(contentType) == contentTypeAdult {
|
||||
return upstreamListTypeAdult
|
||||
}
|
||||
return upstreamListTypeNonAdult
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PaginationVM 分页条数据(页面 UI,非接口字段映射)。
|
||||
type PaginationVM struct {
|
||||
Visible bool
|
||||
HasPrev bool
|
||||
HasNext bool
|
||||
PrevURL string
|
||||
NextURL string
|
||||
Page int
|
||||
TotalPages int
|
||||
Items []PaginationItemVM
|
||||
}
|
||||
|
||||
// PaginationItemVM 页码或省略号。
|
||||
type PaginationItemVM struct {
|
||||
Label string
|
||||
URL string
|
||||
Active bool
|
||||
Dots bool
|
||||
}
|
||||
|
||||
// FilterChipVM 筛选 / Tab UI。
|
||||
type FilterChipVM struct {
|
||||
Label string
|
||||
URL string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// ThemeChipVM 题材筛选芯片(ID/Name 来自接口,URL/Active 为页面状态)。
|
||||
type ThemeChipVM struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// FindThemeSlugByID 查询 ID 对应的 slug;无 slug 时继续使用 ID 路由。
|
||||
func FindThemeSlugByID(themes []PlayletThemeItem, id int64) string {
|
||||
if id <= 0 {
|
||||
return ""
|
||||
}
|
||||
for _, theme := range themes {
|
||||
if theme.ID == id {
|
||||
return strings.TrimSpace(theme.Slug)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func listPageURL(themeID int64, themeSlug string, sortOrder, pageNum, contentType int) string {
|
||||
if sortOrder != sortTodayUpdate {
|
||||
sortOrder = sortHeat
|
||||
}
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
cleanSlug := strings.TrimSpace(themeSlug)
|
||||
defaultSort := sortHeat
|
||||
if cleanSlug == "ai-short-play" || cleanSlug == "ai-series" {
|
||||
defaultSort = sortTodayUpdate
|
||||
}
|
||||
if themeID <= 0 && cleanSlug == "" && sortOrder == sortHeat && pageNum == 1 {
|
||||
return "/list/"
|
||||
}
|
||||
path := "/list"
|
||||
segment := pathSegment(themeSlug, themeID)
|
||||
if segment == "" {
|
||||
segment = "all"
|
||||
}
|
||||
path += "/" + segment + "/" + strconv.Itoa(sortOrder)
|
||||
if themeID <= 0 && cleanSlug != "" && sortOrder == defaultSort && pageNum == 1 {
|
||||
return "/list/" + segment + "/"
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
// ListCanonicalPath 返回列表页唯一的无 query 规范路径。
|
||||
func ListCanonicalPath(q ListQuery) string {
|
||||
q.Normalize()
|
||||
return listPageURL(q.ThemeID, q.ThemeSlug, q.SortOrder, q.PageNum, q.Type)
|
||||
}
|
||||
|
||||
// ListResetURL 重置筛选并生成无 query 的默认排序路径。
|
||||
func ListResetURL(q ListQuery) string {
|
||||
q.Normalize()
|
||||
return ListCanonicalPath(ListQuery{Type: q.Type})
|
||||
}
|
||||
|
||||
// BuildListThemes 题材芯片;Name/ID 保持接口字段语义。
|
||||
func BuildListThemes(themes []PlayletThemeItem, q ListQuery) []ThemeChipVM {
|
||||
q.Normalize()
|
||||
out := make([]ThemeChipVM, 0, len(themes)+1)
|
||||
out = append(out, ThemeChipVM{
|
||||
ID: 0,
|
||||
Name: "全部",
|
||||
URL: listPageURL(0, "", q.SortOrder, 1, q.Type),
|
||||
Active: q.ThemeID == 0 && strings.TrimSpace(q.ThemeSlug) == "",
|
||||
})
|
||||
for _, t := range themes {
|
||||
if !t.Status {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimSpace(t.Name)
|
||||
if name == "" || t.ID <= 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, ThemeChipVM{
|
||||
ID: t.ID,
|
||||
Name: name,
|
||||
URL: listPageURL(t.ID, t.Slug, q.SortOrder, 1, q.Type),
|
||||
Active: q.ThemeID == t.ID || (strings.TrimSpace(q.ThemeSlug) != "" && strings.TrimSpace(q.ThemeSlug) == strings.TrimSpace(t.Slug)),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// BuildListSortChips 排序芯片。
|
||||
func BuildListSortChips(q ListQuery) (heat, update FilterChipVM) {
|
||||
q.Normalize()
|
||||
heat = FilterChipVM{
|
||||
Label: "热度优先",
|
||||
URL: listPageURL(q.ThemeID, q.ThemeSlug, sortHeat, 1, q.Type),
|
||||
Active: q.SortOrder == sortHeat,
|
||||
}
|
||||
update = FilterChipVM{
|
||||
Label: "今日更新",
|
||||
URL: listPageURL(q.ThemeID, q.ThemeSlug, sortTodayUpdate, 1, q.Type),
|
||||
Active: q.SortOrder == sortTodayUpdate,
|
||||
}
|
||||
return heat, update
|
||||
}
|
||||
|
||||
// BuildListPagination 列表分页。
|
||||
func BuildListPagination(q ListQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return listPageURL(q.ThemeID, q.ThemeSlug, q.SortOrder, p, q.Type)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// BuildPagination 生成分页 VM;pageURL 生成指定页链接。
|
||||
func BuildPagination(pageURL func(int) string, pageNum, pageSize int, totalCount int64) PaginationVM {
|
||||
if pageURL == nil {
|
||||
pageURL = func(p int) string {
|
||||
if p <= 1 {
|
||||
return "#"
|
||||
}
|
||||
return "?page=" + strconv.Itoa(p)
|
||||
}
|
||||
}
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = defaultListPageSize
|
||||
}
|
||||
totalPages := int((totalCount + int64(pageSize) - 1) / int64(pageSize))
|
||||
if totalPages <= 1 {
|
||||
return PaginationVM{Visible: false}
|
||||
}
|
||||
if pageNum > totalPages {
|
||||
pageNum = totalPages
|
||||
}
|
||||
|
||||
return PaginationVM{
|
||||
Visible: true,
|
||||
HasPrev: pageNum > 1,
|
||||
HasNext: pageNum < totalPages,
|
||||
PrevURL: pageURL(pageNum - 1),
|
||||
NextURL: pageURL(pageNum + 1),
|
||||
Page: pageNum,
|
||||
TotalPages: totalPages,
|
||||
Items: buildPageItems(pageNum, totalPages, pageURL),
|
||||
}
|
||||
}
|
||||
|
||||
func buildPageItems(current, total int, pageURL func(int) string) []PaginationItemVM {
|
||||
if total <= 0 {
|
||||
return nil
|
||||
}
|
||||
if total <= 7 {
|
||||
out := make([]PaginationItemVM, 0, total)
|
||||
for i := 1; i <= total; i++ {
|
||||
out = append(out, PaginationItemVM{
|
||||
Label: strconv.Itoa(i),
|
||||
URL: pageURL(i),
|
||||
Active: i == current,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
addPage := func(out *[]PaginationItemVM, p int) {
|
||||
*out = append(*out, PaginationItemVM{
|
||||
Label: strconv.Itoa(p),
|
||||
URL: pageURL(p),
|
||||
Active: p == current,
|
||||
})
|
||||
}
|
||||
addDots := func(out *[]PaginationItemVM) {
|
||||
*out = append(*out, PaginationItemVM{Dots: true, Label: "…"})
|
||||
}
|
||||
|
||||
var out []PaginationItemVM
|
||||
addPage(&out, 1)
|
||||
if current > 3 {
|
||||
addDots(&out)
|
||||
}
|
||||
start := current - 1
|
||||
end := current + 1
|
||||
if start < 2 {
|
||||
start = 2
|
||||
}
|
||||
if end > total-1 {
|
||||
end = total - 1
|
||||
}
|
||||
for p := start; p <= end; p++ {
|
||||
addPage(&out, p)
|
||||
}
|
||||
if current < total-2 {
|
||||
addDots(&out)
|
||||
}
|
||||
addPage(&out, total)
|
||||
return out
|
||||
}
|
||||
|
||||
// ParseListQuery 从 gin query 解析列表参数。
|
||||
func ParseListQuery(pageStr, sortStr, typeStr string) ListQuery {
|
||||
q := ListQuery{PageSize: defaultListPageSize, SortOrder: sortHeat, Type: contentTypeNonAdult}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(sortStr)); err == nil {
|
||||
q.SortOrder = n
|
||||
}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(typeStr)); err == nil {
|
||||
q.Type = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const operateListPath = "/api/app/playlet/operate/list"
|
||||
|
||||
type OperateListQuery struct {
|
||||
OperateType int
|
||||
FilterType int
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
func (q *OperateListQuery) Normalize() {
|
||||
if q.OperateType < 1 || q.OperateType > 2 {
|
||||
q.OperateType = 1
|
||||
}
|
||||
if q.FilterType < 1 || q.FilterType > 3 {
|
||||
q.FilterType = 1
|
||||
}
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = 40
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
}
|
||||
|
||||
// FetchOperateList 按运营类型和筛选类型查询已上架短剧。
|
||||
func FetchOperateList(c *gin.Context, q OperateListQuery) (*PlayletOperateListResp, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("operateType", strconv.Itoa(q.OperateType))
|
||||
params.Set("filterType", strconv.Itoa(q.FilterType))
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
|
||||
var env APIEnvelope[PlayletOperateListResp]
|
||||
if err := upstream.GetPublicJSON(c, operateListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet operate list code=%d msg=%s tip=%s", env.Code, env.Msg, env.Tip)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchOperateListOrEmpty 为 SSR 页面提供容错,接口异常时仍渲染完整页面骨架。
|
||||
func FetchOperateListOrEmpty(c *gin.Context, q OperateListQuery) *PlayletOperateListResp {
|
||||
q.Normalize()
|
||||
data, err := FetchOperateList(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet operate list failed", log.E(err))
|
||||
return &PlayletOperateListResp{
|
||||
OperateType: q.OperateType,
|
||||
FilterType: q.FilterType,
|
||||
PageNum: q.PageNum,
|
||||
PageSize: q.PageSize,
|
||||
}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletOperateListResp{
|
||||
OperateType: q.OperateType,
|
||||
FilterType: q.FilterType,
|
||||
PageNum: q.PageNum,
|
||||
PageSize: q.PageSize,
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
rankPath = "/api/app/playlet/rank"
|
||||
|
||||
defaultRankPageSize = 30
|
||||
|
||||
// 排行榜 sortOrder:1-热播榜,2-新剧榜,3-追剧榜
|
||||
rankSortHot = 1
|
||||
rankSortNew = 2
|
||||
rankSortBinge = 3
|
||||
)
|
||||
|
||||
// RankQuery 排行榜查询参数。
|
||||
type RankQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
SortOrder int
|
||||
}
|
||||
|
||||
// Normalize 校正分页与榜单类型。
|
||||
func (q *RankQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultRankPageSize
|
||||
}
|
||||
if q.PageSize > 50 {
|
||||
q.PageSize = 50
|
||||
}
|
||||
switch q.SortOrder {
|
||||
case rankSortNew, rankSortBinge:
|
||||
default:
|
||||
q.SortOrder = rankSortHot
|
||||
}
|
||||
}
|
||||
|
||||
// FetchRank 分页查询短剧排行榜。
|
||||
func FetchRank(c *gin.Context, q RankQuery) (*PlayletVideoResp, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
params.Set("sortOrder", strconv.Itoa(q.SortOrder))
|
||||
|
||||
var env APIEnvelope[PlayletVideoResp]
|
||||
if err := upstream.GetPublicJSON(c, rankPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet rank code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchRankOrEmpty 失败时返回空榜单。
|
||||
func FetchRankOrEmpty(c *gin.Context, q RankQuery) *PlayletVideoResp {
|
||||
data, err := FetchRank(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet rank failed", log.E(err))
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
data.SeoInfo.Normalize()
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func formatCollectHeat(n int64) string {
|
||||
if n <= 0 {
|
||||
return "0 收藏"
|
||||
}
|
||||
if n < 10000 {
|
||||
return fmt.Sprintf("%d 收藏", n)
|
||||
}
|
||||
v := float64(n) / 10000
|
||||
if v >= 100 {
|
||||
return fmt.Sprintf("%.0f万 收藏", v)
|
||||
}
|
||||
return fmt.Sprintf("%.1f万 收藏", v)
|
||||
}
|
||||
|
||||
func rankPageURL(sortOrder, pageNum int) string {
|
||||
switch sortOrder {
|
||||
case rankSortNew, rankSortBinge:
|
||||
default:
|
||||
sortOrder = rankSortHot
|
||||
}
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
path := "/rank"
|
||||
if sortOrder != rankSortHot {
|
||||
path += "/" + strconv.Itoa(sortOrder)
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
// BuildRankTabs 排行榜 Tab。
|
||||
func BuildRankTabs(q RankQuery) []FilterChipVM {
|
||||
q.Normalize()
|
||||
return []FilterChipVM{
|
||||
{Label: "热播榜", URL: rankPageURL(rankSortHot, 1), Active: q.SortOrder == rankSortHot},
|
||||
{Label: "新剧榜", URL: rankPageURL(rankSortNew, 1), Active: q.SortOrder == rankSortNew},
|
||||
{Label: "追剧榜", URL: rankPageURL(rankSortBinge, 1), Active: q.SortOrder == rankSortBinge},
|
||||
}
|
||||
}
|
||||
|
||||
// BuildRankPagination 排行榜分页。
|
||||
func BuildRankPagination(q RankQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return rankPageURL(q.SortOrder, p)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// RankCanonicalPath 返回排行榜筛选和分页对应的唯一规范路径。
|
||||
func RankCanonicalPath(q RankQuery) string {
|
||||
q.Normalize()
|
||||
return rankPageURL(q.SortOrder, q.PageNum)
|
||||
}
|
||||
|
||||
// RankOffset 当前页起始排名偏移(0-based)。
|
||||
func RankOffset(q RankQuery) int {
|
||||
q.Normalize()
|
||||
return (q.PageNum - 1) * q.PageSize
|
||||
}
|
||||
|
||||
// ParseRankQuery 从 query 解析排行榜参数。
|
||||
func ParseRankQuery(pageStr, sortStr string) RankQuery {
|
||||
q := RankQuery{PageSize: defaultRankPageSize, SortOrder: rankSortHot}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(sortStr)); err == nil {
|
||||
q.SortOrder = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
|
||||
// IsRankBinge 是否追剧榜(热度展示用 countCollect)。
|
||||
func IsRankBinge(sortOrder int) bool {
|
||||
return sortOrder == rankSortBinge
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package playletser
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRankCanonicalPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
q RankQuery
|
||||
want string
|
||||
}{
|
||||
{name: "default", q: RankQuery{}, want: "/rank/"},
|
||||
{name: "new", q: RankQuery{SortOrder: rankSortNew}, want: "/rank/2/"},
|
||||
{name: "paged", q: RankQuery{SortOrder: rankSortBinge, PageNum: 3}, want: "/rank/3/page/3/"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := RankCanonicalPath(tt.q); got != tt.want {
|
||||
t.Fatalf("RankCanonicalPath(%#v) = %q, want %q", tt.q, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
recommendListPath = "/api/app/playlet/list"
|
||||
defaultRecommendSize = 25
|
||||
)
|
||||
|
||||
// RecommendQuery 专题详情分页参数。
|
||||
type RecommendQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
SortOrder int
|
||||
ThemeID int64
|
||||
ThemeSlug string
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *RecommendQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultRecommendSize
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
if q.SortOrder != sortTodayUpdate {
|
||||
q.SortOrder = sortHeat
|
||||
}
|
||||
}
|
||||
|
||||
func recommendListURL(q RecommendQuery) string {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
params.Set("sortOrder", strconv.Itoa(q.SortOrder))
|
||||
if slug := strings.TrimSpace(q.ThemeSlug); slug != "" {
|
||||
params.Set("themeSlug", slug)
|
||||
} else if q.ThemeID > 0 {
|
||||
params.Set("themeId", strconv.FormatInt(q.ThemeID, 10))
|
||||
}
|
||||
return recommendListPath + "?" + params.Encode()
|
||||
}
|
||||
|
||||
// FetchRecommendList 按 Swagger 的题材 ID 或 slug 参数分页查询专题短剧。
|
||||
func FetchRecommendList(c *gin.Context, q RecommendQuery) (*PlayletVideoResp, error) {
|
||||
var env APIEnvelope[PlayletVideoResp]
|
||||
if err := upstream.GetPublicJSON(c, recommendListURL(q), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet recommend list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchRecommendListOrEmpty 失败时返回空列表。
|
||||
func FetchRecommendListOrEmpty(c *gin.Context, q RecommendQuery) *PlayletVideoResp {
|
||||
q.Normalize()
|
||||
data, err := FetchRecommendList(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet recommend list failed", log.E(err))
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
data.SeoInfo.Normalize()
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func recommendPageURL(themeID int64, themeSlug string, pageNum int) string {
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
path := "/topic"
|
||||
if segment := pathSegment(themeSlug, themeID); segment != "" {
|
||||
path += "/" + segment
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
func RecommendPagePath(q RecommendQuery) string {
|
||||
q.Normalize()
|
||||
return recommendPageURL(q.ThemeID, q.ThemeSlug, q.PageNum)
|
||||
}
|
||||
|
||||
// RecommendThemeTitle 专题页标题:优先题材名称,其次使用列表接口 SEO 标题。
|
||||
func RecommendThemeTitle(name, seoTitle string, themeID int64) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if name != "" {
|
||||
return name
|
||||
}
|
||||
seoTitle = strings.TrimSpace(seoTitle)
|
||||
if seoTitle != "" {
|
||||
return seoTitle
|
||||
}
|
||||
if themeID > 0 {
|
||||
return "专题短剧"
|
||||
}
|
||||
return "专题推荐"
|
||||
}
|
||||
|
||||
// RecommendCanonicalPath 推荐页 canonical(不含 page)。
|
||||
func RecommendCanonicalPath(themeID int64, themeSlug string) string {
|
||||
return recommendPageURL(themeID, themeSlug, 1)
|
||||
}
|
||||
|
||||
// BuildRecommendPagination 推荐列表分页。
|
||||
func BuildRecommendPagination(q RecommendQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return recommendPageURL(q.ThemeID, q.ThemeSlug, p)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// ParseRecommendQuery 从路由解析分页。
|
||||
func ParseRecommendQuery(pageStr string) RecommendQuery {
|
||||
q := RecommendQuery{PageSize: defaultRecommendSize, SortOrder: sortHeat}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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 (
|
||||
searchPath = "/api/app/playlet/search"
|
||||
defaultSearchPageSize = 25
|
||||
)
|
||||
|
||||
// SearchQuery 搜索分页参数(keyword 对应上游 query)。
|
||||
type SearchQuery struct {
|
||||
Keyword string
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *SearchQuery) Normalize() {
|
||||
q.Keyword = strings.TrimSpace(q.Keyword)
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultSearchPageSize
|
||||
}
|
||||
if q.PageSize > 50 {
|
||||
q.PageSize = 50
|
||||
}
|
||||
}
|
||||
|
||||
// FetchSearch ES 分页搜索短剧。
|
||||
func FetchSearch(c *gin.Context, q SearchQuery) (*PlayletVideoResp, error) {
|
||||
q.Normalize()
|
||||
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)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
func fetchSearchOnce(c *gin.Context, q SearchQuery) (*APIEnvelope[PlayletVideoResp], error) {
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
params.Set("keyword", q.Keyword)
|
||||
var env APIEnvelope[PlayletVideoResp]
|
||||
if err := upstream.GetJSON(c, searchPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// FetchSearchOrEmpty 失败时返回空列表。
|
||||
func FetchSearchOrEmpty(c *gin.Context, q SearchQuery) *PlayletVideoResp {
|
||||
data, err := FetchSearch(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet search failed", log.E(err))
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func searchPageURL(keyword string, pageNum int) string {
|
||||
keyword = strings.TrimSpace(keyword)
|
||||
if keyword == "" {
|
||||
return "/search/"
|
||||
}
|
||||
path := "/search/" + url.PathEscape(keyword)
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
func SearchCanonicalPath(q SearchQuery) string {
|
||||
q.Normalize()
|
||||
return searchPageURL(q.Keyword, q.PageNum)
|
||||
}
|
||||
|
||||
// BuildSearchPagination 搜索分页。
|
||||
func BuildSearchPagination(q SearchQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return searchPageURL(q.Keyword, p)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// ParseSearchQuery 从站点 query 解析(q → keyword)。
|
||||
func ParseSearchQuery(qStr, pageStr string) SearchQuery {
|
||||
q := SearchQuery{PageSize: defaultSearchPageSize, Keyword: strings.TrimSpace(qStr)}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PageOutOfRange 判断分页是否越界(第 1 页始终合法,即使列表为空)。
|
||||
func PageOutOfRange(pageNum, pageSize int, totalCount int64) bool {
|
||||
if pageNum <= 1 {
|
||||
return false
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = defaultListPageSize
|
||||
}
|
||||
totalPages := int((totalCount + int64(pageSize) - 1) / int64(pageSize))
|
||||
if totalPages < 1 {
|
||||
return true
|
||||
}
|
||||
return pageNum > totalPages
|
||||
}
|
||||
|
||||
// PageTitleSuffix 分页标题后缀:第 1 页为空,其余为「 - 第N页」。
|
||||
func PageTitleSuffix(pageNum int) string {
|
||||
if pageNum <= 1 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(" - 第%d页", pageNum)
|
||||
}
|
||||
|
||||
// PaginatedTitle 为第 2 页及以后追加页码,并避免重复追加。
|
||||
func PaginatedTitle(title string, pageNum int) string {
|
||||
title = strings.TrimSpace(title)
|
||||
if title == "" || pageNum <= 1 {
|
||||
return title
|
||||
}
|
||||
marker := fmt.Sprintf("第%d页", pageNum)
|
||||
if strings.Contains(title, marker) {
|
||||
return title
|
||||
}
|
||||
return title + PageTitleSuffix(pageNum)
|
||||
}
|
||||
|
||||
// PaginateSeoInfo 统一生成分页页的唯一 title 与 description。
|
||||
// fallbackDescription 仅在上游未提供 description 时使用。
|
||||
func PaginateSeoInfo(base SeoInfo, fallbackDescription string, pageNum int) SeoInfo {
|
||||
base.Normalize()
|
||||
if pageNum <= 1 {
|
||||
return base
|
||||
}
|
||||
base.Title = PaginatedTitle(base.Title, pageNum)
|
||||
if base.Description == "" {
|
||||
base.Description = strings.TrimSpace(fallbackDescription)
|
||||
}
|
||||
if base.Description != "" {
|
||||
marker := fmt.Sprintf("第%d页", pageNum)
|
||||
if !strings.Contains(base.Description, marker) {
|
||||
base.Description = strings.TrimRight(base.Description, "。;; ") + " - " + marker
|
||||
}
|
||||
}
|
||||
base.Normalize()
|
||||
return base
|
||||
}
|
||||
|
||||
// UnmarshalJSON 兼容 swagger proto.SeoInfo,并容忍上游别名 / 字符串 keywords。
|
||||
// 主字段:title、description、keywords[]、canonicalUrl。
|
||||
func (s *SeoInfo) UnmarshalJSON(raw []byte) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
raw = bytes.TrimSpace(raw)
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
if raw[0] == '"' {
|
||||
var encoded string
|
||||
if err := json.Unmarshal(raw, &encoded); err != nil {
|
||||
return err
|
||||
}
|
||||
encoded = strings.TrimSpace(encoded)
|
||||
if encoded == "" {
|
||||
return nil
|
||||
}
|
||||
inner := bytes.TrimSpace([]byte(encoded))
|
||||
if len(inner) == 0 || inner[0] != '{' {
|
||||
return nil
|
||||
}
|
||||
return s.UnmarshalJSON(inner)
|
||||
}
|
||||
var aux struct {
|
||||
Title string `json:"title"`
|
||||
WebTitle string `json:"webTitle"`
|
||||
Description string `json:"description"`
|
||||
WebDescription string `json:"webDescription"`
|
||||
CanonicalURL string `json:"canonicalUrl"`
|
||||
Canonical string `json:"canonical"`
|
||||
WebSiteName string `json:"webSiteName"`
|
||||
Keywords json.RawMessage `json:"keywords"`
|
||||
Keyworld json.RawMessage `json:"keyworld"`
|
||||
WebKeyworld json.RawMessage `json:"webKeyworld"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &aux); err != nil {
|
||||
return err
|
||||
}
|
||||
s.Title = firstNonEmpty(aux.Title, aux.WebTitle)
|
||||
s.Description = firstNonEmpty(aux.Description, aux.WebDescription)
|
||||
s.CanonicalURL = firstNonEmpty(aux.CanonicalURL, aux.Canonical)
|
||||
s.WebSiteName = strings.TrimSpace(aux.WebSiteName)
|
||||
s.Keywords = decodeKeywordList(aux.Keywords, aux.Keyworld, aux.WebKeyworld)
|
||||
s.Normalize()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Normalize 去掉 seoInfo 空白项,保证模板可直接渲染。
|
||||
func (s *SeoInfo) Normalize() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.Title = strings.TrimSpace(s.Title)
|
||||
s.Description = strings.TrimSpace(s.Description)
|
||||
s.CanonicalURL = strings.TrimSpace(s.CanonicalURL)
|
||||
s.WebSiteName = strings.TrimSpace(s.WebSiteName)
|
||||
if len(s.Keywords) == 0 {
|
||||
return
|
||||
}
|
||||
out := make([]string, 0, len(s.Keywords))
|
||||
seen := make(map[string]struct{}, len(s.Keywords))
|
||||
for _, k := range s.Keywords {
|
||||
k = strings.TrimSpace(k)
|
||||
if k == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[k]; ok {
|
||||
continue
|
||||
}
|
||||
seen[k] = struct{}{}
|
||||
out = append(out, k)
|
||||
}
|
||||
s.Keywords = out
|
||||
}
|
||||
|
||||
func decodeKeywordList(vals ...json.RawMessage) []string {
|
||||
for _, raw := range vals {
|
||||
if items := parseKeywordsRaw(raw); len(items) > 0 {
|
||||
return items
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseKeywordsRaw(raw json.RawMessage) []string {
|
||||
raw = bytes.TrimSpace(raw)
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
switch raw[0] {
|
||||
case '"':
|
||||
var s string
|
||||
if err := json.Unmarshal(raw, &s); err != nil {
|
||||
return nil
|
||||
}
|
||||
return splitKeywordText(s)
|
||||
case '[':
|
||||
var anyItems []any
|
||||
if err := json.Unmarshal(raw, &anyItems); err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(anyItems))
|
||||
for _, it := range anyItems {
|
||||
s, ok := it.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func splitKeywordText(s string) []string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
s = strings.NewReplacer(",", ",", "、", ",", ";", ",", ";", ",").Replace(s)
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if t := strings.TrimSpace(p); t != "" {
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func joinStrings(items []string, sep string) string {
|
||||
parts := make([]string, 0, len(items))
|
||||
for _, s := range items {
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
parts = append(parts, s)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, sep)
|
||||
}
|
||||
|
||||
// MergeSeoInfo 按字段合并 SEO:优先 primary,缺失时回退 fallback。
|
||||
func MergeSeoInfo(primary, fallback SeoInfo) SeoInfo {
|
||||
out := SeoInfo{
|
||||
Title: firstNonEmpty(primary.Title, fallback.Title),
|
||||
Description: firstNonEmpty(primary.Description, fallback.Description),
|
||||
CanonicalURL: firstNonEmpty(primary.CanonicalURL, fallback.CanonicalURL),
|
||||
WebSiteName: firstNonEmpty(primary.WebSiteName, fallback.WebSiteName),
|
||||
}
|
||||
if len(primary.Keywords) > 0 {
|
||||
out.Keywords = append([]string(nil), primary.Keywords...)
|
||||
} else {
|
||||
out.Keywords = append([]string(nil), fallback.Keywords...)
|
||||
}
|
||||
out.Normalize()
|
||||
return out
|
||||
}
|
||||
|
||||
// SEOSelection 描述页面当前选中的筛选维度,用于生成差异化 TDK。
|
||||
type SEOSelection struct {
|
||||
Dimension string
|
||||
Value string
|
||||
}
|
||||
|
||||
// DifferentiateSeoInfo 按基础 TDK - 选项1 - 选项2 的顺序拼接筛选条件。
|
||||
func DifferentiateSeoInfo(base SeoInfo, selections []SEOSelection) SeoInfo {
|
||||
base.Normalize()
|
||||
normalized := make([]SEOSelection, 0, len(selections))
|
||||
seen := make(map[string]struct{}, len(selections))
|
||||
for _, selection := range selections {
|
||||
dimension := strings.TrimSpace(selection.Dimension)
|
||||
value := strings.TrimSpace(selection.Value)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
key := dimension + "\x00" + value
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
normalized = append(normalized, SEOSelection{Dimension: dimension, Value: value})
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
return base
|
||||
}
|
||||
|
||||
values := make([]string, 0, len(normalized))
|
||||
keywords := append([]string(nil), base.Keywords...)
|
||||
for _, selection := range normalized {
|
||||
values = append(values, selection.Value)
|
||||
keywords = append(keywords, selection.Value)
|
||||
}
|
||||
base.Title = joinSEOParts(base.Title, values)
|
||||
base.Description = joinSEOParts(base.Description, values)
|
||||
base.Keywords = keywords
|
||||
base.Normalize()
|
||||
return base
|
||||
}
|
||||
|
||||
func joinSEOParts(base string, values []string) string {
|
||||
parts := make([]string, 0, len(values)+1)
|
||||
if base = strings.TrimSpace(base); base != "" {
|
||||
parts = append(parts, base)
|
||||
}
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(value)
|
||||
if value != "" {
|
||||
parts = append(parts, value)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " - ")
|
||||
}
|
||||
|
||||
// ResolvePlayPageSEO 播放页 SEO:章节详情 seoInfo 优先,短剧详情作字段级回退。
|
||||
func ResolvePlayPageSEO(chapter *PlayletChapterInfoResp, playlet *PlayletInfoResp) SeoInfo {
|
||||
var chapterSEO, playletSEO SeoInfo
|
||||
if chapter != nil {
|
||||
chapterSEO = chapter.SeoInfo
|
||||
}
|
||||
if playlet != nil {
|
||||
playletSEO = playlet.SeoInfo
|
||||
}
|
||||
return MergeSeoInfo(chapterSEO, playletSEO)
|
||||
}
|
||||
|
||||
// ResolvePlayPageTitle 播放页标题:优先章节 seoInfo.title,否则短剧名 + 集数。
|
||||
func ResolvePlayPageTitle(chapter *PlayletChapterInfoResp, playlet *PlayletInfoResp) string {
|
||||
seo := ResolvePlayPageSEO(chapter, playlet)
|
||||
if seo.Title != "" {
|
||||
return seo.Title
|
||||
}
|
||||
title := "播放"
|
||||
if playlet != nil && playlet.Title != "" {
|
||||
title = playlet.Title
|
||||
}
|
||||
if chapter != nil && chapter.CurrentEpisode > 0 {
|
||||
return fmt.Sprintf("%s - 第%d集", title, chapter.CurrentEpisode)
|
||||
}
|
||||
return title
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeoInfo_UnmarshalJSON_SwaggerShape(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"title":"灵气复苏,我成为了万古医圣",
|
||||
"keywords":["灵气复苏,我成为了万古医圣","职场"],
|
||||
"description":"灵气复苏,我成为了万古医圣",
|
||||
"canonicalUrl":"/detail/example-show"
|
||||
}`)
|
||||
var seo SeoInfo
|
||||
if err := json.Unmarshal(raw, &seo); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if seo.Title != "灵气复苏,我成为了万古医圣" {
|
||||
t.Fatalf("title=%q", seo.Title)
|
||||
}
|
||||
if seo.Description != "灵气复苏,我成为了万古医圣" {
|
||||
t.Fatalf("description=%q", seo.Description)
|
||||
}
|
||||
if seo.CanonicalURL != "/detail/example-show" {
|
||||
t.Fatalf("canonicalUrl=%q", seo.CanonicalURL)
|
||||
}
|
||||
want := []string{"灵气复苏,我成为了万古医圣", "职场"}
|
||||
if !reflect.DeepEqual(seo.Keywords, want) {
|
||||
t.Fatalf("keywords=%v", seo.Keywords)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeoInfo_UnmarshalJSON_AliasesAndStringKeywords(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"webTitle":"镇龙",
|
||||
"webDescription":"短剧简介",
|
||||
"keyworld":"镇龙,玄幻",
|
||||
"canonical":"/detail/example-show"
|
||||
}`)
|
||||
var seo SeoInfo
|
||||
if err := json.Unmarshal(raw, &seo); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if seo.Title != "镇龙" || seo.Description != "短剧简介" {
|
||||
t.Fatalf("got title=%q desc=%q", seo.Title, seo.Description)
|
||||
}
|
||||
if seo.CanonicalURL != "/detail/example-show" {
|
||||
t.Fatalf("canonicalUrl=%q", seo.CanonicalURL)
|
||||
}
|
||||
want := []string{"镇龙", "玄幻"}
|
||||
if !reflect.DeepEqual(seo.Keywords, want) {
|
||||
t.Fatalf("keywords=%v", seo.Keywords)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIEnvelope_UnmarshalJSON_ObjectData(t *testing.T) {
|
||||
raw := []byte(`{"code":200,"msg":"ok","data":{"id":10741,"title":"都市逍遥神医","seoInfo":""}}`)
|
||||
var env APIEnvelope[PlayletInfoResp]
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if env.Code != 200 || env.Data.ID != 10741 || env.Data.Title != "都市逍遥神医" {
|
||||
t.Fatalf("env=%+v data=%+v", env, env.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIEnvelope_UnmarshalJSON_StringEncodedData(t *testing.T) {
|
||||
raw := []byte(`{"code":200,"msg":"ok","data":"{\"id\":10741,\"title\":\"都市逍遥神医\",\"seoInfo\":\"\"}"}`)
|
||||
var env APIEnvelope[PlayletInfoResp]
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if env.Data.ID != 10741 || env.Data.Title != "都市逍遥神医" {
|
||||
t.Fatalf("data=%+v", env.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIEnvelope_UnmarshalJSON_EmptyStringData(t *testing.T) {
|
||||
raw := []byte(`{"code":200,"msg":"ok","data":""}`)
|
||||
var env APIEnvelope[PlayletInfoResp]
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if env.Data.ID != 0 {
|
||||
t.Fatalf("data=%+v", env.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlayletInfoResp_SeoInfoEmptyString(t *testing.T) {
|
||||
raw := []byte(`{"id":10741,"title":"都市逍遥神医","seoInfo":""}`)
|
||||
var info PlayletInfoResp
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if info.ID != 10741 || info.Title != "都市逍遥神医" {
|
||||
t.Fatalf("info=%+v", info)
|
||||
}
|
||||
if info.SeoInfo.Title != "" {
|
||||
t.Fatalf("seoInfo=%+v", info.SeoInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlayletInfoResp_KeepsSeoInfo(t *testing.T) {
|
||||
raw := []byte(`{"id":10619,"slug":"example-show","title":"剧名","seoInfo":{"title":"SEO标题","description":"SEO描述","keywords":["a","b"],"canonicalUrl":"/detail/example-show"}}`)
|
||||
var info PlayletInfoResp
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if info.SeoInfo.Title != "SEO标题" || info.SeoInfo.CanonicalURL != "/detail/example-show" {
|
||||
t.Fatalf("seoInfo=%+v", info.SeoInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlayletChapterInfoResp_KeepsSeoInfo(t *testing.T) {
|
||||
raw := []byte(`{"id":12743,"playletId":10619,"currentEpisode":1,"title":"1","seoInfo":{"title":"剧名 1","description":"剧名","keywords":["剧名","短剧"],"canonicalUrl":"/play/example-show/12743"}}`)
|
||||
var info PlayletChapterInfoResp
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if info.SeoInfo.Title != "剧名 1" || info.SeoInfo.CanonicalURL != "/play/example-show/12743" {
|
||||
t.Fatalf("seoInfo=%+v", info.SeoInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePlayPageSEO_PrefersChapter(t *testing.T) {
|
||||
chapter := &PlayletChapterInfoResp{
|
||||
CurrentEpisode: 1,
|
||||
SeoInfo: SeoInfo{
|
||||
Title: "章节标题",
|
||||
Description: "章节描述",
|
||||
Keywords: []string{"章节"},
|
||||
CanonicalURL: "/play/example-show/2",
|
||||
},
|
||||
}
|
||||
playlet := &PlayletInfoResp{
|
||||
Title: "短剧名",
|
||||
SeoInfo: SeoInfo{
|
||||
Title: "短剧SEO",
|
||||
Description: "短剧描述",
|
||||
Keywords: []string{"短剧"},
|
||||
CanonicalURL: "/detail/example-show",
|
||||
},
|
||||
}
|
||||
seo := ResolvePlayPageSEO(chapter, playlet)
|
||||
if seo.Title != "章节标题" || seo.CanonicalURL != "/play/example-show/2" {
|
||||
t.Fatalf("seo=%+v", seo)
|
||||
}
|
||||
if !reflect.DeepEqual(seo.Keywords, []string{"章节"}) {
|
||||
t.Fatalf("keywords=%v", seo.Keywords)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePlayPageTitle_UsesChapterSeoTitle(t *testing.T) {
|
||||
chapter := &PlayletChapterInfoResp{
|
||||
CurrentEpisode: 1,
|
||||
SeoInfo: SeoInfo{Title: "灵气复苏,我成为了万古医圣 1"},
|
||||
}
|
||||
playlet := &PlayletInfoResp{Title: "灵气复苏,我成为了万古医圣"}
|
||||
if got := ResolvePlayPageTitle(chapter, playlet); got != "灵气复苏,我成为了万古医圣 1" {
|
||||
t.Fatalf("title=%q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
seriesOperateType = 2
|
||||
seriesPageSize = 25
|
||||
seriesFilterLatest = 1
|
||||
seriesFilterHot = 2
|
||||
seriesFilterOrigin = 3
|
||||
)
|
||||
|
||||
var seriesFilters = []struct {
|
||||
Type int
|
||||
Slug string
|
||||
Label string
|
||||
}{
|
||||
{Type: seriesFilterLatest, Slug: "latest", Label: "最新更新"},
|
||||
{Type: seriesFilterHot, Slug: "popular", Label: "当前热播"},
|
||||
{Type: seriesFilterOrigin, Slug: "original", Label: "独家原创"},
|
||||
}
|
||||
|
||||
// ParseSeriesQuery 将语义化筛选路由转换为 Swagger 的 operateType/filterType 参数。
|
||||
func ParseSeriesQuery(filterSlug, pageStr string) (OperateListQuery, bool) {
|
||||
filterType, ok := seriesFilterType(filterSlug)
|
||||
if !ok {
|
||||
return OperateListQuery{}, false
|
||||
}
|
||||
q := OperateListQuery{
|
||||
OperateType: seriesOperateType,
|
||||
FilterType: filterType,
|
||||
PageSize: seriesPageSize,
|
||||
}
|
||||
if page, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = page
|
||||
}
|
||||
q.Normalize()
|
||||
return q, true
|
||||
}
|
||||
|
||||
func seriesFilterType(slug string) (int, bool) {
|
||||
slug = strings.TrimSpace(slug)
|
||||
if slug == "" || slug == "latest" {
|
||||
return seriesFilterLatest, true
|
||||
}
|
||||
for _, filter := range seriesFilters {
|
||||
if filter.Slug == slug {
|
||||
return filter.Type, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func seriesFilterSlug(filterType int) string {
|
||||
for _, filter := range seriesFilters {
|
||||
if filter.Type == filterType {
|
||||
return filter.Slug
|
||||
}
|
||||
}
|
||||
return "latest"
|
||||
}
|
||||
|
||||
func seriesPageURL(filterType, pageNum int) string {
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
path := "/series"
|
||||
if filterType != seriesFilterLatest {
|
||||
path += "/" + seriesFilterSlug(filterType)
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
// SeriesCanonicalPath 返回 AI 成人剧集页唯一规范路径。
|
||||
func SeriesCanonicalPath(q OperateListQuery) string {
|
||||
q.Normalize()
|
||||
return seriesPageURL(q.FilterType, q.PageNum)
|
||||
}
|
||||
|
||||
// BuildSeriesFilterTabs 构建 Figma 中的三个运营筛选项。
|
||||
func BuildSeriesFilterTabs(q OperateListQuery) []FilterChipVM {
|
||||
q.Normalize()
|
||||
out := make([]FilterChipVM, 0, len(seriesFilters))
|
||||
for _, filter := range seriesFilters {
|
||||
out = append(out, FilterChipVM{
|
||||
Label: filter.Label,
|
||||
URL: seriesPageURL(filter.Type, 1),
|
||||
Active: q.FilterType == filter.Type,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func SeriesSectionTitle(filterType int) string {
|
||||
for _, filter := range seriesFilters {
|
||||
if filter.Type == filterType {
|
||||
return filter.Label + "的AI成人剧集"
|
||||
}
|
||||
}
|
||||
return "最新更新的AI成人剧集"
|
||||
}
|
||||
|
||||
func BuildSeriesPagination(q OperateListQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(page int) string {
|
||||
return seriesPageURL(q.FilterType, page)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// SeriesPathFromLegacyList 将原 /list/ai-series 排序地址映射到新页面。
|
||||
func SeriesPathFromLegacyList(sortOrder, pageNum int) string {
|
||||
filterType := seriesFilterLatest
|
||||
if sortOrder == sortHeat {
|
||||
filterType = seriesFilterHot
|
||||
}
|
||||
return seriesPageURL(filterType, pageNum)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package playletser
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseSeriesQueryMapsSwaggerOperateFilters(t *testing.T) {
|
||||
tests := []struct {
|
||||
slug string
|
||||
wantFilter int
|
||||
}{
|
||||
{slug: "", wantFilter: seriesFilterLatest},
|
||||
{slug: "latest", wantFilter: seriesFilterLatest},
|
||||
{slug: "popular", wantFilter: seriesFilterHot},
|
||||
{slug: "original", wantFilter: seriesFilterOrigin},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
q, ok := ParseSeriesQuery(tt.slug, "2")
|
||||
if !ok {
|
||||
t.Fatalf("ParseSeriesQuery(%q) rejected valid filter", tt.slug)
|
||||
}
|
||||
if q.OperateType != 2 || q.FilterType != tt.wantFilter || q.PageNum != 2 || q.PageSize != 25 {
|
||||
t.Fatalf("ParseSeriesQuery(%q) = %#v", tt.slug, q)
|
||||
}
|
||||
}
|
||||
if _, ok := ParseSeriesQuery("unknown", "1"); ok {
|
||||
t.Fatal("unknown filter should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeriesCanonicalPaths(t *testing.T) {
|
||||
tests := []struct {
|
||||
filter int
|
||||
page int
|
||||
want string
|
||||
}{
|
||||
{filter: seriesFilterLatest, page: 1, want: "/series"},
|
||||
{filter: seriesFilterLatest, page: 3, want: "/series/page/3"},
|
||||
{filter: seriesFilterHot, page: 1, want: "/series/popular"},
|
||||
{filter: seriesFilterOrigin, page: 4, want: "/series/original/page/4"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := seriesPageURL(tt.filter, tt.page)
|
||||
if got != tt.want {
|
||||
t.Fatalf("seriesPageURL(%d, %d) = %q, want %q", tt.filter, tt.page, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSeriesFilterTabs(t *testing.T) {
|
||||
tabs := BuildSeriesFilterTabs(OperateListQuery{OperateType: 2, FilterType: 2, PageNum: 1, PageSize: 25})
|
||||
if len(tabs) != 3 || tabs[0].URL != "/series" || tabs[1].URL != "/series/popular" || !tabs[1].Active || tabs[2].URL != "/series/original" {
|
||||
t.Fatalf("unexpected series tabs: %#v", tabs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
shortPlayOperateType = 1
|
||||
shortPlayPageSize = 25
|
||||
)
|
||||
|
||||
var shortPlayFilters = []struct {
|
||||
Type int
|
||||
Slug string
|
||||
Label string
|
||||
}{
|
||||
{Type: 1, Slug: "latest", Label: "最新更新"},
|
||||
{Type: 2, Slug: "popular", Label: "当前热播"},
|
||||
{Type: 3, Slug: "original", Label: "独家原创"},
|
||||
}
|
||||
|
||||
// ParseShortPlayQuery 将短剧页路由转换为 operate/list 的 Swagger 参数。
|
||||
func ParseShortPlayQuery(filter, page string) (OperateListQuery, bool) {
|
||||
filterType, ok := shortPlayFilterType(filter)
|
||||
if !ok {
|
||||
return OperateListQuery{}, false
|
||||
}
|
||||
q := OperateListQuery{
|
||||
OperateType: shortPlayOperateType,
|
||||
FilterType: filterType,
|
||||
PageSize: shortPlayPageSize,
|
||||
}
|
||||
if pageNum, err := strconv.Atoi(strings.TrimSpace(page)); err == nil {
|
||||
q.PageNum = pageNum
|
||||
}
|
||||
q.Normalize()
|
||||
return q, true
|
||||
}
|
||||
|
||||
func shortPlayFilterType(filter string) (int, bool) {
|
||||
filter = strings.TrimSpace(filter)
|
||||
switch filter {
|
||||
case "", "latest", "2":
|
||||
return 1, true
|
||||
case "popular", "1":
|
||||
return 2, true
|
||||
case "original", "3":
|
||||
return 3, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func shortPlayFilterSlug(filterType int) string {
|
||||
for _, filter := range shortPlayFilters {
|
||||
if filter.Type == filterType {
|
||||
return filter.Slug
|
||||
}
|
||||
}
|
||||
return "latest"
|
||||
}
|
||||
|
||||
func shortPlayPageURL(filterType, pageNum int) string {
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
path := "/list/ai-short-play"
|
||||
if filterType != 1 || pageNum > 1 {
|
||||
path += "/" + shortPlayFilterSlug(filterType)
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
func ShortPlayCanonicalPath(q OperateListQuery) string {
|
||||
q.Normalize()
|
||||
return shortPlayPageURL(q.FilterType, q.PageNum)
|
||||
}
|
||||
|
||||
func BuildShortPlayFilterTabs(q OperateListQuery) []FilterChipVM {
|
||||
q.Normalize()
|
||||
out := make([]FilterChipVM, 0, len(shortPlayFilters))
|
||||
for _, filter := range shortPlayFilters {
|
||||
out = append(out, FilterChipVM{
|
||||
Label: filter.Label,
|
||||
URL: shortPlayPageURL(filter.Type, 1),
|
||||
Active: q.FilterType == filter.Type,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ShortPlaySectionTitle(filterType int) string {
|
||||
for _, filter := range shortPlayFilters {
|
||||
if filter.Type == filterType {
|
||||
return filter.Label + "的AI成人短剧"
|
||||
}
|
||||
}
|
||||
return "最新更新的AI成人短剧"
|
||||
}
|
||||
|
||||
func BuildShortPlayPagination(q OperateListQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(page int) string {
|
||||
return shortPlayPageURL(q.FilterType, page)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHomeResponseDecodesDocumentedFields(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"announcements":[{"id":1,"title":"公告","content":"内容"}],
|
||||
"homeRecommendThemes":[{"id":2,"name":"都市","slug":"urban","playletCount":8}],
|
||||
"homeBannerData":[{"id":3,"name":"轮播A","image":"https://cdn.example.com/a.png","verticalImage":"https://cdn.example.com/a-v.png","url":"https://example.com","rank":1,"status":true}]
|
||||
}`)
|
||||
var got HomePlayletResponse
|
||||
if err := json.Unmarshal(raw, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Announcements) != 1 || got.Announcements[0].Content != "内容" {
|
||||
t.Fatalf("announcements not decoded: %#v", got.Announcements)
|
||||
}
|
||||
if len(got.HomeRecommendThemes) != 1 || got.HomeRecommendThemes[0].Slug != "urban" {
|
||||
t.Fatalf("recommended themes not decoded: %#v", got.HomeRecommendThemes)
|
||||
}
|
||||
if len(got.HomeBannerData) != 1 || got.HomeBannerData[0].Name != "轮播A" || got.HomeBannerData[0].Image == "" || got.HomeBannerData[0].VerticalImage == "" || !got.HomeBannerData[0].Status {
|
||||
t.Fatalf("banner additions not decoded: %#v", got.HomeBannerData)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperateListQueryNormalize(t *testing.T) {
|
||||
q := OperateListQuery{OperateType: 9, FilterType: -1, PageNum: 0, PageSize: 999}
|
||||
q.Normalize()
|
||||
if q.OperateType != 1 || q.FilterType != 1 || q.PageNum != 1 || q.PageSize != 100 {
|
||||
t.Fatalf("unexpected normalized query: %#v", q)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
tagListPath = "/api/app/playlet/tag/list"
|
||||
defaultTagSize = 30
|
||||
)
|
||||
|
||||
type TagListQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
TagID int64
|
||||
TagSlug string
|
||||
}
|
||||
|
||||
func (q *TagListQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultTagSize
|
||||
}
|
||||
if q.PageSize > 100 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
if q.TagID < 0 {
|
||||
q.TagID = 0
|
||||
}
|
||||
}
|
||||
|
||||
func FetchTagList(c *gin.Context, q TagListQuery) (*PlayletVideoResp, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
if slug := strings.TrimSpace(q.TagSlug); slug != "" {
|
||||
params.Set("tagSlug", slug)
|
||||
} else if q.TagID > 0 {
|
||||
params.Set("tagId", strconv.FormatInt(q.TagID, 10))
|
||||
}
|
||||
|
||||
var env APIEnvelope[PlayletVideoResp]
|
||||
if err := upstream.GetPublicJSON(c, tagListPath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet tag list code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
func FetchTagListOrEmpty(c *gin.Context, q TagListQuery) *PlayletVideoResp {
|
||||
data, err := FetchTagList(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet tag list failed", log.E(err))
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func tagListPageURL(tagID int64, tagSlug string, pageNum int) string {
|
||||
if pageNum <= 0 {
|
||||
pageNum = 1
|
||||
}
|
||||
path := "/tag"
|
||||
if segment := pathSegment(tagSlug, tagID); segment != "" {
|
||||
path += "/" + segment
|
||||
}
|
||||
if pageNum > 1 {
|
||||
path += "/page/" + strconv.Itoa(pageNum)
|
||||
}
|
||||
return path + "/"
|
||||
}
|
||||
|
||||
func tagListURL(item CommonData) string {
|
||||
return cardTag(item).URL
|
||||
}
|
||||
|
||||
func tagListURLByKey(slug string, id int64) string {
|
||||
if segment := pathSegment(slug, id); segment != "" {
|
||||
return "/tag/" + segment + "/"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func themeListURLByKey(slug string, id int64) string {
|
||||
if segment := pathSegment(slug, id); segment != "" {
|
||||
return "/list/" + segment + "/"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type NamedTag struct {
|
||||
Name string
|
||||
URL string
|
||||
}
|
||||
|
||||
func cardTag(item CommonData) NamedTag {
|
||||
tags := cardTags(item)
|
||||
if len(tags) > 0 {
|
||||
return tags[0]
|
||||
}
|
||||
return NamedTag{}
|
||||
}
|
||||
|
||||
// cardTags returns at most three distinct labels for a poster card. Regular
|
||||
// tags keep their API order, followed by theme labels when space remains.
|
||||
func cardTags(item CommonData) []NamedTag {
|
||||
out := make([]NamedTag, 0, 3)
|
||||
seen := make(map[string]struct{}, 3)
|
||||
appendUnique := func(tags []NamedTag) {
|
||||
for _, tag := range tags {
|
||||
name := strings.TrimSpace(tag.Name)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(name)
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
tag.Name = name
|
||||
out = append(out, tag)
|
||||
seen[key] = struct{}{}
|
||||
if len(out) == 3 {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appendUnique(namedTags(item.TagIDs, item.TagNames, item.TagSlugs))
|
||||
if len(out) < 3 {
|
||||
appendUnique(namedThemeTags(item.ThemeIDs, item.ThemeNames, item.ThemeSlugs))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func namedTags(ids []int64, names, slugs []string) []NamedTag {
|
||||
out := make([]NamedTag, 0, len(names))
|
||||
for i, name := range names {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
item := NamedTag{Name: name}
|
||||
id := int64(0)
|
||||
slug := ""
|
||||
if i < len(ids) {
|
||||
id = ids[i]
|
||||
}
|
||||
if i < len(slugs) {
|
||||
slug = slugs[i]
|
||||
}
|
||||
item.URL = tagListURLByKey(slug, id)
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func namedThemeTags(ids []int64, names, slugs []string) []NamedTag {
|
||||
out := make([]NamedTag, 0, len(names))
|
||||
for i, name := range names {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
item := NamedTag{Name: name}
|
||||
if i < len(ids) {
|
||||
slug := ""
|
||||
if i < len(slugs) {
|
||||
slug = slugs[i]
|
||||
}
|
||||
item.URL = themeListURLByKey(slug, ids[i])
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TagListCanonicalPath(q TagListQuery) string {
|
||||
q.Normalize()
|
||||
return tagListPageURL(q.TagID, q.TagSlug, q.PageNum)
|
||||
}
|
||||
|
||||
func BuildTagListPagination(q TagListQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return tagListPageURL(q.TagID, q.TagSlug, p)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
func ParseTagListQuery(pageStr string) TagListQuery {
|
||||
q := TagListQuery{PageSize: defaultTagSize}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
|
||||
func FindTagNameBySlug(list []CommonData, slug string) string {
|
||||
slug = strings.TrimSpace(slug)
|
||||
if slug == "" {
|
||||
return ""
|
||||
}
|
||||
for _, item := range list {
|
||||
for i, itemSlug := range item.TagSlugs {
|
||||
if strings.TrimSpace(itemSlug) == slug && i < len(item.TagNames) {
|
||||
return strings.TrimSpace(item.TagNames[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func FindTagName(list []CommonData, tagID int64) string {
|
||||
if tagID <= 0 {
|
||||
return ""
|
||||
}
|
||||
for _, item := range list {
|
||||
for i, id := range item.TagIDs {
|
||||
if id == tagID && i < len(item.TagNames) {
|
||||
return strings.TrimSpace(item.TagNames[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func FindTagSlug(list []CommonData, tagID int64) string {
|
||||
if tagID <= 0 {
|
||||
return ""
|
||||
}
|
||||
for _, item := range list {
|
||||
for i, id := range item.TagIDs {
|
||||
if id == tagID && i < len(item.TagSlugs) {
|
||||
return strings.TrimSpace(item.TagSlugs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TagListPageTitle(tagName string, pageNum int, seo SeoInfo) string {
|
||||
if title := strings.TrimSpace(seo.Title); title != "" {
|
||||
return title
|
||||
}
|
||||
base := "标签短剧"
|
||||
if tagName != "" {
|
||||
base = tagName + "短剧"
|
||||
}
|
||||
return base + PageTitleSuffix(pageNum)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package playletser
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTagListPageURLUsesSemanticSlugRoute(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
id int64
|
||||
slug string
|
||||
page int
|
||||
want string
|
||||
}{
|
||||
{name: "root", page: 1, want: "/tag"},
|
||||
{name: "slug", id: 99, slug: "urban-love", page: 1, want: "/tag/urban-love"},
|
||||
{name: "slug page", id: 99, slug: "urban-love", page: 3, want: "/tag/urban-love/page/3"},
|
||||
{name: "id fallback", id: 99, page: 1, want: "/tag/99"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tagListPageURL(tt.id, tt.slug, tt.page); got != tt.want {
|
||||
t.Fatalf("tagListPageURL(%d, %q, %d) = %q, want %q", tt.id, tt.slug, tt.page, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagListURLByKeyPrefersSlugAndFallsBackToID(t *testing.T) {
|
||||
if got := tagListURLByKey("fantasy", 12); got != "/tag/fantasy" {
|
||||
t.Fatalf("slug URL = %q", got)
|
||||
}
|
||||
if got := tagListURLByKey("", 12); got != "/tag/12" {
|
||||
t.Fatalf("id fallback URL = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardTagsReturnsAtMostThreeDistinctLabels(t *testing.T) {
|
||||
item := CommonData{
|
||||
TagIDs: []int64{1, 2, 3},
|
||||
TagNames: []string{"都市", "甜宠", "都市"},
|
||||
TagSlugs: []string{"city", "sweet", "city-copy"},
|
||||
ThemeIDs: []int64{4, 5},
|
||||
ThemeNames: []string{"逆袭", "复仇"},
|
||||
ThemeSlugs: []string{"counterattack", "revenge"},
|
||||
}
|
||||
|
||||
got := cardTags(item)
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("cardTags length = %d, want 3", len(got))
|
||||
}
|
||||
if got[0].Name != "都市" || got[0].URL != "/tag/city" {
|
||||
t.Fatalf("first tag = %#v", got[0])
|
||||
}
|
||||
if got[1].Name != "甜宠" || got[1].URL != "/tag/sweet" {
|
||||
t.Fatalf("second tag = %#v", got[1])
|
||||
}
|
||||
if got[2].Name != "逆袭" || got[2].URL != "/list/counterattack" {
|
||||
t.Fatalf("third tag = %#v", got[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNamedTagsUsesSlugWithoutID(t *testing.T) {
|
||||
got := namedTags(nil, []string{"甜宠"}, []string{"sweet-love"})
|
||||
if len(got) != 1 || got[0].URL != "/tag/sweet-love" {
|
||||
t.Fatalf("namedTags slug-only URL = %#v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const defaultThemeIndexPageSize = 20
|
||||
|
||||
// ThemeIndexQuery 专题列表页分页参数。
|
||||
type ThemeIndexQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
func (q *ThemeIndexQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultThemeIndexPageSize
|
||||
}
|
||||
}
|
||||
|
||||
// ParseThemeIndexQuery 从语义化分页路由读取页码。
|
||||
func ParseThemeIndexQuery(page string) ThemeIndexQuery {
|
||||
q := ThemeIndexQuery{PageSize: defaultThemeIndexPageSize}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(page)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
|
||||
// BuildThemeIndexPage 过滤已启用专题,并按设计稿每页 20 项分页。
|
||||
func BuildThemeIndexPage(themes []PlayletThemeItem, q ThemeIndexQuery) ([]PlayletThemeItem, int64) {
|
||||
q.Normalize()
|
||||
visible := make([]PlayletThemeItem, 0, len(themes))
|
||||
for _, theme := range themes {
|
||||
if !theme.Status || theme.ID <= 0 || strings.TrimSpace(theme.Name) == "" {
|
||||
continue
|
||||
}
|
||||
visible = append(visible, theme)
|
||||
}
|
||||
total := int64(len(visible))
|
||||
start := (q.PageNum - 1) * q.PageSize
|
||||
if start >= len(visible) {
|
||||
return nil, total
|
||||
}
|
||||
end := start + q.PageSize
|
||||
if end > len(visible) {
|
||||
end = len(visible)
|
||||
}
|
||||
return visible[start:end], total
|
||||
}
|
||||
|
||||
func themeIndexPageURL(page int) string {
|
||||
if page <= 1 {
|
||||
return "/topic/"
|
||||
}
|
||||
return "/topic/page/" + strconv.Itoa(page) + "/"
|
||||
}
|
||||
|
||||
func ThemeIndexCanonicalPath(q ThemeIndexQuery) string {
|
||||
q.Normalize()
|
||||
return themeIndexPageURL(q.PageNum)
|
||||
}
|
||||
|
||||
func BuildThemeIndexPagination(q ThemeIndexQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(themeIndexPageURL, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package playletser
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBuildThemeIndexPage(t *testing.T) {
|
||||
themes := make([]PlayletThemeItem, 0, 23)
|
||||
for i := 1; i <= 23; i++ {
|
||||
themes = append(themes, PlayletThemeItem{ID: int64(i), Name: "专题", Status: true})
|
||||
}
|
||||
themes[1].Status = false
|
||||
themes[2].Name = ""
|
||||
|
||||
first, total := BuildThemeIndexPage(themes, ParseThemeIndexQuery("1"))
|
||||
if total != 21 || len(first) != 20 {
|
||||
t.Fatalf("first page = (%d, %d), want (20, 21)", len(first), total)
|
||||
}
|
||||
second, _ := BuildThemeIndexPage(themes, ParseThemeIndexQuery("2"))
|
||||
if len(second) != 1 {
|
||||
t.Fatalf("second page length = %d, want 1", len(second))
|
||||
}
|
||||
if got := ThemeIndexCanonicalPath(ParseThemeIndexQuery("2")); got != "/topic/page/2" {
|
||||
t.Fatalf("canonical path = %q, want /topic/page/2", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"videoweb/app/service/upstream"
|
||||
"videoweb/pub/common/log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
todayUpdatePath = "/api/app/playlet/today-update"
|
||||
defaultTodayUpdateSize = 40
|
||||
)
|
||||
|
||||
// TodayUpdateQuery 今日更新分页参数。
|
||||
type TodayUpdateQuery struct {
|
||||
PageNum int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// Normalize 校正分页默认值。
|
||||
func (q *TodayUpdateQuery) Normalize() {
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = defaultTodayUpdateSize
|
||||
}
|
||||
if q.PageSize > 50 {
|
||||
q.PageSize = 50
|
||||
}
|
||||
}
|
||||
|
||||
// FetchTodayUpdate 分页查询今日更新短剧。
|
||||
func FetchTodayUpdate(c *gin.Context, q TodayUpdateQuery) (*PlayletVideoResp, error) {
|
||||
q.Normalize()
|
||||
params := url.Values{}
|
||||
params.Set("pageNum", strconv.Itoa(q.PageNum))
|
||||
params.Set("pageSize", strconv.Itoa(q.PageSize))
|
||||
|
||||
var env APIEnvelope[PlayletVideoResp]
|
||||
if err := upstream.GetPublicJSON(c, todayUpdatePath+"?"+params.Encode(), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if env.Code != 200 {
|
||||
return nil, fmt.Errorf("playlet today-update code=%d msg=%s", env.Code, env.Msg)
|
||||
}
|
||||
return &env.Data, nil
|
||||
}
|
||||
|
||||
// FetchTodayUpdateOrEmpty 失败时返回空列表。
|
||||
func FetchTodayUpdateOrEmpty(c *gin.Context, q TodayUpdateQuery) *PlayletVideoResp {
|
||||
data, err := FetchTodayUpdate(c, q)
|
||||
if err != nil {
|
||||
log.Error("fetch playlet today-update failed", log.E(err))
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
if data == nil {
|
||||
return &PlayletVideoResp{PageNum: q.PageNum, PageSize: q.PageSize}
|
||||
}
|
||||
data.SeoInfo.Normalize()
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func todayUpdatePageURL(pageNum int) string {
|
||||
if pageNum <= 1 {
|
||||
return "/today-update/"
|
||||
}
|
||||
return "/today-update/page/" + strconv.Itoa(pageNum) + "/"
|
||||
}
|
||||
|
||||
func TodayUpdateCanonicalPath(q TodayUpdateQuery) string {
|
||||
q.Normalize()
|
||||
return todayUpdatePageURL(q.PageNum)
|
||||
}
|
||||
|
||||
// BuildTodayUpdatePagination 今日更新分页。
|
||||
func BuildTodayUpdatePagination(q TodayUpdateQuery, totalCount int64) PaginationVM {
|
||||
q.Normalize()
|
||||
return BuildPagination(func(p int) string {
|
||||
return todayUpdatePageURL(p)
|
||||
}, q.PageNum, q.PageSize, totalCount)
|
||||
}
|
||||
|
||||
// ParseTodayUpdateQuery 从 query 解析分页。
|
||||
func ParseTodayUpdateQuery(pageStr string) TodayUpdateQuery {
|
||||
q := TodayUpdateQuery{PageSize: defaultTodayUpdateSize}
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(pageStr)); err == nil {
|
||||
q.PageNum = n
|
||||
}
|
||||
q.Normalize()
|
||||
return q
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TemplateFuncs 模板辅助:仅做展示格式化 / URL,不把接口字段映射成另一套名字。
|
||||
func TemplateFuncs() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"detailURL": detailURL,
|
||||
"playURL": playURL,
|
||||
"chapterPlayURL": chapterPlayURL,
|
||||
"categoryURL": categoryURL,
|
||||
"categoryDetailURL": categoryDetailURL,
|
||||
"themeListURL": themeListURLByKey,
|
||||
"coverURL": coverURL,
|
||||
"formatHeat": formatHeat,
|
||||
"formatCollect": formatCollectHeat,
|
||||
"formatLikeCount": formatLikeCount,
|
||||
"episodeLabel": episodeText,
|
||||
"displayTag": displayTag,
|
||||
"firstTagName": firstTagName,
|
||||
"themeTagText": themeTagText,
|
||||
"tagListURL": tagListURL,
|
||||
"cardTag": cardTag,
|
||||
"cardTags": cardTags,
|
||||
"namedTags": namedTags,
|
||||
"namedThemeTags": namedThemeTags,
|
||||
"firstName": firstName,
|
||||
"rankClass": rankClass,
|
||||
"add": addInt,
|
||||
"contains": strings.Contains,
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
"footerLinkURL": footerLinkURL,
|
||||
"footerLinkIsExternal": footerLinkIsExternal,
|
||||
"footerContactURL": footerContactURL,
|
||||
"footerContactName": footerContactName,
|
||||
"footerContactValue": footerContactValue,
|
||||
"navDisplayURL": navDisplayURL,
|
||||
"urlquery": url.QueryEscape,
|
||||
"pathescape": url.PathEscape,
|
||||
"metaLine": metaLine,
|
||||
"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,
|
||||
"historyStatus": historyStatus,
|
||||
"formatHistoryAt": formatHistoryAt,
|
||||
"formatShortDateTime": formatShortDateTime,
|
||||
"absInt64": absInt64Tpl,
|
||||
"absURL": absURLTpl,
|
||||
"canonicalOr": canonicalOr,
|
||||
"joinStrings": joinStrings,
|
||||
"dict": dict,
|
||||
}
|
||||
}
|
||||
|
||||
// dict builds a map for nested template calls: {{template "x" dict "K" v}}.
|
||||
func dict(values ...interface{}) (map[string]interface{}, error) {
|
||||
if len(values)%2 != 0 {
|
||||
return nil, fmt.Errorf("dict requires an even number of arguments")
|
||||
}
|
||||
out := make(map[string]interface{}, len(values)/2)
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("dict keys must be strings")
|
||||
}
|
||||
out[key] = values[i+1]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func navDisplayURL(raw string) string {
|
||||
value := strings.TrimSpace(raw)
|
||||
value = strings.TrimPrefix(value, "https://")
|
||||
value = strings.TrimPrefix(value, "http://")
|
||||
return strings.TrimRight(value, "/")
|
||||
}
|
||||
|
||||
// footerLinkURL 按配置地址跳转:/richtext/xxx 进入富文本页,http 开头视为外链原样返回。
|
||||
func footerLinkURL(_, raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "/" || raw == "#" {
|
||||
return ""
|
||||
}
|
||||
if footerLinkIsExternal(raw) {
|
||||
return raw
|
||||
}
|
||||
if href := footerRichtextHref(raw); href != "" {
|
||||
return href
|
||||
}
|
||||
return normalizeFooterInternalURL(raw)
|
||||
}
|
||||
|
||||
func footerLinkIsExternal(raw string) bool {
|
||||
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(raw)), "http")
|
||||
}
|
||||
|
||||
func footerRichtextHref(raw string) string {
|
||||
path := raw
|
||||
if i := strings.IndexAny(raw, "?#"); i >= 0 {
|
||||
path = raw[:i]
|
||||
}
|
||||
path = strings.TrimRight(strings.TrimSpace(path), "/")
|
||||
if path == "/richtext" {
|
||||
return "/richtext/"
|
||||
}
|
||||
if strings.HasPrefix(path, "/richtext/") {
|
||||
return path + "/"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func normalizeFooterInternalURL(raw string) string {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
if parsed.Scheme != "" || parsed.Host != "" || !strings.HasPrefix(parsed.Path, "/") {
|
||||
return raw
|
||||
}
|
||||
if parsed.Path != "/" && !strings.HasSuffix(parsed.Path, "/") {
|
||||
if parsed.RawQuery == "" && parsed.Fragment == "" {
|
||||
return raw + "/"
|
||||
}
|
||||
parsed.Path += "/"
|
||||
href := parsed.Path
|
||||
if parsed.RawQuery != "" {
|
||||
href += "?" + parsed.RawQuery
|
||||
}
|
||||
if parsed.Fragment != "" {
|
||||
href += "#" + parsed.Fragment
|
||||
}
|
||||
return href
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
// footerContactURL 把页脚联系方式转换为可点击地址,并使用全站配置补齐按钮型文案。
|
||||
func footerContactURL(name, value, gmailAddr, tgGroup, customerServiceHost string) string {
|
||||
normalizedName := strings.ToLower(strings.ReplaceAll(footerContactName(name), " ", ""))
|
||||
switch {
|
||||
case strings.Contains(normalizedName, "官方群") || strings.Contains(normalizedName, "telegram") || strings.Contains(normalizedName, "tg群"):
|
||||
return firstContactURL(tgGroup, value)
|
||||
case strings.Contains(normalizedName, "商务") || strings.Contains(normalizedName, "合作"):
|
||||
return firstContactURL(customerServiceHost, value, gmailAddr)
|
||||
case strings.Contains(normalizedName, "邮箱") || strings.Contains(normalizedName, "email") || strings.Contains(normalizedName, "e-mail"):
|
||||
return firstContactURL(value, gmailAddr)
|
||||
default:
|
||||
return firstContactURL(value)
|
||||
}
|
||||
}
|
||||
|
||||
func footerContactName(name string) string {
|
||||
return cleanFooterContactAction(name)
|
||||
}
|
||||
|
||||
func footerContactValue(value string) string {
|
||||
return cleanFooterContactAction(value)
|
||||
}
|
||||
|
||||
func cleanFooterContactAction(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
for _, action := range []string{"立即联系", "立即加入"} {
|
||||
value = strings.ReplaceAll(value, action, "")
|
||||
}
|
||||
for {
|
||||
cleaned := strings.TrimSpace(strings.Trim(value, "::"))
|
||||
if cleaned == value {
|
||||
return cleaned
|
||||
}
|
||||
value = cleaned
|
||||
}
|
||||
}
|
||||
|
||||
func firstContactURL(values ...string) string {
|
||||
for _, value := range values {
|
||||
if href := normalizeContactURL(value); href != "" {
|
||||
return href
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func normalizeContactURL(value string) string {
|
||||
value = footerContactValue(value)
|
||||
if value == "" || strings.ContainsAny(value, " \t\r\n") {
|
||||
return ""
|
||||
}
|
||||
lower := strings.ToLower(value)
|
||||
if strings.HasPrefix(lower, "https://") || strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "mailto:") || strings.HasPrefix(lower, "tel:") {
|
||||
return value
|
||||
}
|
||||
if strings.HasPrefix(value, "//") {
|
||||
return "https:" + value
|
||||
}
|
||||
if strings.HasPrefix(value, "/") {
|
||||
return value
|
||||
}
|
||||
if strings.Contains(value, "@") && strings.Contains(value, ".") {
|
||||
return "mailto:" + value
|
||||
}
|
||||
if strings.Contains(value, ".") {
|
||||
return "https://" + value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// absURLTpl 模板内绝对化 URL:absURL foreverUrlAddr path
|
||||
func absURLTpl(siteURL, path string) string {
|
||||
return joinAbs(siteURL, path)
|
||||
}
|
||||
|
||||
// canonicalOr 优先使用接口返回的 canonical,否则用 foreverUrlAddr+fallbackPath。
|
||||
func canonicalOr(siteURL, preferred, fallbackPath string) string {
|
||||
preferred = strings.TrimSpace(preferred)
|
||||
if preferred != "" {
|
||||
if strings.HasPrefix(preferred, "http://") || strings.HasPrefix(preferred, "https://") {
|
||||
return preferred
|
||||
}
|
||||
return joinAbs(siteURL, preferred)
|
||||
}
|
||||
return joinAbs(siteURL, fallbackPath)
|
||||
}
|
||||
|
||||
func joinAbs(siteURL, path string) string {
|
||||
siteURL = strings.TrimRight(strings.TrimSpace(siteURL), "/")
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
if siteURL == "" {
|
||||
return "/"
|
||||
}
|
||||
return siteURL + "/"
|
||||
}
|
||||
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
|
||||
return path
|
||||
}
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
if siteURL == "" {
|
||||
return path
|
||||
}
|
||||
return siteURL + path
|
||||
}
|
||||
|
||||
// coverURL 选出封面地址。返回 template.URL,避免 html/template 把 data-src
|
||||
// 当 URL 上下文时把已百分号编码的中文路径再次转成 %25xx(导致封面 404)。
|
||||
func coverURL(primary, fallback string) template.URL {
|
||||
return template.URL(firstNonEmpty(primary, fallback))
|
||||
}
|
||||
|
||||
func displayTag(item CommonData) string {
|
||||
if name := firstName(item.TagNames); name != "" {
|
||||
return name
|
||||
}
|
||||
if name := firstName(item.ThemeNames); name != "" {
|
||||
return name
|
||||
}
|
||||
return "短剧"
|
||||
}
|
||||
|
||||
func firstTagName(item CommonData) string {
|
||||
if len(item.TagNames) == 0 {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(item.TagNames[0])
|
||||
}
|
||||
|
||||
func firstName(names []string) string {
|
||||
for _, n := range names {
|
||||
n = strings.TrimSpace(n)
|
||||
if n != "" {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func themeTagText(themeNames, tagNames []string) string {
|
||||
theme := firstName(themeNames)
|
||||
tag := firstName(tagNames)
|
||||
switch {
|
||||
case theme != "" && tag != "" && theme != tag:
|
||||
return theme + " · " + tag
|
||||
case tag != "":
|
||||
return tag
|
||||
default:
|
||||
return theme
|
||||
}
|
||||
}
|
||||
|
||||
func addInt(a, b int) int { return a + b }
|
||||
|
||||
func absInt64Tpl(n int64) int64 {
|
||||
if n < 0 {
|
||||
return -n
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func formatShortDateTime(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) >= 16 {
|
||||
raw = raw[:16]
|
||||
}
|
||||
raw = strings.ReplaceAll(raw, "-", "/")
|
||||
return raw
|
||||
}
|
||||
|
||||
func metaLine(item CommonData) string {
|
||||
cat := firstName(item.ThemeNames)
|
||||
if cat == "" {
|
||||
cat = firstName(item.TagNames)
|
||||
}
|
||||
if item.TotalEpisode > 0 {
|
||||
if cat != "" {
|
||||
return fmt.Sprintf("%s·%d集", cat, item.TotalEpisode)
|
||||
}
|
||||
return fmt.Sprintf("%d集", item.TotalEpisode)
|
||||
}
|
||||
return cat
|
||||
}
|
||||
|
||||
// playletYearText 详情 PC 元信息年份;无有效 onlineAt 时展示「年份未知」。
|
||||
func playletYearText(onlineAt string) string {
|
||||
onlineAt = strings.TrimSpace(onlineAt)
|
||||
if len(onlineAt) < 4 {
|
||||
return "年份未知"
|
||||
}
|
||||
year := onlineAt[:4]
|
||||
for _, c := range year {
|
||||
if c < '0' || c > '9' {
|
||||
return "年份未知"
|
||||
}
|
||||
}
|
||||
if year == "0001" || year == "1970" {
|
||||
return "年份未知"
|
||||
}
|
||||
return year
|
||||
}
|
||||
|
||||
// playletDateText formats the first valid detail-page date as YYYY.MM.DD.
|
||||
func playletDateText(values ...string) string {
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(value)
|
||||
if len(value) < 10 {
|
||||
continue
|
||||
}
|
||||
date := strings.NewReplacer("-", ".", "/", ".").Replace(value[:10])
|
||||
parts := strings.Split(date, ".")
|
||||
if len(parts) != 3 || len(parts[0]) != 4 || len(parts[1]) != 2 || len(parts[2]) != 2 {
|
||||
continue
|
||||
}
|
||||
validDigits := true
|
||||
for _, part := range parts {
|
||||
for _, c := range part {
|
||||
if c < '0' || c > '9' {
|
||||
validDigits = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !validDigits {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !validDigits || parts[0] == "0001" || parts[0] == "1970" {
|
||||
continue
|
||||
}
|
||||
parsed, err := time.Parse("2006.01.02", date)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
return parsed.Format("2006.01.02")
|
||||
}
|
||||
return "时间未知"
|
||||
}
|
||||
|
||||
// isPlayletAllFree 全部剧集 PayType==0 时视为全站免费。
|
||||
func isPlayletAllFree(chapters []PlayletChapterData) bool {
|
||||
if len(chapters) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, ch := range chapters {
|
||||
if ch.PayType != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package playletser
|
||||
|
||||
// HomePlayletResponse 对应 swagger proto.HomePlayletResponse
|
||||
// GET /api/app/playlet/home
|
||||
type HomePlayletResponse struct {
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
Announcements []AnnouncementItem `json:"announcements"`
|
||||
HomeBannerData []HomeBannerData `json:"homeBannerData"`
|
||||
HomeTodayUpdateData []CommonData `json:"homeTodayUpdateData"`
|
||||
HomeCategoryData []HomeCategoryData `json:"homeCategoryData"`
|
||||
HomeRecommendThemes []HomeRecommendTheme `json:"homeRecommendThemes"`
|
||||
}
|
||||
|
||||
type AnnouncementItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type HomeRecommendTheme struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Icon string `json:"icon"`
|
||||
Rank int `json:"rank"`
|
||||
PlayletCount int64 `json:"playletCount"`
|
||||
}
|
||||
|
||||
// HomeBannerData 对应 swagger proto.HomeBannerData
|
||||
type HomeBannerData struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Image string `json:"image"`
|
||||
VerticalImage string `json:"verticalImage"`
|
||||
URL string `json:"url"`
|
||||
Rank int `json:"rank"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
// HomeCategoryData 对应 swagger proto.HomeCategoryData
|
||||
type HomeCategoryData struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Desc string `json:"desc"`
|
||||
Icon string `json:"icon"`
|
||||
Rank int `json:"rank"`
|
||||
List []CommonData `json:"list"`
|
||||
}
|
||||
|
||||
// CommonData 对应 swagger proto.CommonData
|
||||
type CommonData struct {
|
||||
ID int64 `json:"id"`
|
||||
Status int `json:"status"`
|
||||
IsFeatured bool `json:"isFeatured"`
|
||||
IsNew bool `json:"isNew"`
|
||||
IsRecommend bool `json:"isRecommend"`
|
||||
OperateType int `json:"operateType"`
|
||||
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"`
|
||||
Description string `json:"description"`
|
||||
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"`
|
||||
HeatValue int64 `json:"heatValue"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
}
|
||||
|
||||
// PlayletVideoResp 对应 swagger proto.PlayletVideoResp
|
||||
// GET /api/app/playlet/list
|
||||
type PlayletVideoResp struct {
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
List []CommonData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// PlayletRecommendListResp 对应 swagger proto.PlayletRecommendListResp。
|
||||
// GET /api/app/playlet/recommend/list
|
||||
type PlayletRecommendListResp struct {
|
||||
CategoryID int64 `json:"categoryId"`
|
||||
CategoryName string `json:"categoryName"`
|
||||
CategorySlug string `json:"categorySlug"`
|
||||
CategoryDesc string `json:"categoryDesc"`
|
||||
List []CommonData `json:"list"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
}
|
||||
|
||||
// PlayletThemeItem 对应 swagger proto.PlayletThemeItem
|
||||
type PlayletThemeItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Icon string `json:"icon"`
|
||||
Rank int `json:"rank"`
|
||||
Status bool `json:"status"`
|
||||
IsRecommend bool `json:"isRecommend"`
|
||||
PlayletCount int64 `json:"playletCount"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
}
|
||||
|
||||
// PlayletThemeListResponse 对应 swagger proto.PlayletThemeListResponse
|
||||
// GET /api/app/theme/list
|
||||
type PlayletThemeListResponse struct {
|
||||
List []PlayletThemeItem `json:"list"`
|
||||
}
|
||||
|
||||
// PlayletChapterData 对应 swagger proto.PlayletChapterData
|
||||
// 出现在 GET /api/app/playlet/detail 的 playletChapterInfo。
|
||||
type PlayletChapterData struct {
|
||||
ID int64 `json:"id"`
|
||||
PlayletID int64 `json:"playletId"`
|
||||
CurrentEpisode int `json:"currentEpisode"`
|
||||
Title string `json:"title"`
|
||||
MD5 string `json:"md5"`
|
||||
Hash string `json:"hash"`
|
||||
Height int `json:"height"`
|
||||
Width int `json:"width"`
|
||||
Ratio float64 `json:"ratio"`
|
||||
VideoURL string `json:"videoUrl"`
|
||||
MediaSize int64 `json:"mediaSize"`
|
||||
MediaTime int `json:"mediaTime"`
|
||||
PayType int `json:"payType"`
|
||||
SingleCoins int `json:"singleCoins"`
|
||||
CostCoins int64 `json:"costCoins"`
|
||||
Balance int64 `json:"balance"`
|
||||
CanWatch bool `json:"canWatch"`
|
||||
IsUnlocked bool `json:"isUnlocked"`
|
||||
NeedUnlock bool `json:"needUnlock"`
|
||||
NeedVip bool `json:"needVip"`
|
||||
VipValid bool `json:"vipValid"`
|
||||
}
|
||||
|
||||
// PlayletChapterListResp 对应 swagger proto.PlayletChapterListResp。
|
||||
type PlayletChapterListResp struct {
|
||||
PlayletID int64 `json:"playletId"`
|
||||
List []PlayletChapterData `json:"list"`
|
||||
}
|
||||
|
||||
// PlayletOperateListResp 对应 swagger proto.PlayletOperateListResp。
|
||||
type PlayletOperateListResp struct {
|
||||
OperateType int `json:"operateType"`
|
||||
FilterType int `json:"filterType"`
|
||||
PageNum int `json:"pageNum"`
|
||||
PageSize int `json:"pageSize"`
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
List []CommonData `json:"list"`
|
||||
}
|
||||
|
||||
// PlayletInfoResp 对应 swagger proto.PlayletInfoResp
|
||||
// GET /api/app/playlet/detail
|
||||
type PlayletInfoResp struct {
|
||||
ID int64 `json:"id"`
|
||||
Status int `json:"status"`
|
||||
IsFeatured bool `json:"isFeatured"`
|
||||
IsNew bool `json:"isNew"`
|
||||
IsRecommend bool `json:"isRecommend"`
|
||||
OperateType int `json:"operateType"`
|
||||
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"`
|
||||
Description string `json:"description"`
|
||||
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"`
|
||||
HeatValue int64 `json:"heatValue"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
IsLike int `json:"isLike"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
RelatedRecommendData []CommonData `json:"relatedRecommendData"`
|
||||
PlayletChapterInfo []PlayletChapterData `json:"playletChapterInfo"`
|
||||
}
|
||||
|
||||
// SeoInfo 对应 GET /api/app/playlet/detail 的 proto.SeoInfo。
|
||||
// 字段:title / description / keywords / canonicalUrl / webSiteName。
|
||||
type SeoInfo struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Keywords []string `json:"keywords"`
|
||||
CanonicalURL string `json:"canonicalUrl"`
|
||||
WebSiteName string `json:"webSiteName"`
|
||||
}
|
||||
|
||||
// PlayletChapterInfoResp 对应 swagger proto.PlayletChapterInfoResp
|
||||
// GET /api/app/playlet/chapter/detail
|
||||
type PlayletChapterInfoResp struct {
|
||||
ID int64 `json:"id"`
|
||||
PlayletID int64 `json:"playletId"`
|
||||
CurrentEpisode int `json:"currentEpisode"`
|
||||
Title string `json:"title"`
|
||||
MD5 string `json:"md5"`
|
||||
Hash string `json:"hash"`
|
||||
Height int `json:"height"`
|
||||
Width int `json:"width"`
|
||||
Ratio float64 `json:"ratio"`
|
||||
VideoURL string `json:"videoUrl"`
|
||||
MediaSize int64 `json:"mediaSize"`
|
||||
MediaTime int `json:"mediaTime"`
|
||||
CountComment int64 `json:"countComment"`
|
||||
CountBrowse int64 `json:"countBrowse"`
|
||||
CountCollect int64 `json:"countCollect"`
|
||||
CountLike int64 `json:"countLike"`
|
||||
IsLike int `json:"isLike"`
|
||||
IsCollect int `json:"isCollect"`
|
||||
PayType int `json:"payType"`
|
||||
SingleCoins int `json:"singleCoins"`
|
||||
CostCoins int64 `json:"costCoins"`
|
||||
Balance int64 `json:"balance"`
|
||||
CanWatch bool `json:"canWatch"`
|
||||
IsUnlocked bool `json:"isUnlocked"`
|
||||
NeedUnlock bool `json:"needUnlock"`
|
||||
NeedVip bool `json:"needVip"`
|
||||
VipValid bool `json:"vipValid"`
|
||||
SeoInfo SeoInfo `json:"seoInfo"`
|
||||
}
|
||||
|
||||
// APIEnvelope 上游统一响应壳
|
||||
type APIEnvelope[T any] struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Tip string `json:"tip"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package playletser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func pathSegment(slug string, id int64) string {
|
||||
slug = strings.TrimSpace(slug)
|
||||
if slug == "" && id > 0 {
|
||||
slug = strconv.FormatInt(id, 10)
|
||||
}
|
||||
if slug == "" {
|
||||
return ""
|
||||
}
|
||||
return url.PathEscape(slug)
|
||||
}
|
||||
|
||||
func detailURL(slug string, id int64) string {
|
||||
if segment := pathSegment(slug, id); segment != "" {
|
||||
return "/detail/" + segment + "/"
|
||||
}
|
||||
return "#"
|
||||
}
|
||||
|
||||
func playURL(slug string, playletID int64) string {
|
||||
if segment := pathSegment(slug, playletID); segment != "" {
|
||||
return "/play/" + segment + "/"
|
||||
}
|
||||
return "#"
|
||||
}
|
||||
|
||||
func chapterPlayURL(slug string, playletID, chapterID int64) string {
|
||||
path := playURL(slug, playletID)
|
||||
if path == "#" || chapterID <= 0 {
|
||||
return path
|
||||
}
|
||||
return fmt.Sprintf("%s%d/", path, chapterID)
|
||||
}
|
||||
|
||||
func categoryURL(slug string, id int64) string {
|
||||
if segment := pathSegment(slug, id); segment != "" {
|
||||
return "/topic/" + segment + "/"
|
||||
}
|
||||
return "/topic/"
|
||||
}
|
||||
|
||||
func DetailPath(slug string, id int64) string {
|
||||
return detailURL(slug, id)
|
||||
}
|
||||
|
||||
func PlayPath(slug string, id int64) string {
|
||||
return playURL(slug, id)
|
||||
}
|
||||
|
||||
func ChapterPlayPath(slug string, playletID, chapterID int64) string {
|
||||
return chapterPlayURL(slug, playletID, chapterID)
|
||||
}
|
||||
|
||||
func updateStatusText(status int) string {
|
||||
if status == 2 {
|
||||
return "已完结"
|
||||
}
|
||||
return "连载中"
|
||||
}
|
||||
|
||||
func browseText(n int64) string {
|
||||
if n <= 0 {
|
||||
return "0次播放"
|
||||
}
|
||||
if n < 10000 {
|
||||
return fmt.Sprintf("%d次播放", n)
|
||||
}
|
||||
v := float64(n) / 10000
|
||||
if v >= 100 {
|
||||
return fmt.Sprintf("%.0f万次播放", v)
|
||||
}
|
||||
return fmt.Sprintf("%.1f万次播放", v)
|
||||
}
|
||||
|
||||
func usableAnchor(anchor string) string {
|
||||
anchor = strings.TrimSpace(anchor)
|
||||
if anchor == "" || anchor == "暂无" {
|
||||
return ""
|
||||
}
|
||||
return anchor
|
||||
}
|
||||
|
||||
func rankClass(rank int) string {
|
||||
switch rank {
|
||||
case 1:
|
||||
return "gold"
|
||||
case 2:
|
||||
return "silver"
|
||||
case 3:
|
||||
return "bronze"
|
||||
default:
|
||||
return "dark"
|
||||
}
|
||||
}
|
||||
|
||||
func episodeText(n int) string {
|
||||
if n <= 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d集", n)
|
||||
}
|
||||
|
||||
func formatHeat(n int64) string {
|
||||
if n <= 0 {
|
||||
return "0 热度"
|
||||
}
|
||||
if n < 10000 {
|
||||
return fmt.Sprintf("%d 热度", n)
|
||||
}
|
||||
v := float64(n) / 10000
|
||||
if v >= 100 {
|
||||
return fmt.Sprintf("%.0f万 热度", v)
|
||||
}
|
||||
return fmt.Sprintf("%.1f万 热度", v)
|
||||
}
|
||||
|
||||
// formatLikeCount 封面点赞数展示:不足一万原样,否则 x.x万。
|
||||
func formatLikeCount(n int64) string {
|
||||
if n <= 0 {
|
||||
return "0"
|
||||
}
|
||||
if n < 10000 {
|
||||
return fmt.Sprintf("%d", n)
|
||||
}
|
||||
v := float64(n) / 10000
|
||||
if v >= 100 {
|
||||
return fmt.Sprintf("%.0f万", v)
|
||||
}
|
||||
return fmt.Sprintf("%.1f万", v)
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, v := range values {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package playletser
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPlayletURLsPreferSlugAndFallbackToIDPath(t *testing.T) {
|
||||
if got := detailURL("my-show", 12); got != "/detail/my-show" {
|
||||
t.Fatalf("detailURL with slug = %q", got)
|
||||
}
|
||||
if got := detailURL("", 12); got != "/detail/12" {
|
||||
t.Fatalf("detailURL ID fallback = %q", got)
|
||||
}
|
||||
if got := chapterPlayURL("my-show", 12, 3); got != "/play/my-show/3" {
|
||||
t.Fatalf("chapterPlayURL with slug = %q", got)
|
||||
}
|
||||
if got := chapterPlayURL("", 12, 3); got != "/play/12/3" {
|
||||
t.Fatalf("chapterPlayURL ID fallback = %q", got)
|
||||
}
|
||||
if got := themeListURLByKey("wuxia", 10404); got != "/list/wuxia" {
|
||||
t.Fatalf("themeListURLByKey with slug = %q", got)
|
||||
}
|
||||
if got := themeListURLByKey("", 10404); got != "/list/10404" {
|
||||
t.Fatalf("themeListURLByKey ID fallback = %q", got)
|
||||
}
|
||||
if got := categoryURL("editor-picks", 12); got != "/topic/editor-picks" {
|
||||
t.Fatalf("categoryURL with slug = %q", got)
|
||||
}
|
||||
if got := categoryURL("", 12); got != "/topic/12" {
|
||||
t.Fatalf("categoryURL ID fallback = %q", got)
|
||||
}
|
||||
if got := recommendPageURL(12, "editor-picks", 2); got != "/topic/editor-picks/page/2" {
|
||||
t.Fatalf("recommendPageURL pagination = %q", got)
|
||||
}
|
||||
if got := rankPageURL(rankSortNew, 1); got != "/rank/2" {
|
||||
t.Fatalf("rankPageURL with sort order = %q", got)
|
||||
}
|
||||
if got := rankPageURL(rankSortNew, 2); got != "/rank/2/page/2" {
|
||||
t.Fatalf("rankPageURL pagination = %q", got)
|
||||
}
|
||||
q := ListQuery{ThemeSlug: "jiating", SortOrder: sortTodayUpdate, Type: contentTypeNonAdult}
|
||||
if got := listPageURL(q.ThemeID, q.ThemeSlug, q.SortOrder, 1, q.Type); got != "/list/jiating/2" {
|
||||
t.Fatalf("listPageURL with theme and sort = %q", got)
|
||||
}
|
||||
if got := listPageURL(q.ThemeID, q.ThemeSlug, q.SortOrder, 2, q.Type); got != "/list/jiating/2/page/2" {
|
||||
t.Fatalf("listPageURL pagination = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPageURLUsesSortPath(t *testing.T) {
|
||||
if got := listPageURL(0, "zhichang", sortTodayUpdate, 1, contentTypeNonAdult); got != "/list/zhichang/2" {
|
||||
t.Fatalf("listPageURL with slug and sort = %q", got)
|
||||
}
|
||||
if got := listPageURL(12, "", sortHeat, 1, contentTypeAdult); got != "/list/12/1" {
|
||||
t.Fatalf("listPageURL ID fallback = %q", got)
|
||||
}
|
||||
if got := listPageURL(0, "ai-short-play", sortTodayUpdate, 1, contentTypeAdult); got != "/list/ai-short-play" {
|
||||
t.Fatalf("listPageURL editorial default = %q", got)
|
||||
}
|
||||
if got := listPageURL(0, "ai-short-play", sortHeat, 1, contentTypeAdult); got != "/list/ai-short-play/1" {
|
||||
t.Fatalf("listPageURL editorial hot = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlayletDateText(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"2020-09-09 12:30:00": "2020.09.09",
|
||||
"2026/03/18": "2026.03.18",
|
||||
"2026.03.18T08:00:00": "2026.03.18",
|
||||
"": "时间未知",
|
||||
"1970-01-01": "时间未知",
|
||||
"2026-13-40": "时间未知",
|
||||
"invalid-date": "时间未知",
|
||||
}
|
||||
for input, want := range tests {
|
||||
if got := playletDateText(input); got != want {
|
||||
t.Fatalf("playletDateText(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
if got := playletDateText("", "2026-04-05 10:20:30", "2025-01-01"); got != "2026.04.05" {
|
||||
t.Fatalf("playletDateText fallback = %q, want %q", got, "2026.04.05")
|
||||
}
|
||||
if got := playletDateText("invalid-date", "", "2025/08/09"); got != "2025.08.09" {
|
||||
t.Fatalf("playletDateText valid fallback = %q, want %q", got, "2025.08.09")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user