mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-28 03:06:38 +08:00
Remove unused recycle bin and add optional local file delete (#26)
Soft-delete restore/purge/list and the recycle_purge job are gone. Admin delete now removes library index rows, with an optional delete_files query that also deletes local media + sidecar NFO. UI copy is renamed from 移入回收站 to 删除, with a confirm checkbox. Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: truewhile <truewhile@users.noreply.github.com>
This commit is contained in:
@@ -51,7 +51,7 @@
|
||||
| **网盘与 STRM** | OpenList、CloudDrive2、115、WebDAV 等;STRM 同步、上传/下载队列、直链/302 播放 |
|
||||
| **下载与整理** | qBittorrent 接入、站点搜索与订阅、下载后自动整理、文件管理器(复制/移动/硬链/软链) |
|
||||
| **用户与权限** | 管理员/普通用户、有效期、成人内容开关、播放配置 PIN、细粒度操作权限 |
|
||||
| **运维能力** | 统一任务队列、回收站、存储统计、DLNA 投屏、系统设置与日志 |
|
||||
| **运维能力** | 统一任务队列、存储统计、DLNA 投屏、系统设置与日志 |
|
||||
|
||||
### 技术栈
|
||||
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ In practice, MeBox gives you:
|
||||
| **Cloud & STRM** | OpenList, CloudDrive2, 115, WebDAV; STRM sync; upload/download queues; direct or 302 playback |
|
||||
| **Downloads & organize** | qBittorrent, site search/subscriptions, post-download organization, file manager |
|
||||
| **Users & permissions** | Admin/regular users, expiry, NSFW toggle, play-profile PIN, granular permissions |
|
||||
| **Operations** | Unified task queue, recycle bin, storage stats, DLNA casting, settings and logs |
|
||||
| **Operations** | Unified task queue, storage stats, DLNA casting, settings and logs |
|
||||
|
||||
### Tech stack
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// Package handler — media delete endpoint.
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
|
||||
func deleteMediaHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
deleteFiles := parseDeleteFilesQuery(c.Query("delete_files"))
|
||||
if err := svc.Media.DeleteMedia(c.Request.Context(), c.Param("id"), deleteFiles); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func parseDeleteFilesQuery(raw string) bool {
|
||||
raw = strings.TrimSpace(strings.ToLower(raw))
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
if raw == "1" || raw == "true" || raw == "yes" {
|
||||
return true
|
||||
}
|
||||
v, err := strconv.ParseBool(raw)
|
||||
return err == nil && v
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package handler
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseDeleteFilesQuery(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
want bool
|
||||
}{
|
||||
{"", false},
|
||||
{"0", false},
|
||||
{"false", false},
|
||||
{"1", true},
|
||||
{"true", true},
|
||||
{"TRUE", true},
|
||||
{"yes", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := parseDeleteFilesQuery(tc.raw); got != tc.want {
|
||||
t.Fatalf("parseDeleteFilesQuery(%q)=%v, want %v", tc.raw, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
// Package handler — recycle bin endpoints.
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
|
||||
func deleteMediaHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if err := svc.Media.SoftDelete(c.Request.Context(), c.Param("id")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func restoreMediaHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if err := svc.Media.RestoreDeleted(c.Request.Context(), c.Param("id")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func purgeMediaHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if err := svc.Media.PurgeDeleted(c.Request.Context(), c.Param("id")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ func registerAuthenticatedRoutes(api *gin.RouterGroup, cfg *config.Config, svc *
|
||||
registerAuthedCollectionRoutes(authed, svc)
|
||||
registerAuthedFileRoutes(authed, svc)
|
||||
registerAuthedDLNARoutes(authed, svc)
|
||||
registerAuthedRecycleAndRealtimeRoutes(authed, svc)
|
||||
registerAuthedRealtimeRoutes(authed, svc)
|
||||
registerAuthedUISurfaceRoutes(authed, svc)
|
||||
registerAuthedSearchRoutes(authed, svc)
|
||||
registerAuthedSystemExtraRoutes(authed, svc)
|
||||
|
||||
@@ -50,8 +50,6 @@ func registerAuthedMediaRoutes(authed *gin.RouterGroup, svc *service.Container)
|
||||
authed.POST("/media/scrape/apply", middleware.AdminRequired(), manualScrapeApplyBatchHandler(svc))
|
||||
authed.POST("/media/:id/probe", middleware.AdminRequired(), reprobeHandler(svc))
|
||||
authed.DELETE("/media/:id", middleware.AdminRequired(), deleteMediaHandler(svc))
|
||||
authed.POST("/media/:id/restore", middleware.AdminRequired(), restoreMediaHandler(svc))
|
||||
authed.DELETE("/media/:id/purge", middleware.AdminRequired(), purgeMediaHandler(svc))
|
||||
authed.GET("/media/:id/subtitles", listSubtitlesHandler(svc))
|
||||
authed.GET("/subtitles/:id", serveSubtitleHandler(svc))
|
||||
authed.POST("/media/:id/nfo", middleware.AdminRequired(), exportNFOHandler(svc))
|
||||
|
||||
@@ -20,7 +20,7 @@ func registerAuthedDLNARoutes(authed *gin.RouterGroup, svc *service.Container) {
|
||||
authed.POST("/dlna/cast", dlnaCastHandler(svc))
|
||||
}
|
||||
|
||||
func registerAuthedRecycleAndRealtimeRoutes(authed *gin.RouterGroup, svc *service.Container) {
|
||||
func registerAuthedRealtimeRoutes(authed *gin.RouterGroup, svc *service.Container) {
|
||||
authed.GET("/ws", wsHandler(svc))
|
||||
authed.GET("/events", sseHandler(svc))
|
||||
}
|
||||
|
||||
@@ -240,8 +240,8 @@ func (r *MediaRepository) DeleteByLibraryRoot(ctx context.Context, libraryID, ro
|
||||
Delete(&model.Media{}).Error
|
||||
}
|
||||
|
||||
// PurgeByLibrary permanently removes media tied to a library. Used for virtual
|
||||
// cloud mounts where "remove mount" must not populate the recycle bin.
|
||||
// PurgeByLibrary permanently removes media tied to a library. Used when
|
||||
// removing a library or virtual mount so indexed rows are dropped immediately.
|
||||
func (r *MediaRepository) PurgeByLibrary(ctx context.Context, libraryID string) error {
|
||||
return r.db.WithContext(ctx).Unscoped().Where("library_id = ?", libraryID).Delete(&model.Media{}).Error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
)
|
||||
|
||||
// DeleteMedia removes a media row from the library index.
|
||||
// When deleteFiles is true and the path is a local filesystem file, the media
|
||||
// file and its sidecar NFO are also removed. cloud:// paths are never touched on disk.
|
||||
func (s *MediaService) DeleteMedia(ctx context.Context, id string, deleteFiles bool) error {
|
||||
var media model.Media
|
||||
err := s.repo.DB.WithContext(ctx).Where("id = ?", id).First(&media).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if deleteFiles {
|
||||
if err := deleteLocalMediaFiles(s.log, media.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = s.repo.DB.WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&model.Media{}).Error
|
||||
if err == nil {
|
||||
s.invalidateMediaCache(ctx)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func deleteLocalMediaFiles(log *zap.Logger, path string) error {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(path), "cloud://") {
|
||||
if log != nil {
|
||||
log.Info("skip local file delete for cloud media path", zap.String("path", path))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := removeMediaAndNFO(path); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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 TestDeleteMediaInvalidatesMediaAndStatsCache(t *testing.T) {
|
||||
db := newServiceTestDB(t, &model.Media{})
|
||||
repos := repository.New(db)
|
||||
media := model.Media{
|
||||
Base: model.Base{ID: "local-media"},
|
||||
Title: "Cached Movie",
|
||||
Path: filepath.Join(t.TempDir(), "Cached Movie.mkv"),
|
||||
}
|
||||
if err := repos.DB.Create(&media).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cache := NewRuntimeCacheService(&config.Config{}, zap.NewNop())
|
||||
cache.SetJSON(t.Context(), "media:list:test", map[string]string{"state": "stale"}, time.Minute)
|
||||
cache.SetJSON(t.Context(), "stats:snapshot:base", map[string]int{"media": 1}, time.Minute)
|
||||
svc := NewMediaService(&config.Config{}, zap.NewNop(), repos).SetRuntimeCache(cache)
|
||||
if err := svc.DeleteMedia(t.Context(), media.ID, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var mediaCache map[string]string
|
||||
if cache.GetJSON(t.Context(), "media:list:test", &mediaCache) {
|
||||
t.Fatal("delete should invalidate media cache")
|
||||
}
|
||||
var statsCache map[string]int
|
||||
if cache.GetJSON(t.Context(), "stats:snapshot:base", &statsCache) {
|
||||
t.Fatal("delete should invalidate stats cache")
|
||||
}
|
||||
var count int64
|
||||
if err := db.Unscoped().Model(&model.Media{}).Where("id = ?", media.ID).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("media row still present, count=%d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMediaRemovesLocalFilesWhenRequested(t *testing.T) {
|
||||
db := newServiceTestDB(t, &model.Media{})
|
||||
repos := repository.New(db)
|
||||
dir := t.TempDir()
|
||||
mediaPath := filepath.Join(dir, "Movie.mkv")
|
||||
nfo := filepath.Join(dir, "Movie.nfo")
|
||||
if err := os.WriteFile(mediaPath, []byte("video"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(nfo, []byte("nfo"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
media := model.Media{
|
||||
Base: model.Base{ID: "local-delete-files"},
|
||||
Title: "Movie",
|
||||
Path: mediaPath,
|
||||
}
|
||||
if err := repos.DB.Create(&media).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
svc := NewMediaService(&config.Config{}, zap.NewNop(), repos)
|
||||
if err := svc.DeleteMedia(t.Context(), media.ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(mediaPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected media file removed, err=%v", err)
|
||||
}
|
||||
if _, err := os.Stat(nfo); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected nfo removed, err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMediaKeepsLocalFilesByDefault(t *testing.T) {
|
||||
db := newServiceTestDB(t, &model.Media{})
|
||||
repos := repository.New(db)
|
||||
dir := t.TempDir()
|
||||
mediaPath := filepath.Join(dir, "Keep.mkv")
|
||||
if err := os.WriteFile(mediaPath, []byte("video"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
media := model.Media{
|
||||
Base: model.Base{ID: "keep-files"},
|
||||
Title: "Keep",
|
||||
Path: mediaPath,
|
||||
}
|
||||
if err := repos.DB.Create(&media).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
svc := NewMediaService(&config.Config{}, zap.NewNop(), repos)
|
||||
if err := svc.DeleteMedia(t.Context(), media.ID, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(mediaPath); err != nil {
|
||||
t.Fatalf("expected media file kept, err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMediaSkipsCloudPaths(t *testing.T) {
|
||||
db := newServiceTestDB(t, &model.Media{})
|
||||
repos := repository.New(db)
|
||||
media := model.Media{
|
||||
Base: model.Base{ID: "cloud-media"},
|
||||
Title: "Cloud",
|
||||
Path: "cloud://openlist/Movie.mkv",
|
||||
}
|
||||
if err := repos.DB.Create(&media).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
svc := NewMediaService(&config.Config{}, zap.NewNop(), repos)
|
||||
if err := svc.DeleteMedia(t.Context(), media.ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Unscoped().Model(&model.Media{}).Where("id = ?", media.ID).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("cloud media row still present, count=%d", count)
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
)
|
||||
|
||||
const maxRecycleBinRecords = 200
|
||||
|
||||
// SoftDelete 物理删除媒体记录(统一硬删除以降低 SQLite 存储与索引压力)。
|
||||
func (s *MediaService) SoftDelete(ctx context.Context, id string) error {
|
||||
err := s.repo.DB.WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&model.Media{}).Error
|
||||
if err == nil {
|
||||
s.invalidateMediaCache(ctx)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// RestoreDeleted unsets DeletedAt for a single media row.
|
||||
func (s *MediaService) RestoreDeleted(ctx context.Context, id string) error {
|
||||
err := s.repo.DB.WithContext(ctx).Unscoped().Model(&model.Media{}).
|
||||
Where("id = ?", id).Update("deleted_at", nil).Error
|
||||
if err == nil {
|
||||
s.invalidateMediaCache(ctx)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ListRecycleBin returns every soft-deleted row, newest first.
|
||||
func (s *MediaService) ListRecycleBin(ctx context.Context, limit int) ([]model.Media, error) {
|
||||
if err := pruneRecycleBinRows(ctx, s.repo.DB, maxRecycleBinRecords); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if limit <= 0 || limit > maxRecycleBinRecords {
|
||||
limit = maxRecycleBinRecords
|
||||
}
|
||||
var rows []model.Media
|
||||
err := s.repo.DB.Unscoped().
|
||||
Where("deleted_at IS NOT NULL").
|
||||
Order("deleted_at desc").
|
||||
Limit(limit).
|
||||
Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func pruneRecycleBinRows(ctx context.Context, db *gorm.DB, keep int) error {
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
if keep <= 0 {
|
||||
keep = maxRecycleBinRecords
|
||||
}
|
||||
var rows []struct {
|
||||
ID string
|
||||
}
|
||||
if err := db.WithContext(ctx).Unscoped().
|
||||
Model(&model.Media{}).
|
||||
Select("id").
|
||||
Where("deleted_at IS NOT NULL").
|
||||
Order("deleted_at desc").
|
||||
Limit(100000).
|
||||
Offset(keep).
|
||||
Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if row.ID != "" {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return db.WithContext(ctx).Unscoped().Where("id IN ?", ids).Delete(&model.Media{}).Error
|
||||
}
|
||||
|
||||
// PurgeDeleted permanently removes a soft-deleted row from the database.
|
||||
func (s *MediaService) PurgeDeleted(ctx context.Context, id string) error {
|
||||
err := s.repo.DB.WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&model.Media{}).Error
|
||||
if err == nil {
|
||||
s.invalidateMediaCache(ctx)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/config"
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
"github.com/truewhile/MeBox/internal/repository"
|
||||
)
|
||||
|
||||
func TestListRecycleBinPrunesOldRowsOverLimit(t *testing.T) {
|
||||
db := newServiceTestDB(t, &model.Media{})
|
||||
repos := repository.New(db)
|
||||
now := time.Now()
|
||||
for i := 0; i < maxRecycleBinRecords+5; i++ {
|
||||
deletedAt := now.Add(time.Duration(i) * time.Second)
|
||||
media := model.Media{
|
||||
Base: model.Base{
|
||||
ID: fmt.Sprintf("media-%03d", i),
|
||||
DeletedAt: gorm.DeletedAt{Time: deletedAt, Valid: true},
|
||||
},
|
||||
Title: fmt.Sprintf("Movie %03d", i),
|
||||
Path: filepath.Join(t.TempDir(), fmt.Sprintf("Movie %03d.mkv", i)),
|
||||
}
|
||||
if err := db.Unscoped().Create(&media).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
svc := NewMediaService(&config.Config{}, zap.NewNop(), repos)
|
||||
rows, err := svc.ListRecycleBin(t.Context(), 500)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != maxRecycleBinRecords {
|
||||
t.Fatalf("recycle rows = %d, want %d", len(rows), maxRecycleBinRecords)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Unscoped().Model(&model.Media{}).Where("deleted_at IS NOT NULL").Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != maxRecycleBinRecords {
|
||||
t.Fatalf("stored recycle rows = %d, want %d", count, maxRecycleBinRecords)
|
||||
}
|
||||
var oldCount int64
|
||||
if err := db.Unscoped().Model(&model.Media{}).Where("id IN ?", []string{"media-000", "media-001", "media-002", "media-003", "media-004"}).Count(&oldCount).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if oldCount != 0 {
|
||||
t.Fatalf("oldest recycle rows were not pruned, count=%d", oldCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSoftDeleteInvalidatesMediaAndStatsCache(t *testing.T) {
|
||||
db := newServiceTestDB(t, &model.Media{})
|
||||
repos := repository.New(db)
|
||||
media := model.Media{
|
||||
Base: model.Base{ID: "local-media"},
|
||||
Title: "Cached Movie",
|
||||
Path: filepath.Join(t.TempDir(), "Cached Movie.mkv"),
|
||||
}
|
||||
if err := repos.DB.Create(&media).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cache := NewRuntimeCacheService(&config.Config{}, zap.NewNop())
|
||||
cache.SetJSON(t.Context(), "media:list:test", map[string]string{"state": "stale"}, time.Minute)
|
||||
cache.SetJSON(t.Context(), "stats:snapshot:base", map[string]int{"media": 1}, time.Minute)
|
||||
svc := NewMediaService(&config.Config{}, zap.NewNop(), repos).SetRuntimeCache(cache)
|
||||
if err := svc.SoftDelete(t.Context(), media.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var mediaCache map[string]string
|
||||
if cache.GetJSON(t.Context(), "media:list:test", &mediaCache) {
|
||||
t.Fatal("soft delete should invalidate media cache")
|
||||
}
|
||||
var statsCache map[string]int
|
||||
if cache.GetJSON(t.Context(), "stats:snapshot:base", &statsCache) {
|
||||
t.Fatal("soft delete should invalidate stats cache")
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,6 @@
|
||||
// organize_source opt-in — organize the configured staging folder.
|
||||
// transcode_cleanup every 24 h — purge HLS transcode artefacts
|
||||
// older than 24 h.
|
||||
// recycle_purge every 24 h — empty the recycle bin of rows
|
||||
// soft-deleted more than 30 days
|
||||
// ago.
|
||||
//
|
||||
// Each job runs at most once at a time (an in-flight run blocks the
|
||||
// next tick). All work happens on a long-lived background context so
|
||||
@@ -128,11 +125,6 @@ func (s *SchedulerService) Start(ctx context.Context) {
|
||||
interval: 24 * time.Hour,
|
||||
run: s.jobCleanTranscodeCache,
|
||||
},
|
||||
{
|
||||
name: "recycle_purge",
|
||||
interval: 24 * time.Hour,
|
||||
run: s.jobPurgeRecycleBin,
|
||||
},
|
||||
{
|
||||
name: "image_cache_cleanup",
|
||||
interval: 1 * time.Hour,
|
||||
|
||||
@@ -8,9 +8,6 @@ import (
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
)
|
||||
|
||||
// jobScanLibraries re-walks every enabled library.
|
||||
@@ -181,29 +178,6 @@ func (s *SchedulerService) jobCleanTranscodeCache(ctx context.Context) error {
|
||||
return walkAndPrune(s.cacheDir+"/hls", cutoff)
|
||||
}
|
||||
|
||||
// jobPurgeRecycleBin permanently deletes media rows soft-deleted >30 days
|
||||
// ago. The on-disk file is left untouched (delete is operator-driven).
|
||||
func (s *SchedulerService) jobPurgeRecycleBin(ctx context.Context) error {
|
||||
cutoff := time.Now().Add(-30 * 24 * time.Hour)
|
||||
res := s.repo.DB.WithContext(ctx).
|
||||
Unscoped().
|
||||
Where("deleted_at IS NOT NULL AND deleted_at < ?", cutoff).
|
||||
Delete(&model.Media{})
|
||||
if res.Error != nil && !isMissingTableErr(res.Error) {
|
||||
return res.Error
|
||||
}
|
||||
return pruneRecycleBinRows(ctx, s.repo.DB, maxRecycleBinRecords)
|
||||
}
|
||||
|
||||
// isMissingTableErr lets the test harness ignore "no such table" errors
|
||||
// that show up before AutoMigrate has run.
|
||||
func isMissingTableErr(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
return err == gorm.ErrInvalidDB
|
||||
}
|
||||
|
||||
// jobCleanImageCache prunes image proxy cache files when disk usage exceeds the configured limit.
|
||||
func (s *SchedulerService) jobCleanImageCache(ctx context.Context) error {
|
||||
if s.cacheDir == "" {
|
||||
|
||||
@@ -225,6 +225,19 @@ export const mediaAPI = {
|
||||
{ timeout: BATCH_REQUEST_TIMEOUT },
|
||||
)
|
||||
.then((r) => r.data),
|
||||
|
||||
delete: (id: string, options?: { deleteFiles?: boolean }) =>
|
||||
api
|
||||
.delete(`/media/${id}`, {
|
||||
params: options?.deleteFiles ? { delete_files: true } : undefined,
|
||||
})
|
||||
.then((r) => r.data),
|
||||
|
||||
exportNFO: (id: string) =>
|
||||
api.post<{ path: string }>(`/media/${id}/nfo`).then((r) => r.data),
|
||||
|
||||
exportLibraryNFO: (id: string) =>
|
||||
api.post<{ written: number }>(`/libraries/${id}/nfo`).then((r) => r.data),
|
||||
}
|
||||
|
||||
function episodeImageOption(options?: ScrapeOptions): boolean | undefined {
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { api } from './client'
|
||||
|
||||
export const recycleAPI = {
|
||||
softDelete: (id: string) => api.delete(`/media/${id}`).then((r) => r.data),
|
||||
|
||||
restore: (id: string) => api.post(`/media/${id}/restore`).then((r) => r.data),
|
||||
|
||||
purge: (id: string) => api.delete(`/media/${id}/purge`).then((r) => r.data),
|
||||
|
||||
exportNFO: (id: string) =>
|
||||
api.post<{ path: string }>(`/media/${id}/nfo`).then((r) => r.data),
|
||||
|
||||
exportLibraryNFO: (id: string) =>
|
||||
api.post<{ written: number }>(`/libraries/${id}/nfo`).then((r) => r.data),
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
|
||||
export type ConfirmOptions = {
|
||||
@@ -6,6 +7,13 @@ export type ConfirmOptions = {
|
||||
confirmText?: string
|
||||
cancelText?: string
|
||||
danger?: boolean
|
||||
checkboxLabel?: string
|
||||
checkboxDefaultChecked?: boolean
|
||||
}
|
||||
|
||||
export type ConfirmResult = {
|
||||
confirmed: boolean
|
||||
checked: boolean
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
@@ -13,13 +21,15 @@ export function ConfirmDialog({
|
||||
onClose,
|
||||
}: {
|
||||
options: ConfirmOptions
|
||||
onClose: (value: boolean) => void
|
||||
onClose: (value: ConfirmResult) => void
|
||||
}) {
|
||||
const danger = options.danger ?? true
|
||||
const hasCheckbox = Boolean(options.checkboxLabel)
|
||||
const [checked, setChecked] = useState(Boolean(options.checkboxDefaultChecked))
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/35 p-4 backdrop-blur-sm"
|
||||
onClick={() => onClose(false)}
|
||||
onClick={() => onClose({ confirmed: false, checked })}
|
||||
>
|
||||
<div
|
||||
role="dialog"
|
||||
@@ -40,20 +50,31 @@ export function ConfirmDialog({
|
||||
<h3 className="font-display text-lg font-bold text-ink-600">
|
||||
{options.title || '确认操作'}
|
||||
</h3>
|
||||
<p className="mt-2 text-sm leading-6 text-ink-50">{options.message}</p>
|
||||
<p className="mt-2 whitespace-pre-line text-sm leading-6 text-ink-50">{options.message}</p>
|
||||
{hasCheckbox ? (
|
||||
<label className="mt-4 flex cursor-pointer items-start gap-2.5 text-sm text-ink-100">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5 h-4 w-4 rounded border-gray-300 text-red-500 focus:ring-red-400"
|
||||
checked={checked}
|
||||
onChange={(event) => setChecked(event.target.checked)}
|
||||
/>
|
||||
<span>{options.checkboxLabel}</span>
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 border-t border-gray-100 bg-gray-50/80 px-5 py-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onClose(false)}
|
||||
onClick={() => onClose({ confirmed: false, checked })}
|
||||
className="rounded-xl border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-ink-100 hover:bg-gray-50"
|
||||
>
|
||||
{options.cancelText || '取消'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onClose(true)}
|
||||
onClick={() => onClose({ confirmed: true, checked })}
|
||||
className={
|
||||
'rounded-xl px-4 py-2 text-sm font-semibold text-white shadow-sm transition ' +
|
||||
(danger ? 'bg-red-500 hover:bg-red-600' : 'bg-brand-500 hover:bg-brand-600')
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { createRoot } from 'react-dom/client'
|
||||
|
||||
import { ConfirmDialog, type ConfirmOptions } from './ConfirmDialog'
|
||||
import { ConfirmDialog, type ConfirmOptions, type ConfirmResult } from './ConfirmDialog'
|
||||
|
||||
export function confirmAction(options: ConfirmOptions): Promise<boolean> {
|
||||
return confirmActionResult(options).then((result) => result.confirmed)
|
||||
}
|
||||
|
||||
export function confirmActionResult(options: ConfirmOptions): Promise<ConfirmResult> {
|
||||
return new Promise((resolve) => {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
const close = (value: boolean) => {
|
||||
const close = (value: ConfirmResult) => {
|
||||
root.unmount()
|
||||
host.remove()
|
||||
resolve(value)
|
||||
|
||||
@@ -10,7 +10,7 @@ type LibraryMovieActionsProps = {
|
||||
onManualScrape: (media: Media) => void
|
||||
onProbe: (media: Media) => void
|
||||
onNFO: (media: Media) => void
|
||||
onSoftDelete: (media: Media) => void
|
||||
onDelete: (media: Media) => void
|
||||
}
|
||||
|
||||
export function LibraryMovieActions({
|
||||
@@ -20,11 +20,11 @@ export function LibraryMovieActions({
|
||||
onManualScrape,
|
||||
onProbe,
|
||||
onNFO,
|
||||
onSoftDelete,
|
||||
onDelete,
|
||||
}: LibraryMovieActionsProps) {
|
||||
const buttonClass = 'flex h-8 w-8 items-center justify-center rounded-lg border border-white/70 bg-white/90 text-gray-700 shadow-sm backdrop-blur transition hover:bg-brand-50 hover:text-brand-600 disabled:opacity-50'
|
||||
|
||||
// 远程 Emby 条目为只读视图:刮削/探测/NFO/回收站不适用。
|
||||
// 远程 Emby 条目为只读视图:刮削/探测/NFO/删除不适用。
|
||||
if (isRemoteEmbyID(media.id)) {
|
||||
return null
|
||||
}
|
||||
@@ -43,7 +43,7 @@ export function LibraryMovieActions({
|
||||
<button title="写出本地 NFO" disabled={busy} onClick={() => onNFO(media)} className={buttonClass}>
|
||||
<FileText size={13} />
|
||||
</button>
|
||||
<button title="移入回收站" disabled={busy} onClick={() => onSoftDelete(media)} className={`${buttonClass} hover:!bg-red-50 hover:!text-red-500`}>
|
||||
<button title="删除" disabled={busy} onClick={() => onDelete(media)} className={`${buttonClass} hover:!bg-red-50 hover:!text-red-500`}>
|
||||
<Trash2 size={13} />
|
||||
</button>
|
||||
</>
|
||||
|
||||
@@ -162,7 +162,7 @@ export function LibraryPage() {
|
||||
handleSeriesProbe,
|
||||
handleSeriesNFO,
|
||||
handleSeriesOrganize,
|
||||
handleSeriesSoftDelete,
|
||||
handleSeriesDelete,
|
||||
movieActions,
|
||||
} = useLibraryAdminActions({
|
||||
libraryID: id,
|
||||
@@ -283,7 +283,7 @@ export function LibraryPage() {
|
||||
onProbe={handleSeriesProbe}
|
||||
onNFO={handleSeriesNFO}
|
||||
onOrganize={handleSeriesOrganize}
|
||||
onSoftDelete={handleSeriesSoftDelete}
|
||||
onDelete={handleSeriesDelete}
|
||||
onSeasonChange={setSelectedSeason}
|
||||
/>
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ type LibrarySeriesDetailHeaderProps = {
|
||||
onProbe: () => void
|
||||
onNFO: () => void
|
||||
onOrganize: () => void
|
||||
onSoftDelete: () => void
|
||||
onDelete: () => void
|
||||
}
|
||||
|
||||
export function LibrarySeriesDetailHeader({
|
||||
@@ -47,7 +47,7 @@ export function LibrarySeriesDetailHeader({
|
||||
onProbe,
|
||||
onNFO,
|
||||
onOrganize,
|
||||
onSoftDelete,
|
||||
onDelete,
|
||||
}: LibrarySeriesDetailHeaderProps) {
|
||||
const firstEpisode = firstPlayableEpisode(visibleEpisodes.length > 0 ? visibleEpisodes : allEpisodes)
|
||||
|
||||
@@ -131,9 +131,9 @@ export function LibrarySeriesDetailHeader({
|
||||
<FolderInput size={13} />
|
||||
<span>{seriesToolBusy === 'organize' ? '整理中…' : '整理当前合集'}</span>
|
||||
</button>
|
||||
<button onClick={onSoftDelete} disabled={!!seriesToolBusy} className="btn-outline px-3.5 py-2 text-xs gap-1.5 !border-red-100 !text-red-500 hover:!border-red-200 hover:!bg-red-50">
|
||||
<button onClick={onDelete} disabled={!!seriesToolBusy} className="btn-outline px-3.5 py-2 text-xs gap-1.5 !border-red-100 !text-red-500 hover:!border-red-200 hover:!bg-red-50">
|
||||
<Trash2 size={13} />
|
||||
<span>{seriesToolBusy === 'delete' ? '处理中…' : '移入回收站'}</span>
|
||||
<span>{seriesToolBusy === 'delete' ? '处理中…' : '删除'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -31,7 +31,7 @@ type LibrarySeriesDetailSectionProps = {
|
||||
onProbe: () => void
|
||||
onNFO: () => void
|
||||
onOrganize: () => void
|
||||
onSoftDelete: () => void
|
||||
onDelete: () => void
|
||||
onSeasonChange: (season: number) => void
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ export function LibrarySeriesDetailSection({
|
||||
onProbe,
|
||||
onNFO,
|
||||
onOrganize,
|
||||
onSoftDelete,
|
||||
onDelete,
|
||||
onSeasonChange,
|
||||
}: LibrarySeriesDetailSectionProps) {
|
||||
return (
|
||||
@@ -86,7 +86,7 @@ export function LibrarySeriesDetailSection({
|
||||
onProbe={onProbe}
|
||||
onNFO={onNFO}
|
||||
onOrganize={onOrganize}
|
||||
onSoftDelete={onSoftDelete}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
|
||||
<LibrarySeriesEpisodesPanel
|
||||
|
||||
@@ -14,7 +14,7 @@ type MediaDetailAdminPanelProps = {
|
||||
onOrganize: () => void
|
||||
onProbe: () => void
|
||||
onExportNFO: () => void
|
||||
onSoftDelete: () => void
|
||||
onDelete: () => void
|
||||
}
|
||||
|
||||
export function MediaDetailAdminPanel({
|
||||
@@ -27,7 +27,7 @@ export function MediaDetailAdminPanel({
|
||||
onOrganize,
|
||||
onProbe,
|
||||
onExportNFO,
|
||||
onSoftDelete,
|
||||
onDelete,
|
||||
}: MediaDetailAdminPanelProps) {
|
||||
if (isRemoteEmbyID(media.id)) {
|
||||
return null
|
||||
@@ -70,11 +70,11 @@ export function MediaDetailAdminPanel({
|
||||
<span>写出本地 NFO 属性</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={onSoftDelete}
|
||||
onClick={onDelete}
|
||||
className="btn-outline py-2 px-3.5 text-xs gap-1.5 !border-red-100 !text-red-500 hover:!bg-red-50 hover:!border-red-200"
|
||||
>
|
||||
<Trash2 size={13} />
|
||||
<span>移入回收站</span>
|
||||
<span>删除</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -42,7 +42,7 @@ export function MediaDetailPage() {
|
||||
onOrganize={() => detail.setOrganizeOpen(true)}
|
||||
onProbe={detail.reprobe}
|
||||
onExportNFO={detail.exportNFO}
|
||||
onSoftDelete={detail.softDelete}
|
||||
onDelete={detail.deleteMedia}
|
||||
/>
|
||||
|
||||
{detail.hasEpisodes && (
|
||||
|
||||
@@ -31,7 +31,7 @@ interface MediaDetailMainContentProps extends MediaDetailPlaybackActionsProps {
|
||||
onOrganize: () => void
|
||||
onProbe: () => void
|
||||
onExportNFO: () => void
|
||||
onSoftDelete: () => void
|
||||
onDelete: () => void
|
||||
}
|
||||
|
||||
interface MediaDetailDialogsProps {
|
||||
@@ -147,7 +147,7 @@ export function MediaDetailMainContent({
|
||||
onOrganize,
|
||||
onProbe,
|
||||
onExportNFO,
|
||||
onSoftDelete,
|
||||
onDelete,
|
||||
}: MediaDetailMainContentProps) {
|
||||
return (
|
||||
<div className="relative z-10 p-6 sm:p-10 flex flex-col md:flex-row gap-8 lg:gap-12">
|
||||
@@ -174,7 +174,7 @@ export function MediaDetailMainContent({
|
||||
onOrganize={onOrganize}
|
||||
onProbe={onProbe}
|
||||
onExportNFO={onExportNFO}
|
||||
onSoftDelete={onSoftDelete}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -3,9 +3,9 @@ import toast from 'react-hot-toast'
|
||||
|
||||
import { api } from '../api/client'
|
||||
import { libraryAPI } from '../api/library'
|
||||
import { recycleAPI } from '../api/recycle'
|
||||
import { mediaAPI } from '../api/library'
|
||||
import { toolsAPI } from '../api/tools'
|
||||
import { confirmAction } from '../components/confirmAction'
|
||||
import { confirmAction, confirmActionResult } from '../components/confirmAction'
|
||||
import type { Library, Media } from '../types'
|
||||
import { seriesTitle, type SeriesCard } from '../utils/groupSeries'
|
||||
import { LibraryMovieActions } from './LibraryMovieActions'
|
||||
@@ -92,7 +92,7 @@ export function useLibraryAdminActions({
|
||||
}
|
||||
|
||||
const handleSeriesNFO = () => {
|
||||
runSeriesTool('nfo', '整剧 NFO 写出', (media) => recycleAPI.exportNFO(media.id))
|
||||
runSeriesTool('nfo', '整剧 NFO 写出', (media) => mediaAPI.exportNFO(media.id))
|
||||
}
|
||||
|
||||
const handleSeriesOrganize = async () => {
|
||||
@@ -128,14 +128,16 @@ export function useLibraryAdminActions({
|
||||
}
|
||||
}
|
||||
|
||||
const handleSeriesSoftDelete = async () => {
|
||||
const handleSeriesDelete = async () => {
|
||||
if (!selectedSeries || selectedSeriesEpisodes.length === 0) return
|
||||
if (!(await confirmAction({
|
||||
title: '移入回收站',
|
||||
message: `将「${seriesTitle(selectedSeries.rep)}」的 ${selectedSeriesEpisodes.length} 个媒体移至回收站? (磁盘文件保留)`,
|
||||
confirmText: '移入回收站',
|
||||
}))) return
|
||||
await runSeriesTool('delete', '整剧移入回收站', (media) => recycleAPI.softDelete(media.id))
|
||||
const result = await confirmActionResult({
|
||||
title: '删除整剧',
|
||||
message: `确定从媒体库删除「${seriesTitle(selectedSeries.rep)}」的 ${selectedSeriesEpisodes.length} 个媒体?\n默认仅移除索引记录,磁盘文件会保留。`,
|
||||
confirmText: '删除',
|
||||
checkboxLabel: '同时删除本地文件(含同名 NFO)',
|
||||
})
|
||||
if (!result.confirmed) return
|
||||
await runSeriesTool('delete', '整剧删除', (media) => mediaAPI.delete(media.id, { deleteFiles: result.checked }))
|
||||
clearSelectedSeries()
|
||||
}
|
||||
|
||||
@@ -166,16 +168,18 @@ export function useLibraryAdminActions({
|
||||
}
|
||||
|
||||
const handleMovieNFO = (media: Media) => {
|
||||
runMovieTool(media, 'nfo', 'NFO 写出', (item) => recycleAPI.exportNFO(item.id))
|
||||
runMovieTool(media, 'nfo', 'NFO 写出', (item) => mediaAPI.exportNFO(item.id))
|
||||
}
|
||||
|
||||
const handleMovieSoftDelete = async (media: Media) => {
|
||||
if (!(await confirmAction({
|
||||
title: '移入回收站',
|
||||
message: `将「${media.title}」移至回收站? (磁盘文件保留)`,
|
||||
confirmText: '移入回收站',
|
||||
}))) return
|
||||
await runMovieTool(media, 'delete', '移入回收站', (item) => recycleAPI.softDelete(item.id))
|
||||
const handleMovieDelete = async (media: Media) => {
|
||||
const result = await confirmActionResult({
|
||||
title: '删除媒体',
|
||||
message: `确定从媒体库删除「${media.title}」?\n默认仅移除索引记录,磁盘文件会保留。`,
|
||||
confirmText: '删除',
|
||||
checkboxLabel: '同时删除本地文件(含同名 NFO)',
|
||||
})
|
||||
if (!result.confirmed) return
|
||||
await runMovieTool(media, 'delete', '删除', (item) => mediaAPI.delete(item.id, { deleteFiles: result.checked }))
|
||||
}
|
||||
|
||||
const movieActions = (media: Media): ReactNode => {
|
||||
@@ -188,7 +192,7 @@ export function useLibraryAdminActions({
|
||||
onManualScrape={setManualMovie}
|
||||
onProbe={handleMovieProbe}
|
||||
onNFO={handleMovieNFO}
|
||||
onSoftDelete={handleMovieSoftDelete}
|
||||
onDelete={handleMovieDelete}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -205,7 +209,7 @@ export function useLibraryAdminActions({
|
||||
handleSeriesProbe,
|
||||
handleSeriesNFO,
|
||||
handleSeriesOrganize,
|
||||
handleSeriesSoftDelete,
|
||||
handleSeriesDelete,
|
||||
movieActions,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,7 @@ import toast from 'react-hot-toast'
|
||||
import { api } from '../api/client'
|
||||
import { mediaAPI } from '../api/library'
|
||||
import { playbackAPI } from '../api/playback'
|
||||
import { recycleAPI } from '../api/recycle'
|
||||
import { confirmAction } from '../components/confirmAction'
|
||||
import { confirmActionResult } from '../components/confirmAction'
|
||||
import type { Media } from '../types'
|
||||
import { mediaLibraryBackTarget } from './MediaDetailPageModel'
|
||||
|
||||
@@ -181,11 +180,11 @@ function useMediaDetailActions({
|
||||
)
|
||||
const reprobe = useCallback(() => reprobeMedia(media, refresh), [media, refresh])
|
||||
const exportNFO = useCallback(() => exportMediaNFO(media), [media])
|
||||
const softDelete = useCallback(
|
||||
() => softDeleteMedia(media, navigate),
|
||||
const deleteMedia = useCallback(
|
||||
() => deleteMediaFromLibrary(media, navigate),
|
||||
[media, navigate],
|
||||
)
|
||||
return { goBack, toggleFavourite, rescrape, reprobe, exportNFO, softDelete }
|
||||
return { goBack, toggleFavourite, rescrape, reprobe, exportNFO, deleteMedia }
|
||||
}
|
||||
|
||||
function goBackFromMediaDetail(media: Media | null, navigate: NavigateFunction, replace = false): void {
|
||||
@@ -237,23 +236,24 @@ async function reprobeMedia(media: Media | null, refresh: () => Promise<void>):
|
||||
async function exportMediaNFO(media: Media | null): Promise<void> {
|
||||
if (!media) return
|
||||
try {
|
||||
const result = await recycleAPI.exportNFO(media.id)
|
||||
const result = await mediaAPI.exportNFO(media.id)
|
||||
toast.success(`NFO 已成功写入 ${result.path}`)
|
||||
} catch (err: unknown) {
|
||||
toast.error(apiErrorMessage(err, '导出失败'))
|
||||
}
|
||||
}
|
||||
|
||||
async function softDeleteMedia(media: Media | null, navigate: NavigateFunction): Promise<void> {
|
||||
async function deleteMediaFromLibrary(media: Media | null, navigate: NavigateFunction): Promise<void> {
|
||||
if (!media) return
|
||||
const confirmed = await confirmAction({
|
||||
title: '移入回收站',
|
||||
message: `将「${media.title}」移至回收站? (磁盘文件保留)`,
|
||||
confirmText: '移入回收站',
|
||||
const result = await confirmActionResult({
|
||||
title: '删除媒体',
|
||||
message: `确定从媒体库删除「${media.title}」?\n默认仅移除索引记录,磁盘文件会保留。`,
|
||||
confirmText: '删除',
|
||||
checkboxLabel: '同时删除本地文件(含同名 NFO)',
|
||||
})
|
||||
if (!confirmed) return
|
||||
await recycleAPI.softDelete(media.id)
|
||||
toast.success('已移至回收站')
|
||||
if (!result.confirmed) return
|
||||
await mediaAPI.delete(media.id, { deleteFiles: result.checked })
|
||||
toast.success(result.checked ? '已删除媒体及本地文件' : '已从媒体库删除')
|
||||
goBackFromMediaDetail(media, navigate, true)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user