// // 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. /// `year` is a release year parsed from the file name, when present; it /// lets search-result ranking prefer the same-year entry. case movie(title: String, id: MetadataFileID? = nil, year: Int? = 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::` 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 } } // 1950–2099 keeps resolutions (720/1080) and tiny numbers out of the match. // Group 1 is the year in both; the class metacharacters must be escaped or // ICU refuses to compile the pattern at all. private let bracketedYearRegex = try? NSRegularExpression(pattern: "[\\(\\[\\{](19[5-9][0-9]|20[0-9][0-9])[\\)\\]\\}]") private let delimitedYearRegex = try? NSRegularExpression(pattern: "[._ ](19[5-9][0-9]|20[0-9][0-9])(?:[._ ]|$)") /// Extracts a release year from the file name. ParseFilename strips the year /// from the title it emits but never reports it, so it is recovered here. /// Bracketed years (`(2026)`, `[2026]`, `{2026}`) are the authoritative /// release-name decoration and win over bare dot/space-delimited ones, which /// can also hit resolution numbers (`Movie.1920.1080p.x264`). private func parseFilenameYear(_ filename: String) -> Int? { for regex in [bracketedYearRegex, delimitedYearRegex].compactMap({ $0 }) { guard let match = regex.firstMatch(in: filename, range: NSRange(filename.startIndex..., in: filename)), let yearRange = Range(match.range(at: 1), in: filename) else { continue } return Int(filename[yearRange]) } 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), year: parseFilenameYear(filename)) } } 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) } /// The release year decorated in a file name (`Title (2026)`, `Title.2026`), when present. func parsedAsFilenameYear() -> Int? { return parseFilenameYear(self) } } // MARK: - Movie result ranking private func normalizedSearchTitle(_ title: String) -> String { let folded = title.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) return String(String.UnicodeScalarView(folded.unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) })) } /// The release year of a search result, as far as its (usually ISO) release /// date string exposes it. private func movieResultYear(_ result: MetadataResult) -> Int? { guard let releaseDate = result[.releaseDate] as? String else { return nil } return Int(releaseDate.split(separator: "-").first ?? "") } /// Orders movie title-search results so the most likely match for a searched /// title comes first: exact title matches on top (year-matching ones before /// the rest), then year-matching fuzzy hits, then the service's own order. /// The sort is stable, so the provider's relevance ranking survives inside /// each band — it only stops exact matches from being scattered among the /// fuzzy ones. Keep every caller indexing into the same list ranking the same /// way (the AppleScript result list and its index-based fetch must agree). func rankMovieResults(_ results: [MetadataResult], title: String, year: Int?) -> [MetadataResult] { let wanted = normalizedSearchTitle(title) func rank(_ result: MetadataResult) -> Int { let name = (result[.name] as? String).map(normalizedSearchTitle) let titleMatch = wanted.isEmpty == false && name == wanted let yearMatch = year != nil && movieResultYear(result) == year switch (titleMatch, yearMatch) { case (true, true): return 3 case (true, false): return 2 case (false, true): return 1 case (false, false): return 0 } } struct Ranked { let offset: Int; let result: MetadataResult; let rank: Int } let ranked = results.enumerated().map { Ranked(offset: $0.offset, result: $0.element, rank: rank($0.element)) } let ordered: [Ranked] = ranked.sorted { (a: Ranked, b: Ranked) -> Bool in return a.rank != b.rank ? a.rank > b.rank : a.offset < b.offset } return ordered.map { $0.result } }