mirror of
https://github.com/truewhile/MeBox.git
synced 2026-11-12 19:34:24 +08:00
65 lines
2.2 KiB
Go
65 lines
2.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/truewhile/MeBox/internal/model"
|
|
"github.com/truewhile/MeBox/internal/repository"
|
|
)
|
|
|
|
// SyncUserFavorite keeps favourite state in the local favourites table, keyed
|
|
// by MeBox user_id. Remote Emby mounts share one upstream account, so favourite
|
|
// state is intentionally not proxied upstream.
|
|
func SyncUserFavorite(ctx context.Context, repo *repository.Container, _ *EmbyRemoteService, userID, mediaID string, favorite bool) error {
|
|
if repo == nil || userID == "" || mediaID == "" {
|
|
return errors.New("missing favourite sync inputs")
|
|
}
|
|
return setLocalFavorite(ctx, repo, userID, mediaID, favorite)
|
|
}
|
|
|
|
// 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
|
|
// 收藏行的删除是软删除;重新收藏时必须连已软删除的行一起查出来,
|
|
// 否则会再次插入同一 (user_id, media_id),撞上唯一索引后稳定返回
|
|
// 500,用户表现为“取消收藏后无法再收藏”。
|
|
err := repo.DB.WithContext(ctx).Unscoped().
|
|
Where("user_id = ? AND media_id = ?", userID, mediaID).
|
|
First(&existing).Error
|
|
switch {
|
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
|
return repo.DB.WithContext(ctx).Create(&model.Favorite{
|
|
UserID: userID,
|
|
MediaID: mediaID,
|
|
}).Error
|
|
case err != nil:
|
|
return err
|
|
case existing.DeletedAt.Valid:
|
|
return repo.DB.WithContext(ctx).Unscoped().
|
|
Model(&model.Favorite{}).
|
|
Where("id = ?", existing.ID).
|
|
Update("deleted_at", nil).Error
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
return repo.DB.WithContext(ctx).
|
|
Where("user_id = ? AND media_id = ?", userID, mediaID).
|
|
Delete(&model.Favorite{}).Error
|
|
}
|