91 lines
2.6 KiB
Go
91 lines
2.6 KiB
Go
package translationser
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
"videoweb/app/service/upstream"
|
|
"videoweb/pub/common/log"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
categoryListPath = "/api/app/translation/category/list"
|
|
categoryListCacheTTL = 60 * time.Second
|
|
)
|
|
|
|
var (
|
|
navMu sync.Mutex
|
|
navCache []TranslationCategory
|
|
navAt time.Time
|
|
)
|
|
|
|
// FetchCategoryList 拉取导航分类及每个分类对应的 seoInfo。
|
|
func FetchCategoryList(c *gin.Context) (*AppTranslationInfo, error) {
|
|
var env APIEnvelope[AppTranslationInfo]
|
|
if err := upstream.GetPublicJSON(c, categoryListPath, &env); err != nil {
|
|
return nil, err
|
|
}
|
|
if env.Code != 200 {
|
|
return nil, fmt.Errorf("translation category list code=%d msg=%s", env.Code, env.Msg)
|
|
}
|
|
return &env.Data, nil
|
|
}
|
|
|
|
// FetchHeaderCategoryListOrDefault 返回接口 categoryList(带短缓存);失败时兜底。
|
|
func FetchHeaderCategoryListOrDefault(c *gin.Context) []TranslationCategory {
|
|
navMu.Lock()
|
|
defer navMu.Unlock()
|
|
if navCache != nil && time.Since(navAt) < categoryListCacheTTL {
|
|
return append([]TranslationCategory(nil), navCache...)
|
|
}
|
|
|
|
info, err := FetchCategoryList(c)
|
|
if err != nil {
|
|
log.Error("fetch translation category list failed", log.E(err))
|
|
return DefaultCategoryList()
|
|
}
|
|
list := filterHeaderCategories(info)
|
|
if len(list) == 0 {
|
|
return DefaultCategoryList()
|
|
}
|
|
navCache = list
|
|
navAt = time.Now()
|
|
return append([]TranslationCategory(nil), list...)
|
|
}
|
|
|
|
func filterHeaderCategories(info *AppTranslationInfo) []TranslationCategory {
|
|
if info == nil {
|
|
return nil
|
|
}
|
|
out := make([]TranslationCategory, 0, len(info.CategoryList))
|
|
for _, cat := range info.CategoryList {
|
|
if cat.CategoryType == TranslationTypeBottom {
|
|
continue
|
|
}
|
|
if cat.Name == "" && cat.URLValue == "" {
|
|
continue
|
|
}
|
|
out = append(out, cat)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// DefaultCategoryList 接口失败时的兜底导航(字段与接口一致)。
|
|
func DefaultCategoryList() []TranslationCategory {
|
|
return []TranslationCategory{
|
|
{Name: "首页", URLValue: "/", CategoryType: TranslationTypeURL},
|
|
{Name: "短剧", URLValue: "/list", CategoryType: TranslationTypeURL},
|
|
{Name: "剧集", URLValue: "/series", CategoryType: TranslationTypeURL},
|
|
{Name: "专题", URLValue: "/topic", CategoryType: TranslationTypeURL},
|
|
{Name: "排行榜", URLValue: "/rank", CategoryType: TranslationTypeURL},
|
|
}
|
|
}
|
|
|
|
// FetchHeaderNavOrDefault 兼容旧调用:转为 HeaderNavItemVM。
|
|
func FetchHeaderNavOrDefault(c *gin.Context) []HeaderNavItemVM {
|
|
list := FetchHeaderCategoryListOrDefault(c)
|
|
return BuildHeaderNav(&AppTranslationInfo{CategoryList: list})
|
|
}
|