diff --git a/CHANGES.md b/CHANGES.md index d3ebd00..f27a839 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,7 +8,7 @@ original Subler checkout. from the GitHub Subler project. - **Since then**: 18 commits in the app repository and 15 in the **MP42Foundation** submodule (2026-11-25 → 2026-11-28). -- **Fork identity**: version `1.9.5mkv1` (upstream base + `mkv` + a fork +- **Fork identity**: version `1.9.5mkv2` (upstream base + `mkv` + a fork change counter), builds as `SublerMKV.app` (`org.galad.SublerMKV`); development moved from GitHub to Gitea (`git.technomancer.com:Scott-Files/`). @@ -138,6 +138,23 @@ inside the app bundle so they never drift from the app's own code. The search sheet, the queue metadata action, and the AppleScript fetch-metadata command try the direct TMDb lookup first and fall back to title search when the ID is unknown or unsupported. + - **ID lookup now fires on already-tagged files**: `extractSearchTerms` + short-circuited to the file's existing name/release-date/media-kind when a + movie was already tagged, returning a bare title and **dropping the + embedded ID** — so a second search on a tagged (or previously-searched) + file ignored its `{tmdb-…}`. That branch now also parses the file name, so + the direct lookup works regardless of prior tagging. +- **Search-result ranking**: movie title-search results are re-ordered (in the + sheet, the queue metadata action, and both AppleScript commands, with + identical ranking so scripted indexes stay aligned) so **exact title matches + sort to the top** of the fuzzy TMDb list, with a **parsed release year** + used to pick the default entry — exact+year first, then exact, then + year-only, then the provider's own order (a stable sort, so relevance + survives within each band). The year is recovered from the file name in + Swift (ParseFilename strips it from the title without reporting it); + bracketed years `(2026)` win over bare dot/space years so resolutions like + `.1920.1080p` don't win. The chosen default is also highlighted in the + results list. ## 4. Fork infrastructure and distribution @@ -151,7 +168,7 @@ inside the app bundle so they never drift from the app's own code. updates itself however its users choose. - **Fork version scheme `.mkv`** distinguishes fork builds from upstream without touching the forked-from version: the trailing counter in - `MARKETING_VERSION`/`CURRENT_PROJECT_VERSION` (currently `1.9.5mkv1`) + `MARKETING_VERSION`/`CURRENT_PROJECT_VERSION` (currently `1.9.5mkv2`) increments with each batch of fork changes, and restarts at 1 whenever upstream's base version moves. - **Build output renamed `SublerMKV.app`**: target renamed and `PRODUCT_NAME` diff --git a/Classes/ChapterSearchController.swift b/Classes/ChapterSearchController.swift index b661b4c..504a848 100644 --- a/Classes/ChapterSearchController.swift +++ b/Classes/ChapterSearchController.swift @@ -41,7 +41,7 @@ final class ChapterSearchController: ViewController, NSTableViewDataSource, NSTa switch info { - case .movie(let title, _): + case .movie(let title, _, _): searchTerm = title case .tvShow, .none: searchTerm = title diff --git a/Classes/MP42FileAdditions.swift b/Classes/MP42FileAdditions.swift index 58e0dc6..dfaaa4f 100644 --- a/Classes/MP42FileAdditions.swift +++ b/Classes/MP42FileAdditions.swift @@ -51,15 +51,26 @@ extension MP42File { let _ = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyReleaseDate).first?.stringValue, let mediaKind = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyMediaKind).first?.numberValue?.intValue, mediaKind == MediaKind.movie.rawValue { - return MetadataSearchTerms.movie(title: title) + // Only the file name can carry a service ID or release year, so parse + // it even when the metadata already describes the movie: an already + // tagged file (or one tagged by an earlier search) still gets the + // direct ID lookup and the year preference from `{tmdb-…}`-style names. + var fileID: MetadataFileID? + var fileYear: Int? + if let url = firstSourceURL ?? fallbackURL, + case let .movie(_, urlID, urlYear) = url.deletingPathExtension().lastPathComponent.parsedAsFilename() { + fileID = urlID + fileYear = urlYear + } + return MetadataSearchTerms.movie(title: title, id: fileID, year: fileYear) } else if let url = firstSourceURL ?? fallbackURL { let parsed = url.deletingPathExtension().lastPathComponent.parsedAsFilename() switch parsed { case .none: - let title = url.deletingPathExtension().lastPathComponent - return MetadataSearchTerms.movie(title: title) + let name = url.deletingPathExtension().lastPathComponent + return MetadataSearchTerms.movie(title: name, year: name.parsedAsFilenameYear()) case .tvShow, .movie: return parsed diff --git a/Classes/MetadataImporters/MetadataHelper.swift b/Classes/MetadataImporters/MetadataHelper.swift index a3a0d5e..f5ba96b 100644 --- a/Classes/MetadataImporters/MetadataHelper.swift +++ b/Classes/MetadataImporters/MetadataHelper.swift @@ -20,7 +20,9 @@ public enum MetadataFileID: Equatable { 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) + /// `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 { @@ -87,6 +89,26 @@ private func parseFileID(_ lines: [Substring]) -> MetadataFileID? { } } +// 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 } @@ -119,7 +141,7 @@ private func parseFilename(_ filename: String) -> MetadataSearchTerms? { .replacingOccurrences(of: "[", with: " ") .replacingOccurrences(of: "]", with: " ") .trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) - return MetadataSearchTerms.movie(title: newTitle, id: parseFileID(lines)) + return MetadataSearchTerms.movie(title: newTitle, id: parseFileID(lines), year: parseFilenameYear(filename)) } } @@ -141,4 +163,53 @@ extension String { 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 } } diff --git a/Classes/MetadataSearchController.swift b/Classes/MetadataSearchController.swift index a5df5c7..ac9b5a7 100644 --- a/Classes/MetadataSearchController.swift +++ b/Classes/MetadataSearchController.swift @@ -60,6 +60,10 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N /// Service ID parsed from the file name: consumed by the first automatic movie search. private var pendingMovieID: MetadataFileID? + /// Release year parsed from the file name: consumed by the first completed + /// movie search, so it only steers the search seeded by the file name. + private var pendingMovieYear: Int? + private var movieService: MetadataService = MetadataSearch.defaultMovieService private var tvShowService: MetadataService = MetadataSearch.defaultTVService @@ -125,11 +129,12 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N case .none: updateUI() - case .movie(let title, let id): + case .movie(let title, let id, let year): searchMode.selectTabViewItem(at: 0) movieName.stringValue = title tvSeriesName.stringValue = title pendingMovieID = id + pendingMovieYear = year searchForResults(searchMovieButton) case .tvShow(let tvShow, let season, let episode): @@ -295,6 +300,14 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N private func searchDone(search: MetadataSearch, results: [MetadataResult]) { DispatchQueue.main.async { + var results = results + if search.type == .movie { + // Exact title matches first, the file-name year preferred among + // them; the parsed year steers only the search seeded by the + // file name, so it is consumed here. + results = rankMovieResults(results, title: self.movieName.stringValue, year: self.pendingMovieYear) + self.pendingMovieYear = nil + } if let first = results.first { self.state = .completed(search: search, results: results, selectedResult: first) } @@ -418,9 +431,14 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N startProgressReport() reloadTableData() swithDefaultButton(from: addButton, to: visibleSearchButton(), disableOldButton: true) - case .completed: + case .completed(_, let results, let selectedResult): stopProgressReport() reloadTableData() + // Highlight the default pick (the ranked first result) so the + // user sees what Add would apply. + if let index = results.firstIndex(where: { $0 === selectedResult }) { + resultsTable.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false) + } swithDefaultButton(from: searchMovieButton, to: addButton, disableOldButton: nil) swithDefaultButton(from: searchTvButton, to: addButton, disableOldButton: nil) updateSearchButtonVisibility() diff --git a/Classes/QueueAction.swift b/Classes/QueueAction.swift index c0151ee..d393bb8 100644 --- a/Classes/QueueAction.swift +++ b/Classes/QueueAction.swift @@ -221,7 +221,7 @@ class QueueMetadataAction : NSObject, QueueActionProtocol { var metadata: MetadataResult? = nil switch info { - case let .movie(title, id): + case let .movie(title, id, year): let service = MetadataSearch.service(name: self.movieProvider) if let id = id { // The file name carries a service ID: try the direct lookup (which @@ -232,7 +232,9 @@ class QueueMetadataAction : NSObject, QueueActionProtocol { if metadata == nil { let movieSearch = MetadataSearch.movieSeach(service: service, movie: title, language: self.movieLanguage) _ = movieSearch.search(completionHandler: { - if let result = $0.first { + // The queue auto-applies the top result, so give it the + // ranked one (exact title match, then the file-name year). + if let result = rankMovieResults($0, title: title, year: year).first { _ = movieSearch.loadAdditionalMetadata(result, completionHandler: { metadata = $0 }).run() } }).run() diff --git a/Classes/ScriptCommand.swift b/Classes/ScriptCommand.swift index 6b95eba..90f586a 100644 --- a/Classes/ScriptCommand.swift +++ b/Classes/ScriptCommand.swift @@ -150,7 +150,7 @@ class SBFetchMetadataScriptCommand: NSScriptCommand, ScriptCommandDocumentTarget let preferredArtworkSize = ArtworkSize(rawValue: queuePrefs.providerArtworkSize) ?? .standard switch terms { - case let .movie(title, id): + case let .movie(title, id, year): let language = MetadataSearch.defaultLanguage(service: movieService, type: .movie) // Shared continuation for both the ID lookup and the title search @@ -188,7 +188,9 @@ class SBFetchMetadataScriptCommand: NSScriptCommand, ScriptCommandDocumentTarget let searchByName: () -> Void = { let movieSearch = MetadataSearch.movieSeach(service: movieService, movie: title, language: language) _ = movieSearch.search(completionHandler: { results in - if let result = results.first { + // Same ranking as the search sheet and the queue: exact + // title match first, then the file-name year. + if let result = rankMovieResults(results, title: title, year: year).first { completeWith(result, movieSearch) } else { completion(nil) @@ -663,8 +665,10 @@ class SBFetchMetadataResultsScriptCommand: NSScriptCommand, ScriptCommandDocumen // Perform the search based on media type switch terms { - case .movie(let title, _): - let results = movieService.search(movie: title, language: searchLanguage) + case .movie(let title, _, let parsedYear): + // Ranked so the indexes handed out here line up with the ranked + // list the index-based fetch-metadata command rebuilds later. + let results = rankMovieResults(movieService.search(movie: title, language: searchLanguage), title: title, year: parsedYear) // Convert MetadataResult to SBMetadataResult let sbResults = results.map { result in @@ -814,11 +818,13 @@ class SBFetchAndSetMetadataResultScriptCommand: NSScriptCommand, ScriptCommandDo // Perform the search based on media type // (Title search by design: the caller indexes into the list returned by the - // earlier fetch-metadata-results command, so no ID shortcut here.) + // earlier fetch-metadata-results command, so no ID shortcut here — and the + // same ranking must be applied, so the caller's index selects the same entry.) switch terms { - case let .movie(title, _): + case let .movie(title, _, parsedYear): let movieSearch = MetadataSearch.movieSeach(service: movieService, movie: title, language: searchLanguage) - _ = movieSearch.search(completionHandler: { results in + _ = movieSearch.search(completionHandler: { found in + let results = rankMovieResults(found, title: title, year: parsedYear) if resultIndex >= 0 && resultIndex < results.count { let selectedResult = results[resultIndex] diff --git a/Subler.xcodeproj/project.pbxproj b/Subler.xcodeproj/project.pbxproj index 9d07fa2..8f5c3a9 100644 --- a/Subler.xcodeproj/project.pbxproj +++ b/Subler.xcodeproj/project.pbxproj @@ -1560,7 +1560,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-"; CODE_SIGN_STYLE = Automatic; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1.9.5mkv1; + CURRENT_PROJECT_VERSION = 1.9.5mkv2; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = ""; @@ -1582,7 +1582,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - MARKETING_VERSION = 1.9.5mkv1; + MARKETING_VERSION = 1.9.5mkv2; OTHER_CFLAGS = ""; OTHER_LDFLAGS = "-Wl,-rpath,@loader_path/../Frameworks"; OTHER_SWIFT_FLAGS = ""; @@ -1609,7 +1609,7 @@ CODE_SIGN_IDENTITY = "Mac Developer"; "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1.9.5mkv1; + CURRENT_PROJECT_VERSION = 1.9.5mkv2; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEVELOPMENT_TEAM = ""; @@ -1630,7 +1630,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - MARKETING_VERSION = 1.9.5mkv1; + MARKETING_VERSION = 1.9.5mkv2; OTHER_CFLAGS = ""; OTHER_LDFLAGS = "-Wl,-rpath,@loader_path/../Frameworks"; OTHER_SWIFT_FLAGS = "";