// What lies beside a film, as the phone hands it to the core (open standards,// 7 Nov 2026). The core names a film's sidecars itself// (`cotton_core::films::sidecars`) from every name in its folder, and refuses// a capture whose named sidecar it was not handed; so the phone names// nothing: it hands every name in the folder, the text of every `.nfo` there// and the path of every subtitle and picture there, and the core picks.//// An episode in a season's folder (`Series/Season 02/S02E05.mkv`) hands its// series' folder too, the one above the season's, where `tvshow.nfo` and the// series' poster lie. The core refuses a series folder handed with a file it// reads as no episode, so the phone reads a path as the core does// (`cotton_core::films::from_path`, mirrored like the film importer's name// reading and held to the same `film_names.json`).importFoundation/// One folder beside a film, as `films.capture` takes it (`beside`,/// `seriesBeside`): every name in it, each `.nfo`'s text by its name, and/// the path of each subtitle and picture by its name.publicstructFilmFolder: Encodable, Sendable, Equatable {publicvar siblings: [String]publicvar nfos: [String: String]publicvar files: [String: String]publicinit(siblings: [String], nfos: [String: String] = [:], files: [String: String] = [:]) {self.siblings = siblingsself.nfos = nfosself.files = files }}/// One chapter mark of a film, as the core keeps them.publicstructFilmChapter: Encodable, Sendable, Equatable {publicvar startMs: Intpublicvar title: Stringpublicinit(startMs: Int, title: String) {self.startMs = startMsself.title = title }}publicenumFilmSidecars {/// A subtitle's containers and a picture's: the core's own/// (`cotton_core::films::sidecars`), held equal by `FilmIntakeTests`.staticlet subtitleExtensions: Set<String> = ["srt", "vtt", "ass", "ssa"]staticlet artExtensions: Set<String> = ["jpg", "png"]staticlet nfoExtension = "nfo"/// The most an NFO is read to: a film's NFO is a few kilobytes of XML;/// a file past this under that name is no NFO, and is left unread.staticlet nfoMostBytes = 64 * 1024/// What lies in `directory`: every name, each `.nfo`'s text (read as/// UTF-8) and each subtitle's and picture's path. A hidden file is no/// sidecar.publicstaticfunc folder(at directory: URL) -> FilmFolder {let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path(percentEncoded: false))) ?? []var folder = FilmFolder(siblings: names.filter { !$0.hasPrefix(".") }.sorted())for name in folder.siblings {let url = directory.appendingPathComponent(name)let ext = url.pathExtension.lowercased()if ext == nfoExtension {iflet text = BoundedText.read(url, most: nfoMostBytes) { folder.nfos[name] = text } } elseif subtitleExtensions.contains(ext) || artExtensions.contains(ext) { folder.files[name] = url.path(percentEncoded: false) } }return folder }/// The series' folder of the episode at `video`, named `sourcePath`:/// the one above its season's folder, where the core reads the path as/// an episode in a season's folder and that folder lies within `root`/// (what was picked); else none.staticfunc seriesDirectory(of video: URL, sourcePath: String, root: URL) -> URL? {let folders = FilmPathRule.parts(sourcePath).dropLast()guard folders.count >= 2, let parent = folders.last, FilmPathRule.season(parent) != nil,FilmPathRule.isEpisode(sourcePath) else { returnnil }let series = video.deletingLastPathComponent().deletingLastPathComponent().standardizedFileURLlet top = root.standardizedFileURL.path(percentEncoded: false).trimmingCharacters(in: CharacterSet(charactersIn: "/"))let path = series.path(percentEncoded: false).trimmingCharacters(in: CharacterSet(charactersIn: "/"))return path == top || path.hasPrefix(top + "/") ? series : nil }}/// How the core reads a film's path (`cotton_core::films::from_path`), as/// far as the phone needs it: whether it is an episode.enumFilmPathRule {/// The folders a film's path never comes from (`SKIPPED_FOLDERS`), as/// the one pattern they make.privatestaticlet skipped = try! NSRegularExpression(pattern: "^(?:sample|samples|extras|featurettes|trailers|behind the scenes|deleted scenes|subs)$")staticlet skippedFolders = Set(skipped.pattern.dropFirst(4).dropLast(2).split(separator: "|").map(String.init))staticfunc parts(_ path: String) -> [String] { path.split(separator: "/").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } }/// Whether the core reads `path` as an episode.staticfunc isEpisode(_ path: String) -> Bool {let parts = parts(path)guardlet file = parts.last, let dot = file.lastIndex(of: "."), dot > file.startIndex, filmFileExtensions.contains(file[file.index(after: dot)...].lowercased()) else { returnfalse }let folders = parts.dropLast()if folders.contains(where: { skippedFolders.contains(spaced($0).lowercased()) }) { returnfalse }let stem = spaced(String(file[..<dot]))if stem.split(separator: " ").contains(where: { $0.lowercased() == "sample" }) { returnfalse }let seasonFolder = folders.last.flatMap(season)iflet before = episodeMark(stem) {if seasonFolder != nil, folders.count >= 2 { returntrue }if !title(before).isEmpty { returntrue }return seasonFolder == nil && !folders.isEmpty }guard seasonFolder != nil, folders.count >= 2else { returnfalse }let digits = stem.prefix { $0.isASCII && $0.isNumber }return !digits.isEmpty && UInt32(digits) != nil }/// Dots and underscores between words read as spaces; a dot a space/// follows is the title's own.staticfunc spaced(_ name: String) -> String {let chars = Array(name.trimmingCharacters(in: .whitespacesAndNewlines))let out = chars.enumerated().map { at, char -> Characterinswitch char {case"_": " "case"."where at + 1 >= chars.count || chars[at + 1] != " ": " "default: char } }returnString(out).split(whereSeparator: \.isWhitespace).joined(separator: " ") }/// A season's folder's number: `Season 2`, `Series 02`, `S02`.staticfunc season(_ folder: String) -> UInt32? {let lower = spaced(folder).lowercased()let rest: Substringif lower.hasPrefix("season") { rest = lower.dropFirst("season".count) } elseif lower.hasPrefix("series") { rest = lower.dropFirst("series".count) } elseif lower.hasPrefix("s"), lower.dropFirst().allSatisfy({ $0.isASCII && $0.isNumber }) { rest = lower.dropFirst() } else {returnnil }return UInt32(rest.trimmingCharacters(in: .whitespaces)) }privatestaticlet mark = try! NSRegularExpression(pattern: #"(?i)\bs(\d{1,2})\s?e(\d{1,3})\b|\b(\d{1,2})x(\d{2,3})\b"#)/// What stands before an episode's mark (`S02E05`, `2x05`), where the/// name holds one.staticfunc episodeMark(_ stem: String) -> String? {let whole = NSRange(stem.startIndex..., in: stem)guardlet found = mark.firstMatch(in: stem, range: whole), let at = Range(found.range, in: stem) else { returnnil }returnString(stem[..<at.lowerBound]) }/// The title a name begins with, up to its year or its first release/// word: only whether it is empty is read here, so a title that is only/// the year's or a release word's is no title.staticfunc title(_ name: String) -> String {let words = name.split(whereSeparator: \.isWhitespace)var kept: [Substring] = []for (at, word) in words.enumerated() {let bare = word.trimmingCharacters(in: CharacterSet(charactersIn: "()[]"))let isYear = bare.count == 4 && (bare.hasPrefix("19") || bare.hasPrefix("20")) && bare.allSatisfy { $0.isASCII && $0.isNumber }if isYear, at > 0 { break }if releaseWords.contains(bare.lowercased()) || (word.hasPrefix("[") && at > 0) { break } kept.append(word) }return kept.joined(separator: " ").trimmingCharacters(in: CharacterSet(charactersIn: "-").union(.whitespaces)) }/// The words a release's name runs into after its title/// (`RELEASE_WORDS`), held equal by `FilmIntakeTests`.staticlet releaseWords: Set<String> = ["480p", "576p", "720p", "1080p", "1080i", "2160p", "4k", "uhd", "bluray", "blu-ray", "brrip", "bdrip", "dvdrip", "webrip", "web-dl", "webdl","hdtv", "x264", "x265", "h264", "h265", "hevc", "hdr", "remux", "proper", "repack", ]}