Compare commits

..

1 Commits

Author SHA1 Message Date
truewhile ef8b017c63 Merge pull request #19 from truewhile/main
拉取最新代码
2026-09-02 17:13:21 +08:00
66 changed files with 162 additions and 2856 deletions
-39
View File
@@ -264,42 +264,3 @@ jobs:
if [ -f "$TAR" ]; then
for i in 1 2 3; do gh release upload "$RELEASE_TAG" "$TAR" --clobber && break || sleep 5; done
fi
deploy:
name: Deploy to Server
needs: [version-and-publish]
runs-on: ubuntu-latest
steps:
- name: Deploy via SSH
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
password: ${{ secrets.SERVER_PASSWORD }}
port: ${{ secrets.SERVER_PORT }}
script: |
set -e
echo "==== 开始部署 MeBox ===="
cd /root/dockerData/mebox
# 判断 compose 命令版本兼容性(docker compose 或 docker-compose)
if docker compose version >/dev/null 2>&1; then
COMPOSE_CMD="docker compose"
elif command -v docker-compose >/dev/null 2>&1; then
COMPOSE_CMD="docker-compose"
else
echo "错误: 未找到 docker compose 或 docker-compose"
exit 1
fi
echo "正在拉取最新镜像..."
$COMPOSE_CMD pull
echo "正在重启服务..."
$COMPOSE_CMD up -d
echo "清理旧的无用镜像..."
docker image prune -f
echo "==== 部署完成并已启动 ===="
-38
View File
@@ -61,41 +61,3 @@ jobs:
VERSION=${{ env.RELEASE_VERSION }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy:
name: Deploy to Server
needs: [docker]
runs-on: ubuntu-latest
steps:
- name: Deploy via SSH
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
password: ${{ secrets.SERVER_PASSWORD }}
port: ${{ secrets.SERVER_PORT }}
script: |
set -e
echo "==== 开始部署 MeBox ===="
cd /root/dockerData/mebox
if docker compose version >/dev/null 2>&1; then
COMPOSE_CMD="docker compose"
elif command -v docker-compose >/dev/null 2>&1; then
COMPOSE_CMD="docker-compose"
else
echo "错误: 未找到 docker compose 或 docker-compose"
exit 1
fi
echo "正在拉取最新镜像..."
$COMPOSE_CMD pull
echo "正在重启服务..."
$COMPOSE_CMD up -d
echo "清理旧的无用镜像..."
docker image prune -f
echo "==== 部署完成并已启动 ===="
+1 -1
View File
@@ -1 +1 @@
0.0.94
0.0.81
+14 -99
View File
@@ -94,26 +94,18 @@ func listLibrariesHandler(svc *service.Container) gin.HandlerFunc {
out = append(out, webLibraryPayload{Library: l})
}
}
// 远程 Emby 挂载库追加在本地库之后(非管理员视图仍受 allowed_library_ids 约束)。
// 远程 Emby 挂载库追加在本地库之后。
if svc.EmbyRemote != nil {
if views, err := svc.EmbyRemote.RemoteLibraries(ctx); err == nil {
visibility := mediaVisibilityForRequest(c, svc)
allowedViews := make([]service.RemoteLibraryView, 0, len(views))
for _, v := range views {
if !includeHidden && !service.LibraryVisibleForUser(ctx, svc.Repo, v.Library, visibility) {
continue
}
allowedViews = append(allowedViews, v)
}
remotePayloads := make([]webLibraryPayload, len(allowedViews))
for i, v := range allowedViews {
remotePayloads := make([]webLibraryPayload, len(views))
for i, v := range views {
remotePayloads[i] = webLibraryPayload{Library: v.Library, IsRemoteEmby: true, RemoteSource: v.AccountName}
}
if withPreview && len(allowedViews) > 0 {
if withPreview && len(views) > 0 {
const maxRemotePreviewWorkers = 6
sem := make(chan struct{}, maxRemotePreviewWorkers)
var wg sync.WaitGroup
for i, v := range allowedViews {
for i, v := range views {
i, v := i, v
wg.Add(1)
go func() {
@@ -159,12 +151,6 @@ func getLibraryHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
role, _ := c.Get(middleware.CtxUserRole)
includeHidden := role == "admin" && (c.Query("include_hidden") == "1" || c.Query("include_hidden") == "true" || c.Query("all") == "1")
if !includeHidden && !service.LibraryVisibleForUser(ctx, svc.Repo, view.Library, mediaVisibilityForRequest(c, svc)) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
c.JSON(http.StatusOK, webLibraryPayload{Library: view.Library, IsRemoteEmby: true, RemoteSource: view.AccountName})
return
}
@@ -344,10 +330,6 @@ func listMediaHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if !service.EmbyMountLibraryAllowed(mediaVisibilityForRequest(c, svc), mount) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
itemTypes := ""
if view, err := svc.EmbyRemote.RemoteLibraryByID(ctx, mountID, remoteID); err == nil && view != nil {
itemTypes = remoteLibraryItemTypes(view.CollectionType)
@@ -415,10 +397,6 @@ func getMediaHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if !service.EmbyMountLibraryAllowed(mediaVisibilityForRequest(c, svc), mount) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
m, err := svc.EmbyRemote.RemoteMediaDetail(ctx, mount, acct, remoteID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
@@ -474,114 +452,55 @@ func updateMediaMetadataHandler(svc *service.Container) gin.HandlerFunc {
}
}
func paginateSlice[T any](items []T, page, size int) []T {
if page < 1 {
page = 1
}
if size <= 0 {
size = 50
}
if len(items) == 0 {
return []T{}
}
start := (page - 1) * size
if start >= len(items) {
return []T{}
}
end := start + size
if end > len(items) {
end = len(items)
}
return items[start:end]
}
func searchMediaHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
q := c.Query("q")
visibility := mediaVisibilityForRequest(c, svc)
groupVersions := c.DefaultQuery("group_versions", "1") != "0"
fetchRemote := func(limit int) []model.Media {
if svc.EmbyRemote == nil || strings.TrimSpace(q) == "" {
return nil
}
remoteItems, _ := svc.EmbyRemote.RemoteSearchMedia(ctx, q, limit, visibility)
return remoteItems
}
if c.Query("page") != "" || c.Query("page_size") != "" {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "50"))
if !groupVersions {
localItems, _, err := svc.Media.SearchMediaVisiblePage(ctx, q, 1, 50000, visibility)
items, total, err := svc.Media.SearchMediaVisiblePage(c.Request.Context(), q, page, size, mediaVisibilityForRequest(c, svc))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
remoteItems := fetchRemote(size * 2)
all := append(localItems, remoteItems...)
paged := paginateSlice(all, page, size)
c.JSON(http.StatusOK, gin.H{
"items": paged,
"total": len(all),
"items": items,
"total": total,
"page": page,
"page_size": size,
})
return
}
localItems, err := svc.Media.SearchMediaVisible(ctx, q, 50000, visibility)
items, total, err := svc.Media.SearchMediaVisiblePageGrouped(c.Request.Context(), q, page, size, mediaVisibilityForRequest(c, svc))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
remoteItems := fetchRemote(size * 2)
all := append(localItems, remoteItems...)
grouped := service.GroupMediaVersions(all)
paged := service.PaginateMediaItems(grouped, page, size)
c.JSON(http.StatusOK, gin.H{
"items": paged,
"total": len(grouped),
"items": items,
"total": total,
"page": page,
"page_size": size,
})
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
if limit <= 0 {
limit = 50
}
if !groupVersions {
localItems, err := svc.Media.SearchMediaVisible(ctx, q, limit, visibility)
items, err := svc.Media.SearchMediaVisible(c.Request.Context(), q, limit, mediaVisibilityForRequest(c, svc))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
remoteItems := fetchRemote(limit)
all := append(localItems, remoteItems...)
if len(all) > limit {
all = all[:limit]
}
if all == nil {
all = []model.Media{}
}
c.JSON(http.StatusOK, gin.H{"items": all})
c.JSON(http.StatusOK, gin.H{"items": items})
return
}
localItems, err := svc.Media.SearchMediaVisible(ctx, q, 50000, visibility)
items, err := svc.Media.SearchMediaVisibleGrouped(c.Request.Context(), q, limit, mediaVisibilityForRequest(c, svc))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
remoteItems := fetchRemote(limit)
all := append(localItems, remoteItems...)
grouped := service.GroupMediaVersions(all)
items := service.FirstMediaItems(grouped, limit)
if items == nil {
items = []service.MediaItem{}
}
c.JSON(http.StatusOK, gin.H{"items": items})
}
}
@@ -601,10 +520,6 @@ func streamHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if !service.EmbyMountLibraryAllowed(mediaVisibilityForRequest(c, svc), mount) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if mount.ProxyPlay {
if err := svc.Emby.ProxyRemoteVideoStream(ctx, c.Writer, c.Request, mountID, remoteID); err != nil {
if !c.Writer.Written() {
+19 -16
View File
@@ -13,6 +13,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/truewhile/MeBox/internal/middleware"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/service"
)
@@ -22,18 +23,18 @@ import (
func addMediaFavoriteHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
uid, _ := c.Get(middleware.CtxUserID)
userID := toString(uid)
mediaID := c.Param("id")
favorite, err := service.IsUserFavorite(c.Request.Context(), svc.Repo, userID, mediaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if favorite {
// Check current state.
var existing model.Favorite
err := svc.Repo.DB.WithContext(c.Request.Context()).
Where("user_id = ? AND media_id = ?", uid, c.Param("id")).
First(&existing).Error
if err == nil {
c.JSON(http.StatusOK, gin.H{"favourite": true})
return
}
if err := svc.Playback.SetFavourite(c.Request.Context(), userID, mediaID, true); err != nil {
// Otherwise create.
fav := &model.Favorite{UserID: toString(uid), MediaID: c.Param("id")}
if err := svc.Repo.DB.WithContext(c.Request.Context()).Create(fav).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
@@ -45,7 +46,9 @@ func addMediaFavoriteHandler(svc *service.Container) gin.HandlerFunc {
func removeMediaFavoriteHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
uid, _ := c.Get(middleware.CtxUserID)
if err := svc.Playback.SetFavourite(c.Request.Context(), toString(uid), c.Param("id"), false); err != nil {
if err := svc.Repo.DB.WithContext(c.Request.Context()).
Where("user_id = ? AND media_id = ?", uid, c.Param("id")).
Delete(&model.Favorite{}).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
@@ -57,12 +60,12 @@ func removeMediaFavoriteHandler(svc *service.Container) gin.HandlerFunc {
func getMediaFavoriteStatusHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
uid, _ := c.Get(middleware.CtxUserID)
favorite, err := service.IsUserFavorite(c.Request.Context(), svc.Repo, toString(uid), c.Param("id"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"favourite": favorite})
var n int64
_ = svc.Repo.DB.WithContext(c.Request.Context()).
Model(&model.Favorite{}).
Where("user_id = ? AND media_id = ?", uid, c.Param("id")).
Count(&n).Error
c.JSON(http.StatusOK, gin.H{"favourite": n > 0})
}
}
+2 -174
View File
@@ -436,180 +436,8 @@ func TestEmptyLibraryListsReturnEmptyArraysNotNull(t *testing.T) {
if strings.Contains(body, `"items":null`) {
t.Fatalf("%s: empty library returned items:null (crashes frontend): %s", tc.name, body)
}
if !strings.Contains(body, `"items":[]`) {
t.Fatalf("%s: expected items:[] for empty library, got %s", tc.name, body)
}
}
}
func TestSearchMediaHandlerIncludesEmbyRemote(t *testing.T) {
gin.SetMode(gin.TestMode)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("SearchTerm") == "碧蓝之海" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"TotalRecordCount": 1,
"Items": []map[string]any{
{
"Id": "156030",
"Name": "碧蓝之海",
"Type": "Series",
"ProductionYear": 2018,
},
},
})
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"TotalRecordCount": 0,
"Items": []map[string]any{},
})
}))
defer server.Close()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.Library{}, &model.Media{}, &model.StrmAccount{}, &model.EmbyMount{}, &model.Setting{}, &model.User{}, &model.PlayProfile{}); err != nil {
t.Fatal(err)
}
repos := repository.New(db)
adminUser := model.User{
Base: model.Base{ID: "user-1"},
Username: "admin",
Role: "admin",
}
_ = repos.DB.Create(&adminUser).Error
localLib := model.Library{Name: "本地电影", Path: "/media/movies", Type: "movie", Enabled: true}
if err := repos.Library.Create(t.Context(), &localLib); err != nil {
t.Fatal(err)
}
localMedia := model.Media{
Base: model.Base{ID: "local-1"},
LibraryID: localLib.ID,
Title: "流浪地球",
Year: 2019,
}
if err := repos.DB.Create(&localMedia).Error; err != nil {
t.Fatal(err)
}
rawCfg, _ := json.Marshal(map[string]string{"url": server.URL, "token": "fake-token"})
acct := model.StrmAccount{
Base: model.Base{ID: "acct-1"},
Name: "远程Emby",
Provider: model.StrmProviderEmbyRemote,
Config: string(rawCfg),
Enabled: true,
}
if err := repos.StrmAccount.Create(t.Context(), &acct); err != nil {
t.Fatal(err)
}
mount := model.EmbyMount{
Base: model.Base{ID: "mount-1"},
AccountID: acct.ID,
RemoteViewID: "view-1",
RemoteViewName: "动漫",
CollectionType: "tvshows",
Enabled: true,
}
if err := repos.EmbyMount.Create(t.Context(), &mount); err != nil {
t.Fatal(err)
}
crypto := service.NewCryptoService("", zap.NewNop())
remoteSvc := service.NewEmbyRemoteService(&config.Config{}, zap.NewNop(), repos, crypto)
mediaSvc := service.NewMediaService(&config.Config{}, zap.NewNop(), repos)
svc := &service.Container{
Repo: repos,
Media: mediaSvc,
EmbyRemote: remoteSvc,
}
// 1. 搜索远程挂载媒体(碧蓝之海)
{
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set(middleware.CtxUserID, "user-1")
c.Set(middleware.CtxUserRole, "admin")
c.Request = httptest.NewRequest(http.MethodGet, "/api/media?q=碧蓝之海&limit=8", nil)
searchMediaHandler(svc)(c)
if w.Code != http.StatusOK {
t.Fatalf("search status=%d, body=%s", w.Code, w.Body.String())
}
var res struct {
Items []service.MediaItem `json:"items"`
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if len(res.Items) != 1 {
t.Fatalf("expected 1 item, got %d", len(res.Items))
}
if res.Items[0].Title != "碧蓝之海" {
t.Fatalf("expected Title '碧蓝之海', got %q", res.Items[0].Title)
}
expectedID := service.EncodeEmbyRemoteID("mount-1", "156030")
if res.Items[0].ID != expectedID {
t.Fatalf("expected ID %q, got %q", expectedID, res.Items[0].ID)
}
}
// 2. 搜索本地媒体(流浪地球)
{
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set(middleware.CtxUserID, "user-1")
c.Set(middleware.CtxUserRole, "admin")
c.Request = httptest.NewRequest(http.MethodGet, "/api/media?q=流浪地球&limit=8", nil)
searchMediaHandler(svc)(c)
if w.Code != http.StatusOK {
t.Fatalf("search status=%d, body=%s", w.Code, w.Body.String())
}
var res struct {
Items []service.MediaItem `json:"items"`
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if len(res.Items) != 1 {
t.Fatalf("expected 1 item, got %d", len(res.Items))
}
if res.Items[0].Title != "流浪地球" {
t.Fatalf("expected Title '流浪地球', got %q", res.Items[0].Title)
}
}
// 3. 搜索不存在的媒体
{
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set(middleware.CtxUserID, "user-1")
c.Set(middleware.CtxUserRole, "admin")
c.Request = httptest.NewRequest(http.MethodGet, "/api/media?q=不存在的影片&limit=8", nil)
searchMediaHandler(svc)(c)
if w.Code != http.StatusOK {
t.Fatalf("search status=%d, body=%s", w.Code, w.Body.String())
}
var res struct {
Items []service.MediaItem `json:"items"`
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if len(res.Items) != 0 {
t.Fatalf("expected 0 items, got %d", len(res.Items))
}
if strings.Contains(w.Body.String(), `"items":null`) {
t.Fatalf("expected items:[], got null: %s", w.Body.String())
if !strings.Contains(body, `"items":[]`) {
t.Fatalf("%s: expected items:[] for empty library, got %s", tc.name, body)
}
}
}
-49
View File
@@ -1,49 +0,0 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/truewhile/MeBox/internal/middleware"
"github.com/truewhile/MeBox/internal/service"
)
type pinnedLibrariesReq struct {
LibraryIDs []string `json:"library_ids"`
}
func getPinnedLibrariesHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
uid, _ := c.Get(middleware.CtxUserID)
ids, err := svc.Profile.GetPinnedLibraryIDs(c.Request.Context(), uid.(string))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if ids == nil {
ids = []string{}
}
c.JSON(http.StatusOK, gin.H{"library_ids": ids})
}
}
func setPinnedLibrariesHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
var req pinnedLibrariesReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
uid, _ := c.Get(middleware.CtxUserID)
ids, err := svc.Profile.SetPinnedLibraryIDs(c.Request.Context(), uid.(string), req.LibraryIDs)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if ids == nil {
ids = []string{}
}
c.JSON(http.StatusOK, gin.H{"library_ids": ids})
}
}
-3
View File
@@ -37,7 +37,6 @@ func registerAdminScraperRoutes(admin *gin.RouterGroup, svc *service.Container)
admin.POST("/scraper/queue/clear-done", clearDoneScrapeTasksHandler(svc))
admin.POST("/scraper/queue/clear-finished", clearFinishedScrapeTasksHandler(svc))
admin.POST("/scraper/queue/clear-canceled", clearCanceledScrapeTasksHandler(svc))
admin.POST("/scraper/queue/clear-failed", clearFailedScrapeTasksHandler(svc))
admin.POST("/scraper/queue/retry-failed", retryAllFailedScrapeTasksHandler(svc))
admin.POST("/scraper/queue/cancel-pending", cancelPendingScrapeTasksHandler(svc))
admin.POST("/scraper/queue/enqueue-library/:id", enqueueLibraryScrapeHandler(svc))
@@ -88,7 +87,6 @@ func registerAdminStrmRoutes(admin *gin.RouterGroup, svc *service.Container) {
admin.POST("/strm/downloads/clear-done", clearDoneDownloadsHandler(svc))
admin.POST("/strm/downloads/clear-finished", clearFinishedDownloadsHandler(svc))
admin.POST("/strm/downloads/clear-canceled", clearCanceledDownloadsHandler(svc))
admin.POST("/strm/downloads/clear-failed", clearFailedDownloadsHandler(svc))
admin.POST("/strm/downloads/retry-failed", retryAllFailedDownloadsHandler(svc))
admin.POST("/strm/downloads/cancel-pending", cancelPendingDownloadsHandler(svc))
admin.GET("/strm/uploads", uploadQueueHandler(svc))
@@ -99,7 +97,6 @@ func registerAdminStrmRoutes(admin *gin.RouterGroup, svc *service.Container) {
admin.POST("/strm/uploads/clear-done", clearDoneUploadsHandler(svc))
admin.POST("/strm/uploads/clear-finished", clearFinishedUploadsHandler(svc))
admin.POST("/strm/uploads/clear-canceled", clearCanceledUploadsHandler(svc))
admin.POST("/strm/uploads/clear-failed", clearFailedUploadsHandler(svc))
admin.POST("/strm/uploads/retry-failed", retryAllFailedUploadsHandler(svc))
admin.POST("/strm/uploads/cancel-pending", cancelPendingUploadsHandler(svc))
}
@@ -10,8 +10,6 @@ import (
func registerAuthedUserAndLicenseRoutes(authed *gin.RouterGroup, svc *service.Container) {
authed.GET("/me", meHandler(svc))
authed.PATCH("/me", updateProfileHandler(svc))
authed.GET("/me/pinned-libraries", getPinnedLibrariesHandler(svc))
authed.PUT("/me/pinned-libraries", setPinnedLibrariesHandler(svc))
authed.POST("/me/password", changePasswordHandler(svc))
authed.POST("/me/logout", logoutHandler(svc))
@@ -25,8 +25,6 @@ func TestAuthenticatedRouteSurfacesAreRegistered(t *testing.T) {
for _, want := range []string{
"GET /api/me",
"GET /api/me/pinned-libraries",
"PUT /api/me/pinned-libraries",
"GET /api/auth/permissions",
"GET /api/libraries",
"GET /api/media",
-11
View File
@@ -101,17 +101,6 @@ func clearCanceledScrapeTasksHandler(svc *service.Container) gin.HandlerFunc {
}
}
func clearFailedScrapeTasksHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
n, err := svc.Scraper.ClearFailedScrapeTasks(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"deleted": n})
}
}
func retryAllFailedScrapeTasksHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
n, err := svc.Scraper.RetryAllFailedScrapeTasks(c.Request.Context())
+2 -23
View File
@@ -7,7 +7,6 @@ package handler
import (
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
@@ -17,26 +16,16 @@ import (
// searchUnifiedHandler is the basic /api/search endpoint.
func searchUnifiedHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
q := c.Query("q")
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "30"))
if limit <= 0 || limit > 200 {
limit = 30
}
visibility := mediaVisibilityForRequest(c, svc)
items, err := svc.Media.SearchMediaVisible(ctx, q, limit, visibility)
items, err := svc.Media.SearchMediaVisible(c.Request.Context(), q, limit, mediaVisibilityForRequest(c, svc))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if svc.EmbyRemote != nil && strings.TrimSpace(q) != "" {
if remoteItems, _ := svc.EmbyRemote.RemoteSearchMedia(ctx, q, limit, visibility); len(remoteItems) > 0 {
items = append(items, remoteItems...)
if len(items) > limit {
items = items[:limit]
}
}
}
c.JSON(http.StatusOK, gin.H{"items": items, "total": len(items)})
}
}
@@ -47,26 +36,16 @@ func searchUnifiedHandler(svc *service.Container) gin.HandlerFunc {
// them back. This keeps API parity without a giant query builder.
func searchAdvancedHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
q := c.Query("q")
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "30"))
if limit <= 0 || limit > 200 {
limit = 30
}
visibility := mediaVisibilityForRequest(c, svc)
items, err := svc.Media.SearchMediaVisible(ctx, q, limit, visibility)
items, err := svc.Media.SearchMediaVisible(c.Request.Context(), q, limit, mediaVisibilityForRequest(c, svc))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if svc.EmbyRemote != nil && strings.TrimSpace(q) != "" {
if remoteItems, _ := svc.EmbyRemote.RemoteSearchMedia(ctx, q, limit, visibility); len(remoteItems) > 0 {
items = append(items, remoteItems...)
if len(items) > limit {
items = items[:limit]
}
}
}
c.JSON(http.StatusOK, gin.H{
"items": items,
"filters": gin.H{
-12
View File
@@ -74,10 +74,6 @@ func listLibrarySeriesHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if !service.EmbyMountLibraryAllowed(mediaVisibilityForRequest(c, svc), mount) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
cards, err := svc.EmbyRemote.RemoteSeriesCards(ctx, mount, acct, remoteID)
if err != nil {
writeInternalOrCanceled(c, err)
@@ -169,10 +165,6 @@ func listLibrarySeriesEpisodesHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if !service.EmbyMountLibraryAllowed(mediaVisibilityForRequest(c, svc), mount) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
items, err := svc.EmbyRemote.RemoteEpisodes(ctx, mount, acct, remoteSeriesID)
if err != nil {
writeInternalOrCanceled(c, err)
@@ -215,10 +207,6 @@ func listMediaEpisodesHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if !service.EmbyMountLibraryAllowed(mediaVisibilityForRequest(c, svc), mount) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
items, err := svc.EmbyRemote.RemoteEpisodes(ctx, mount, acct, remoteID)
if err != nil {
writeInternalOrCanceled(c, err)
-22
View File
@@ -526,17 +526,6 @@ func clearCanceledDownloadsHandler(svc *service.Container) gin.HandlerFunc {
}
}
func clearFailedDownloadsHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
n, err := svc.Strm.ClearFailedDownloadTasks(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"deleted": n})
}
}
func clearCanceledUploadsHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
n, err := svc.Strm.ClearCanceledUploadTasks(c.Request.Context())
@@ -548,17 +537,6 @@ func clearCanceledUploadsHandler(svc *service.Container) gin.HandlerFunc {
}
}
func clearFailedUploadsHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
n, err := svc.Strm.ClearFailedUploadTasks(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"deleted": n})
}
}
func clearDoneUploadsHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
n, err := svc.Strm.ClearDoneUploadTasks(c.Request.Context())
+17 -22
View File
@@ -8,7 +8,6 @@ package handler
import (
"net/http"
"runtime"
"strings"
"time"
"github.com/gin-gonic/gin"
@@ -23,30 +22,26 @@ import (
// without threading state through the container.
var startedAt = time.Now()
func systemInfoHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
directOnly := false
if svc.Repo != nil && svc.Repo.Setting != nil {
if v, err := svc.Repo.Setting.Get(c.Request.Context(), service.PlaybackDirectOnlySettingKey); err == nil {
directOnly = service.ParseBoolSetting(v, false)
}
func systemInfoHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
directOnly := false
if svc.Repo != nil && svc.Repo.Setting != nil {
if v, err := svc.Repo.Setting.Get(c.Request.Context(), service.PlaybackDirectOnlySettingKey); err == nil {
directOnly = service.ParseBoolSetting(v, false)
}
version := svc.Version
if strings.TrimSpace(version) == "" {
version = "dev"
}
c.JSON(http.StatusOK, gin.H{
"name": "MeBox",
"version": version,
"go": runtime.Version(),
"os": runtime.GOOS,
"arch": runtime.GOARCH,
"data_dir": svc.Cfg.App.DataDir,
"cache_dir": svc.Cfg.Cache.CacheDir,
"direct_play_only": directOnly,
})
}
c.JSON(http.StatusOK, gin.H{
"name": "MeBox",
"version": "0.1.0",
"go": runtime.Version(),
"os": runtime.GOOS,
"arch": runtime.GOARCH,
"data_dir": svc.Cfg.App.DataDir,
"cache_dir": svc.Cfg.Cache.CacheDir,
"direct_play_only": directOnly,
})
}
}
func systemStatusHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
-23
View File
@@ -25,9 +25,6 @@ type User struct {
// 为空时代表不限制(全库可访问)。
AllowedLibraryIDs string `gorm:"type:text" json:"-"`
AllowedLibraryList []string `gorm:"-" json:"allowed_library_ids,omitempty"`
// PinnedLibraryIDs 存储用户置顶的媒体库 ID 列表(JSON 字符串),顺序即置顶优先级。
PinnedLibraryIDs string `gorm:"type:text" json:"-"`
PinnedLibraryList []string `gorm:"-" json:"pinned_library_ids,omitempty"`
// ExpiredAt is the account expiry time. Nil means the account never
// expires. When set and in the past, the account is treated as expired
// (login blocked) until an admin or a redemption code renews it.
@@ -62,30 +59,10 @@ func (u *User) DecodeAllowedLibraryIDs() []string {
return out
}
// DecodePinnedLibraryIDs 解析 PinnedLibraryIDs 字段。
func (u *User) DecodePinnedLibraryIDs() []string {
if u == nil || strings.TrimSpace(u.PinnedLibraryIDs) == "" {
return nil
}
var ids []string
if err := json.Unmarshal([]byte(u.PinnedLibraryIDs), &ids); err != nil {
return nil
}
var out []string
for _, id := range ids {
trimmed := strings.TrimSpace(id)
if trimmed != "" {
out = append(out, trimmed)
}
}
return out
}
// PopulateComputedFields 填充非 DB 虚拟计算字段(如 AllowedLibraryList)。
func (u *User) PopulateComputedFields() {
if u == nil {
return
}
u.AllowedLibraryList = u.DecodeAllowedLibraryIDs()
u.PinnedLibraryList = u.DecodePinnedLibraryIDs()
}
@@ -236,16 +236,6 @@ func (r *ScrapeTaskRepository) ClearCanceled(ctx context.Context) (int64, error)
return count, err
}
func (r *ScrapeTaskRepository) ClearFailed(ctx context.Context) (int64, error) {
var count int64
err := withSQLiteBusyRetry(ctx, func() error {
res := r.db.WithContext(ctx).Unscoped().Where("status = ?", model.ScrapeTaskFailed).Delete(&model.ScrapeTask{})
count = res.RowsAffected
return res.Error
})
return count, err
}
func (r *ScrapeTaskRepository) RetryAllFailed(ctx context.Context) (int64, error) {
var count int64
err := withSQLiteBusyRetry(ctx, func() error {
-22
View File
@@ -402,17 +402,6 @@ func (r *StrmDownloadTaskRepository) ClearCanceled(ctx context.Context) (int64,
return count, err
}
// ClearFailed 清空全部已失败下载任务。
func (r *StrmDownloadTaskRepository) ClearFailed(ctx context.Context) (int64, error) {
var count int64
err := withSQLiteBusyRetry(ctx, func() error {
res := r.db.WithContext(ctx).Unscoped().Where("status = ?", model.StrmTaskFailed).Delete(&model.StrmDownloadTask{})
count = res.RowsAffected
return res.Error
})
return count, err
}
// RetryAllFailed 把所有失败任务重置回待处理,清空错误与重试计数。
func (r *StrmDownloadTaskRepository) RetryAllFailed(ctx context.Context) (int64, error) {
var count int64
@@ -720,17 +709,6 @@ func (r *StrmUploadTaskRepository) ClearCanceled(ctx context.Context) (int64, er
return count, err
}
// ClearFailed 清空全部已失败上传任务。
func (r *StrmUploadTaskRepository) ClearFailed(ctx context.Context) (int64, error) {
var count int64
err := withSQLiteBusyRetry(ctx, func() error {
res := r.db.WithContext(ctx).Unscoped().Where("status = ?", model.StrmTaskFailed).Delete(&model.StrmUploadTask{})
count = res.RowsAffected
return res.Error
})
return count, err
}
// RetryAllFailed 把所有失败任务重置回待处理,清空错误与重试计数。
func (r *StrmUploadTaskRepository) RetryAllFailed(ctx context.Context) (int64, error) {
var count int64
+1 -1
View File
@@ -77,7 +77,7 @@ func (c *CryptoService) Encrypt(plain string) string {
// Decrypt returns the plaintext for an encrypted value. Plaintext rows
// (no prefix) are returned unchanged.
func (c *CryptoService) Decrypt(value string) string {
if c == nil || value == "" || c.aead == nil {
if value == "" || c.aead == nil {
return value
}
if !strings.HasPrefix(value, encPrefix) {
-12
View File
@@ -148,17 +148,11 @@ func (e *EmbyService) Items(ctx context.Context, p ItemsParams) (map[string]any,
if e.remote != nil {
// 远程目录浏览:ParentId 带远程前缀 → 完整转发给远程 Emby 承接分页。
if IsEmbyRemoteID(p.ParentID) {
if containsEmbyFilter(p.Filters, "IsFavorite") {
return e.favoriteItems(ctx, p)
}
mountID, _, _ := DecodeEmbyRemoteID(p.ParentID)
mount, acct, _ := e.remote.ResolveMount(ctx, mountID)
if mount == nil || acct == nil {
return emptyItemsEnvelope(p.StartIndex), nil
}
if !EmbyMountLibraryAllowed(e.mediaVisibility(ctx, p.UserID), mount) {
return emptyItemsEnvelope(p.StartIndex), nil
}
out, err := e.remote.RemoteItems(ctx, mount, acct, p)
if err != nil {
return nil, err
@@ -177,9 +171,6 @@ func (e *EmbyService) Items(ctx context.Context, p ItemsParams) (map[string]any,
if containsEmbyFilter(p.Filters, "IsResumable") {
return e.resumableItems(ctx, p)
}
if containsEmbyFilter(p.Filters, "IsFavorite") {
return e.favoriteItems(ctx, p)
}
if len(p.IDs) > 0 {
items := make([]map[string]any, 0, len(p.IDs))
@@ -278,9 +269,6 @@ func (e *EmbyService) aggregatedSearch(ctx context.Context, p ItemsParams) (map[
if !m.Enabled {
continue
}
if !EmbyMountLibraryAllowed(e.mediaVisibility(ctx, p.UserID), &m) {
continue
}
acct := e.remote.AccountByID(ctx, m.AccountID)
if acct == nil {
continue
-145
View File
@@ -21,9 +21,6 @@ func (e *EmbyService) Item(ctx context.Context, mediaID, userID string) (map[str
if mount == nil || acct == nil {
return nil, nil
}
if !EmbyMountLibraryAllowed(e.mediaVisibility(ctx, userID), mount) {
return nil, nil
}
out, err := e.remote.RemoteItem(ctx, mount, acct, remoteID)
if err != nil || out == nil {
return out, err
@@ -31,14 +28,6 @@ func (e *EmbyService) Item(ctx context.Context, mediaID, userID string) (map[str
if err := e.mergeRemoteUserData(ctx, userID, out); err != nil {
return nil, err
}
if favorite, _ := IsUserFavorite(ctx, e.repo, userID, mediaID); favorite {
userData, _ := out["UserData"].(map[string]any)
if userData == nil {
userData = map[string]any{}
out["UserData"] = userData
}
userData["IsFavorite"] = true
}
return out, nil
}
if lib, err := e.repo.Library.FindByID(ctx, mediaID); err != nil {
@@ -112,9 +101,6 @@ func (e *EmbyService) LatestItems(ctx context.Context, userID, parentID string,
if mount == nil || acct == nil {
return nil, nil
}
if !EmbyMountLibraryAllowed(e.mediaVisibility(ctx, userID), mount) {
return nil, nil
}
out, err := e.remote.RemoteLatest(ctx, mount, acct, remoteParent, limit)
if err != nil {
return nil, err
@@ -194,137 +180,6 @@ func (e *EmbyService) ResumeItems(ctx context.Context, userID string, limit int)
return e.resumableItems(ctx, ItemsParams{UserID: userID, Limit: limit})
}
// favoriteItems returns favourited media for Emby clients, including mounted
// remote items stored only in the local favourites table.
func (e *EmbyService) favoriteItems(ctx context.Context, p ItemsParams) (map[string]any, error) {
if p.Limit <= 0 || p.Limit > 500 {
p.Limit = 50
}
if p.StartIndex < 0 {
p.StartIndex = 0
}
if strings.TrimSpace(p.UserID) == "" {
return map[string]any{"Items": []any{}, "TotalRecordCount": int64(0), "StartIndex": p.StartIndex}, nil
}
var favs []model.Favorite
if err := e.repo.DB.WithContext(ctx).
Where("user_id = ?", p.UserID).
Order("created_at desc").
Find(&favs).Error; err != nil {
return nil, err
}
if len(favs) == 0 {
return map[string]any{"Items": []any{}, "TotalRecordCount": int64(0), "StartIndex": p.StartIndex}, nil
}
localIDs := make([]string, 0, len(favs))
for _, fav := range favs {
if !IsEmbyRemoteID(fav.MediaID) {
localIDs = append(localIDs, fav.MediaID)
}
}
byID := map[string]*model.Media{}
if len(localIDs) > 0 {
var medias []model.Media
q := e.repo.DB.WithContext(ctx).Where("id IN ?", localIDs)
q = e.applyUserMediaVisibility(ctx, q, p.UserID)
if err := q.Find(&medias).Error; err != nil {
return nil, err
}
for i := range medias {
byID[medias[i].ID] = &medias[i]
}
}
items := make([]map[string]any, 0, len(favs))
for _, fav := range favs {
if m, ok := byID[fav.MediaID]; ok {
if !favoriteMatchesParent(ctx, e, p.ParentID, fav.MediaID, m.LibraryID, m.SeriesID, nil) {
continue
}
if p.SearchTerm != "" {
needle := strings.ToLower(p.SearchTerm)
if !strings.Contains(strings.ToLower(m.Title), needle) &&
!strings.Contains(strings.ToLower(m.OriginalName), needle) {
continue
}
}
items = append(items, e.itemPayload(ctx, m, true, 0))
continue
}
if e.remote == nil || !IsEmbyRemoteID(fav.MediaID) {
continue
}
mountID, remoteID, _ := DecodeEmbyRemoteID(fav.MediaID)
mount, acct, err := e.remote.ResolveMount(ctx, mountID)
if err != nil || mount == nil || acct == nil {
continue
}
item, err := e.remote.RemoteItem(ctx, mount, acct, remoteID)
if err != nil || item == nil {
continue
}
if !favoriteMatchesParent(ctx, e, p.ParentID, fav.MediaID, "", "", item) {
continue
}
if p.SearchTerm != "" {
needle := strings.ToLower(p.SearchTerm)
name, _ := item["Name"].(string)
orig, _ := item["OriginalTitle"].(string)
if !strings.Contains(strings.ToLower(name), needle) &&
!strings.Contains(strings.ToLower(orig), needle) {
continue
}
}
userData, _ := item["UserData"].(map[string]any)
if userData == nil {
userData = map[string]any{}
item["UserData"] = userData
}
userData["IsFavorite"] = true
items = append(items, item)
}
total := int64(len(items))
if p.StartIndex >= len(items) {
return map[string]any{"Items": []map[string]any{}, "TotalRecordCount": total, "StartIndex": p.StartIndex}, nil
}
end := minInt(p.StartIndex+p.Limit, len(items))
return map[string]any{"Items": items[p.StartIndex:end], "TotalRecordCount": total, "StartIndex": p.StartIndex}, nil
}
func favoriteMatchesParent(ctx context.Context, e *EmbyService, parentID, mediaID, libraryID, seriesID string, remoteItem map[string]any) bool {
if parentID == "" {
return true
}
if libraryID != "" {
if libraryID == parentID || seriesID == parentID {
return true
}
for _, id := range e.mergedLibraryIDs(ctx, parentID) {
if id == libraryID {
return true
}
}
return false
}
if remoteItem == nil {
return false
}
itemParent, _ := remoteItem["ParentId"].(string)
itemSeries, _ := remoteItem["SeriesId"].(string)
if itemParent == parentID || itemSeries == parentID || mediaID == parentID {
return true
}
if !IsEmbyRemoteID(parentID) {
return false
}
wantMountID, _, _ := DecodeEmbyRemoteID(parentID)
gotMountID, _, _ := DecodeEmbyRemoteID(mediaID)
return wantMountID != "" && gotMountID == wantMountID
}
// resumableItems 返回未完成播放进度的媒体(包含本地媒体与挂载的远程媒体),支持分页。
func (e *EmbyService) resumableItems(ctx context.Context, p ItemsParams) (map[string]any, error) {
if p.Limit <= 0 || p.Limit > 100 {
-70
View File
@@ -1,70 +0,0 @@
package service
import (
"encoding/json"
"testing"
"github.com/truewhile/MeBox/internal/model"
)
func TestViewsHidesDisallowedMountedEmbyLibraries(t *testing.T) {
svc := newTestEmbyService(t)
if err := svc.repo.DB.AutoMigrate(&model.EmbyMount{}); err != nil {
t.Fatal(err)
}
local := model.Library{Name: "Local", Path: "/media/local", Type: "movie", Enabled: true}
if err := svc.repo.Library.Create(t.Context(), &local); err != nil {
t.Fatal(err)
}
mount := &model.EmbyMount{
AccountID: "acct-1",
RemoteViewID: "view-1",
RemoteViewName: "Remote Movies",
Enabled: true,
}
if err := svc.repo.EmbyMount.Create(t.Context(), mount); err != nil {
t.Fatal(err)
}
remoteID := EncodeEmbyRemoteID(mount.ID, mount.RemoteViewID)
user := &model.User{Username: "viewer", PasswordHash: "hash", Role: "user"}
allowed, err := json.Marshal([]string{local.ID})
if err != nil {
t.Fatal(err)
}
user.AllowedLibraryIDs = string(allowed)
if err := svc.repo.User.Create(t.Context(), user); err != nil {
t.Fatal(err)
}
// Without a live remote service, remoteViews is empty; assert helper ACL instead
// and that local Views still honor the allow-list.
views, err := svc.Views(t.Context(), user.ID)
if err != nil {
t.Fatalf("Views: %v", err)
}
items := views["Items"].([]map[string]any)
for _, item := range items {
if id, _ := item["Id"].(string); id == remoteID {
t.Fatalf("disallowed remote library should not appear in Views: %#v", item)
}
}
if !EmbyMountLibraryAllowed(MediaVisibility{AllowedLibraryIDs: []string{local.ID, remoteID}}, mount) {
t.Fatal("expected remote library allowed when listed")
}
if EmbyMountLibraryAllowed(MediaVisibility{AllowedLibraryIDs: []string{local.ID}}, mount) {
t.Fatal("expected remote library denied when not listed")
}
}
func TestLibraryIDAllowed(t *testing.T) {
if !LibraryIDAllowed(MediaVisibility{}, "any") {
t.Fatal("empty allow-list should allow all")
}
if LibraryIDAllowed(MediaVisibility{AllowedLibraryIDs: []string{"a"}}, "b") {
t.Fatal("missing id should be denied")
}
if !LibraryIDAllowed(MediaVisibility{AllowedLibraryIDs: []string{"a", "b"}}, "b") {
t.Fatal("listed id should be allowed")
}
}
-3
View File
@@ -24,9 +24,6 @@ func (e *EmbyService) PlaybackInfo(ctx context.Context, mediaID, userID string)
if err != nil {
return nil, ErrEmbyRemoteNotFound
}
if !EmbyMountLibraryAllowed(e.mediaVisibility(ctx, userID), mount) {
return nil, ErrEmbyRemoteNotFound
}
out, err := e.remote.RemotePlaybackInfo(ctx, mount, acct, remoteID, userID)
if err != nil {
return nil, err
+8 -146
View File
@@ -13,7 +13,6 @@ import (
"sort"
"strconv"
"strings"
"sync"
"time"
"go.uber.org/zap"
@@ -301,22 +300,11 @@ func (r *EmbyRemoteService) MapRemoteItemToMedia(ctx context.Context, mount *mod
media.SeasonNum = 0
media.EpisodeNum = 0
}
if mount != nil && strings.TrimSpace(mount.RemoteViewID) != "" {
libID := EncodeEmbyRemoteID(mount.ID, mount.RemoteViewID)
media.DisplayLibraryID = libID
media.LibraryID = libID
libName := strings.TrimSpace(mount.Name)
if libName == "" {
libName = strings.TrimSpace(mount.RemoteViewName)
}
if libName == "" && acct != nil {
libName = acct.Name
} else if acct != nil && acct.Name != "" && !strings.Contains(libName, acct.Name) {
libName = acct.Name + " · " + libName
}
media.LibraryName = libName
media.DisplayLibraryName = libName
}
if mount != nil && strings.TrimSpace(mount.RemoteViewID) != "" {
libID := EncodeEmbyRemoteID(mount.ID, mount.RemoteViewID)
media.DisplayLibraryID = libID
media.LibraryID = libID
}
return media
}
@@ -514,136 +502,10 @@ func (r *EmbyRemoteService) RemoteLatestCards(ctx context.Context, mount *model.
m := r.MapRemoteItemToMedia(ctx, mount, acct, cfg, it)
cards = append(cards, SeriesCard{Key: m.ID, Rep: m, LinkMedia: m, Count: 0})
}
if r.cache != nil {
r.cache.SetJSON(ctx, cacheKey, cards, r.remoteMediaCacheTTL())
}
return cards, nil
if r.cache != nil {
r.cache.SetJSON(ctx, cacheKey, cards, r.remoteMediaCacheTTL())
}
// RemoteSearchMedia 在全部启用的挂载库中并发搜索影视条目(Movie,Series),
// 并将远程结果映射为 model.Media。遵循当前用户的 MediaVisibility 权限规则。
func (r *EmbyRemoteService) RemoteSearchMedia(ctx context.Context, query string, limit int, visibility MediaVisibility) ([]model.Media, error) {
if r == nil {
return nil, nil
}
query = strings.TrimSpace(query)
if query == "" {
return nil, nil
}
if limit <= 0 {
limit = 50
} else if limit > maxMediaSearchLimit {
limit = maxMediaSearchLimit
}
mounts, err := r.ListMounts(ctx)
if err != nil || len(mounts) == 0 {
return nil, err
}
type mountTarget struct {
mount model.EmbyMount
acct *model.StrmAccount
cfg *EmbyRemoteConfig
}
var targets []mountTarget
for _, m := range mounts {
if !m.Enabled {
continue
}
libID := EncodeEmbyRemoteID(m.ID, m.RemoteViewID)
hidden := false
for _, hid := range visibility.HiddenLibraryIDs {
if hid == libID {
hidden = true
break
}
}
if hidden {
continue
}
if len(visibility.AllowedLibraryIDs) > 0 {
allowed := false
for _, aid := range visibility.AllowedLibraryIDs {
if aid == libID {
allowed = true
break
}
}
if !allowed {
continue
}
}
acct := r.AccountByID(ctx, m.AccountID)
if acct == nil {
continue
}
cfg, cfgErr := r.configOf(acct)
if cfgErr != nil {
continue
}
targets = append(targets, mountTarget{mount: m, acct: acct, cfg: cfg})
}
if len(targets) == 0 {
return nil, nil
}
searchCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
sem := make(chan struct{}, 6)
var wg sync.WaitGroup
type searchResult struct {
items []model.Media
}
results := make([]searchResult, len(targets))
for i, t := range targets {
wg.Add(1)
go func(idx int, target mountTarget) {
defer wg.Done()
select {
case sem <- struct{}{}:
defer func() { <-sem }()
case <-searchCtx.Done():
return
}
q := url.Values{}
q.Set("ParentId", target.mount.RemoteViewID)
q.Set("Recursive", "true")
q.Set("SearchTerm", query)
q.Set("IncludeItemTypes", "Movie,Series")
q.Set("Fields", "Overview,Genres,ProviderIds,Path,SeriesPrimaryImage,MediaStreams,MediaSources,DateCreated,PremiereDate,ProductionYear,CommunityRating,CriticRating")
q.Set("Limit", strconv.Itoa(limit))
q.Set("StartIndex", "0")
var body struct {
Items []map[string]any `json:"Items"`
}
if err := r.doGet(searchCtx, target.acct, target.cfg, "/Users/"+url.PathEscape(r.remoteUserID(target.cfg))+"/Items", q, &body); err != nil {
if r.log != nil {
r.log.Warn("remote search failed",
zap.String("mount", target.mount.RemoteViewName), zap.Error(err))
}
return
}
medias := make([]model.Media, 0, len(body.Items))
for _, it := range body.Items {
RewriteEmbyRemoteIDs(it, target.mount.ID)
m := r.MapRemoteItemToMedia(searchCtx, &target.mount, target.acct, target.cfg, it)
medias = append(medias, m)
}
results[idx] = searchResult{items: medias}
}(i, t)
}
wg.Wait()
var out []model.Media
for _, res := range results {
out = append(out, res.items...)
}
return out, nil
return cards, nil
}
// WebStreamURL 远程条目的网页播放地址(302 直连远程 Emby 流端点)。
+2 -118
View File
@@ -2,17 +2,10 @@ package service
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"go.uber.org/zap"
"github.com/truewhile/MeBox/internal/config"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/repository"
)
func TestMapRemoteItemToMediaSortingFields(t *testing.T) {
@@ -68,116 +61,7 @@ func TestMapRemoteItemToMediaCriticRatingFallback(t *testing.T) {
if media.Rating != 9.2 {
t.Fatalf("Rating = %f, want 9.2 from CriticRating", media.Rating)
}
if media.Year != 2022 {
t.Fatalf("Year = %d, want 2022 from PremiereDate", media.Year)
}
}
func TestRemoteSearchMedia(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("SearchTerm") == "碧蓝之海" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"TotalRecordCount": 1,
"Items": []map[string]any{
{
"Id": "156030",
"Name": "碧蓝之海",
"Type": "Series",
"ProductionYear": 2018,
},
},
})
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"TotalRecordCount": 0,
"Items": []map[string]any{},
})
}))
defer server.Close()
db := newServiceTestDB(t, &model.StrmAccount{}, &model.EmbyMount{})
repos := repository.New(db)
svc := NewEmbyRemoteService(&config.Config{}, zap.NewNop(), repos, NewCryptoService("", zap.NewNop()))
rawConfig, _ := json.Marshal(map[string]string{
"url": server.URL,
"token": "fake-token",
})
acct := &model.StrmAccount{
Base: model.Base{ID: "acct-1"},
Name: "test-emby",
Provider: model.StrmProviderEmbyRemote,
Config: string(rawConfig),
Enabled: true,
}
if err := repos.StrmAccount.Create(t.Context(), acct); err != nil {
t.Fatalf("create account: %v", err)
}
mount := &model.EmbyMount{
Base: model.Base{ID: "mount-1"},
AccountID: acct.ID,
RemoteViewID: "view-1",
RemoteViewName: "动漫",
CollectionType: "tvshows",
Enabled: true,
}
if err := repos.EmbyMount.Create(t.Context(), mount); err != nil {
t.Fatalf("create mount: %v", err)
}
// 1. 正常搜索
items, err := svc.RemoteSearchMedia(t.Context(), "碧蓝之海", 10, MediaVisibility{IncludeNSFW: true})
if err != nil {
t.Fatalf("RemoteSearchMedia failed: %v", err)
}
if len(items) != 1 {
t.Fatalf("expected 1 item, got %d", len(items))
}
if items[0].Title != "碧蓝之海" {
t.Fatalf("expected Title '碧蓝之海', got %q", items[0].Title)
}
expectedID := EncodeEmbyRemoteID("mount-1", "156030")
if items[0].ID != expectedID {
t.Fatalf("expected ID %q, got %q", expectedID, items[0].ID)
}
// 2. 搜索不到的内容
notFound, err := svc.RemoteSearchMedia(t.Context(), "其它不存在的剧", 10, MediaVisibility{IncludeNSFW: true})
if err != nil {
t.Fatalf("RemoteSearchMedia failed: %v", err)
}
if len(notFound) != 0 {
t.Fatalf("expected 0 items, got %d", len(notFound))
}
// 3. 白名单过滤:当白名单不包含该挂载虚拟库 ID 时应过滤掉
allowedLibID := "local-lib-1"
filtered, err := svc.RemoteSearchMedia(t.Context(), "碧蓝之海", 10, MediaVisibility{
IncludeNSFW: true,
AllowedLibraryIDs: []string{allowedLibID},
})
if err != nil {
t.Fatalf("RemoteSearchMedia with allowed filter failed: %v", err)
}
if len(filtered) != 0 {
t.Fatalf("expected 0 items due to AllowedLibraryIDs, got %d", len(filtered))
}
// 4. 黑名单过滤:当黑名单包含该挂载虚拟库 ID 时应过滤掉
mountLibID := EncodeEmbyRemoteID("mount-1", "view-1")
hiddenFiltered, err := svc.RemoteSearchMedia(t.Context(), "碧蓝之海", 10, MediaVisibility{
IncludeNSFW: true,
HiddenLibraryIDs: []string{mountLibID},
})
if err != nil {
t.Fatalf("RemoteSearchMedia with hidden filter failed: %v", err)
}
if len(hiddenFiltered) != 0 {
t.Fatalf("expected 0 items due to HiddenLibraryIDs, got %d", len(hiddenFiltered))
if media.Year != 2022 {
t.Fatalf("Year = %d, want 2022 from PremiereDate", media.Year)
}
}
+1 -52
View File
@@ -2,7 +2,6 @@ package service
import (
"context"
"sort"
"strings"
"time"
@@ -126,8 +125,7 @@ func (e *EmbyService) userPayload(u *model.User) map[string]any {
}
// Views 返回 Emby 中"虚拟根目录"——每个 library 一个条目,外加所有启用的
// 远程 Emby 挂载的媒体库(联邦聚合)。顺序遵循用户置顶偏好:置顶库靠前,
// 未置顶保持原有 sort_order / 远程挂载顺序。
// 远程 Emby 挂载的媒体库(联邦聚合)。
func (e *EmbyService) Views(ctx context.Context, userID string) (map[string]any, error) {
libs, err := e.repo.Library.List(ctx)
if err != nil {
@@ -143,60 +141,11 @@ func (e *EmbyService) Views(ctx context.Context, userID string) (map[string]any,
items = append(items, e.libraryAsView(ctx, &l))
}
for _, remote := range e.remoteViews(ctx) {
id, _ := remote["Id"].(string)
if !LibraryIDAllowed(visibility, id) {
continue
}
items = append(items, remote)
}
items = sortViewItemsByPinnedIDs(items, e.pinnedLibraryIDsForUser(ctx, userID))
return map[string]any{"Items": items, "TotalRecordCount": len(items), "StartIndex": 0}, nil
}
func (e *EmbyService) pinnedLibraryIDsForUser(ctx context.Context, userID string) []string {
if e == nil || e.repo == nil || e.repo.User == nil || strings.TrimSpace(userID) == "" {
return nil
}
user, err := e.repo.User.FindByID(ctx, userID)
if err != nil || user == nil {
return nil
}
return user.DecodePinnedLibraryIDs()
}
func sortViewItemsByPinnedIDs(items []map[string]any, pinnedIDs []string) []map[string]any {
if len(items) < 2 || len(pinnedIDs) == 0 {
return items
}
rank := make(map[string]int, len(pinnedIDs))
for i, id := range pinnedIDs {
if id == "" {
continue
}
if _, exists := rank[id]; !exists {
rank[id] = i
}
}
if len(rank) == 0 {
return items
}
sorted := append([]map[string]any(nil), items...)
sort.SliceStable(sorted, func(i, j int) bool {
iID, _ := sorted[i]["Id"].(string)
jID, _ := sorted[j]["Id"].(string)
iRank, iPinned := rank[iID]
jRank, jPinned := rank[jID]
if iPinned != jPinned {
return iPinned
}
if iPinned && jPinned {
return iRank < jRank
}
return false
})
return sorted
}
// remoteViews 返回全部启用挂载的远程媒体库视图(只有显式挂载的库才出现)。
func (e *EmbyService) remoteViews(ctx context.Context) []map[string]any {
if e == nil || e.remote == nil {
+26 -24
View File
@@ -7,17 +7,35 @@ import (
"strings"
"time"
"gorm.io/gorm"
"github.com/truewhile/MeBox/internal/model"
)
// SetFavorite 把 mediaID 标为 userID 的收藏。挂载的远程 Emby 条目会同时写入
// 本地 favourites 表并透传到对应远程服务器,保证网页与第三方 Emby 客户端一致。
// SetFavorite 把 mediaID 标为 userID 的收藏。远程 Emby 条目直接透传到对应
// 服务器(本地不落库)。
func (e *EmbyService) SetFavorite(ctx context.Context, userID, mediaID string, favorite bool) error {
if err := SyncUserFavorite(ctx, e.repo, e.remote, userID, mediaID, favorite); err != nil {
if e.remote != nil && IsEmbyRemoteID(mediaID) {
acctID, remoteID, _ := DecodeEmbyRemoteID(mediaID)
if err := e.ProxyRemoteSetFavorite(ctx, acctID, remoteID, favorite); err != nil {
return err
}
return nil
}
if favorite {
var f model.Favorite
err := e.repo.DB.WithContext(ctx).
Where("user_id = ? AND media_id = ?", userID, mediaID).First(&f).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return e.repo.DB.WithContext(ctx).Create(&model.Favorite{
UserID: userID, MediaID: mediaID,
}).Error
}
return err
}
e.invalidateEmbyItemsCache(ctx)
return nil
return e.repo.DB.WithContext(ctx).
Where("user_id = ? AND media_id = ?", userID, mediaID).
Delete(&model.Favorite{}).Error
}
// MarkPlayed 把 mediaID 标为已看(写一个 100% 进度的 history 行)。
@@ -104,7 +122,8 @@ func (e *EmbyService) RecordProgress(ctx context.Context, userID, mediaID string
}
// mergeRemoteUserData applies the current MeBox user's locally recorded playback
// and favourite state to remote Emby payloads.
// state to remote Emby payloads. Remote metadata remains authoritative unless the
// user has played the item through MeBox.
func (e *EmbyService) mergeRemoteUserData(ctx context.Context, userID string, payload any) error {
if strings.TrimSpace(userID) == "" || payload == nil {
return nil
@@ -133,27 +152,10 @@ func (e *EmbyService) mergeRemoteUserData(ctx context.Context, userID string, pa
for i := range histories {
byMediaID[histories[i].MediaID] = &histories[i]
}
var favs []model.Favorite
if err := e.repo.DB.WithContext(ctx).Where("user_id = ? AND media_id IN ?", userID, ids).Find(&favs).Error; err != nil {
return err
}
favSet := make(map[string]bool, len(favs))
for _, fav := range favs {
favSet[fav.MediaID] = true
}
for _, item := range items {
id, _ := item["Id"].(string)
userData, _ := item["UserData"].(map[string]any)
if h := byMediaID[id]; h != nil {
item["UserData"] = mergedRemoteUserData(userData, h)
userData, _ = item["UserData"].(map[string]any)
}
if favSet[id] {
if userData == nil {
userData = map[string]any{}
item["UserData"] = userData
}
userData["IsFavorite"] = true
item["UserData"] = mergedRemoteUserData(item["UserData"], h)
}
}
return nil
@@ -1,66 +0,0 @@
package service
import (
"encoding/json"
"testing"
"github.com/truewhile/MeBox/internal/model"
)
func TestViewsOrdersPinnedLibrariesFirst(t *testing.T) {
svc := newTestEmbyService(t)
first := model.Library{Name: "AAA", Path: "/media/a", Type: "movie", Enabled: true, SortOrder: 0}
second := model.Library{Name: "BBB", Path: "/media/b", Type: "movie", Enabled: true, SortOrder: 1}
third := model.Library{Name: "CCC", Path: "/media/c", Type: "movie", Enabled: true, SortOrder: 2}
for _, lib := range []*model.Library{&first, &second, &third} {
if err := svc.repo.Library.Create(t.Context(), lib); err != nil {
t.Fatalf("create library: %v", err)
}
}
user := &model.User{Username: "viewer", PasswordHash: "hash", Role: "user"}
pinned, err := json.Marshal([]string{third.ID, first.ID})
if err != nil {
t.Fatal(err)
}
user.PinnedLibraryIDs = string(pinned)
if err := svc.repo.User.Create(t.Context(), user); err != nil {
t.Fatalf("create user: %v", err)
}
views, err := svc.Views(t.Context(), user.ID)
if err != nil {
t.Fatalf("Views: %v", err)
}
items := views["Items"].([]map[string]any)
if len(items) != 3 {
t.Fatalf("expected 3 views, got %d", len(items))
}
got := []string{items[0]["Id"].(string), items[1]["Id"].(string), items[2]["Id"].(string)}
want := []string{third.ID, first.ID, second.ID}
for i := range want {
if got[i] != want[i] {
t.Fatalf("Views order = %v, want %v", got, want)
}
}
}
func TestSortViewItemsByPinnedIDsKeepsUnpinnedOrder(t *testing.T) {
items := []map[string]any{
{"Id": "a", "Name": "A"},
{"Id": "b", "Name": "B"},
{"Id": "c", "Name": "C"},
{"Id": "d", "Name": "D"},
}
sorted := sortViewItemsByPinnedIDs(items, []string{"c", "a"})
got := make([]string, len(sorted))
for i, item := range sorted {
got[i] = item["Id"].(string)
}
want := []string{"c", "a", "b", "d"}
for i := range want {
if got[i] != want[i] {
t.Fatalf("order = %v, want %v", got, want)
}
}
}
-74
View File
@@ -1,74 +0,0 @@
package service
import (
"context"
"errors"
"gorm.io/gorm"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/repository"
)
// SyncUserFavorite keeps favourite state aligned across the local favourites table
// and the upstream remote Emby server for mounted items.
func SyncUserFavorite(ctx context.Context, repo *repository.Container, remote *EmbyRemoteService, userID, mediaID string, favorite bool) error {
if repo == nil || userID == "" || mediaID == "" {
return errors.New("missing favourite sync inputs")
}
if err := setLocalFavorite(ctx, repo, userID, mediaID, favorite); err != nil {
return err
}
if favorite || IsEmbyRemoteID(mediaID) {
if err := proxyRemoteFavorite(ctx, remote, mediaID, favorite); err != nil {
return err
}
}
return nil
}
// IsUserFavorite reports whether the user has favourited mediaID locally.
func IsUserFavorite(ctx context.Context, repo *repository.Container, userID, mediaID string) (bool, error) {
if repo == nil || userID == "" || mediaID == "" {
return false, nil
}
var count int64
err := repo.DB.WithContext(ctx).Model(&model.Favorite{}).
Where("user_id = ? AND media_id = ?", userID, mediaID).
Count(&count).Error
return count > 0, err
}
func setLocalFavorite(ctx context.Context, repo *repository.Container, userID, mediaID string, favorite bool) error {
if favorite {
var existing model.Favorite
err := repo.DB.WithContext(ctx).
Where("user_id = ? AND media_id = ?", userID, mediaID).
First(&existing).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return repo.DB.WithContext(ctx).Create(&model.Favorite{
UserID: userID,
MediaID: mediaID,
}).Error
}
return err
}
return repo.DB.WithContext(ctx).
Where("user_id = ? AND media_id = ?", userID, mediaID).
Delete(&model.Favorite{}).Error
}
func proxyRemoteFavorite(ctx context.Context, remote *EmbyRemoteService, mediaID string, favorite bool) error {
if remote == nil || !IsEmbyRemoteID(mediaID) {
return nil
}
mountID, remoteItemID, ok := DecodeEmbyRemoteID(mediaID)
if !ok {
return nil
}
_, acct, err := remote.ResolveMount(ctx, mountID)
if err != nil {
return err
}
return remote.ProxySetFavorite(ctx, acct, remoteItemID, favorite)
}
-75
View File
@@ -1,75 +0,0 @@
package service
import (
"context"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/repository"
)
func TestSyncUserFavoriteWritesLocalForRemoteID(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.Favorite{}); err != nil {
t.Fatal(err)
}
repos := repository.New(db)
userID := "user-1"
remoteMediaID := EncodeEmbyRemoteID("mount-1", "remote-item-1")
if err := SyncUserFavorite(context.Background(), repos, nil, userID, remoteMediaID, true); err != nil {
t.Fatalf("SyncUserFavorite favorite: %v", err)
}
favorite, err := IsUserFavorite(context.Background(), repos, userID, remoteMediaID)
if err != nil {
t.Fatalf("IsUserFavorite: %v", err)
}
if !favorite {
t.Fatal("expected remote favourite to be stored locally")
}
if err := SyncUserFavorite(context.Background(), repos, nil, userID, remoteMediaID, false); err != nil {
t.Fatalf("SyncUserFavorite unfavorite: %v", err)
}
favorite, err = IsUserFavorite(context.Background(), repos, userID, remoteMediaID)
if err != nil {
t.Fatalf("IsUserFavorite after delete: %v", err)
}
if favorite {
t.Fatal("expected remote favourite to be removed locally")
}
}
func TestFavoriteItemsIncludesRemoteFavourites(t *testing.T) {
db := newServiceTestDB(t, &model.User{}, &model.Library{}, &model.Media{}, &model.Favorite{})
repos := repository.New(db)
viewer := &model.User{Username: "viewer", PasswordHash: "hash", Role: "user"}
if err := repos.User.Create(t.Context(), viewer); err != nil {
t.Fatal(err)
}
remoteMediaID := EncodeEmbyRemoteID("mount-1", "remote-item-1")
if err := db.Create(&model.Favorite{UserID: viewer.ID, MediaID: remoteMediaID}).Error; err != nil {
t.Fatal(err)
}
svc := &EmbyService{repo: repos}
out, err := svc.favoriteItems(t.Context(), ItemsParams{UserID: viewer.ID, Limit: 50})
if err != nil {
t.Fatalf("favoriteItems: %v", err)
}
total, _ := out["TotalRecordCount"].(int64)
if total != 0 {
// Without a wired remote service hydration is skipped, but local-only path
// should not error and should not count unavailable remote rows.
items, _ := out["Items"].([]map[string]any)
if len(items) != 0 {
t.Fatalf("expected no hydrated remote rows without remote service, got %#v", out)
}
}
}
-41
View File
@@ -44,11 +44,6 @@ func paginateMediaItems(items []MediaItem, page, pageSize int) []MediaItem {
return items[start:end]
}
// PaginateMediaItems 导出分页辅助函数。
func PaginateMediaItems(items []MediaItem, page, pageSize int) []MediaItem {
return paginateMediaItems(items, page, pageSize)
}
func firstMediaItems(items []MediaItem, limit int) []MediaItem {
if len(items) == 0 {
return nil
@@ -65,11 +60,6 @@ func firstMediaItems(items []MediaItem, limit int) []MediaItem {
return items[:limit]
}
// FirstMediaItems 导出截取前 N 项辅助函数。
func FirstMediaItems(items []MediaItem, limit int) []MediaItem {
return firstMediaItems(items, limit)
}
func groupMediaVersions(items []model.Media) []MediaItem {
if len(items) == 0 {
return nil
@@ -114,17 +104,7 @@ func groupMediaVersions(items []model.Media) []MediaItem {
return out
}
// GroupMediaVersions 导出多版本分组函数。
func GroupMediaVersions(items []model.Media) []MediaItem {
return groupMediaVersions(items)
}
func mediaVersionGroupKey(m model.Media) string {
// 远程 Emby 挂载条目保持独立,不与其它远程条目或本地条目折叠合并。
if IsEmbyRemoteID(m.ID) {
return fmt.Sprintf("embyremote:%s", m.ID)
}
if m.SeasonNum > 0 || m.EpisodeNum > 0 {
switch {
case m.TMDbID > 0:
@@ -151,32 +131,14 @@ func mediaVersionGroupKey(m model.Media) string {
fmt.Sprintf("%d:%d", m.SeasonNum, m.EpisodeNum),
}, "|")
}
libKey := strings.ToLower(strings.TrimSpace(m.LibraryID))
if libKey == "" {
libKey = strings.ToLower(strings.TrimSpace(m.DisplayLibraryID))
}
switch {
case m.TMDbID > 0:
if libKey != "" {
return fmt.Sprintf("movie:%s:tmdb:%d", libKey, m.TMDbID)
}
return fmt.Sprintf("tmdb:%d", m.TMDbID)
case m.BangumiID > 0:
if libKey != "" {
return fmt.Sprintf("movie:%s:bangumi:%d", libKey, m.BangumiID)
}
return fmt.Sprintf("bangumi:%d", m.BangumiID)
case strings.TrimSpace(m.DoubanID) != "":
if libKey != "" {
return fmt.Sprintf("movie:%s:douban:%s", libKey, strings.ToLower(strings.TrimSpace(m.DoubanID)))
}
return "douban:" + strings.ToLower(strings.TrimSpace(m.DoubanID))
case strings.TrimSpace(m.TheTVDBID) != "":
if libKey != "" {
return fmt.Sprintf("movie:%s:thetvdb:%s", libKey, strings.ToLower(strings.TrimSpace(m.TheTVDBID)))
}
return "thetvdb:" + strings.ToLower(strings.TrimSpace(m.TheTVDBID))
}
title := firstNonEmpty(m.OriginalName, m.Title)
@@ -196,9 +158,6 @@ func mediaVersionGroupKey(m model.Media) string {
if year <= 0 {
_, year = CleanQuery(m.Path)
}
if libKey != "" {
return fmt.Sprintf("movie:%s:%s:%d", libKey, title, year)
}
return fmt.Sprintf("movie:%s:%d", title, year)
}
-46
View File
@@ -218,49 +218,3 @@ func TestSearchMediaVisiblePageGroupedPaginatesAfterVersionGrouping(t *testing.T
t.Fatalf("primary version = %q, want %q", page[0].Media.Path, rows[0].Path)
}
}
func TestGroupMediaVersionsDoesNotMergeDifferentRemoteSeries(t *testing.T) {
// 模拟来自两个不同挂载库(如 00 新番连载 与 2018 动漫)的同名剧集《碧蓝之海》
season1 := model.Media{
Base: model.Base{ID: EncodeEmbyRemoteID("mount-1", "156019")},
LibraryID: EncodeEmbyRemoteID("mount-1", "view-1"),
Title: "碧蓝之海",
Year: 2018,
LibraryName: "2018 动漫",
}
season2 := model.Media{
Base: model.Base{ID: EncodeEmbyRemoteID("mount-2", "156030")},
LibraryID: EncodeEmbyRemoteID("mount-2", "view-2"),
Title: "碧蓝之海",
Year: 2024,
LibraryName: "00 新番连载",
}
grouped := groupMediaVersions([]model.Media{season1, season2})
if len(grouped) != 2 {
t.Fatalf("expected 2 separate groups for different remote series/libraries, got %d: %#v", len(grouped), grouped)
}
if grouped[0].Title != "碧蓝之海" || grouped[1].Title != "碧蓝之海" {
t.Fatalf("expected both titles to be '碧蓝之海'")
}
}
func TestGroupMediaVersionsDoesNotMergeAcrossDifferentLibrariesForMovies(t *testing.T) {
movieLib1 := model.Media{
Base: model.Base{ID: "m-1"},
LibraryID: "lib-1",
Title: "碧蓝之海",
Year: 2018,
}
movieLib2 := model.Media{
Base: model.Base{ID: "m-2"},
LibraryID: "lib-2",
Title: "碧蓝之海",
Year: 2018,
}
grouped := groupMediaVersions([]model.Media{movieLib1, movieLib2})
if len(grouped) != 2 {
t.Fatalf("expected 2 separate groups for movies in different libraries, got %d", len(grouped))
}
}
+1 -14
View File
@@ -159,20 +159,7 @@ func (p *PlaybackService) RecentHistory(ctx context.Context, userID string, limi
// ToggleFavourite flips the favourite flag and reports the new state.
func (p *PlaybackService) ToggleFavourite(ctx context.Context, userID, mediaID string) (bool, error) {
current, err := IsUserFavorite(ctx, p.repo, userID, mediaID)
if err != nil {
return false, err
}
next := !current
if err := p.SetFavourite(ctx, userID, mediaID, next); err != nil {
return false, err
}
return next, nil
}
// SetFavourite sets favourite state for a media item.
func (p *PlaybackService) SetFavourite(ctx context.Context, userID, mediaID string, favorite bool) error {
return SyncUserFavorite(ctx, p.repo, p.remote, userID, mediaID, favorite)
return p.repo.Favorite.Toggle(ctx, userID, mediaID)
}
// ListFavourites returns every favourited media for a user.
-120
View File
@@ -3,7 +3,6 @@ package service
import (
"context"
"encoding/json"
"errors"
"strings"
@@ -82,125 +81,6 @@ func (p *ProfileService) UpdateProfile(ctx context.Context, userID string, patch
return p.repo.User.FindByID(ctx, userID)
}
// GetPinnedLibraryIDs returns the user's pinned library IDs, filtered to libraries
// they can still access.
func (p *ProfileService) GetPinnedLibraryIDs(ctx context.Context, userID string) ([]string, error) {
user, err := p.repo.User.FindByID(ctx, userID)
if err != nil {
return nil, err
}
if user == nil {
return nil, errors.New("user not found")
}
visibility := UserDefaultMediaVisibility(ctx, p.repo, userID)
accessible, err := p.accessibleLibraryIDSet(ctx, visibility)
if err != nil {
return nil, err
}
return filterPinnedLibraryIDs(user.DecodePinnedLibraryIDs(), accessible), nil
}
// SetPinnedLibraryIDs persists the user's pinned library order after filtering to
// accessible, enabled libraries.
func (p *ProfileService) SetPinnedLibraryIDs(ctx context.Context, userID string, ids []string) ([]string, error) {
if userID == "" {
return nil, errors.New("missing user id")
}
user, err := p.repo.User.FindByID(ctx, userID)
if err != nil {
return nil, err
}
if user == nil {
return nil, errors.New("user not found")
}
visibility := UserDefaultMediaVisibility(ctx, p.repo, userID)
accessible, err := p.accessibleLibraryIDSet(ctx, visibility)
if err != nil {
return nil, err
}
normalized := filterPinnedLibraryIDs(normalizePinnedLibraryIDs(ids), accessible)
if normalized == nil {
normalized = []string{}
}
raw, err := json.Marshal(normalized)
if err != nil {
return nil, err
}
if err := p.repo.User.UpdateFields(ctx, userID, map[string]any{
"pinned_library_ids": string(raw),
}); err != nil {
return nil, err
}
return normalized, nil
}
func (p *ProfileService) accessibleLibraryIDSet(ctx context.Context, visibility MediaVisibility) (map[string]struct{}, error) {
libs, err := p.repo.Library.List(ctx)
if err != nil {
return nil, err
}
out := make(map[string]struct{})
for _, lib := range libs {
if !lib.Enabled {
continue
}
if !LibraryVisibleForUser(ctx, p.repo, lib, visibility) {
continue
}
out[lib.ID] = struct{}{}
}
// Mounted Emby libraries are not rows in the local libraries table; their
// web IDs are embyremote~{mountID}~{remoteViewID}. Include enabled mounts
// from the mount table so pinning them does not get stripped (and so a
// pin-save that includes remotes cannot accidentally wipe local pins).
if p.repo.EmbyMount != nil {
mounts, err := p.repo.EmbyMount.List(ctx)
if err != nil {
return nil, err
}
for _, mount := range mounts {
if !mount.Enabled || strings.TrimSpace(mount.RemoteViewID) == "" {
continue
}
out[EncodeEmbyRemoteID(mount.ID, mount.RemoteViewID)] = struct{}{}
}
}
return out, nil
}
func normalizePinnedLibraryIDs(ids []string) []string {
if len(ids) == 0 {
return nil
}
seen := make(map[string]struct{}, len(ids))
out := make([]string, 0, len(ids))
for _, id := range ids {
trimmed := strings.TrimSpace(id)
if trimmed == "" {
continue
}
if _, ok := seen[trimmed]; ok {
continue
}
seen[trimmed] = struct{}{}
out = append(out, trimmed)
}
return out
}
func filterPinnedLibraryIDs(ids []string, accessible map[string]struct{}) []string {
if len(ids) == 0 {
return nil
}
out := make([]string, 0, len(ids))
for _, id := range ids {
if _, ok := accessible[id]; ok {
out = append(out, id)
}
}
return out
}
// AdminUpdateRole lets administrators promote / demote another user. The
// caller is expected to gate the route with AdminRequired.
func (p *ProfileService) AdminUpdateRole(ctx context.Context, userID, role string) (*model.User, error) {
-123
View File
@@ -1,123 +0,0 @@
package service
import (
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/repository"
"go.uber.org/zap"
)
func TestProfilePinnedLibrariesFiltersInaccessibleAndPreservesOrder(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.User{}, &model.Library{}, &model.EmbyMount{}); err != nil {
t.Fatal(err)
}
repos := repository.New(db)
svc := NewProfileService(zap.NewNop(), repos)
user := &model.User{Username: "viewer", PasswordHash: "hash", Role: "user"}
if err := repos.User.Create(t.Context(), user); err != nil {
t.Fatal(err)
}
libA := &model.Library{Name: "Movies", Path: "/media/movies", Type: "movie", Enabled: true}
libB := &model.Library{Name: "TV", Path: "/media/tv", Type: "tv", Enabled: true}
libHidden := &model.Library{Name: "Adult", Path: "/media/adult", Type: "movie", Enabled: true}
for _, lib := range []*model.Library{libA, libB, libHidden} {
if err := repos.Library.Create(t.Context(), lib); err != nil {
t.Fatal(err)
}
}
if err := repos.User.UpdateFields(t.Context(), user.ID, map[string]any{
"allowed_library_ids": `["` + libA.ID + `","` + libB.ID + `"]`,
}); err != nil {
t.Fatal(err)
}
got, err := svc.SetPinnedLibraryIDs(t.Context(), user.ID, []string{
libB.ID, libHidden.ID, libA.ID, libB.ID, "missing",
})
if err != nil {
t.Fatalf("SetPinnedLibraryIDs: %v", err)
}
want := []string{libB.ID, libA.ID}
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("SetPinnedLibraryIDs = %v, want %v", got, want)
}
loaded, err := svc.GetPinnedLibraryIDs(t.Context(), user.ID)
if err != nil {
t.Fatalf("GetPinnedLibraryIDs: %v", err)
}
if len(loaded) != len(want) || loaded[0] != want[0] || loaded[1] != want[1] {
t.Fatalf("GetPinnedLibraryIDs = %v, want %v", loaded, want)
}
}
func TestProfilePinnedLibrariesKeepsMountedEmbyAndLocalPins(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.User{}, &model.Library{}, &model.EmbyMount{}); err != nil {
t.Fatal(err)
}
repos := repository.New(db)
svc := NewProfileService(zap.NewNop(), repos)
user := &model.User{Username: "viewer", PasswordHash: "hash", Role: "user"}
if err := repos.User.Create(t.Context(), user); err != nil {
t.Fatal(err)
}
local := &model.Library{Name: "Movies", Path: "/media/movies", Type: "movie", Enabled: true}
if err := repos.Library.Create(t.Context(), local); err != nil {
t.Fatal(err)
}
mount := &model.EmbyMount{
AccountID: "acct-1",
RemoteViewID: "view-42",
RemoteViewName: "Remote Movies",
Enabled: true,
}
if err := repos.EmbyMount.Create(t.Context(), mount); err != nil {
t.Fatal(err)
}
remoteID := EncodeEmbyRemoteID(mount.ID, mount.RemoteViewID)
disabled := &model.EmbyMount{
AccountID: "acct-1",
RemoteViewID: "view-99",
Enabled: true,
}
if err := repos.EmbyMount.Create(t.Context(), disabled); err != nil {
t.Fatal(err)
}
if err := db.Model(disabled).Update("enabled", false).Error; err != nil {
t.Fatal(err)
}
disabledID := EncodeEmbyRemoteID(disabled.ID, disabled.RemoteViewID)
got, err := svc.SetPinnedLibraryIDs(t.Context(), user.ID, []string{
local.ID, remoteID, disabledID, "embyremote~missing~view",
})
if err != nil {
t.Fatalf("SetPinnedLibraryIDs: %v", err)
}
want := []string{local.ID, remoteID}
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("SetPinnedLibraryIDs = %v, want %v", got, want)
}
loaded, err := svc.GetPinnedLibraryIDs(t.Context(), user.ID)
if err != nil {
t.Fatalf("GetPinnedLibraryIDs: %v", err)
}
if len(loaded) != len(want) || loaded[0] != want[0] || loaded[1] != want[1] {
t.Fatalf("GetPinnedLibraryIDs = %v, want %v", loaded, want)
}
}
-4
View File
@@ -345,10 +345,6 @@ func (s *ScraperService) ClearCanceledScrapeTasks(ctx context.Context) (int64, e
return s.repo.ScrapeTask.ClearCanceled(ctx)
}
func (s *ScraperService) ClearFailedScrapeTasks(ctx context.Context) (int64, error) {
return s.repo.ScrapeTask.ClearFailed(ctx)
}
func (s *ScraperService) RetryAllFailedScrapeTasks(ctx context.Context) (int64, error) {
return s.repo.ScrapeTask.RetryAllFailed(ctx)
}
-1
View File
@@ -15,7 +15,6 @@ import (
// Container 持有在启动时初始化的每个服务。Handler 接收指向它的指针并选择相关字段。
type Container struct {
Version string
Cfg *config.Config
Log *zap.Logger
Repo *repository.Container
+6 -7
View File
@@ -27,13 +27,12 @@ func newServiceContainer(cfg *config.Config, log *zap.Logger, repos *repository.
cfg: cfg,
log: log,
repos: repos,
version: normalizeSystemUpdateVersion(version),
c: &Container{
Version: normalizeSystemUpdateVersion(version),
Cfg: cfg,
Log: log,
Repo: repos,
},
version: normalizeSystemUpdateVersion(version),
c: &Container{
Cfg: cfg,
Log: log,
Repo: repos,
},
}
builder.startRealtimeServices()
builder.initProviderServices()
-10
View File
@@ -610,21 +610,11 @@ func (s *StrmService) ClearCanceledDownloadTasks(ctx context.Context) (int64, er
return s.repo.StrmDownload.ClearCanceled(ctx)
}
// ClearFailedDownloadTasks 清空全部已失败的下载记录,返回删除数量。
func (s *StrmService) ClearFailedDownloadTasks(ctx context.Context) (int64, error) {
return s.repo.StrmDownload.ClearFailed(ctx)
}
// ClearCanceledUploadTasks 清空全部已取消的上传记录,返回删除数量。
func (s *StrmService) ClearCanceledUploadTasks(ctx context.Context) (int64, error) {
return s.repo.StrmUpload.ClearCanceled(ctx)
}
// ClearFailedUploadTasks 清空全部已失败的上传记录,返回删除数量。
func (s *StrmService) ClearFailedUploadTasks(ctx context.Context) (int64, error) {
return s.repo.StrmUpload.ClearFailed(ctx)
}
// ClearDoneUploadTasks 清空全部已完成上传记录,返回删除数量。
func (s *StrmService) ClearDoneUploadTasks(ctx context.Context) (int64, error) {
return s.repo.StrmUpload.ClearDone(ctx)
+11 -30
View File
@@ -131,39 +131,20 @@ func DecodeAllowedLibraryIDs(raw string) []string {
return out
}
// LibraryIDAllowed reports whether libraryID is permitted by the allow-list.
// An empty AllowedLibraryIDs means unrestricted access.
func LibraryIDAllowed(visibility MediaVisibility, libraryID string) bool {
if len(visibility.AllowedLibraryIDs) == 0 {
return true
}
for _, id := range visibility.AllowedLibraryIDs {
if id == libraryID {
return true
}
}
return false
}
// EmbyMountLibraryID is the web/Emby library id for a mounted remote view.
func EmbyMountLibraryID(mount *model.EmbyMount) string {
if mount == nil {
return ""
}
return EncodeEmbyRemoteID(mount.ID, mount.RemoteViewID)
}
// EmbyMountLibraryAllowed reports whether a mounted Emby library is allowed for
// the given visibility policy.
func EmbyMountLibraryAllowed(visibility MediaVisibility, mount *model.EmbyMount) bool {
return LibraryIDAllowed(visibility, EmbyMountLibraryID(mount))
}
// LibraryVisibleForUser applies profile library limits and adult-directory
// hiding to a library card/folder.
func LibraryVisibleForUser(ctx context.Context, repo *repository.Container, lib model.Library, visibility MediaVisibility) bool {
if !LibraryIDAllowed(visibility, lib.ID) {
return false
if len(visibility.AllowedLibraryIDs) > 0 {
found := false
for _, id := range visibility.AllowedLibraryIDs {
if id == lib.ID {
found = true
break
}
}
if !found {
return false
}
}
if visibility.IncludeNSFW {
return true
+3 -7
View File
@@ -1,4 +1,4 @@
import { api, MIGRATION_REQUEST_TIMEOUT } from './client'
import { api } from './client'
import type { AccessLog, Setting, User } from '../types'
export interface DatabaseStatus {
@@ -137,12 +137,8 @@ export const adminAPI = {
testDatabaseConnection: (payload: DatabaseConnectionPayload) =>
api.post<PostgresTestResult>('/admin/database/test', payload).then((r) => r.data),
migrateDatabase: (payload: DatabaseConnectionPayload) =>
api
.post<DatabaseMigrationResult>('/admin/database/migrate', payload, {
timeout: MIGRATION_REQUEST_TIMEOUT,
})
.then((r) => r.data),
migrateDatabase: (payload: DatabaseConnectionPayload) =>
api.post<DatabaseMigrationResult>('/admin/database/migrate', payload).then((r) => r.data),
saveDatabaseConfig: (payload: DatabaseConnectionPayload) =>
api.post<{ message: string; type: string }>('/admin/database/save-config', payload).then((r) => r.data),
-1
View File
@@ -12,7 +12,6 @@ export const api = axios.create({
export const LONG_REQUEST_TIMEOUT = 120_000
export const BATCH_REQUEST_TIMEOUT = 300_000
export const MIGRATION_REQUEST_TIMEOUT = 600_000
// Flag to prevent multiple simultaneous refresh attempts
let isRefreshing = false
-6
View File
@@ -12,12 +12,6 @@ export const profileAPI = {
}) =>
api.patch<User>('/me', patch).then((r) => r.data),
getPinnedLibraries: () =>
api.get<{ library_ids: string[] }>('/me/pinned-libraries').then((r) => r.data.library_ids ?? []),
setPinnedLibraries: (libraryIds: string[]) =>
api.put<{ library_ids: string[] }>('/me/pinned-libraries', { library_ids: libraryIds }).then((r) => r.data.library_ids ?? []),
adminUpdateRole: (id: string, role: 'admin' | 'user') =>
api.patch<User>(`/admin/users/${id}/role`, { role }).then((r) => r.data),
}
-3
View File
@@ -39,9 +39,6 @@ export const scraperAPI = {
clearCanceled: () =>
api.post<{ deleted: number }>('/admin/scraper/queue/clear-canceled').then((r) => r.data),
clearFailed: () =>
api.post<{ deleted: number }>('/admin/scraper/queue/clear-failed').then((r) => r.data),
retryFailed: () =>
api.post<{ retried: number }>('/admin/scraper/queue/retry-failed').then((r) => r.data),
-6
View File
@@ -159,9 +159,6 @@ export const strmAPI = {
clearCanceledDownloads: () =>
api.post<{ deleted: number }>('/admin/strm/downloads/clear-canceled').then((r) => r.data),
clearFailedDownloads: () =>
api.post<{ deleted: number }>('/admin/strm/downloads/clear-failed').then((r) => r.data),
retryFailedDownloads: () =>
api.post<{ retried: number }>('/admin/strm/downloads/retry-failed').then((r) => r.data),
@@ -199,9 +196,6 @@ export const strmAPI = {
clearCanceledUploads: () =>
api.post<{ deleted: number }>('/admin/strm/uploads/clear-canceled').then((r) => r.data),
clearFailedUploads: () =>
api.post<{ deleted: number }>('/admin/strm/uploads/clear-failed').then((r) => r.data),
retryFailedUploads: () =>
api.post<{ retried: number }>('/admin/strm/uploads/retry-failed').then((r) => r.data),
}
@@ -278,19 +278,12 @@ export function AdminUserLibrariesDialog({
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-semibold text-ink-600">
{lib.name}
{lib.is_remote_emby ? (
<span className="ml-1.5 rounded bg-sky-50 px-1.5 py-0.5 text-[10px] font-bold text-sky-700">
Emby 挂载
</span>
) : null}
</p>
<p
className="truncate text-[10px] text-sand-500"
title={lib.is_remote_emby ? lib.remote_source || lib.name : lib.path}
title={lib.path}
>
{lib.is_remote_emby
? `远程 · ${lib.remote_source || 'Emby'}`
: `${lib.type} · ${libraryDisplayPath(lib.path)}`}
{lib.type} · {libraryDisplayPath(lib.path)}
</p>
</div>
</div>
+1 -1
View File
@@ -26,7 +26,7 @@ export function GlobalEvents() {
return
}
if (p.queued) {
toast.loading(String(p.message ?? '媒体库扫描已加入后台队列,会自动入库'), { id })
toast.loading(String(p.message ?? '云盘扫描已加入后台队列,会自动入库'), { id })
return
}
if (p.cloud && p.stage) {
+3 -10
View File
@@ -239,16 +239,9 @@ function LayoutHeaderSearch() {
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<p className="truncate text-xs font-bold text-[var(--app-text)] group-hover:text-brand-500">
{item.title}
</p>
{(item.display_library_name || item.library_name) && (
<span className="shrink-0 text-[9px] px-1.5 py-0.5 rounded bg-[var(--app-panel-elevated)] border border-[var(--app-border)] text-[var(--app-muted)] max-w-[130px] truncate">
{item.display_library_name || item.library_name}
</span>
)}
</div>
<p className="truncate text-xs font-bold text-[var(--app-text)] group-hover:text-brand-500">
{item.title}
</p>
<div className="flex items-center gap-2 text-[10px] text-[var(--app-muted)] mt-0.5">
{item.year > 0 && <span>{item.year}</span>}
{item.rating > 0 && (
+1 -1
View File
@@ -43,9 +43,9 @@ export const LAYOUT_NAV_ITEMS: LayoutNavItem[] = [
{ to: '/queue', label: '任务队列', icon: ListChecks, adminOnly: true },
{ to: '/admin', label: '用户管理', icon: Users, adminOnly: true },
{ to: '/files', label: '文件管理', icon: FolderOpen, adminOnly: true },
{ to: '/settings', label: '系统设置', icon: Settings, adminOnly: true },
{ to: '/emby-mount', label: 'Emby 挂载', icon: Tv, adminOnly: true },
{ to: '/strm', label: 'STRM 管理', icon: FileOutput, adminOnly: true },
{ to: '/settings', label: '系统设置', icon: Settings, adminOnly: true },
]
/** Media browsing links for the mobile drawer when browsing libraries. */
-75
View File
@@ -1,75 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import {
loadPinnedLibraryIds,
savePinnedLibraryIds,
togglePinnedLibraryId,
} from '../utils/pinnedLibraries'
export function usePinnedLibraries() {
const [pinnedIds, setPinnedIds] = useState<string[]>([])
const [loading, setLoading] = useState(true)
const [syncing, setSyncing] = useState(false)
const [loadError, setLoadError] = useState(false)
const loadedRef = useRef(false)
const pinnedIdsRef = useRef<string[]>([])
const syncingRef = useRef(false)
useEffect(() => {
pinnedIdsRef.current = pinnedIds
}, [pinnedIds])
useEffect(() => {
let cancelled = false
setLoading(true)
setLoadError(false)
loadedRef.current = false
loadPinnedLibraryIds()
.then((ids) => {
if (cancelled) return
loadedRef.current = true
pinnedIdsRef.current = ids
setPinnedIds(ids)
setLoadError(false)
})
.catch(() => {
if (cancelled) return
loadedRef.current = false
setLoadError(true)
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [])
const togglePin = useCallback(async (libraryId: string) => {
if (!loadedRef.current || loading || loadError || syncingRef.current) return
// Compute the next list synchronously from a ref. Do NOT capture the next
// value inside setState updater callbacks — React may defer those, leaving
// optimistic as [] and wiping the server-side pin list.
const previous = pinnedIdsRef.current
const optimistic = togglePinnedLibraryId(previous, libraryId)
pinnedIdsRef.current = optimistic
setPinnedIds(optimistic)
syncingRef.current = true
setSyncing(true)
try {
const saved = await savePinnedLibraryIds(optimistic)
pinnedIdsRef.current = saved
setPinnedIds(saved)
} catch {
pinnedIdsRef.current = previous
setPinnedIds(previous)
} finally {
syncingRef.current = false
setSyncing(false)
}
}, [loading, loadError])
return { pinnedIds, loading, syncing, loadError, togglePin }
}
-330
View File
@@ -1,330 +0,0 @@
import { useEffect, useState } from 'react'
import {
BookOpen,
Check,
Copy,
Cpu,
Database,
ExternalLink,
Film,
FolderOpen,
Github,
HardDrive,
Info,
Layers,
ListChecks,
MessageSquare,
Play,
Server,
Sparkles,
Tag,
Tv,
Users,
} from 'lucide-react'
import toast from 'react-hot-toast'
import { systemAPI } from '../api/system'
type SystemInfo = {
name: string
version: string
go: string
os: string
arch: string
data_dir: string
cache_dir: string
}
const GITHUB_REPO_URL = 'https://github.com/truewhile/MeBox'
const MODULE_GUIDES = [
{
icon: Film,
title: '媒体库管理',
badge: '核心存储',
description:
'支持创建电影、电视剧、动漫、纪录片等多种类型媒体库。支持本地目录与网络挂载路径,集成文件监控(Inotify / 定时轮询),新增与修改文件自动入库。剧集支持智能按季、集归类与多版本合并。',
},
{
icon: Sparkles,
title: '智能刮削与元数据',
badge: '海报与信息',
description:
'内置 TMDb、Bangumi、TheTVDB、豆瓣等元数据源。入库时自动识别文件名匹配海报、背景图、演职员及中文简介。支持手动精确搜刮、重命名整理规则、识别词过滤(过滤广告词与压制组标签)及 NFO 本地文件导出。',
},
{
icon: Play,
title: '流媒体播放与转码',
badge: '播放引擎',
description:
'现代化 Web 播放器支持原画直连(Direct Play)与 HLS 实时兼容转码。支持 Intel QSV、NVIDIA NVENC、VAAPI 等硬件加速。支持内嵌与外挂字幕(ASS/SRT/VTT)渲染、多音轨切换,并支持一键调用 PotPlayer、VLC、IINA、Infuse 等本地播放器。',
},
{
icon: MessageSquare,
title: '实时弹幕系统',
badge: '弹幕互动',
description:
'播放时自动/手动匹配对应剧集的弹幕源。支持设置弹幕字号、滚动速度、透明度、屏幕占比限制(1/4屏、半屏、全屏)及防遮挡字幕开关,打造沉浸式的观影交流体验。',
},
{
icon: Tv,
title: 'Emby 挂载与远程同步',
badge: '扩展聚合',
description:
'支持以客户端形式直接挂载远程 Emby 媒体服务器,无需本地下载即可无缝串流播放远程资源,同时保留本地的刮削、播放历史、收藏与弹幕能力,实现多端影视资源大聚合。',
},
{
icon: Layers,
title: 'STRM 管理与云盘转存',
badge: '海量存储',
description:
'针对 115、阿里云盘、OpenList 等网盘挂载场景,提供批量的 STRM 索引文件生成与下载队列管理。本地仅占用微量磁盘空间,即可享受数百 TB 云端影视的高速直链秒播。',
},
{
icon: FolderOpen,
title: '内置文件管理器',
badge: '资源维护',
description:
'内置可视化文件浏览器,支持对本地媒体目录及云盘目录进行直接浏览、批量移动、重命名及删除操作,方便快速定位未刮削或命名不规范的文件并进行整理。',
},
{
icon: ListChecks,
title: '后台任务队列',
badge: '异步作业',
description:
'全生命周期监控媒体扫描、元数据批量刮削、STRM 生成及音视频探测等后台异步任务。实时展示队列进度百分比、执行状态及错误日志,支持手动重试与任务取消。',
},
{
icon: Users,
title: '多用户与权限体系',
badge: '安全访问',
description:
'支持管理员与普通用户角色。管理员可精细化控制各账号的访问边界,包括特定媒体库可见性(如敏感/Adult媒体库)、是否允许调用外部播放器、是否允许下载原始文件等。',
},
{
icon: Database,
title: '数据库与系统设置',
badge: '底层基建',
description:
'支持轻量级单文件 SQLite 与高并发 PostgreSQL 数据库,并提供一键平滑数据热迁移工具;支持自定义 HTTPS 证书绑定、转码缓存自动清理及实时系统资源监控。',
},
]
export function AboutSettingsPanel() {
const [info, setInfo] = useState<SystemInfo | null>(null)
const [loading, setLoading] = useState(true)
const [copied, setCopied] = useState(false)
useEffect(() => {
systemAPI
.info()
.then((res) => {
setInfo({
name: res.name || 'MeBox',
version: res.version || '0.1.0',
go: res.go || '',
os: res.os || '',
arch: res.arch || '',
data_dir: res.data_dir || '',
cache_dir: res.cache_dir || '',
})
})
.catch(() => {
setInfo({
name: 'MeBox',
version: '0.1.0',
go: '',
os: '',
arch: '',
data_dir: '',
cache_dir: '',
})
})
.finally(() => setLoading(false))
}, [])
const handleCopyGitURL = async () => {
try {
await navigator.clipboard.writeText(GITHUB_REPO_URL)
setCopied(true)
toast.success('GitHub 地址已复制到剪贴板')
setTimeout(() => setCopied(false), 2000)
} catch {
toast.error('复制失败,请手动复制')
}
}
return (
<div className="space-y-6">
{/* 顶部概览与项目卡片 */}
<div className="glass-panel overflow-hidden p-6 sm:p-8">
<div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-3">
<h2 className="font-display text-2xl sm:text-3xl font-bold text-ink-600">
MeBox 影音管理系统
</h2>
<span className="inline-flex items-center gap-1.5 rounded-full bg-brand-500/10 px-3 py-1 text-xs font-semibold text-brand-600 border border-brand-500/20">
<Tag size={13} />
{loading ? '加载中...' : `v${info?.version || '0.1.0'}`}
</span>
</div>
<p className="max-w-2xl text-sm leading-relaxed text-sand-600">
MeBox 是一款专为个人与家庭设计的现代化开源媒体库管理与流媒体点播系统。
集媒体资源归纳、智能多源刮削、弹幕交互、海量云盘 STRM 转存与多端播放于一体,让观影体验更轻快自由。
</p>
</div>
{/* 仓库链接操作区 */}
<div className="flex flex-wrap items-center gap-3">
<a
href={GITHUB_REPO_URL}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 rounded-xl bg-ink-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-ink-700 hover:shadow"
>
<Github size={16} />
<span>访问 GitHub 仓库</span>
<ExternalLink size={14} className="opacity-70" />
</a>
<button
type="button"
onClick={handleCopyGitURL}
className="inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white/80 px-4 py-2.5 text-sm font-medium text-ink-600 shadow-sm transition hover:bg-white hover:text-brand-600"
>
{copied ? <Check size={16} className="text-emerald-500" /> : <Copy size={16} />}
<span>{copied ? '已复制' : '复制地址'}</span>
</button>
</div>
</div>
{/* 运行环境规格栏 */}
<div className="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-4 border-t border-gray-200/60 pt-6">
<div className="rounded-xl bg-sand-100/50 p-3.5">
<div className="flex items-center gap-1.5 text-xs text-sand-500">
<Tag size={13} />
<span>系统版本</span>
</div>
<p className="mt-1 font-mono text-sm font-semibold text-ink-600">
{loading ? '...' : info?.version || '0.1.0'}
</p>
</div>
<div className="rounded-xl bg-sand-100/50 p-3.5">
<div className="flex items-center gap-1.5 text-xs text-sand-500">
<Server size={13} />
<span>运行环境</span>
</div>
<p className="mt-1 font-mono text-sm font-semibold text-ink-600">
{loading ? '...' : `${info?.os || 'linux'} / ${info?.arch || 'amd64'}`}
</p>
</div>
<div className="rounded-xl bg-sand-100/50 p-3.5">
<div className="flex items-center gap-1.5 text-xs text-sand-500">
<Cpu size={13} />
<span>Go 运行时</span>
</div>
<p className="mt-1 font-mono text-sm font-semibold text-ink-600">
{loading ? '...' : info?.go || 'go1.x'}
</p>
</div>
<div className="rounded-xl bg-sand-100/50 p-3.5">
<div className="flex items-center gap-1.5 text-xs text-sand-500">
<HardDrive size={13} />
<span>数据目录</span>
</div>
<p className="mt-1 truncate font-mono text-xs font-semibold text-ink-600" title={info?.data_dir}>
{loading ? '...' : info?.data_dir || './data'}
</p>
</div>
</div>
</div>
{/* 快速入门与使用流程 */}
<div className="glass-panel p-6 sm:p-8 space-y-4">
<div className="flex items-center gap-2">
<BookOpen className="text-brand-500" size={20} />
<h3 className="font-display text-lg font-bold text-ink-600">使用说明与快速上手</h3>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="flex flex-col gap-2 rounded-2xl border border-gray-200/80 bg-white/60 p-4 shadow-sm">
<div className="flex items-center gap-2">
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-brand-500 text-xs font-bold text-white">
1
</span>
<span className="font-semibold text-ink-600 text-sm">创建与关联媒体库</span>
</div>
<p className="text-xs leading-relaxed text-sand-500">
在侧边栏进入「媒体库」,点击添加媒体库。选择媒体类型(电影/电视剧),指定服务器上的实际媒体路径或挂载目录,保存后系统将自动创建索引并监控变动。
</p>
</div>
<div className="flex flex-col gap-2 rounded-2xl border border-gray-200/80 bg-white/60 p-4 shadow-sm">
<div className="flex items-center gap-2">
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-brand-500 text-xs font-bold text-white">
2
</span>
<span className="font-semibold text-ink-600 text-sm">智能识别与刮削</span>
</div>
<p className="text-xs leading-relaxed text-sand-500">
扫描入库后,后台服务会自动提取文件名并通过 TMDb / 豆瓣 / Bangumi 等抓取高清海报、演职员与分集信息;如遇特殊命名,可在详情页中一键进行「手动搜刮」。
</p>
</div>
<div className="flex flex-col gap-2 rounded-2xl border border-gray-200/80 bg-white/60 p-4 shadow-sm">
<div className="flex items-center gap-2">
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-brand-500 text-xs font-bold text-white">
3
</span>
<span className="font-semibold text-ink-600 text-sm">多端随心畅享观影</span>
</div>
<p className="text-xs leading-relaxed text-sand-500">
直接在浏览器中享受原画秒开与实时弹幕互动;对于高码率或特殊封装格式,支持开启 HLS 转码播放或直接一键唤醒本地 PotPlayer、Infuse 等外部播放器。
</p>
</div>
</div>
</div>
{/* 各功能模块详细使用说明 */}
<div className="space-y-4">
<div className="flex items-center justify-between px-1">
<div className="flex items-center gap-2">
<Info className="text-brand-500" size={20} />
<h3 className="font-display text-lg font-bold text-ink-600">各功能模块详细说明</h3>
</div>
<span className="text-xs text-sand-500">涵盖系统十大核心子系统</span>
</div>
<div className="grid gap-4 sm:grid-cols-2">
{MODULE_GUIDES.map((mod) => {
const Icon = mod.icon
return (
<div
key={mod.title}
className="group flex flex-col justify-between rounded-2xl border border-gray-200/90 bg-white/70 p-5 shadow-sm transition hover:border-brand-500/40 hover:bg-white hover:shadow-md"
>
<div className="space-y-2.5">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5">
<div className="flex h-9 w-9 items-center justify-center rounded-xl bg-brand-500/10 text-brand-500 transition group-hover:bg-brand-500 group-hover:text-white">
<Icon size={18} />
</div>
<h4 className="font-semibold text-ink-600 text-sm sm:text-base">
{mod.title}
</h4>
</div>
<span className="rounded-md bg-sand-100 px-2 py-0.5 text-[11px] font-medium text-sand-600">
{mod.badge}
</span>
</div>
<p className="text-xs leading-relaxed text-sand-600 sm:text-[13px]">
{mod.description}
</p>
</div>
</div>
)
})}
</div>
</div>
</div>
)
}
+3 -8
View File
@@ -5,8 +5,6 @@ import { historyAPI } from '../api/history'
import type { HistoryItem } from '../api/playback'
import type { Library, Media } from '../types'
import type { SeriesCard } from '../utils/groupSeries'
import { usePinnedLibraries } from '../hooks/usePinnedLibraries'
import { sortByPinnedIds } from '../utils/pinnedLibraries'
import {
ContinueWatchingSection,
HomeCarouselSection,
@@ -24,7 +22,6 @@ export function HomePage() {
const [libraryData, setLibraryData] = useState<Record<string, { cards: SeriesCard[]; items: Media[]; total: number }>>({})
const [history, setHistory] = useState<HistoryItem[]>([])
const [loading, setLoading] = useState(true)
const { pinnedIds } = usePinnedLibraries()
useEffect(() => {
let cancelled = false
@@ -129,8 +126,6 @@ export function HomePage() {
return candidateMedia.slice(0, 10)
}, [libraries, libraryData])
const sortedLibraries = useMemo(() => sortByPinnedIds(libraries, pinnedIds), [libraries, pinnedIds])
const empty =
!loading &&
libraries.length === 0 &&
@@ -155,9 +150,9 @@ export function HomePage() {
{history.length > 0 && <ContinueWatchingSection history={history} />}
{/* 3. 媒体库卡片区 */}
{sortedLibraries.length > 0 && (
{libraries.length > 0 && (
<HomeLibrariesSection
libraries={sortedLibraries}
libraries={libraries}
libraryData={libraryData}
libraryCounts={libraryCounts}
/>
@@ -165,7 +160,7 @@ export function HomePage() {
{/* 4. 各媒体库内容展示行 */}
<div className="space-y-10">
{sortedLibraries.map((lib) => {
{libraries.map((lib) => {
const cards = libraryData[lib.id]?.cards || []
if (cards.length === 0) return null
return (
+5 -6
View File
@@ -3,18 +3,17 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
import { libraryAPI } from '../api/library'
import { toolsAPI } from '../api/tools'
import { openManageLibrariesDialog } from '../components/manageLibrariesDialog'
import { usePinnedLibraries } from '../hooks/usePinnedLibraries'
import {
LibrariesContent,
LibrariesEmptyState,
LibrariesHeader,
} from './LibrariesPageSections'
import type { LibraryPreview } from './librariesPageModel'
import { sortLibraryPreviews } from '../utils/pinnedLibraries'
import { readPinnedLibraryIds, sortLibraryPreviews, togglePinnedLibraryId } from '../utils/pinnedLibraries'
export function LibrariesPage() {
const [previews, setPreviews] = useState<LibraryPreview[]>([])
const { pinnedIds, loading: pinnedLoading, togglePin } = usePinnedLibraries()
const [pinnedIds, setPinnedIds] = useState<string[]>(() => readPinnedLibraryIds())
const [loading, setLoading] = useState(true)
const [repairing, setRepairing] = useState(false)
const [repairEpisodeArtwork, setRepairEpisodeArtwork] = useState(false)
@@ -63,12 +62,12 @@ export function LibrariesPage() {
const sortedPreviews = useMemo(() => sortLibraryPreviews(previews, pinnedIds), [previews, pinnedIds])
const handleTogglePin = useCallback((libraryId: string) => {
void togglePin(libraryId)
}, [togglePin])
setPinnedIds(togglePinnedLibraryId(libraryId))
}, [])
const total = useMemo(() => previews.reduce((sum, preview) => sum + preview.total, 0), [previews])
if (loading || pinnedLoading) {
if (loading) {
return <p className="px-2 py-8 text-sm text-sand-500">媒体库加载中…</p>
}
-17
View File
@@ -9,7 +9,6 @@ import {
MediaDetailMainContent,
MediaDetailMissing,
} from './MediaDetailPageSections'
import { LibrarySeriesEpisodes } from './LibrarySeriesEpisodes'
import { useMediaDetailPageState } from './useMediaDetailPageState'
export function MediaDetailPage() {
@@ -32,7 +31,6 @@ export function MediaDetailPage() {
media={media}
isAdmin={role === 'admin'}
favourite={detail.favourite}
playTargetId={detail.firstPlayableEpisode?.id}
scrapeEpisodeArtwork={detail.scrapeEpisodeArtwork}
onToggleFavourite={detail.toggleFavourite}
onScrapeEpisodeArtworkChange={detail.setScrapeEpisodeArtwork}
@@ -44,21 +42,6 @@ export function MediaDetailPage() {
onExportNFO={detail.exportNFO}
onSoftDelete={detail.softDelete}
/>
{detail.hasEpisodes && (
<div className="relative z-10 px-6 pb-8 sm:px-10 space-y-6">
<div className="divider border-gray-200/60" />
<LibrarySeriesEpisodes
loading={detail.loadingEpisodes}
selectedEpisodes={detail.seasonGroups}
selectedSeason={detail.selectedSeason}
visibleEpisodes={detail.visibleEpisodes}
playbackFrom={`/media/${media.id}`}
onSeasonChange={detail.setSelectedSeason}
/>
</div>
)}
<MediaDetailDialogs
media={media}
manualScrapeOpen={detail.manualScrapeOpen}
+6 -4
View File
@@ -1,11 +1,13 @@
import type { Media } from '../types'
import { mediaLibraryTarget } from '../utils/mediaNavigation'
export function mediaLibraryBackTarget(media: Media): string {
const seriesTarget = mediaLibraryTarget(media)
if (seriesTarget) return seriesTarget
const libraryID = media.display_library_id || media.library_id
if (libraryID) {
return `/library/${encodeURIComponent(libraryID)}`
}
return '/libraries'
if (!libraryID) return ''
return `/library/${encodeURIComponent(libraryID)}`
}
export function mediaDetailScrapeMediaType(media: Media): string | undefined {
+4 -13
View File
@@ -18,7 +18,6 @@ interface MediaDetailPlaybackActionsProps {
media: Media
favourite: boolean
onToggleFavourite: () => void
playTargetId?: string
}
interface MediaDetailMainContentProps extends MediaDetailPlaybackActionsProps {
@@ -94,19 +93,17 @@ export function MediaDetailPlaybackActions({
media,
favourite,
onToggleFavourite,
playTargetId,
}: MediaDetailPlaybackActionsProps) {
const targetId = playTargetId || media.id
return (
<div className="flex flex-wrap gap-3">
<Link to={`/play/${targetId}`} state={{ from: `/media/${media.id}` }} className="btn-primary px-6 py-3.5 shadow-sm">
<Link to={`/play/${media.id}`} state={{ from: `/media/${media.id}` }} className="btn-primary px-6 py-3.5 shadow-sm">
<Play size={16} fill="currentColor" />
<span>立即播放</span>
</Link>
{!isDirectStreamMedia(media) && (
<Link
to={`/play/${targetId}?mode=hls`}
to={`/play/${media.id}?mode=hls`}
state={{ from: `/media/${media.id}` }}
className="btn-outline border-brand-500/30 hover:border-brand-500 text-[#c9954a] hover:bg-brand-50 px-5"
>
@@ -115,7 +112,7 @@ export function MediaDetailPlaybackActions({
</Link>
)}
<ExternalPlayerButton mediaId={targetId} />
<ExternalPlayerButton mediaId={media.id} />
<button
onClick={onToggleFavourite}
@@ -137,7 +134,6 @@ export function MediaDetailMainContent({
media,
isAdmin,
favourite,
playTargetId,
scrapeEpisodeArtwork,
onToggleFavourite,
onScrapeEpisodeArtworkChange,
@@ -157,12 +153,7 @@ export function MediaDetailMainContent({
<MediaDetailMetadata media={media} />
<div className="divider border-gray-200/60" />
<div className="flex flex-col gap-5">
<MediaDetailPlaybackActions
media={media}
favourite={favourite}
onToggleFavourite={onToggleFavourite}
playTargetId={playTargetId}
/>
<MediaDetailPlaybackActions media={media} favourite={favourite} onToggleFavourite={onToggleFavourite} />
{isAdmin && (
<MediaDetailAdminPanel
media={media}
-1
View File
@@ -155,7 +155,6 @@ export function ProfileLibraryAccessField({
}
>
{library.name}
{library.is_remote_emby ? ' · Emby' : ''}
</button>
))}
{libraries.length === 0 && (
+2 -194
View File
@@ -227,13 +227,8 @@ export function ScraperQueuePage({ embedded = false }: { embedded?: boolean }) {
}, [tasks, filter, search])
const counts = snapshot?.counts
const pendingCount = counts?.pending ?? 0
const runningCount = counts?.running ?? 0
const activeTaskCount = pendingCount + runningCount
const doneCount = counts?.done ?? 0
const activeTaskCount = (counts?.pending ?? 0) + (counts?.running ?? 0)
const failedCount = counts?.failed ?? 0
const canceledCount = counts?.canceled ?? 0
const finishedCount = doneCount + failedCount + canceledCount
const allCurrentChecked =
filteredTasks.length > 0 && filteredTasks.every((t) => selectedIds.has(t.id))
@@ -455,7 +450,7 @@ export function ScraperQueuePage({ embedded = false }: { embedded?: boolean }) {
)}
</div>
{selectedIds.size > 0 ? (
{selectedIds.size > 0 && (
<div className="flex flex-wrap items-center gap-2 rounded-xl border border-brand-500/30 bg-primary-400/10 px-3 py-2 text-xs animate-in fade-in zoom-in-95">
<span className="font-bold text-brand-500">已选中 {selectedIds.size} 项</span>
<div className="h-3.5 w-px bg-brand-300/40 mx-1" />
@@ -495,193 +490,6 @@ export function ScraperQueuePage({ embedded = false }: { embedded?: boolean }) {
<X size={13} />
</button>
</div>
) : (
<div className="flex flex-wrap items-center gap-2">
{/* 当前状态专属快捷批量按钮 */}
{filter === 'all' && (
<>
{failedCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={() => runGlobalBatch(() => scraperAPI.retryFailed(), '确定重新入队所有失败任务?')}
className="inline-flex items-center gap-1 rounded-xl border border-brand-500/40 bg-white px-3 py-1.5 text-xs font-semibold text-brand-500 hover:bg-brand-50 disabled:opacity-50"
>
<RefreshCw size={12} />
全部重试 ({failedCount})
</button>
)}
{activeTaskCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={() => runGlobalBatch(() => scraperAPI.cancelPending(), '确定取消所有排队及进行中的刮削任务?')}
className="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-600 hover:bg-amber-50 disabled:opacity-50"
>
<Ban size={12} />
全部取消 ({activeTaskCount})
</button>
)}
{finishedCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={() => runGlobalBatch(() => scraperAPI.clearFinished(), '确定清空所有已完成、失败及取消的历史记录?')}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除 ({finishedCount})
</button>
)}
</>
)}
{(filter === 'pending' || filter === 'running') && (
<button
type="button"
disabled={batchBusy || activeTaskCount === 0}
onClick={() => runGlobalBatch(() => scraperAPI.cancelPending(), '确定取消所有排队及进行中的刮削任务?')}
className="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-600 hover:bg-amber-50 disabled:opacity-50"
>
<Ban size={12} />
全部取消{activeTaskCount > 0 ? ` (${activeTaskCount})` : ''}
</button>
)}
{filter === 'done' && (
<button
type="button"
disabled={batchBusy || doneCount === 0}
onClick={() => runGlobalBatch(() => scraperAPI.clearDone(), '确定清空所有已匹配完成的记录?')}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除{doneCount > 0 ? ` (${doneCount})` : ''}
</button>
)}
{filter === 'failed' && (
<>
<button
type="button"
disabled={batchBusy || failedCount === 0}
onClick={() => runGlobalBatch(() => scraperAPI.retryFailed(), '确定重新入队所有失败任务?')}
className="inline-flex items-center gap-1 rounded-xl border border-brand-500/40 bg-white px-3 py-1.5 text-xs font-semibold text-brand-500 hover:bg-brand-50 disabled:opacity-50"
>
<RefreshCw size={12} />
全部重试{failedCount > 0 ? ` (${failedCount})` : ''}
</button>
<button
type="button"
disabled={batchBusy || failedCount === 0}
onClick={() => runGlobalBatch(() => scraperAPI.clearFailed(), '确定清空所有失败记录?')}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除{failedCount > 0 ? ` (${failedCount})` : ''}
</button>
</>
)}
{filter === 'canceled' && (
<button
type="button"
disabled={batchBusy || canceledCount === 0}
onClick={() => runGlobalBatch(() => scraperAPI.clearCanceled(), '确定清空所有已取消的任务记录?')}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除{canceledCount > 0 ? ` (${canceledCount})` : ''}
</button>
)}
{/* 下拉批量操作菜单:随时可做任意全局操作 */}
<details className="relative inline-block">
<summary className="inline-flex cursor-pointer list-none items-center gap-1.5 rounded-xl border border-gray-200 bg-white px-3 py-1.5 text-xs font-semibold text-ink-100 shadow-sm transition hover:border-gray-300 hover:bg-gray-50 [&::-webkit-details-marker]:hidden">
<Trash2 size={12} className="text-sand-500" />
<span>批量清理</span>
</summary>
<div className="absolute right-0 top-9 z-30 min-w-44 rounded-xl border border-gray-200 bg-white p-1.5 shadow-xl backdrop-blur">
{failedCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(() => scraperAPI.retryFailed(), '确定重新入队所有失败任务?')
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-brand-500 hover:bg-brand-50"
>
<RefreshCw size={13} />
<span>重试所有失败 ({failedCount})</span>
</button>
)}
{activeTaskCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(() => scraperAPI.cancelPending(), '确定取消所有排队及进行中的刮削任务?')
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-amber-600 hover:bg-amber-50"
>
<Ban size={13} />
<span>取消所有进行中 ({activeTaskCount})</span>
</button>
)}
<div className="my-1 border-t border-gray-100" />
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(() => scraperAPI.clearDone(), '确定清空所有已匹配完成的记录?')
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-ink-100 hover:bg-gray-50"
>
<CheckCircle2 size={13} className="text-emerald-500" />
<span>清空已完成记录 ({doneCount})</span>
</button>
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(() => scraperAPI.clearFailed(), '确定清空所有失败的记录?')
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-rose-500 hover:bg-rose-50"
>
<AlertCircle size={13} />
<span>清空失败记录 ({failedCount})</span>
</button>
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(() => scraperAPI.clearCanceled(), '确定清空所有已取消的任务记录?')
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-ink-100 hover:bg-gray-50"
>
<Ban size={13} className="text-amber-500" />
<span>清空已取消记录 ({canceledCount})</span>
</button>
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(() => scraperAPI.clearFinished(), '确定清空所有已完成、失败及取消的历史记录?')
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-rose-500 hover:bg-rose-50"
>
<Trash2 size={13} />
<span>清空全部历史记录 ({finishedCount})</span>
</button>
</div>
</details>
</div>
)}
</div>
-2
View File
@@ -8,7 +8,6 @@ import { libraryAPI } from '../api/library'
import type { Library, Setting } from '../types'
import { APIConfigsPanel } from '../components/APIConfigsPanel'
import { FFToolsPanel } from '../components/FFToolsPanel'
import { AboutSettingsPanel } from './AboutSettingsPanel'
import { AdultSettingsPanel } from './AdultSettingsPanel'
import { DatabaseSettingsPanel } from './DatabaseSettingsPanel'
import { RecognitionWordsPanel } from './RecognitionWordsPanel'
@@ -175,7 +174,6 @@ export function SettingsPage() {
{group.key === 'recognition-words' && <RecognitionWordsPanel />}
{group.key === 'adult' && <AdultSettingsPanel />}
{group.key === 'general' && <FFToolsPanel onInstalled={() => refresh().catch(() => undefined)} />}
{group.key === 'about' && <AboutSettingsPanel />}
{group.key !== 'adult' && group.key !== 'library' && group.items.length > 0 && (
<form onSubmit={onSave} className="glass-panel space-y-4">
{group.description && <p className="text-xs text-sand-500">{group.description}</p>}
+3 -253
View File
@@ -224,13 +224,8 @@ export function StrmQueuePanel({
}, [tasks, filter, search])
const counts = snapshot?.counts
const pendingCount = counts?.pending ?? 0
const runningCount = counts?.running ?? 0
const activeTaskCount = pendingCount + runningCount
const doneCount = counts?.done ?? 0
const activeTaskCount = (counts?.pending ?? 0) + (counts?.running ?? 0)
const failedCount = counts?.failed ?? 0
const canceledCount = counts?.canceled ?? 0
const finishedCount = doneCount + failedCount + canceledCount
const allCurrentChecked =
filteredTasks.length > 0 && filteredTasks.every((t) => selectedIds.has(t.id))
@@ -480,8 +475,8 @@ export function StrmQueuePanel({
)}
</div>
{/* Batch Actions Toolbar */}
{selectedIds.size > 0 ? (
{/* Selected Batch Toolbar */}
{selectedIds.size > 0 && (
<div className="flex flex-wrap items-center gap-2 rounded-xl border border-brand-500/30 bg-primary-400/10 px-3 py-2 text-xs animate-in fade-in zoom-in-95">
<span className="font-bold text-brand-500">已选中 {selectedIds.size} 项</span>
<div className="h-3.5 w-px bg-brand-300/40 mx-1" />
@@ -521,251 +516,6 @@ export function StrmQueuePanel({
<X size={13} />
</button>
</div>
) : (
<div className="flex flex-wrap items-center gap-2">
{/* 当前状态专属快捷批量按钮 */}
{filter === 'all' && (
<>
{failedCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.retryFailedDownloads() : strmAPI.retryFailedUploads()),
'确定重新入队所有失败任务?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-brand-500/40 bg-white px-3 py-1.5 text-xs font-semibold text-brand-500 hover:bg-brand-50 disabled:opacity-50"
>
<RefreshCw size={12} />
全部重试 ({failedCount})
</button>
)}
{activeTaskCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.cancelPendingDownloads() : strmAPI.cancelPendingUploads()),
'确定取消所有排队及进行中的任务?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-600 hover:bg-amber-50 disabled:opacity-50"
>
<Ban size={12} />
全部取消 ({activeTaskCount})
</button>
)}
{finishedCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.clearFinishedDownloads() : strmAPI.clearFinishedUploads()),
'确定清空所有已完成、失败及取消的历史记录?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除 ({finishedCount})
</button>
)}
</>
)}
{(filter === 'pending' || filter === 'running') && (
<button
type="button"
disabled={batchBusy || activeTaskCount === 0}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.cancelPendingDownloads() : strmAPI.cancelPendingUploads()),
'确定取消所有排队及进行中的任务?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-600 hover:bg-amber-50 disabled:opacity-50"
>
<Ban size={12} />
全部取消{activeTaskCount > 0 ? ` (${activeTaskCount})` : ''}
</button>
)}
{filter === 'done' && (
<button
type="button"
disabled={batchBusy || doneCount === 0}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.clearDoneDownloads() : strmAPI.clearDoneUploads()),
'确定清空所有已完成记录?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除{doneCount > 0 ? ` (${doneCount})` : ''}
</button>
)}
{filter === 'failed' && (
<>
<button
type="button"
disabled={batchBusy || failedCount === 0}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.retryFailedDownloads() : strmAPI.retryFailedUploads()),
'确定重新入队所有失败任务?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-brand-500/40 bg-white px-3 py-1.5 text-xs font-semibold text-brand-500 hover:bg-brand-50 disabled:opacity-50"
>
<RefreshCw size={12} />
全部重试{failedCount > 0 ? ` (${failedCount})` : ''}
</button>
<button
type="button"
disabled={batchBusy || failedCount === 0}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.clearFailedDownloads() : strmAPI.clearFailedUploads()),
'确定清空所有失败记录?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除{failedCount > 0 ? ` (${failedCount})` : ''}
</button>
</>
)}
{filter === 'canceled' && (
<button
type="button"
disabled={batchBusy || canceledCount === 0}
onClick={() =>
runGlobalBatch(
() => (isDownload ? strmAPI.clearCanceledDownloads() : strmAPI.clearCanceledUploads()),
'确定清空所有已取消的任务记录?',
)
}
className="inline-flex items-center gap-1 rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-50"
>
<Trash2 size={12} />
全部删除{canceledCount > 0 ? ` (${canceledCount})` : ''}
</button>
)}
{/* 下拉批量操作菜单:随时可做任意全局操作 */}
<details className="relative inline-block">
<summary className="inline-flex cursor-pointer list-none items-center gap-1.5 rounded-xl border border-gray-200 bg-white px-3 py-1.5 text-xs font-semibold text-ink-100 shadow-sm transition hover:border-gray-300 hover:bg-gray-50 [&::-webkit-details-marker]:hidden">
<Trash2 size={12} className="text-sand-500" />
<span>批量清理</span>
</summary>
<div className="absolute right-0 top-9 z-30 min-w-44 rounded-xl border border-gray-200 bg-white p-1.5 shadow-xl backdrop-blur">
{failedCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(
() => (isDownload ? strmAPI.retryFailedDownloads() : strmAPI.retryFailedUploads()),
'确定重新入队所有失败任务?',
)
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-brand-500 hover:bg-brand-50"
>
<RefreshCw size={13} />
<span>重试所有失败 ({failedCount})</span>
</button>
)}
{activeTaskCount > 0 && (
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(
() => (isDownload ? strmAPI.cancelPendingDownloads() : strmAPI.cancelPendingUploads()),
'确定取消所有排队及进行中的任务?',
)
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-amber-600 hover:bg-amber-50"
>
<Ban size={13} />
<span>取消所有进行中 ({activeTaskCount})</span>
</button>
)}
<div className="my-1 border-t border-gray-100" />
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(
() => (isDownload ? strmAPI.clearDoneDownloads() : strmAPI.clearDoneUploads()),
'确定清空所有已完成记录?',
)
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-ink-100 hover:bg-gray-50"
>
<CheckCircle2 size={13} className="text-emerald-500" />
<span>清空已完成记录 ({doneCount})</span>
</button>
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(
() => (isDownload ? strmAPI.clearFailedDownloads() : strmAPI.clearFailedUploads()),
'确定清空所有失败记录?',
)
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-rose-500 hover:bg-rose-50"
>
<AlertCircle size={13} />
<span>清空失败记录 ({failedCount})</span>
</button>
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(
() => (isDownload ? strmAPI.clearCanceledDownloads() : strmAPI.clearCanceledUploads()),
'确定清空所有已取消的任务记录?',
)
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-ink-100 hover:bg-gray-50"
>
<Ban size={13} className="text-amber-500" />
<span>清空已取消记录 ({canceledCount})</span>
</button>
<button
type="button"
disabled={batchBusy}
onClick={(e) => {
e.currentTarget.closest('details')?.removeAttribute('open')
runGlobalBatch(
() => (isDownload ? strmAPI.clearFinishedDownloads() : strmAPI.clearFinishedUploads()),
'确定清空所有已完成、失败及取消的历史记录?',
)
}}
className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs font-medium text-rose-500 hover:bg-rose-50"
>
<Trash2 size={13} />
<span>清空全部历史记录 ({finishedCount})</span>
</button>
</div>
</details>
</div>
)}
</div>
-8
View File
@@ -14,13 +14,6 @@ export const databaseSettingsGroup: SettingGroup = {
items: [],
}
export const aboutSettingsGroup: SettingGroup = {
key: 'about',
label: '关于',
description: '项目信息、版本信息与使用指南',
items: [],
}
export const GROUPS: SettingGroup[] = [
generalSettingsGroup,
databaseSettingsGroup,
@@ -28,7 +21,6 @@ export const GROUPS: SettingGroup[] = [
recognitionWordsSettingsGroup,
danmakuSettingsGroup,
adultSettingsGroup,
aboutSettingsGroup,
]
export const ALL_KEYS = new Set(GROUPS.flatMap((group) => group.items.map((item) => item.key)))
+2 -2
View File
@@ -163,8 +163,8 @@ function useEditableLibraryRootActions(refresh: () => Promise<void>, drafts: Edi
function useLibraryActions(refresh: () => Promise<void>) {
const scanLibrary = async (library: Library) => {
const result = await libraryAPI.scan(library.id)
if (result.queued) toast.success(result.message || '媒体库扫描已加入后台队列,会自动入库')
else toast.success(`扫描完成,新增 ${result.added ?? 0},更新 ${result.updated ?? 0}`)
if (result.queued) toast.success('云盘扫描已加入后台队列,会自动入库')
else toast.success(`扫描完成,新增 ${result.added},更新 ${result.updated ?? 0}`)
}
const toggleCarouselLibrary = async (library: Library) => {
+3 -16
View File
@@ -40,13 +40,6 @@ export function useLibraryScanStatus({
setScanProgress(String(event.message ?? '扫描已排队,后台会自动入库'))
return
}
if (typeof event.visited === 'number' && !event.finished) {
setScanning(true)
const added = Number(event.added ?? 0)
const updated = Number(event.updated ?? 0)
setScanProgress(`正在扫描:已扫描 ${event.visited} 项 · 新增 ${added} · 更新 ${updated}`)
return
}
}, [isAdmin, libraryID, onLibraryChanged])
useWebSocket(onRealtimeEvent)
@@ -56,19 +49,13 @@ export function useLibraryScanStatus({
setScanProgress('正在提交扫描任务…')
try {
const result = await libraryAPI.scan(libraryID)
if (result.queued) {
const msg = result.message || '扫描任务已在后台启动,正在扫描…'
toast.success(msg)
setScanProgress(msg)
return
}
toast.success(`扫描完成:新增 ${result.added ?? 0} 项,更新 ${result.updated ?? 0} 项`)
setScanProgress(`扫描完成:新增 ${result.added ?? 0} · 更新 ${result.updated ?? 0}`)
setScanning(false)
toast.success(`扫描完成:新增 ${result.added} 项,更新 ${result.updated ?? 0} 项`)
setScanProgress(`扫描完成:新增 ${result.added} · 更新 ${result.updated ?? 0}`)
onLibraryChanged()
} catch {
toast.error('扫描失败')
setScanProgress('扫描失败,请查看日志或稍后重试')
} finally {
setScanning(false)
}
}, [libraryID, onLibraryChanged])
+6 -76
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react'
import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react'
import type { NavigateFunction } from 'react-router-dom'
import toast from 'react-hot-toast'
@@ -20,8 +20,6 @@ interface MediaDetailRefreshParams {
setMedia: Dispatch<SetStateAction<Media | null>>
setFavourite: Dispatch<SetStateAction<boolean>>
setLoading: Dispatch<SetStateAction<boolean>>
setEpisodes: Dispatch<SetStateAction<Media[]>>
setLoadingEpisodes: Dispatch<SetStateAction<boolean>>
}
interface MediaDetailActionsParams {
@@ -36,23 +34,12 @@ export function useMediaDetailPageState({ id, navigate }: MediaDetailPageStatePa
const [media, setMedia] = useState<Media | null>(null)
const [favourite, setFavourite] = useState(false)
const [loading, setLoading] = useState(true)
const [episodes, setEpisodes] = useState<Media[]>([])
const [loadingEpisodes, setLoadingEpisodes] = useState(false)
const [selectedSeason, setSelectedSeason] = useState<number | null>(null)
const [manualScrapeOpen, setManualScrapeOpen] = useState(false)
const [metadataEditOpen, setMetadataEditOpen] = useState(false)
const [organizeOpen, setOrganizeOpen] = useState(false)
const [scrapeEpisodeArtwork, setScrapeEpisodeArtwork] = useState(false)
const refresh = useMediaDetailRefresh({
id,
setMedia,
setFavourite,
setLoading,
setEpisodes,
setLoadingEpisodes,
})
const refresh = useMediaDetailRefresh({ id, setMedia, setFavourite, setLoading })
const actions = useMediaDetailActions({
media,
scrapeEpisodeArtwork,
@@ -65,41 +52,6 @@ export function useMediaDetailPageState({ id, navigate }: MediaDetailPageStatePa
refresh().catch(() => undefined)
}, [refresh])
const seasonGroups = useMemo(() => {
if (episodes.length === 0) return []
const seasons = new Map<number, Media[]>()
for (const ep of episodes) {
const s = ep.episode_num > 0 ? (ep.season_num ?? 0) : (ep.season_num || 1)
if (!seasons.has(s)) seasons.set(s, [])
seasons.get(s)!.push(ep)
}
for (const [, list] of seasons) {
list.sort((a, b) => (a.episode_num || 0) - (b.episode_num || 0))
}
return Array.from(seasons.entries())
.sort(([a], [b]) => a - b)
.map(([season, list]) => ({ season, episodes: list }))
}, [episodes])
const visibleEpisodes = useMemo(() => {
if (selectedSeason == null) return seasonGroups[0]?.episodes ?? []
return seasonGroups.find((s) => s.season === selectedSeason)?.episodes ?? []
}, [seasonGroups, selectedSeason])
const hasEpisodes = useMemo(() => {
if (episodes.length > 1) return true
if (episodes.length === 1 && media) {
// 只有单条时,如果明确是集(有 episode_num > 0)或 ID 与自身不同,则按剧集渲染
return episodes[0].episode_num > 0 || episodes[0].id !== media.id
}
return false
}, [episodes, media])
const firstPlayableEpisode = useMemo(() => {
if (episodes.length === 0) return null
return (visibleEpisodes.length > 0 ? visibleEpisodes[0] : episodes[0]) || null
}, [episodes, visibleEpisodes])
const handleMetadataSaved = useCallback(async (next: Media) => {
setMedia(next)
await refresh()
@@ -109,14 +61,6 @@ export function useMediaDetailPageState({ id, navigate }: MediaDetailPageStatePa
media,
favourite,
loading,
episodes,
loadingEpisodes,
seasonGroups,
selectedSeason,
visibleEpisodes,
hasEpisodes,
firstPlayableEpisode,
setSelectedSeason,
manualScrapeOpen,
metadataEditOpen,
organizeOpen,
@@ -136,31 +80,19 @@ function useMediaDetailRefresh({
setMedia,
setFavourite,
setLoading,
setEpisodes,
setLoadingEpisodes,
}: MediaDetailRefreshParams): () => Promise<void> {
return useCallback(async () => {
if (!id) return
setLoading(true)
setLoadingEpisodes(true)
try {
const nextMedia = await mediaAPI.get(id)
setMedia(nextMedia)
const favourites = await playbackAPI.listFavourites().catch(() => [])
setFavourite(favourites.some((item) => item.id === nextMedia.id))
// 异步加载分集列表
try {
const epRes = await mediaAPI.getEpisodes(id)
setEpisodes(epRes.items ?? [])
} catch {
setEpisodes([])
} finally {
setLoadingEpisodes(false)
}
} finally {
setLoading(false)
}
}, [id, setFavourite, setLoading, setMedia, setEpisodes, setLoadingEpisodes])
}, [id, setFavourite, setLoading, setMedia])
}
function useMediaDetailActions({
@@ -189,12 +121,10 @@ function useMediaDetailActions({
}
function goBackFromMediaDetail(media: Media | null, navigate: NavigateFunction, replace = false): void {
if (!media) {
navigate('/libraries')
return
}
if (!media) return
const backTarget = mediaLibraryBackTarget(media)
navigate(backTarget || '/libraries', replace ? { replace: true } : undefined)
if (backTarget) navigate(backTarget, replace ? { replace: true } : undefined)
else navigate(-1)
}
async function toggleMediaFavourite(
-1
View File
@@ -10,7 +10,6 @@ export interface User {
force_password_reset: boolean
is_active: boolean
allowed_library_ids?: string[]
pinned_library_ids?: string[]
is_default_admin?: boolean
is_protected?: boolean
realtime_online?: boolean
+7 -56
View File
@@ -1,7 +1,4 @@
import { profileAPI } from '../api/profile'
const STORAGE_KEY = 'mebox_pinned_libraries'
const MIGRATION_KEY = 'mebox_pinned_libraries_migrated'
function parsePinnedIds(raw: string | null): string[] {
if (!raw) return []
@@ -14,74 +11,28 @@ function parsePinnedIds(raw: string | null): string[] {
}
}
export function readLegacyPinnedLibraryIds(): string[] {
export function readPinnedLibraryIds(): string[] {
if (typeof window === 'undefined') return []
return parsePinnedIds(window.localStorage.getItem(STORAGE_KEY))
}
function writeLegacyPinnedLibraryIds(ids: string[]): void {
export function writePinnedLibraryIds(ids: string[]): void {
if (typeof window === 'undefined') return
if (ids.length === 0) {
window.localStorage.removeItem(STORAGE_KEY)
return
}
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(ids))
}
function markPinnedLibrariesMigrated(): void {
if (typeof window === 'undefined') return
window.localStorage.setItem(MIGRATION_KEY, '1')
window.localStorage.removeItem(STORAGE_KEY)
}
function hasPinnedLibrariesMigrated(): boolean {
if (typeof window === 'undefined') return true
return window.localStorage.getItem(MIGRATION_KEY) === '1'
}
export async function loadPinnedLibraryIds(): Promise<string[]> {
const remote = await profileAPI.getPinnedLibraries()
if (!hasPinnedLibrariesMigrated()) {
const legacy = readLegacyPinnedLibraryIds()
if (legacy.length > 0 && remote.length === 0) {
const migrated = await profileAPI.setPinnedLibraries(legacy)
markPinnedLibrariesMigrated()
return migrated
}
markPinnedLibrariesMigrated()
}
return remote
}
export async function savePinnedLibraryIds(ids: string[]): Promise<string[]> {
const saved = await profileAPI.setPinnedLibraries(ids)
writeLegacyPinnedLibraryIds(saved)
return saved
}
export function togglePinnedLibraryId(current: string[], id: string): string[] {
export function togglePinnedLibraryId(id: string): string[] {
const current = readPinnedLibraryIds()
const index = current.indexOf(id)
return index >= 0 ? current.filter((item) => item !== id) : [...current, id]
const next = index >= 0 ? current.filter((item) => item !== id) : [...current, id]
writePinnedLibraryIds(next)
return next
}
export function isLibraryPinned(id: string, pinnedIds: string[]): boolean {
return pinnedIds.includes(id)
}
export function sortByPinnedIds<T extends { id: string }>(items: T[], pinnedIds: string[]): T[] {
if (pinnedIds.length === 0) return items
const rank = new Map(pinnedIds.map((pinnedId, index) => [pinnedId, index]))
return [...items].sort((a, b) => {
const aRank = rank.get(a.id)
const bRank = rank.get(b.id)
const aPinned = aRank !== undefined
const bPinned = bRank !== undefined
if (aPinned !== bPinned) return aPinned ? -1 : 1
if (aPinned && bPinned) return aRank - bRank
return 0
})
}
export function sortLibraryPreviews<T extends { library: { id: string } }>(items: T[], pinnedIds: string[]): T[] {
if (pinnedIds.length === 0) return items
const rank = new Map(pinnedIds.map((id, index) => [id, index]))