Files
MeBox/internal/service/media_library.go
T
truewhile 0d9ba2c33a 处理删库重建库没有媒体数据bug
本地文件入库媒体库删除后重新入库导致0条目bug
2026-08-19 22:33:23 +08:00

63 lines
2.0 KiB
Go

package service
import (
"context"
"github.com/ShukeBta/MediaStationGo/internal/model"
"gorm.io/gorm"
)
// ListLibraries returns every library configured on the server.
func (s *MediaService) ListLibraries(ctx context.Context) ([]model.Library, error) {
return s.repo.Library.List(ctx)
}
// DeleteLibrary removes a library and its media rows. The on-disk files are
// left untouched.
func (s *MediaService) DeleteLibrary(ctx context.Context, id string) error {
lib, err := s.repo.Library.FindByID(ctx, id)
if err != nil {
return err
}
if lib != nil {
if _, ok := ParseCloudLibraryMount(lib.Path); ok {
err := s.repo.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Unscoped().Where("library_id = ?", id).Delete(&model.Media{}).Error; err != nil {
return err
}
if err := hardDeleteLibraryRoots(ctx, tx, id); err != nil {
return err
}
return tx.Unscoped().Where("id = ?", id).Delete(&model.Library{}).Error
})
if err == nil {
s.invalidateMediaCache(ctx)
}
return err
}
}
err = s.repo.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 本地库媒体行统一硬删除(与云库分支一致):删库即彻底清空该库的
// media 行,避免重扫时旧行被 upsert 复活却仍挂在已删库下,导致重建
// 同名库后条目始终为 0。只作用于数据库表行,磁盘文件不受影响。
if err := tx.Unscoped().Where("library_id = ?", id).Delete(&model.Media{}).Error; err != nil {
return err
}
if err := hardDeleteLibraryRoots(ctx, tx, id); err != nil {
return err
}
return tx.Delete(&model.Library{}, "id = ?", id).Error
})
if err == nil {
s.invalidateMediaCache(ctx)
}
return err
}
func hardDeleteLibraryRoots(ctx context.Context, tx *gorm.DB, libraryID string) error {
if tx == nil || !tx.Migrator().HasTable(&model.LibraryRoot{}) {
return nil
}
return tx.WithContext(ctx).Unscoped().Where("library_id = ?", libraryID).Delete(&model.LibraryRoot{}).Error
}