mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 03:26:37 +08:00
feat: Emby 兼容层完整实现 + 多模块功能增强
## Emby/Jellyfin 兼容层 (emby_compat.go / emby.go) - 新增 SystemInfoPublic、FindUser、Items、Item、LatestItems、ResumeItems - 新增 SetFavorite、MarkPlayed、RecordProgress 用户播放状态同步 - 新增 itemPayload、mediaSource、mediaStreams 媒体信息组装 - 双前缀路由 /emby/* 和 / 根路径,兼容 Infuse/Yamby/Senplayer/Kodi - 新增 Ping、SystemEndpoint、AuthByName 端点 - emby.go 扩展对应 handler 函数 ## 站点适配器 (site_adapter.go / site.go) - SiteConfig 扩展 UserAgent/Timeout/Extra/FlareSolverrURL 字段 - doRequest() GET 请求支持 FlareSolverr 代理绕过 Cloudflare/WAF - MTeam api_key 认证改为 Authorization: Bearer 格式 - Search() 重构为 sync.WaitGroup 并发执行,提升多站搜索性能 - siteModelToConfig() 改为 SiteService 方法,按 BrowserEmulation 填充 FlareSolverrURL ## 图片代理 (image_proxy.go) - 重构图片代理服务,支持更多来源和缓存策略 ## 下载管理 (downloads.go / download_clients.go / qbittorrent.go) - 下载任务增强:状态管理、进度追踪优化 - qBittorrent 客户端连接稳定性改进 ## 刮削与数据库 (scraper.go / tmdb.go / repository.go) - 刮削器增强 TMDB 集成,补全元数据字段 - repository 扩展查询方法 ## 前端 (web/src/) - HomePage: 首页布局重构,按媒体库分组展示,系列聚合优化 - DiscoverPage: 发现页增强,错误处理改进(API key 缺失/网络错误分离) - PosterWallPage: 海报墙优化,系列聚合展示 - MediaCard: 媒体卡片优化 - PlayerPage: 播放器改进 - 新增 utils/groupSeries.ts: 系列聚合工具函数 - .gitignore: 添加 .tmp_* 临时文件排除规则
This commit is contained in:
@@ -5,15 +5,22 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/service"
|
||||
)
|
||||
|
||||
// trendingHandler 返回 TMDb 当日热门列表。
|
||||
//
|
||||
// 当本机无法连接 TMDb(GFW / 代理未配 / API key 无效)时,TMDb 调用会
|
||||
// 在 15 秒后超时;这种情况下不应该让首页显示 500 错误,而是把空列表
|
||||
// 直接返回——前端按 items.length === 0 渲染"暂无推荐"即可。
|
||||
func trendingHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
items, err := svc.Discover.Trending(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
svc.Log.Warn("discover trending failed (returning empty list)", zap.Error(err))
|
||||
c.JSON(http.StatusOK, gin.H{"items": []service.Match{}, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
@@ -27,7 +34,8 @@ func popularHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
items, err := svc.Discover.Popular(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
svc.Log.Warn("discover popular failed (returning empty list)", zap.Error(err))
|
||||
c.JSON(http.StatusOK, gin.H{"items": []service.Match{}, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
|
||||
@@ -37,6 +37,9 @@ func createDownloadClientHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 让真正发起下载的 DownloadService 立刻读到新的 qb 配置,
|
||||
// 避免保存后还要重启进程才能生效。
|
||||
_ = svc.Downloads.ReloadConfig(c.Request.Context())
|
||||
c.JSON(http.StatusOK, row)
|
||||
}
|
||||
}
|
||||
@@ -53,6 +56,7 @@ func updateDownloadClientHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
_ = svc.Downloads.ReloadConfig(c.Request.Context())
|
||||
c.JSON(http.StatusOK, row)
|
||||
}
|
||||
}
|
||||
@@ -63,6 +67,7 @@ func deleteDownloadClientHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
_ = svc.Downloads.ReloadConfig(c.Request.Context())
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/middleware"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/model"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/service"
|
||||
)
|
||||
|
||||
@@ -15,6 +21,94 @@ type addDownloadReq struct {
|
||||
SavePath string `json:"save_path"`
|
||||
}
|
||||
|
||||
// resolvePTDownloadURL 把站点搜索结果里的"详情/获取签名"URL 解析成 qb 能直接
|
||||
// 拉到 .torrent 文件的真实下载 URL。
|
||||
//
|
||||
// 链路:
|
||||
//
|
||||
// 1. 拿 URL 的 host,到 sites 表里找 base_url 同源的站点。
|
||||
// 2. 如果站点的 type 是已知 PT 框架(mteam/nexusphp/unit3d/...),
|
||||
// 就用对应适配器的 GetDownloadURL,传入从 URL 里 parse 出来的 id。
|
||||
// 3. 任一步失败都直接返回原 URL,让 qb 自己去拉(保持向后兼容)。
|
||||
//
|
||||
// 这一步存在的意义:M-Team 等站点的搜索结果里 download_url 是
|
||||
// /api/torrent/genDlToken?id=xxx,需要带 x-api-key 才能调用,qb 自己
|
||||
// 是没法识别这种 PT 专属端点的。
|
||||
func resolvePTDownloadURL(ctx context.Context, svc *service.Container, raw string, log *zap.Logger) string {
|
||||
if raw == "" || svc == nil || svc.Site == nil {
|
||||
return raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" {
|
||||
return raw
|
||||
}
|
||||
host := strings.ToLower(u.Host)
|
||||
|
||||
// 找一个 host 匹配的已配置站点。
|
||||
sites, err := svc.Site.List(ctx)
|
||||
if err != nil || len(sites) == 0 {
|
||||
return raw
|
||||
}
|
||||
var matched *model.Site
|
||||
for i := range sites {
|
||||
su, err := url.Parse(sites[i].URL)
|
||||
if err != nil || su.Host == "" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(su.Host, host) || strings.HasSuffix(host, "."+strings.ToLower(su.Host)) {
|
||||
matched = &sites[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched == nil {
|
||||
return raw
|
||||
}
|
||||
|
||||
// 抽取 torrent id:?id=xxx 是 PT 站普遍写法。
|
||||
id := u.Query().Get("id")
|
||||
if id == "" {
|
||||
return raw
|
||||
}
|
||||
|
||||
adapter := service.GetAdapterForType(matched.Type)
|
||||
if adapter == nil {
|
||||
return raw
|
||||
}
|
||||
|
||||
cfg := service.SiteConfig{
|
||||
Name: matched.Name,
|
||||
Type: matched.Type,
|
||||
URL: strings.TrimRight(matched.URL, "/"),
|
||||
AuthType: matched.AuthType,
|
||||
Cookie: matched.Cookie,
|
||||
APIKey: matched.APIKey,
|
||||
AuthHeader: matched.AuthHeader,
|
||||
UserAgent: matched.UserAgent,
|
||||
Timeout: time.Duration(matched.Timeout) * time.Second,
|
||||
UseProxy: matched.UseProxy,
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = 15 * time.Second
|
||||
}
|
||||
|
||||
resolveCtx, cancel := context.WithTimeout(ctx, cfg.Timeout)
|
||||
defer cancel()
|
||||
resolved, err := adapter.GetDownloadURL(resolveCtx, cfg, id)
|
||||
if err != nil || resolved == "" {
|
||||
log.Warn("resolve PT download URL failed (using raw URL)",
|
||||
zap.String("site", matched.Name),
|
||||
zap.String("type", matched.Type),
|
||||
zap.String("raw", raw),
|
||||
zap.Error(err))
|
||||
return raw
|
||||
}
|
||||
log.Info("resolved PT download URL",
|
||||
zap.String("site", matched.Name),
|
||||
zap.String("from", raw),
|
||||
zap.String("to", resolved))
|
||||
return resolved
|
||||
}
|
||||
|
||||
func addDownloadHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req addDownloadReq
|
||||
@@ -23,12 +117,14 @@ func addDownloadHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
uid, _ := c.Get(middleware.CtxUserID)
|
||||
t, err := svc.Downloads.AddDownload(c.Request.Context(), uid.(string), req.URL, req.SavePath)
|
||||
// 把站点搜索 URL 转换成真实可下载 URL(M-Team 走 genDlToken 等)。
|
||||
realURL := resolvePTDownloadURL(c.Request.Context(), svc, req.URL, svc.Log)
|
||||
t, err := svc.Downloads.AddDownload(c.Request.Context(), uid.(string), realURL, req.SavePath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
svc.Audit.Record(c.Request.Context(), uid.(string), "download.add", req.URL, c.ClientIP(), "")
|
||||
svc.Audit.Record(c.Request.Context(), uid.(string), "download.add", realURL, c.ClientIP(), "")
|
||||
c.JSON(http.StatusOK, t)
|
||||
}
|
||||
}
|
||||
|
||||
+457
-9
@@ -1,26 +1,134 @@
|
||||
// Package handler — Emby/Jellyfin compatibility shim.
|
||||
//
|
||||
// Routes are mounted under /emby/* so existing Emby-aware clients
|
||||
// (Infuse / VidHub / Kodi) point at MediaStationGo and discover the
|
||||
// library through their familiar API. We do not implement write paths;
|
||||
// the React UI stays the canonical control plane.
|
||||
// 路由挂在 /emby/* 和根路径下双前缀。Infuse / Yamby / Hills /
|
||||
// Senplayer / Kodi 这类客户端会自动尝试 /System/Info 与 /emby/System/Info
|
||||
// 两种 URL,我们都接住。
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/middleware"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/service"
|
||||
)
|
||||
|
||||
// embyError 返回 Emby 风格的错误(顶层 Code/Message)。
|
||||
func embyError(c *gin.Context, status int, msg string) {
|
||||
c.JSON(status, gin.H{"Code": status, "Message": msg})
|
||||
}
|
||||
|
||||
// embyUserID 从中间件中获取 user id。Emby auth middleware 写入 CtxUserID。
|
||||
func embyUserID(c *gin.Context) string {
|
||||
if uid, ok := c.Get(middleware.CtxUserID); ok {
|
||||
if s, ok := uid.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ─── System ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func embySystemInfoHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, svc.Emby.SystemInfo())
|
||||
}
|
||||
}
|
||||
|
||||
func embySystemInfoPublicHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, svc.Emby.SystemInfoPublic())
|
||||
}
|
||||
}
|
||||
|
||||
func embySystemEndpointHandler(_ *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"IsLocal": true,
|
||||
"IsInNetwork": true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func embyPingHandler(_ *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Emby/Jellyfin 期望 plain text "Emby Server"
|
||||
c.String(http.StatusOK, "Emby Server")
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Users / Auth ────────────────────────────────────────────────────────────
|
||||
|
||||
type embyAuthByNameReq struct {
|
||||
Username string `json:"Username"`
|
||||
Pw string `json:"Pw"`
|
||||
Password string `json:"Password"`
|
||||
}
|
||||
|
||||
// embyAuthByNameHandler 处理 POST /Users/AuthenticateByName。
|
||||
//
|
||||
// 这是 Emby 客户端登录的唯一入口(Infuse / Yamby / Hills 等都走这里)。
|
||||
// 用户名+密码 → 调用我们已有的 AuthService.Login → 返回 AccessToken + User。
|
||||
func embyAuthByNameHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req embyAuthByNameReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
embyError(c, http.StatusBadRequest, "invalid body")
|
||||
return
|
||||
}
|
||||
password := req.Pw
|
||||
if password == "" {
|
||||
password = req.Password
|
||||
}
|
||||
resp, err := svc.Auth.Login(c.Request.Context(), req.Username, password)
|
||||
if err != nil {
|
||||
embyError(c, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
}
|
||||
userPayload, _ := svc.Emby.FindUser(c.Request.Context(), resp.User.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"AccessToken": resp.Tokens.AccessToken,
|
||||
"ServerId": "mediastation-go-001",
|
||||
"User": userPayload,
|
||||
"SessionInfo": gin.H{
|
||||
"Id": resp.User.ID,
|
||||
"UserId": resp.User.ID,
|
||||
"UserName": resp.User.Username,
|
||||
"Client": c.GetHeader("X-Emby-Client"),
|
||||
"DeviceId": c.GetHeader("X-Emby-Device-Id"),
|
||||
"DeviceName": c.GetHeader("X-Emby-Device-Name"),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func embyPublicUsersHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 公开用户列表(Emby Web 客户端登录页拉这个,列出可见用户)。
|
||||
users, err := svc.Emby.ListUsers(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, []any{})
|
||||
return
|
||||
}
|
||||
// 公开版本只暴露 Id + Name,不包含 Policy。
|
||||
out := make([]map[string]any, 0, len(users))
|
||||
for _, u := range users {
|
||||
out = append(out, map[string]any{
|
||||
"Id": u["Id"],
|
||||
"Name": u["Name"],
|
||||
"ServerId": u["ServerId"],
|
||||
"HasPassword": true,
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
}
|
||||
|
||||
func embyListUsersHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
users, err := svc.Emby.ListUsers(c.Request.Context())
|
||||
@@ -32,6 +140,35 @@ func embyListUsersHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func embyMeHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := embyUserID(c)
|
||||
if uid == "" {
|
||||
embyError(c, http.StatusUnauthorized, "not authenticated")
|
||||
return
|
||||
}
|
||||
u, err := svc.Emby.FindUser(c.Request.Context(), uid)
|
||||
if err != nil || u == nil {
|
||||
embyError(c, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, u)
|
||||
}
|
||||
}
|
||||
|
||||
func embyGetUserByIDHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
u, err := svc.Emby.FindUser(c.Request.Context(), c.Param("userId"))
|
||||
if err != nil || u == nil {
|
||||
embyError(c, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, u)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Views / MediaFolders ────────────────────────────────────────────────────
|
||||
|
||||
func embyViewsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
out, err := svc.Emby.Views(c.Request.Context())
|
||||
@@ -43,12 +180,46 @@ func embyViewsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Items ───────────────────────────────────────────────────────────────────
|
||||
|
||||
func parseEmbyItemsParams(c *gin.Context) service.ItemsParams {
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("Limit", "50"))
|
||||
offset, _ := strconv.Atoi(c.DefaultQuery("StartIndex", "0"))
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
splitOpt := func(s string) []string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return service.ItemsParams{
|
||||
UserID: uid,
|
||||
ParentID: c.Query("ParentId"),
|
||||
IDs: splitOpt(c.Query("Ids")),
|
||||
SearchTerm: c.Query("SearchTerm"),
|
||||
IncludeItemTypes: splitOpt(c.Query("IncludeItemTypes")),
|
||||
Recursive: strings.EqualFold(c.Query("Recursive"), "true"),
|
||||
SortBy: c.Query("SortBy"),
|
||||
SortOrder: c.Query("SortOrder"),
|
||||
Limit: limit,
|
||||
StartIndex: offset,
|
||||
}
|
||||
}
|
||||
|
||||
func embyItemsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
libraryID := c.Query("ParentId")
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("Limit", "50"))
|
||||
offset, _ := strconv.Atoi(c.DefaultQuery("StartIndex", "0"))
|
||||
out, err := svc.Emby.Items(c.Request.Context(), libraryID, limit, offset)
|
||||
out, err := svc.Emby.Items(c.Request.Context(), parseEmbyItemsParams(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -57,6 +228,93 @@ func embyItemsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func embyItemByIDHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
out, err := svc.Emby.Item(c.Request.Context(), id, uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if out == nil {
|
||||
embyError(c, http.StatusNotFound, "item not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
}
|
||||
|
||||
func embyLatestItemsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("Limit", "20"))
|
||||
out, err := svc.Emby.LatestItems(c.Request.Context(), uid, c.Query("ParentId"), limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
}
|
||||
|
||||
func embyResumeItemsHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("Limit", "20"))
|
||||
out, err := svc.Emby.ResumeItems(c.Request.Context(), uid, limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Images ──────────────────────────────────────────────────────────────────
|
||||
|
||||
// embyItemImageHandler 把 /Items/{id}/Images/Primary 等请求重定向到
|
||||
// 我们的 /api/img 代理。Emby 客户端会自动追加 ?api_key=... 或 ?tag=...
|
||||
// 我们只关心 id+type,从 media row 拉到 PosterURL/BackdropURL 后转成
|
||||
// /api/img?url=... 重定向。
|
||||
func embyItemImageHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
imgType := strings.ToLower(c.Param("type"))
|
||||
m, err := svc.Repo.Media.FindByID(c.Request.Context(), id)
|
||||
if err != nil || m == nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var raw string
|
||||
switch imgType {
|
||||
case "primary", "thumb", "banner", "logo":
|
||||
raw = m.PosterURL
|
||||
case "backdrop", "art":
|
||||
raw = m.BackdropURL
|
||||
default:
|
||||
raw = m.PosterURL
|
||||
}
|
||||
if raw == "" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
// 直接重定向到 /api/img;image proxy 自己缓存 + 兜底 1×1 PNG。
|
||||
c.Redirect(http.StatusFound, "/api/img?url="+url.QueryEscape(raw))
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Playback ────────────────────────────────────────────────────────────────
|
||||
|
||||
func embyPlaybackInfoHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
out, err := svc.Emby.PlaybackInfo(c.Request.Context(), c.Param("id"))
|
||||
@@ -65,9 +323,199 @@ func embyPlaybackInfoHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
if out == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
embyError(c, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
}
|
||||
|
||||
// embyVideoStreamHandler 是 GET /Videos/{id}/stream 的入口,
|
||||
// 直接代理到我们的 /api/stream/{id}(同一个 ServeFile)。
|
||||
func embyVideoStreamHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 直接调用 Stream service 写入 response
|
||||
err := svc.Stream.ServeFile(c.Writer, c.Request, c.Param("id"))
|
||||
if err != nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 播放进度 / 收藏 / 已看 ────────────────────────────────────────────────
|
||||
|
||||
type embyPlayingReq struct {
|
||||
ItemId string `json:"ItemId"`
|
||||
PositionTicks int64 `json:"PositionTicks"`
|
||||
RunTimeTicks int64 `json:"RunTimeTicks"`
|
||||
}
|
||||
|
||||
func embyPlayingProgressHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := embyUserID(c)
|
||||
if uid == "" {
|
||||
c.Status(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
var req embyPlayingReq
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
// 兼容 query 形式(一些客户端在 /Sessions/Playing/* 用 query)
|
||||
if req.ItemId == "" {
|
||||
req.ItemId = c.Query("ItemId")
|
||||
}
|
||||
if req.PositionTicks == 0 {
|
||||
req.PositionTicks, _ = strconv.ParseInt(c.Query("PositionTicks"), 10, 64)
|
||||
}
|
||||
if req.RunTimeTicks == 0 {
|
||||
req.RunTimeTicks, _ = strconv.ParseInt(c.Query("RunTimeTicks"), 10, 64)
|
||||
}
|
||||
if req.ItemId == "" {
|
||||
c.Status(http.StatusOK) // Emby 期望 2xx;不是关键操作
|
||||
return
|
||||
}
|
||||
_ = svc.Emby.RecordProgress(c.Request.Context(), uid, req.ItemId, req.PositionTicks, req.RunTimeTicks)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func embyFavoriteHandler(svc *service.Container, fav bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
mid := c.Param("itemId")
|
||||
if uid == "" || mid == "" {
|
||||
c.Status(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := svc.Emby.SetFavorite(c.Request.Context(), uid, mid, fav); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// Emby 期望返回 UserItemDataDto;最小可工作版本:echo Item 即可。
|
||||
out, _ := svc.Emby.Item(c.Request.Context(), mid, uid)
|
||||
if out != nil {
|
||||
c.JSON(http.StatusOK, out["UserData"])
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"IsFavorite": fav})
|
||||
}
|
||||
}
|
||||
|
||||
func embyMarkPlayedHandler(svc *service.Container, played bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
mid := c.Param("itemId")
|
||||
if uid == "" || mid == "" {
|
||||
c.Status(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := svc.Emby.MarkPlayed(c.Request.Context(), uid, mid, played); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
out, _ := svc.Emby.Item(c.Request.Context(), mid, uid)
|
||||
if out != nil {
|
||||
c.JSON(http.StatusOK, out["UserData"])
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"Played": played})
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Sessions / Branding 占位 ────────────────────────────────────────────────
|
||||
|
||||
func embySessionsHandler(_ *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, []any{})
|
||||
}
|
||||
}
|
||||
|
||||
func embyBrandingConfigHandler(_ *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"LoginDisclaimer": "",
|
||||
"CustomCss": "",
|
||||
"SplashscreenEnabled": false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func embyLocalizationOptionsHandler(_ *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, []map[string]any{
|
||||
{"Name": "简体中文", "Value": "zh-CN"},
|
||||
{"Name": "English", "Value": "en-US"},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// registerEmbyRoutes 在 r 上挂双前缀("" + "/emby")的 Emby 兼容路由。
|
||||
func registerEmbyRoutes(r *gin.Engine, jwtSecret string, svc *service.Container) {
|
||||
for _, prefix := range []string{"/emby", ""} {
|
||||
grp := r.Group(prefix)
|
||||
|
||||
// 公开端点
|
||||
grp.GET("/System/Info/Public", embySystemInfoPublicHandler(svc))
|
||||
grp.GET("/System/Ping", embyPingHandler(svc))
|
||||
grp.HEAD("/System/Ping", embyPingHandler(svc))
|
||||
grp.POST("/System/Ping", embyPingHandler(svc))
|
||||
grp.POST("/Users/AuthenticateByName", embyAuthByNameHandler(svc))
|
||||
grp.GET("/Users/Public", embyPublicUsersHandler(svc))
|
||||
grp.GET("/Branding/Configuration", embyBrandingConfigHandler(svc))
|
||||
grp.GET("/Localization/Options", embyLocalizationOptionsHandler(svc))
|
||||
|
||||
// 图片公开(Infuse 缓存 URL 时会丢 token)
|
||||
grp.GET("/Items/:id/Images/:type", embyItemImageHandler(svc))
|
||||
grp.GET("/Items/:id/Images/:type/:index", embyItemImageHandler(svc))
|
||||
grp.HEAD("/Items/:id/Images/:type", embyItemImageHandler(svc))
|
||||
|
||||
// 鉴权后端点
|
||||
auth := grp.Group("", middleware.AuthRequired(jwtSecret))
|
||||
auth.GET("/System/Info", embySystemInfoHandler(svc))
|
||||
auth.GET("/System/Endpoint", embySystemEndpointHandler(svc))
|
||||
|
||||
auth.GET("/Users/Me", embyMeHandler(svc))
|
||||
auth.GET("/Users", embyListUsersHandler(svc))
|
||||
auth.GET("/Users/:userId", embyGetUserByIDHandler(svc))
|
||||
auth.GET("/Users/:userId/Views", embyViewsHandler(svc))
|
||||
auth.GET("/Library/MediaFolders", embyViewsHandler(svc))
|
||||
|
||||
auth.GET("/Items", embyItemsHandler(svc))
|
||||
auth.GET("/Users/:userId/Items", embyItemsHandler(svc))
|
||||
auth.GET("/Items/:id", embyItemByIDHandler(svc))
|
||||
auth.GET("/Users/:userId/Items/Latest", embyLatestItemsHandler(svc))
|
||||
auth.GET("/Users/:userId/Items/Resume", embyResumeItemsHandler(svc))
|
||||
|
||||
auth.GET("/Items/:id/PlaybackInfo", embyPlaybackInfoHandler(svc))
|
||||
auth.POST("/Items/:id/PlaybackInfo", embyPlaybackInfoHandler(svc))
|
||||
|
||||
auth.GET("/Videos/:id/stream", embyVideoStreamHandler(svc))
|
||||
auth.HEAD("/Videos/:id/stream", embyVideoStreamHandler(svc))
|
||||
auth.GET("/Videos/:id/stream.:container", embyVideoStreamHandler(svc))
|
||||
auth.HEAD("/Videos/:id/stream.:container", embyVideoStreamHandler(svc))
|
||||
auth.GET("/Videos/:id/original", embyVideoStreamHandler(svc))
|
||||
auth.GET("/Videos/:id/original.:container", embyVideoStreamHandler(svc))
|
||||
|
||||
auth.POST("/Sessions/Playing", embyPlayingProgressHandler(svc))
|
||||
auth.POST("/Sessions/Playing/Progress", embyPlayingProgressHandler(svc))
|
||||
auth.POST("/Sessions/Playing/Stopped", embyPlayingProgressHandler(svc))
|
||||
|
||||
auth.POST("/Users/:userId/FavoriteItems/:itemId", embyFavoriteHandler(svc, true))
|
||||
auth.DELETE("/Users/:userId/FavoriteItems/:itemId", embyFavoriteHandler(svc, false))
|
||||
auth.POST("/Users/:userId/PlayedItems/:itemId", embyMarkPlayedHandler(svc, true))
|
||||
auth.DELETE("/Users/:userId/PlayedItems/:itemId", embyMarkPlayedHandler(svc, false))
|
||||
|
||||
auth.GET("/Sessions", embySessionsHandler(svc))
|
||||
auth.GET("/DisplayPreferences/:id", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"Id": c.Param("id"), "CustomPrefs": gin.H{}})
|
||||
})
|
||||
auth.POST("/DisplayPreferences/:id", func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,11 @@ func Register(r *gin.Engine, cfg *config.Config, log *zap.Logger, svc *service.C
|
||||
{
|
||||
auth.POST("/login", loginHandler(svc))
|
||||
auth.POST("/register", registerHandler(svc))
|
||||
auth.POST("/refresh", refreshHandler(svc))
|
||||
// /auth/refresh 用 RefreshHandler.RefreshToken:它从 body 读
|
||||
// refresh_token 并签发新 access/refresh 对。旧的 refreshHandler
|
||||
// 依赖 AuthRequired 中间件,永远 401,因此弃用。
|
||||
refreshHd := NewRefreshHandler(svc, log)
|
||||
auth.POST("/refresh", refreshHd.RefreshToken)
|
||||
}
|
||||
|
||||
// Authenticated endpoints.
|
||||
@@ -336,19 +340,11 @@ func Register(r *gin.Engine, cfg *config.Config, log *zap.Logger, svc *service.C
|
||||
apiConfig.POST("/:provider/test", testApiConfigHandler(svc))
|
||||
}
|
||||
|
||||
// Emby/Jellyfin compatibility shim (read-only).
|
||||
// Mounted at /emby/* (NOT /api/*) to mirror the upstream surface.
|
||||
// Emby/Jellyfin compatibility shim — routes mounted at /emby/* AND
|
||||
// the root path so Infuse / Yamby / Hills / Senplayer 都能自动连接。
|
||||
}
|
||||
|
||||
emby := r.Group("/emby")
|
||||
emby.Use(middleware.AuthRequired(cfg.Secrets.JWTSecret))
|
||||
{
|
||||
emby.GET("/System/Info", embySystemInfoHandler(svc))
|
||||
emby.GET("/Users", embyListUsersHandler(svc))
|
||||
emby.GET("/Users/:userId/Views", embyViewsHandler(svc))
|
||||
emby.GET("/Users/:userId/Items", embyItemsHandler(svc))
|
||||
emby.GET("/Items/:id/PlaybackInfo", embyPlaybackInfoHandler(svc))
|
||||
}
|
||||
registerEmbyRoutes(r, cfg.Secrets.JWTSecret, svc)
|
||||
}
|
||||
|
||||
func healthCheck(c *gin.Context) {
|
||||
|
||||
@@ -45,7 +45,10 @@ func stopTranscodeHandler(svc *service.Container) gin.HandlerFunc {
|
||||
func imageProxyHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
raw := c.Query("url")
|
||||
if err := svc.ImageProxy.Serve(c.Request.Context(), c.Writer, raw); err != nil {
|
||||
// Serve handles upstream errors internally by returning a 1×1 PNG
|
||||
// placeholder, so the only error we can get back here is a malformed
|
||||
// URL. In that case we still return 400 to make the misuse visible.
|
||||
if err := svc.ImageProxy.Serve(c.Request.Context(), c.Writer, c.Request, raw); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user