Files
SublerMKV/Classes/MetadataImporters/MetadataHelper.swift
T
Scott GarrettandClaude Code f20ad7ee45 Search metadata directly from IDs embedded in file names
ParseFilename's movie-IMDB pattern now recognizes parenthesized years and
brace-wrapped service IDs, so names like "Movie (2024) {tmdb-1015812}" no
longer truncate to "Movie (2024) {tmdb". The ID kind is captured (imdb,
tmdb, tvdb, tt; IDs widened to 7-9 digits for modern IMDb IDs) and
emitted as an "id:<kind>:<value>" line.

Parsed IDs ride along in MetadataSearchTerms.movie as a MetadataFileID.
TheMovieDB answers direct lookups (movie/{id} for TMDb IDs, find +
external_source=imdb_id for IMDb IDs) as a movieIDSearch; the search
sheet, the queue metadata action, and the AppleScript fetch-metadata
command try the direct lookup first and fall back to the title search
when the ID is unknown or the provider doesn't support it. Index-based
AppleScript result commands keep the name search by design.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:10:25 -05:00

145 lines
4.9 KiB
Swift

//
// MetadataHelper.swift
// Subler
//
// Created by Damiano Galassi on 31/07/2017.
//
import Foundation
// MARK: - Filename
/// A metadata service ID embedded in the file name (e.g. `{tmdb-1015812}`).
public enum MetadataFileID: Equatable {
case tmdb(Int)
case tvdb(Int)
/// Normalized to the `tt…` form, leading zeros preserved.
case imdb(String)
}
public enum MetadataSearchTerms {
case none
/// `id` is a metadata service ID parsed from the file name, when present.
case movie(title: String, id: MetadataFileID? = nil)
case tvShow(seriesName: String, season: Int?, episode: Int?)
public var isMovie: Bool { get {
switch self {
case .movie:
return true
case .tvShow, .none:
return false
}
}
}
public var isTVShow: Bool {
get {
return !self.isMovie
}
}
}
private func parseAnimeFilename(_ filename: String) -> MetadataSearchTerms? {
guard let regex = try? NSRegularExpression(pattern: "^\\[(.+)\\](?:(?:\\s|_)+)?([^()]+)(?:(?:\\s|_)+)(?:(?:-\\s|-_|Ep)+)([0-9]+)", options: [.caseInsensitive]) else { return nil }
var result: MetadataSearchTerms?
regex.enumerateMatches(in: filename, options: [],
range: NSRange(filename.startIndex..., in: filename)) {
(match, flags, stop) in
if let seriesNameRange = match?.range(at: 2), let episodeRange = match?.range(at: 3) {
let seriesName = (filename as NSString).substring(with: seriesNameRange)
let episode = Int((filename as NSString).substring(with: episodeRange))
if seriesName.isEmpty == false {
result = MetadataSearchTerms.tvShow(seriesName: seriesName, season: 1, episode: episode)
}
}
}
return result
}
/// Parses the `id:<kind>:<value>` line emitted by ParseFilename.pl, when present.
private func parseFileID(_ lines: [Substring]) -> MetadataFileID? {
guard let idLine = lines.first(where: { $0.hasPrefix("id:") }) else { return nil }
let components = idLine.dropFirst(3).split(separator: ":", omittingEmptySubsequences: false)
guard components.count == 2, components[1].isEmpty == false else { return nil }
let kind = components[0]
let value = components[1]
switch kind {
case "tmdb":
return Int(value).map(MetadataFileID.tmdb)
case "tvdb":
return Int(value).map(MetadataFileID.tvdb)
case "imdb", "tt":
// The parser strips the `tt` prefix from IMDb IDs; the find API wants it back.
return .imdb("tt" + value)
default:
// A bare number with no known prefix is too ambiguous for a direct lookup.
return nil
}
}
private func parseFilename(_ filename: String) -> MetadataSearchTerms? {
guard let path = Bundle.main.path(forResource: "ParseFilename", ofType: "") else { return nil }
let stdOut = Pipe()
let stdOutWrite = stdOut.fileHandleForWriting
// Use the ParseFilename perl script
let task = Process()
task.launchPath = "/usr/bin/perl"
task.arguments = ["-I\(path)/lib", "\(path)/ParseFilename.pl", filename]
task.standardOutput = stdOutWrite
task.launch()
task.waitUntilExit()
stdOutWrite.closeFile()
let outputData = stdOut.fileHandleForReading.readDataToEndOfFile()
guard let outputString = String(data: outputData, encoding: .utf8) else { return nil }
let lines = outputString.split(separator: "\n")
if lines.isEmpty == false {
if lines.first == "tv" && lines.count >= 4 {
let newSeriesName = lines[1].isEmpty == false ? lines[1].replacingOccurrences(of: ".", with: " ") : filename
return MetadataSearchTerms.tvShow(seriesName: newSeriesName, season: Int(lines[2]), episode: Int(lines[3]))
}
else if lines.first == "movie" && lines.count >= 2 {
let newTitle = lines[1].replacingOccurrences(of: ".", with: " ")
.replacingOccurrences(of: "(", with: " ")
.replacingOccurrences(of: ")", with: " ")
.replacingOccurrences(of: "[", with: " ")
.replacingOccurrences(of: "]", with: " ")
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return MetadataSearchTerms.movie(title: newTitle, id: parseFileID(lines))
}
}
return nil
}
extension String {
func parsedAsFilename() -> MetadataSearchTerms {
if let parsed = parseAnimeFilename(self) {
return parsed
}
else if let parsed = parseFilename(self) {
return parsed
}
return .none
}
func trimmingWhitespacesAndNewlinews() -> String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}