Cotton code
180 lines · 8.9 KB · SwiftRaw
// 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`).import Foundation/// 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.public struct FilmFolder: Encodable, Sendable, Equatable {    public var siblings: [String]    public var nfos: [String: String]    public var files: [String: String]    public init(siblings: [String], nfos: [String: String] = [:], files: [String: String] = [:]) {        self.siblings = siblings        self.nfos = nfos        self.files = files    }}/// One chapter mark of a film, as the core keeps them.public struct FilmChapter: Encodable, Sendable, Equatable {    public var startMs: Int    public var title: String    public init(startMs: Int, title: String) {        self.startMs = startMs        self.title = title    }}public enum FilmSidecars {    /// A subtitle's containers and a picture's: the core's own    /// (`cotton_core::films::sidecars`), held equal by `FilmIntakeTests`.    static let subtitleExtensions: Set<String> = ["srt", "vtt", "ass", "ssa"]    static let artExtensions: Set<String> = ["jpg", "png"]    static let 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.    static let 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.    public static func 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 {                if let text = BoundedText.read(url, most: nfoMostBytes) { folder.nfos[name] = text }            } else if 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.    static func 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 { return nil }        let series = video.deletingLastPathComponent().deletingLastPathComponent().standardizedFileURL        let 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.enum FilmPathRule {    /// The folders a film's path never comes from (`SKIPPED_FOLDERS`), as    /// the one pattern they make.    private static let skipped = try! NSRegularExpression(pattern: "^(?:sample|samples|extras|featurettes|trailers|behind the scenes|deleted scenes|subs)$")    static let skippedFolders = Set(skipped.pattern.dropFirst(4).dropLast(2).split(separator: "|").map(String.init))    static func parts(_ path: String) -> [String] {        path.split(separator: "/").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }    }    /// Whether the core reads `path` as an episode.    static func isEpisode(_ path: String) -> Bool {        let parts = parts(path)        guard let file = parts.last, let dot = file.lastIndex(of: "."), dot > file.startIndex,              filmFileExtensions.contains(file[file.index(after: dot)...].lowercased()) else { return false }        let folders = parts.dropLast()        if folders.contains(where: { skippedFolders.contains(spaced($0).lowercased()) }) { return false }        let stem = spaced(String(file[..<dot]))        if stem.split(separator: " ").contains(where: { $0.lowercased() == "sample" }) { return false }        let seasonFolder = folders.last.flatMap(season)        if let before = episodeMark(stem) {            if seasonFolder != nil, folders.count >= 2 { return true }            if !title(before).isEmpty { return true }            return seasonFolder == nil && !folders.isEmpty        }        guard seasonFolder != nil, folders.count >= 2 else { return false }        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.    static func spaced(_ name: String) -> String {        let chars = Array(name.trimmingCharacters(in: .whitespacesAndNewlines))        let out = chars.enumerated().map { at, char -> Character in            switch char {            case "_": " "            case "." where at + 1 >= chars.count || chars[at + 1] != " ": " "            default: char            }        }        return String(out).split(whereSeparator: \.isWhitespace).joined(separator: " ")    }    /// A season's folder's number: `Season 2`, `Series 02`, `S02`.    static func season(_ folder: String) -> UInt32? {        let lower = spaced(folder).lowercased()        let rest: Substring        if lower.hasPrefix("season") {            rest = lower.dropFirst("season".count)        } else if lower.hasPrefix("series") {            rest = lower.dropFirst("series".count)        } else if lower.hasPrefix("s"), lower.dropFirst().allSatisfy({ $0.isASCII && $0.isNumber }) {            rest = lower.dropFirst()        } else {            return nil        }        return UInt32(rest.trimmingCharacters(in: .whitespaces))    }    private static let 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.    static func episodeMark(_ stem: String) -> String? {        let whole = NSRange(stem.startIndex..., in: stem)        guard let found = mark.firstMatch(in: stem, range: whole), let at = Range(found.range, in: stem) else { return nil }        return String(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.    static func 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`.    static let 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",    ]}