mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 11:36:36 +08:00
fix: prevent episode metadata from splitting series
This commit is contained in:
@@ -419,13 +419,10 @@ func mergeArtworkMetadata(meta *LocalMetadata, mediaPath, showBaseDir string) {
|
||||
func mergeEpisodeMetadata(dst, episode *LocalMetadata, doc *nfoDocument) {
|
||||
showTitle := cleanXMLText(doc.ShowTitle)
|
||||
// 整剧标题: 优先 <showtitle>(MoviePilot 在单集 NFO 里也会写整剧名);
|
||||
// 其次保留 dst 已有(来自 tvshow.nfo);最后才退而用单集名占位。
|
||||
// 其次保留 dst 已有(来自 tvshow.nfo)。不要把单集 <title> 当整剧标题,
|
||||
// 否则会把"第 11 集/第几期"整理成整剧目录并污染后续 TMDb 查询。
|
||||
if showTitle != "" {
|
||||
dst.Title = showTitle
|
||||
} else if dst.Title == "" {
|
||||
if episodeTitle := cleanXMLText(doc.Title); episodeTitle != "" {
|
||||
dst.Title = episodeTitle
|
||||
}
|
||||
}
|
||||
// 注意: 不要把单集名 / 单集 originaltitle 写进 OriginalName(整剧原名,分组键)。
|
||||
if episodeTitle := firstText(episode.EpisodeTitle, doc.Title); episodeTitle != "" && !strings.EqualFold(episodeTitle, showTitle) {
|
||||
|
||||
@@ -79,6 +79,39 @@ func TestReadLocalEpisodeMetadataMergesShowAndEpisode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLocalEpisodeMetadataWithoutShowTitleDoesNotUseEpisodeTitleAsSeries(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
showDir := filepath.Join(root, "哈哈哈哈哈")
|
||||
seasonDir := filepath.Join(showDir, "Season 06")
|
||||
if err := os.MkdirAll(seasonDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mediaPath := filepath.Join(seasonDir, "哈哈哈哈哈 - S06E11.mkv")
|
||||
if err := os.WriteFile(mediaPath, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(nfoPath(mediaPath), []byte(`<episodedetails><title>第 11 集</title><season>6</season><episode>11</episode><uniqueid type="tmdb">4375419</uniqueid></episodedetails>`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := ReadLocalMetadata(mediaPath, root, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatal("metadata is nil")
|
||||
}
|
||||
if got.Title != "" {
|
||||
t.Fatalf("episode title must not become series title, got %q", got.Title)
|
||||
}
|
||||
if got.EpisodeTitle != "第 11 集" || got.SeasonNum != 6 || got.EpisodeNum != 11 {
|
||||
t.Fatalf("episode metadata not preserved: %+v", got)
|
||||
}
|
||||
if got.TMDbID != 0 {
|
||||
t.Fatalf("episode-level tmdb id must not become series tmdb id, got %d", got.TMDbID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLocalEpisodeMetadataIgnoresNoneNumericFields(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
showDir := filepath.Join(root, "链锯人 总集篇 (2025)")
|
||||
|
||||
@@ -221,7 +221,11 @@ func seriesTitleFromMediaPath(path string) string {
|
||||
if dirIndex < 0 {
|
||||
return ""
|
||||
}
|
||||
return normalizeSeriesPathTitle(parts[dirIndex])
|
||||
title := normalizeSeriesPathTitle(parts[dirIndex])
|
||||
if unsafeAutomaticEpisodeQuery(title) {
|
||||
return ""
|
||||
}
|
||||
return title
|
||||
}
|
||||
|
||||
func seriesDisplayTitle(media model.Media) string {
|
||||
|
||||
@@ -138,6 +138,9 @@ func organizeMetadataMatchTrusted(query string, sourceYear int, match *Match) bo
|
||||
if match == nil || strings.TrimSpace(match.Title) == "" {
|
||||
return false
|
||||
}
|
||||
if unsafeAutomaticEpisodeQuery(query) {
|
||||
return false
|
||||
}
|
||||
if sourceYear > 0 && match.Year > 0 {
|
||||
diff := sourceYear - match.Year
|
||||
if diff < 0 {
|
||||
|
||||
@@ -75,6 +75,73 @@ func TestOrganizeDirectoryRejectsWrongYearScraperRename(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizeDirectoryDoesNotUseEpisodeNFOTitleAsSeriesTitle(t *testing.T) {
|
||||
var queries []string
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
queries = append(queries, r.URL.Query().Get("query"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path != "/search/tv" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("query") != "哈哈哈哈哈" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"results": []any{}})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"results": []map[string]any{{
|
||||
"id": 112732,
|
||||
"name": "哈哈哈哈哈",
|
||||
"first_air_date": "2026-01-01",
|
||||
}},
|
||||
})
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
repos := newOrganizerTestRepo(t)
|
||||
cfg := &config.Config{}
|
||||
cfg.Secrets.TMDbAPIKey = "test-key"
|
||||
cfg.Secrets.TMDbAPIProxy = upstream.URL
|
||||
scraper := NewScraperService(cfg, zap.NewNop(), repos, NewTMDbProvider(cfg, zap.NewNop(), nil), nil, nil, nil, NewHub(zap.NewNop()))
|
||||
|
||||
root := t.TempDir()
|
||||
src := filepath.Join(root, "downloads")
|
||||
dest := filepath.Join(root, "media")
|
||||
sourceFile := filepath.Join(src, "哈哈哈哈哈", "Season 06", "哈哈哈哈哈 - S06E11.mkv")
|
||||
writeOrgFile(t, sourceFile, "episode")
|
||||
if err := os.WriteFile(nfoPath(sourceFile), []byte(`<episodedetails><title>第 11 集</title><season>6</season><episode>11</episode><tmdbid>7129825</tmdbid></episodedetails>`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
organizer := NewOrganizerService(cfg, zap.NewNop(), repos)
|
||||
organizer.SetScraper(scraper)
|
||||
res, err := organizer.OrganizeDirectory(t.Context(), OrganizeOptions{
|
||||
SourcePath: src,
|
||||
DestPath: dest,
|
||||
TransferMode: TransferCopy,
|
||||
MediaType: "tv",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("organize directory: %v", err)
|
||||
}
|
||||
if res.Organized != 1 {
|
||||
t.Fatalf("organized = %d, want 1; items=%#v errors=%#v queries=%v", res.Organized, res.Items, res.Errors, queries)
|
||||
}
|
||||
rejected := filepath.Join(dest, "电视剧", "第 11 集", "Season 06", "第 11 集 - S06E11.mkv")
|
||||
if _, err := os.Stat(rejected); err == nil {
|
||||
t.Fatalf("episode title should not be used as series folder: %q", rejected)
|
||||
}
|
||||
want := filepath.Join(dest, "电视剧", "哈哈哈哈哈", "Season 06", "哈哈哈哈哈 - S06E11.mkv")
|
||||
if _, err := os.Stat(want); err != nil {
|
||||
t.Fatalf("expected organized file at %q: %v; items=%#v queries=%v", want, err, res.Items, queries)
|
||||
}
|
||||
for _, query := range queries {
|
||||
if unsafeAutomaticEpisodeQuery(query) {
|
||||
t.Fatalf("organizer queried unsafe episode title %q; all queries=%v", query, queries)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizeDirectoryDedupsByExternalIDBeforeRename(t *testing.T) {
|
||||
scraper, repos, closeServer := newTestScraper(t)
|
||||
defer closeServer()
|
||||
|
||||
@@ -55,6 +55,13 @@ var releaseBoundaryTokenSet = map[string]struct{}{
|
||||
"x264": {}, "x265": {}, "h264": {}, "h265": {}, "hevc": {}, "avc": {},
|
||||
}
|
||||
|
||||
var (
|
||||
episodeOnlyQueryRE = regexp.MustCompile(`(?i)^\s*(?:e(?:p(?:isode)?)?\s*\d{1,3}|episode\s*\d{1,3}|第\s*[0-9一二三四五六七八九十百零两]+\s*[集期话話](?:\s*[上下])?)\s*$`)
|
||||
episodeTitleQueryRE = regexp.MustCompile(`^\s*第\s*[0-9一二三四五六七八九十百零两]+\s*[集期话話](?:\s*[上下])?\s*[::].+`)
|
||||
genericEpisodeWordsRE = regexp.MustCompile(`^\s*第\s*[集期话話]\s*$`)
|
||||
episodeReleaseTitleTagRE = regexp.MustCompile(`(?i)(?:^|[\s._-])s\d{1,2}e\d{1,3}(?:[\s._-]|$)`)
|
||||
)
|
||||
|
||||
// bracketedTag matches "[anything]", "(anything)" or "{anything}" segments.
|
||||
var bracketedTag = regexp.MustCompile(`[\[\(\{][^\]\)\}]*[\]\)\}]`)
|
||||
var multiWordNoise = []*regexp.Regexp{
|
||||
@@ -150,6 +157,9 @@ func scrapeQueryCandidates(m *model.Media, lib *model.Library) []string {
|
||||
cleaned = strings.TrimSpace(raw)
|
||||
}
|
||||
for _, candidate := range titleCandidates(cleaned) {
|
||||
if unsafeAutomaticEpisodeQuery(candidate) {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(candidate)
|
||||
if _, ok := seen[key]; ok || candidate == "" {
|
||||
continue
|
||||
@@ -394,3 +404,26 @@ func librarySupportsSeasons(lib *model.Library) bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func unsafeAutomaticEpisodeQuery(query string) bool {
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
return true
|
||||
}
|
||||
if episodeOnlyQueryRE.MatchString(query) || genericEpisodeWordsRE.MatchString(query) {
|
||||
return true
|
||||
}
|
||||
if episodeTitleQueryRE.MatchString(query) {
|
||||
return true
|
||||
}
|
||||
_, episode := ParseEpisode(query)
|
||||
if episode > 0 && !looksLikeSeriesReleaseTitle(query) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func looksLikeSeriesReleaseTitle(query string) bool {
|
||||
cleaned, _ := CleanQuery(query)
|
||||
return strings.TrimSpace(cleaned) != "" && episodeReleaseTitleTagRE.MatchString(query)
|
||||
}
|
||||
|
||||
@@ -272,6 +272,42 @@ func TestScrapeQueryCandidatesUseSeriesLibraryRootWhenMountedAtShowFolder(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
func TestScrapeQueryCandidatesSkipEpisodeOnlyTitles(t *testing.T) {
|
||||
lib := &model.Library{
|
||||
Path: `F:\media\电视剧\欧美剧`,
|
||||
Type: "tv",
|
||||
}
|
||||
media := &model.Media{
|
||||
Title: "第1期上:最狠开局!五哈团命悬一线好刺激",
|
||||
Path: `F:\media\电视剧\欧美剧\第1期上:最狠开局!五哈团命悬一线好刺激 (2026)\Season 6\第1期上:最狠开局!五哈团命悬一线好刺激 - S06E01 - 第 1 集.mkv`,
|
||||
SeasonNum: 6,
|
||||
EpisodeNum: 1,
|
||||
}
|
||||
|
||||
got := scrapeQueryCandidates(media, lib)
|
||||
for _, candidate := range got {
|
||||
if unsafeAutomaticEpisodeQuery(candidate) {
|
||||
t.Fatalf("query candidates kept unsafe episode title %q: %#v", candidate, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizeMetadataRejectsEpisodeOnlyQuery(t *testing.T) {
|
||||
match := &Match{Title: "错误节目", Year: 2026, TMDbID: 284725}
|
||||
for _, query := range []string{"第 11 集", "第1期上:最狠开局!五哈团命悬一线好刺激"} {
|
||||
if organizeMetadataMatchTrusted(query, 2026, match) {
|
||||
t.Fatalf("episode-only query %q must not be trusted for automatic match", query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeriesTitleFromMediaPathIgnoresEpisodeOnlyFolder(t *testing.T) {
|
||||
got := seriesTitleFromMediaPath(`F:\media\电视剧\欧美剧\第 11 集 (2026)\Season 6\第 11 集 - S06E11.mkv`)
|
||||
if got != "" {
|
||||
t.Fatalf("series title from episode-only folder = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaIsEpisodicUsesEpisodePatternInPath(t *testing.T) {
|
||||
lib := &model.Library{
|
||||
Path: `/media/movies`,
|
||||
|
||||
@@ -122,7 +122,8 @@ const SERIES_SPECIAL_CJK_RE =
|
||||
function normalizePathSeriesTitle(value?: string): string {
|
||||
const title = normalizeTitle(value)
|
||||
const stripped = stripSeriesSpecialSuffix(title)
|
||||
return stripped || title
|
||||
const normalized = stripped || title
|
||||
return unsafeEpisodeTitle(normalized) ? '' : normalized
|
||||
}
|
||||
|
||||
function stripSeriesSpecialSuffix(title: string): string {
|
||||
@@ -133,6 +134,17 @@ function stripSeriesSpecialSuffix(title: string): string {
|
||||
return title
|
||||
}
|
||||
|
||||
const EPISODE_ONLY_TITLE_RE =
|
||||
/^(?:e(?:p(?:isode)?)?\s*\d{1,3}|episode\s*\d{1,3}|第\s*[0-9一二三四五六七八九十百零两]+\s*[集期话話](?:\s*[上下])?|第\s*[集期话話])$/i
|
||||
|
||||
const EPISODE_TITLE_RE =
|
||||
/^第\s*[0-9一二三四五六七八九十百零两]+\s*[集期话話](?:\s*[上下])?\s*[::].+/
|
||||
|
||||
function unsafeEpisodeTitle(title: string): boolean {
|
||||
const value = title.trim()
|
||||
return EPISODE_ONLY_TITLE_RE.test(value) || EPISODE_TITLE_RE.test(value)
|
||||
}
|
||||
|
||||
export function seriesTitleFromPath(path?: string): string {
|
||||
if (!path) return ''
|
||||
const parts = path.split(/[\\/]+/).filter(Boolean)
|
||||
|
||||
Reference in New Issue
Block a user