mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-28 11:16:37 +08:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fb92373f0d | |||
| 2b99f5f108 | |||
| 9ab32c10ca | |||
| e872223b4e | |||
| c7441e06d4 | |||
| 936be24328 | |||
| b7f2760728 | |||
| ea732e5bd7 | |||
| 4e02692aeb | |||
| e8c710c261 | |||
| 27d2b79e1f | |||
| 1e291df647 |
@@ -94,18 +94,26 @@ func listLibrariesHandler(svc *service.Container) gin.HandlerFunc {
|
||||
out = append(out, webLibraryPayload{Library: l})
|
||||
}
|
||||
}
|
||||
// 远程 Emby 挂载库追加在本地库之后。
|
||||
// 远程 Emby 挂载库追加在本地库之后(非管理员视图仍受 allowed_library_ids 约束)。
|
||||
if svc.EmbyRemote != nil {
|
||||
if views, err := svc.EmbyRemote.RemoteLibraries(ctx); err == nil {
|
||||
remotePayloads := make([]webLibraryPayload, len(views))
|
||||
for i, v := range views {
|
||||
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[i] = webLibraryPayload{Library: v.Library, IsRemoteEmby: true, RemoteSource: v.AccountName}
|
||||
}
|
||||
if withPreview && len(views) > 0 {
|
||||
if withPreview && len(allowedViews) > 0 {
|
||||
const maxRemotePreviewWorkers = 6
|
||||
sem := make(chan struct{}, maxRemotePreviewWorkers)
|
||||
var wg sync.WaitGroup
|
||||
for i, v := range views {
|
||||
for i, v := range allowedViews {
|
||||
i, v := i, v
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
@@ -151,6 +159,12 @@ 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
|
||||
}
|
||||
@@ -330,6 +344,10 @@ 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)
|
||||
@@ -397,6 +415,10 @@ 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()})
|
||||
@@ -579,6 +601,10 @@ 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() {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/middleware"
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
|
||||
@@ -23,18 +22,18 @@ import (
|
||||
func addMediaFavoriteHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid, _ := c.Get(middleware.CtxUserID)
|
||||
// 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 {
|
||||
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 {
|
||||
c.JSON(http.StatusOK, gin.H{"favourite": true})
|
||||
return
|
||||
}
|
||||
// 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 {
|
||||
if err := svc.Playback.SetFavourite(c.Request.Context(), userID, mediaID, true); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -46,9 +45,7 @@ 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.Repo.DB.WithContext(c.Request.Context()).
|
||||
Where("user_id = ? AND media_id = ?", uid, c.Param("id")).
|
||||
Delete(&model.Favorite{}).Error; err != nil {
|
||||
if err := svc.Playback.SetFavourite(c.Request.Context(), toString(uid), c.Param("id"), false); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -60,12 +57,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)
|
||||
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})
|
||||
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})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
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})
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ 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,6 +25,8 @@ 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",
|
||||
|
||||
@@ -74,6 +74,10 @@ 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)
|
||||
@@ -165,6 +169,10 @@ 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)
|
||||
@@ -207,6 +215,10 @@ 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)
|
||||
|
||||
@@ -25,6 +25,9 @@ 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.
|
||||
@@ -59,10 +62,30 @@ 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()
|
||||
}
|
||||
|
||||
@@ -148,11 +148,17 @@ 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
|
||||
@@ -171,6 +177,9 @@ 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))
|
||||
@@ -269,6 +278,9 @@ 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
|
||||
|
||||
@@ -21,6 +21,9 @@ 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
|
||||
@@ -28,6 +31,14 @@ 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 {
|
||||
@@ -101,6 +112,9 @@ 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
|
||||
@@ -180,6 +194,137 @@ 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 {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ 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
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -125,7 +126,8 @@ func (e *EmbyService) userPayload(u *model.User) map[string]any {
|
||||
}
|
||||
|
||||
// Views 返回 Emby 中"虚拟根目录"——每个 library 一个条目,外加所有启用的
|
||||
// 远程 Emby 挂载的媒体库(联邦聚合)。
|
||||
// 远程 Emby 挂载的媒体库(联邦聚合)。顺序遵循用户置顶偏好:置顶库靠前,
|
||||
// 未置顶保持原有 sort_order / 远程挂载顺序。
|
||||
func (e *EmbyService) Views(ctx context.Context, userID string) (map[string]any, error) {
|
||||
libs, err := e.repo.Library.List(ctx)
|
||||
if err != nil {
|
||||
@@ -141,11 +143,60 @@ 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 {
|
||||
|
||||
@@ -7,35 +7,17 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
)
|
||||
|
||||
// SetFavorite 把 mediaID 标为 userID 的收藏。远程 Emby 条目直接透传到对应
|
||||
// 服务器(本地不落库)。
|
||||
// SetFavorite 把 mediaID 标为 userID 的收藏。挂载的远程 Emby 条目会同时写入
|
||||
// 本地 favourites 表并透传到对应远程服务器,保证网页与第三方 Emby 客户端一致。
|
||||
func (e *EmbyService) SetFavorite(ctx context.Context, userID, mediaID string, favorite bool) error {
|
||||
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
|
||||
}
|
||||
if err := SyncUserFavorite(ctx, e.repo, e.remote, userID, mediaID, favorite); err != nil {
|
||||
return err
|
||||
}
|
||||
return e.repo.DB.WithContext(ctx).
|
||||
Where("user_id = ? AND media_id = ?", userID, mediaID).
|
||||
Delete(&model.Favorite{}).Error
|
||||
e.invalidateEmbyItemsCache(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkPlayed 把 mediaID 标为已看(写一个 100% 进度的 history 行)。
|
||||
@@ -122,8 +104,7 @@ func (e *EmbyService) RecordProgress(ctx context.Context, userID, mediaID string
|
||||
}
|
||||
|
||||
// mergeRemoteUserData applies the current MeBox user's locally recorded playback
|
||||
// state to remote Emby payloads. Remote metadata remains authoritative unless the
|
||||
// user has played the item through MeBox.
|
||||
// and favourite state to remote Emby payloads.
|
||||
func (e *EmbyService) mergeRemoteUserData(ctx context.Context, userID string, payload any) error {
|
||||
if strings.TrimSpace(userID) == "" || payload == nil {
|
||||
return nil
|
||||
@@ -152,10 +133,27 @@ 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(item["UserData"], h)
|
||||
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
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,20 @@ 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) {
|
||||
return p.repo.Favorite.Toggle(ctx, userID, mediaID)
|
||||
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)
|
||||
}
|
||||
|
||||
// ListFavourites returns every favourited media for a user.
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
@@ -81,6 +82,125 @@ 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) {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -131,20 +131,39 @@ 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 len(visibility.AllowedLibraryIDs) > 0 {
|
||||
found := false
|
||||
for _, id := range visibility.AllowedLibraryIDs {
|
||||
if id == lib.ID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
if !LibraryIDAllowed(visibility, lib.ID) {
|
||||
return false
|
||||
}
|
||||
if visibility.IncludeNSFW {
|
||||
return true
|
||||
|
||||
@@ -12,6 +12,12 @@ 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),
|
||||
}
|
||||
|
||||
@@ -278,12 +278,19 @@ 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.path}
|
||||
title={lib.is_remote_emby ? lib.remote_source || lib.name : lib.path}
|
||||
>
|
||||
{lib.type} · {libraryDisplayPath(lib.path)}
|
||||
{lib.is_remote_emby
|
||||
? `远程 · ${lib.remote_source || 'Emby'}`
|
||||
: `${lib.type} · ${libraryDisplayPath(lib.path)}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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 }
|
||||
}
|
||||
@@ -5,6 +5,8 @@ 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,
|
||||
@@ -22,6 +24,7 @@ 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
|
||||
@@ -126,6 +129,8 @@ export function HomePage() {
|
||||
return candidateMedia.slice(0, 10)
|
||||
}, [libraries, libraryData])
|
||||
|
||||
const sortedLibraries = useMemo(() => sortByPinnedIds(libraries, pinnedIds), [libraries, pinnedIds])
|
||||
|
||||
const empty =
|
||||
!loading &&
|
||||
libraries.length === 0 &&
|
||||
@@ -150,9 +155,9 @@ export function HomePage() {
|
||||
{history.length > 0 && <ContinueWatchingSection history={history} />}
|
||||
|
||||
{/* 3. 媒体库卡片区 */}
|
||||
{libraries.length > 0 && (
|
||||
{sortedLibraries.length > 0 && (
|
||||
<HomeLibrariesSection
|
||||
libraries={libraries}
|
||||
libraries={sortedLibraries}
|
||||
libraryData={libraryData}
|
||||
libraryCounts={libraryCounts}
|
||||
/>
|
||||
@@ -160,7 +165,7 @@ export function HomePage() {
|
||||
|
||||
{/* 4. 各媒体库内容展示行 */}
|
||||
<div className="space-y-10">
|
||||
{libraries.map((lib) => {
|
||||
{sortedLibraries.map((lib) => {
|
||||
const cards = libraryData[lib.id]?.cards || []
|
||||
if (cards.length === 0) return null
|
||||
return (
|
||||
|
||||
@@ -3,17 +3,18 @@ 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 { readPinnedLibraryIds, sortLibraryPreviews, togglePinnedLibraryId } from '../utils/pinnedLibraries'
|
||||
import { sortLibraryPreviews } from '../utils/pinnedLibraries'
|
||||
|
||||
export function LibrariesPage() {
|
||||
const [previews, setPreviews] = useState<LibraryPreview[]>([])
|
||||
const [pinnedIds, setPinnedIds] = useState<string[]>(() => readPinnedLibraryIds())
|
||||
const { pinnedIds, loading: pinnedLoading, togglePin } = usePinnedLibraries()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [repairing, setRepairing] = useState(false)
|
||||
const [repairEpisodeArtwork, setRepairEpisodeArtwork] = useState(false)
|
||||
@@ -62,12 +63,12 @@ export function LibrariesPage() {
|
||||
const sortedPreviews = useMemo(() => sortLibraryPreviews(previews, pinnedIds), [previews, pinnedIds])
|
||||
|
||||
const handleTogglePin = useCallback((libraryId: string) => {
|
||||
setPinnedIds(togglePinnedLibraryId(libraryId))
|
||||
}, [])
|
||||
void togglePin(libraryId)
|
||||
}, [togglePin])
|
||||
|
||||
const total = useMemo(() => previews.reduce((sum, preview) => sum + preview.total, 0), [previews])
|
||||
|
||||
if (loading) {
|
||||
if (loading || pinnedLoading) {
|
||||
return <p className="px-2 py-8 text-sm text-sand-500">媒体库加载中…</p>
|
||||
}
|
||||
|
||||
|
||||
@@ -155,6 +155,7 @@ export function ProfileLibraryAccessField({
|
||||
}
|
||||
>
|
||||
{library.name}
|
||||
{library.is_remote_emby ? ' · Emby' : ''}
|
||||
</button>
|
||||
))}
|
||||
{libraries.length === 0 && (
|
||||
|
||||
@@ -10,6 +10,7 @@ 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
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
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 []
|
||||
@@ -11,28 +14,74 @@ function parsePinnedIds(raw: string | null): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
export function readPinnedLibraryIds(): string[] {
|
||||
export function readLegacyPinnedLibraryIds(): string[] {
|
||||
if (typeof window === 'undefined') return []
|
||||
return parsePinnedIds(window.localStorage.getItem(STORAGE_KEY))
|
||||
}
|
||||
|
||||
export function writePinnedLibraryIds(ids: string[]): void {
|
||||
function writeLegacyPinnedLibraryIds(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))
|
||||
}
|
||||
|
||||
export function togglePinnedLibraryId(id: string): string[] {
|
||||
const current = readPinnedLibraryIds()
|
||||
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[] {
|
||||
const index = current.indexOf(id)
|
||||
const next = index >= 0 ? current.filter((item) => item !== id) : [...current, id]
|
||||
writePinnedLibraryIds(next)
|
||||
return next
|
||||
return index >= 0 ? current.filter((item) => item !== id) : [...current, id]
|
||||
}
|
||||
|
||||
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]))
|
||||
|
||||
Reference in New Issue
Block a user