// What a shared file IS, and the staged copies the drain reads. // // The four classification rules — the zips, the pictures, the recordings and // the papers — are one decision read by two processes: the share extension, // which knocks for the branch that will take a share (`ShareKnock`), and the // app's drain (`CottonKit/ShareIntake.swift`), which files it. They live in // `CottonMailbox` so the extension reads them without linking the Rust core; // the drain's own header says why each rule is shaped the way it is. import Foundation // MARK: - What one shared file is /// The slice of a shared file the four rules read — the three fields every one /// of the four detectors asks about. public struct SharedFile: Equatable, Sendable { public var path: String public var fileName: String? public var mimeType: String? public init(path: String, fileName: String? = nil, mimeType: String? = nil) { self.path = path self.fileName = fileName self.mimeType = mimeType } /// The file a mailbox entry names, or `nil` when the entry carries no bytes. public init?(_ entry: ShareEntry) { guard let path = entry.path?.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty else { return nil } self.init(path: path, fileName: entry.fileName, mimeType: entry.mimeType) } /// What the rules read as "the name": the sharing app's name when it gave /// one with a suffix, and the staged path otherwise. Providers may give /// a display name without the type their staged file still carries. public var nameOrPath: String { guard let fileName, !shareFileExtension(fileName).isEmpty else { return path.lowercased() } return fileName.lowercased() } public var fileExtension: String { shareFileExtension(nameOrPath) } public var declared: String { (mimeType ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } } /// Where a shared file goes. /// /// `document` is the residue and is honestly named: it is what the LAST file /// branch takes, so a kind this rule does not claim reads as "not ours" rather /// than as a fifth destination. A zip is `document` here too — branch 1 runs /// above every one of these and never consults it. public enum ShareFileKind: String, Sendable, CaseIterable { case photo case video case audio case document } /// The extensions a share may arrive under with no type at all, which is /// ordinary: a file handed over by another app often carries only a name. /// /// Deliberately NARROWER than what the media store would accept. `.pdf` and /// `.txt` are papers, and every raw-photo and exotic-container extension is left /// out on purpose — a format nothing on the phone can draw would be a grid tile /// that never paints, which is worse than a document row that opens. private let pictureExtensions: Set = ["jpg", "jpeg", "png", "webp", "heic", "heif", "gif"] private let movieExtensions: Set = ["mp4", "mov", "m4v", "3gp"] /// The extensions that are audio even with no type declared. **`mp4` is /// deliberately NOT here**: it is the one extension both families claim, and the /// ordinary share is a clip. /// /// Everything else is ``MeetingAudioFormats``'s set, subtracted rather than retyped: /// two lists of what counts as audio is how a fix lands on only one of them, /// and that is exactly how a WhatsApp voice note — `.opus`, usually with no /// declared type at all — used to fall past every branch and be filed as a /// page, leaking its staged copy in the app group on the way. private let audioExtensions: Set = MeetingAudioFormats.extensions.subtracting(movieExtensions) /// iOS hands a UTI where Android hands a MIME type; both name the same thing. private let movieUTIs: Set = ["public.movie", "public.video", "com.apple.quicktime-movie"] private let imageUTIs: Set = ["public.image"] private let audioUTIs: Set = ["public.audio"] /// A declared type that says nothing — the same as saying nothing at all. private let undeclaredTypes: Set = ["", "application/octet-stream", "public.data", "*/*"] /// The extensions the recordings import takes — ``MeetingAudioFormats``'s own set, /// which is the ONE declaration of what may become a meeting on this phone. /// `mp4` belongs here — an audio-only mp4 is a real thing a picker hands over — /// and `isAudioShare` subtracts what the pictures claim rather than restating /// the rule. private let supportedAudioExtensions: Set = MeetingAudioFormats.extensions /// The content types the core files a DOCUMENT under — `cotton-rules`'s /// `media.rs` `DOCUMENT_TYPES`, said again here because a share has to /// name one of them before the bytes are copied, and a type off the list is /// refused (`validate_capture`). `ShareDocumentTypesTests` reads the Rust list /// and holds this one equal to it, so the two cannot drift apart quietly. public let documentContentTypes: Set = [ "application/pdf", "image/png", "image/jpeg", "image/webp", "image/heic", "image/heif", "application/msword", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/plain", "text/csv", "text/html", "application/octet-stream", ] /// What a document arriving with no declared type is, by its extension — only /// the extensions whose type is on the core's list. Anything else is filed as /// `application/octet-stream`, which the core takes and its pipeline sniffs. private let documentExtensionTypes: [String: String] = [ "pdf": "application/pdf", "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "webp": "image/webp", "heic": "image/heic", "heif": "image/heif", "doc": "application/msword", "xls": "application/vnd.ms-excel", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "txt": "text/plain", "csv": "text/csv", "html": "text/html", "htm": "text/html", ] /// The lowercased extension of a name, or `""` when it has none. /// /// Every one of the four rules reaches through it. public func shareFileExtension(_ name: String) -> String { let base = name.trimmingCharacters(in: .whitespaces) .split(whereSeparator: { $0 == "/" || $0 == "\\" }) .last .map(String.init) ?? "" guard let dot = base.lastIndex(of: "."), dot != base.startIndex else { return "" } let after = base.index(after: dot) guard after < base.endIndex else { return "" } return String(base[after...]).lowercased() } /// What this shared file is. /// /// **The DECLARED type wins where it declares something**: a share that says /// `audio/mp4` knows more about its own bytes than a file extension does, and /// believing it is what keeps an audio-only mp4 out of the picture grid. The /// extension answers only when nothing was declared — the ordinary case for a /// file handed over from another app's share sheet. public func shareFileKind(_ file: SharedFile) -> ShareFileKind { let declared = file.declared if !undeclaredTypes.contains(declared) { if declared.hasPrefix("video/") || movieUTIs.contains(declared) { return .video } if declared.hasPrefix("audio/") || audioUTIs.contains(declared) { return .audio } if declared.hasPrefix("image/") || imageUTIs.contains(declared) { return .photo } return .document } let ext = file.fileExtension if movieExtensions.contains(ext) { return .video } if audioExtensions.contains(ext) { return .audio } if pictureExtensions.contains(ext) { return .photo } return .document } /// A zip, by name or by declared type. Half of branch 1. public func isZipShare(_ file: SharedFile) -> Bool { file.nameOrPath.hasSuffix(".zip") || file.declared == "application/zip" || file.declared == "application/x-zip-compressed" } /// A `.txt`, by name or by declared type. /// /// The gate on the two `.txt` rules below, so neither of them is ever asked /// about a PDF, and so the file's first bytes are read for a `.txt` and for /// nothing else. public func isTextShare(_ file: SharedFile) -> Bool { if shareFileExtension(file.nameOrPath) == "txt" { return true } let declared = file.declared return declared == "text/plain" || declared == "public.plain-text" || declared == "public.text" } /// The name WhatsApp gives an export it made. /// /// The same three shapes `cotton_core::import::identity` reads a chat's title /// out of — `_chat.txt` (iOS, inside the zip and on its own), `WhatsApp Chat /// with .txt` and `WhatsApp Chat - .txt` (Android and the iOS share /// sheet) — behind an optional staging prefix, which is the crate's /// `^[0-9]{10,}-` rule said once more here because a share sheet writes one. /// /// A rule about the NAME only. A `.txt` renamed by a person, or handed over /// with no name at all, is caught by ``looksLikeChatExport(_:)`` instead. public func isChatExportName(_ file: SharedFile) -> Bool { guard isTextShare(file) else { return false } var name = file.nameOrPath .split(whereSeparator: { $0 == "/" || $0 == "\\" }) .last .map(String.init) ?? "" // The staging prefix a share sheet writes: `1757000000000-WhatsApp Chat …`. if let dash = name.firstIndex(of: "-"), name[name.startIndex..= 10, name[name.startIndex.. Bool { for line in head.split(whereSeparator: \.isNewline) { let cleaned = chatExportPlainText(String(line)) if cleaned.isEmpty { continue } return startsWithChatExportHeader(cleaned) } return false } /// Branch 1 — the chat exports, whole. /// /// The three rules in one place and in cost order: a zip is free, a name is /// free, and only a `.txt` whose name says nothing costs a read. `head` is a /// closure rather than the text itself so that read never happens for the other /// three branches — the drain passes the app group's file, and the share /// extension passes the copy it has just made. public func isChatExportShare(_ file: SharedFile, head: () -> String?) -> Bool { if isZipShare(file) { return true } guard isTextShare(file) else { return false } if isChatExportName(file) { return true } guard let head = head() else { return false } return looksLikeChatExport(head) } // MARK: - The transcript sniff /// One transcript line with WhatsApp's invisible scaffolding taken off: the /// bidi marks it wraps every timestamp in are dropped, and every kind of space /// it may have written — the narrow no-break one before `AM` included — becomes /// a plain one. private func chatExportPlainText(_ line: String) -> String { var out = String.UnicodeScalarView() for scalar in line.unicodeScalars { switch scalar { case "\u{200E}", "\u{200F}", "\u{202A}"..."\u{202E}", "\u{2066}"..."\u{2069}", "\u{FEFF}": continue default: out.append(CharacterSet.whitespaces.contains(scalar) ? " " : scalar) } } return String(out).trimmingCharacters(in: .whitespaces) } /// `[26/07/2025, 10:12:45 AM] ` or `26/07/2025, 10:12 - `, at the head of a /// line. /// /// Hand-scanned rather than matched with `NSRegularExpression`, for two /// reasons this tree already holds: building one is a `throws` that every /// caller would have to answer or force (and `try!` is banned), and the one /// place to cache it would be a mutable global. The scan is four small takers /// and it says exactly what the shape is. private func startsWithChatExportHeader(_ line: String) -> Bool { var rest = Substring(line) let bracketed = rest.first == "[" if bracketed { rest = rest.dropFirst() } rest = rest.drop(while: { $0 == " " }) guard let afterDate = chatExportDate(rest) else { return false } rest = afterDate if rest.first == "," { rest = rest.dropFirst() } guard rest.first == " " else { return false } rest = rest.drop(while: { $0 == " " }) guard let afterClock = chatExportClock(rest) else { return false } rest = chatExportMeridiem(afterClock).drop(while: { $0 == " " }) if bracketed { return rest.first == "]" } // Android's dash, in the three widths an exporting phone may write it. guard let dash = rest.first, dash == "-" || dash == "\u{2013}" || dash == "\u{2014}" else { return false } return rest.dropFirst().first == " " } /// `26/07/2025`, `7.26.25`, `2025-07-26` — three runs of digits joined by the /// SAME separator twice. Which run is the day is the crate's question. private func chatExportDate(_ text: Substring) -> Substring? { guard let afterFirst = chatExportDigits(text, 1...4) else { return nil } guard let separator = afterFirst.first, separator == "/" || separator == "." || separator == "-" else { return nil } guard let afterSecond = chatExportDigits(afterFirst.dropFirst(), 1...2) else { return nil } guard afterSecond.first == separator else { return nil } return chatExportDigits(afterSecond.dropFirst(), 1...4) } /// `10:12` or `10:12:45`. The seconds are optional — iOS writes them and /// Android does not. private func chatExportClock(_ text: Substring) -> Substring? { guard let afterHour = chatExportDigits(text, 1...2), afterHour.first == ":" else { return nil } guard let afterMinute = chatExportDigits(afterHour.dropFirst(), 2...2) else { return nil } guard afterMinute.first == ":" else { return afterMinute } return chatExportDigits(afterMinute.dropFirst(), 2...2) ?? afterMinute } /// ` AM`, ` a.m.`, ` PM` — or nothing at all on a 24-hour phone, which answers /// the text it was given. private func chatExportMeridiem(_ text: Substring) -> Substring { var rest = text.drop(while: { $0 == " " }) guard let half = rest.first, half == "a" || half == "A" || half == "p" || half == "P" else { return text } rest = rest.dropFirst() if rest.first == "." { rest = rest.dropFirst() } guard let m = rest.first, m == "m" || m == "M" else { return text } rest = rest.dropFirst() if rest.first == "." { rest = rest.dropFirst() } return rest } /// A run of ASCII digits of a length in `allowed`, and what follows it. private func chatExportDigits(_ text: Substring, _ allowed: ClosedRange) -> Substring? { let digits = text.prefix(while: { $0.isASCII && $0.isNumber }) guard allowed.contains(digits.count) else { return nil } return text.dropFirst(digits.count) } /// The extension a Cotton package's file carries (`cotton_store::cottonpkg::EXTENSION`). public let cottonPackageExtension = "cottonpkg" /// Branch 0 — a Cotton package, by its extension. public func isPackageShare(_ file: SharedFile) -> Bool { shareFileExtension(file.nameOrPath) == cottonPackageExtension || shareFileExtension(file.path) == cottonPackageExtension } /// Branch 2 — the pictures. public func isPictureShare(_ file: SharedFile) -> Bool { let kind = shareFileKind(file) return kind == .photo || kind == .video } /// Branch 3 — the recordings. /// /// The MIME type is consulted as well as the extension, unlike the picker path: /// a file arriving from another app's share sheet may carry a name with no /// extension at all, and `audio/…` is then the only thing that identifies it. /// The reverse is also true — a voice memo shares as `audio/x-m4a`, which the /// extension map does not know. public func isAudioShare(_ file: SharedFile) -> Bool { if isPictureShare(file) { return false } return supportedAudioExtensions.contains(shareFileExtension(file.nameOrPath)) || musicOnlyExtensions.contains(shareFileExtension(file.nameOrPath)) || file.declared.hasPrefix("audio/") } /// The song formats no recording comes in: a lossless rip is music, never a /// meeting (Cotton Music, 4 Nov 2026). Not Ogg or Opus: a WhatsApp voice note /// is an `.opus`, and it is a recording. private let musicOnlyExtensions: Set = ["flac", "aif", "aiff"] /// Whether the share is audio only a song comes in as (`musicOnlyExtensions`). public func isMusicOnlyShare(_ file: SharedFile) -> Bool { !isPictureShare(file) && musicOnlyExtensions.contains(shareFileExtension(file.nameOrPath)) } /// The containers a film comes in — `cotton_core::films::VIDEO_EXTENSIONS`, /// said again here because the drain decides before it asks the core; /// `FilmIntakeTests` reads the Rust list and holds this one equal to it. public let filmFileExtensions: Set = ["mp4", "m4v", "mov", "mkv", "avi", "webm", "ts", "m2ts", "wmv", "mpg", "mpeg", "flv"] /// Whether the share is a video a film may be (Cotton Cinemas, 5 Nov 2026): /// by its name's container, MKV and AVI too, which no camera writes. In /// Cotton the core says which are films (`onlyFilms`) and Photos keeps the /// rest. public func isFilmShare(_ file: SharedFile) -> Bool { filmFileExtensions.contains(file.fileExtension) } /// The containers no camera writes: a film whatever its length /// (`cotton_core::films::is_film`). private let filmOnlyExtensions: Set = ["mkv", "avi"] /// Whether the share is a film whatever its length (`filmOnlyExtensions`). public func isFilmOnlyShare(_ file: SharedFile) -> Bool { filmOnlyExtensions.contains(file.fileExtension) } /// Whether, in Cotton, the share is asked of the films' intake: a clip's /// container, which may hold a film, or one no camera writes. Anything else a /// film's container names (`.ts`, `.webm`) stays what it was. public func mayBeFilmShare(_ file: SharedFile) -> Bool { isFilmShare(file) && (shareFileKind(file) == .video || isFilmOnlyShare(file)) } /// Whether the share is a FOLDER (Files' share of a whole album or library): /// the music intake walks it for its songs, Cotton Cinemas' for its films. public func isFolderShare(_ file: SharedFile) -> Bool { var folder: ObjCBool = false return FileManager.default.fileExists(atPath: file.path, isDirectory: &folder) && folder.boolValue } /// Branch 4's content type — every file the three narrow branches leave is a /// document, so this is the type to file it under: always one the core's /// document list carries. /// /// The share's own type when the core takes it, else the extension's when the /// core takes that, else `application/octet-stream` — never a type the core /// would refuse, because a refusal here is a file the person shared and lost. public func documentContentType(_ file: SharedFile) -> String { if documentContentTypes.contains(file.declared) { return file.declared } let ext = file.fileExtension if let typed = documentExtensionTypes[ext] { return typed } return "application/octet-stream" } /// The content type to store a shared picture under /// /// The share's own MIME wins when it says something; the extension answers when /// it does not. **`application/octet-stream` is never stored for a picture**: /// the media store's photo and video lists refuse it, on the ground that a /// surface which always knows what it picked has no business filing an unnamed /// type. public func pictureContentType(_ file: SharedFile) -> String { let mime = file.declared if mime == "video/x-m4v" { return "video/mp4" } if mime.hasPrefix("image/") || mime.hasPrefix("video/") { return mime } let ext = file.fileExtension if movieExtensions.contains(ext) { if ext == "mp4" || ext == "m4v" { return "video/mp4" } if ext == "3gp" { return "video/3gpp" } return "video/quicktime" } if ext == "png" { return "image/png" } if ext == "webp" { return "image/webp" } if ext == "gif" { return "image/gif" } if ext == "heic" || ext == "heif" { return "image/heic" } // A UTI-only share (`public.movie` with a name that says nothing) still has // to be stored as something the grid can draw. if movieUTIs.contains(mime) { return "video/mp4" } return "image/jpeg" } // MARK: - The staged files /// The two things the drain does to the extension's copies. /// /// A protocol so a test drives the six branches without a container, a /// simulator filesystem or a share extension — the same reason /// ``PendingLinkStore`` and ``ShareMailboxStorage`` are protocols. public protocol ShareInboxFiles: Sendable { func exists(_ path: String) -> Bool func discard(_ path: String) /// The file's first bytes as text, for the ONE rule that has to look inside /// one: a `.txt` whose name does not say whether it is a chat export. /// `nil` when there is nothing readable there. func head(_ path: String) -> String? /// Give a staged copy the extension its own declared type implies, and /// answer where it is now. /// /// **Only the meetings branch needs this, and it needs it because the crate /// reads the PATH.** `meetings.create` takes the container off the file's /// own extension and never off the caller's claim, which is right — a key /// is a name and it has to match the bytes behind it. But a share can /// arrive as `audio/x-m4a` with a name carrying no extension at all, and /// the staged copy then ends in nothing. Handing that over would be this /// phone passing on a refusal it could have prevented. /// /// `nil` when the move failed: the caller still has the old path, so /// nothing is lost and the branch reports rather than guessing. func renamed(_ path: String, extension ext: String) -> String? } /// The shipping one: the app group's `share-inbox` directory, on disk. public struct DiskShareInboxFiles: ShareInboxFiles { public init() {} public func exists(_ path: String) -> Bool { FileManager.default.fileExists(atPath: path) } public func discard(_ path: String) { try? FileManager.default.removeItem(atPath: path) } /// The first 8 KiB, decoded leniently. /// /// A HANDLE and a bounded read, never `String(contentsOfFile:)`: an export /// is a body with no ceiling and a whole-file read is the jetsam kill the /// share extension is already written around. A cut in the middle of a /// character lands as a replacement scalar at the very end, which is past /// every line the sniff reads. public func head(_ path: String) -> String? { guard let handle = FileHandle(forReadingAtPath: path) else { return nil } defer { try? handle.close() } guard let data = try? handle.read(upToCount: 8 * 1024), !data.isEmpty else { return nil } return String(decoding: data, as: UTF8.self) } /// A rename inside the app group's own inbox — a MOVE, so no bytes are read /// and none are copied. public func renamed(_ path: String, extension ext: String) -> String? { let source = URL(fileURLWithPath: path) let target = source.deletingPathExtension() .appendingPathExtension(ext) guard target != source else { return path } do { try FileManager.default.moveItem(at: source, to: target) } catch { return nil } return target.path } } // MARK: - Books /// Which reader a book is read in: the `book` table's `format`. public enum BookFormat: String, Sendable, Equatable, CaseIterable { case epub case pdf /// The content type a book of this format is kept under. public var mime: String { switch self { case .epub: "application/epub+zip" case .pdf: "application/pdf" } } } /// What this app files a shared book as. /// /// An EPUB is a book in every app: nothing else reads one. A PDF is a book in /// Cotton Books, whose reader opens it, and a document in Cotton, where a PDF /// is a statement, a scan or a paper far more often than a book (4 Nov 2026). /// The share extension and the drain read the same answer, each from its own /// app's `flavour.json` (``ofThisApp(_:)``). public struct ShareShelf: Sendable, Equatable { /// A shared PDF becomes a book. public var pdfIsBook: Bool /// Every shared audio file, and a shared folder, becomes songs (Cotton /// Music, 4 Nov 2026). Elsewhere an audio file is a song only when its /// tags name one, and a recording otherwise. public var audioIsMusic: Bool /// Every shared video, and a shared folder, becomes films (Cotton /// Cinemas, 5 Nov 2026). public var videoIsFilm: Bool /// A shared video is asked of the films' intake first, and only a film /// is kept there (`onlyFilms`): Cotton, whose kit holds the films. In the /// other apps a video is Photos'. public var videoMayBeFilm: Bool public init(pdfIsBook: Bool, audioIsMusic: Bool = false, videoIsFilm: Bool = false, videoMayBeFilm: Bool = false) { self.pdfIsBook = pdfIsBook self.audioIsMusic = audioIsMusic self.videoIsFilm = videoIsFilm self.videoMayBeFilm = videoMayBeFilm } /// The flavour whose app files a PDF as a book (`project.yml`'s `books`). public static let booksFlavour = "books" /// The flavour whose app files every audio file as a song (`project.yml`'s `music`). public static let musicFlavour = "music" /// The flavour whose app files every video as a film (`project.yml`'s `cinemas`). public static let cinemasFlavour = "cinemas" /// Cotton's own flavour (`CottonManifest/flavour.json`), and Cotton Dev's. public static let cottonFlavour = "cotton" /// The shelf of the app whose manifest names `flavour`. public static func of(flavour: String?) -> ShareShelf { ShareShelf(pdfIsBook: flavour == booksFlavour, audioIsMusic: flavour == musicFlavour, videoIsFilm: flavour == cinemasFlavour, videoMayBeFilm: flavour == cottonFlavour) } /// This process's app's shelf: the manifest the app bundle carries /// (`flavour.json`), read from the app itself or, in its share extension, /// from the app bundle the extension sits in (`.app/PlugIns/.appex`). /// A bundle with no manifest (a test host) is no app's: Cotton's shelf. public static func ofThisApp(_ bundle: Bundle = .main) -> ShareShelf { var app = bundle.bundleURL if app.pathExtension == "appex" { app = app.deletingLastPathComponent().deletingLastPathComponent() } guard let data = try? Data(contentsOf: app.appendingPathComponent("flavour.json")), let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return of(flavour: nil) } return of(flavour: manifest["flavour"] as? String) } } private let epubTypes: Set = ["application/epub+zip", "org.idpf.epub-container"] private let pdfTypes: Set = ["application/pdf", "com.adobe.pdf"] /// The book this shared file is on `shelf`, or nil when it is none: an EPUB /// always, a PDF where the shelf takes one. The declared type answers first, /// the extension when nothing was declared. public func shareBookFormat(_ file: SharedFile, shelf: ShareShelf) -> BookFormat? { let declared = file.declared let format: BookFormat? if epubTypes.contains(declared) { format = .epub } else if pdfTypes.contains(declared) { format = .pdf } else if undeclaredTypes.contains(declared) { switch file.fileExtension { case "epub": format = .epub case "pdf": format = .pdf default: format = nil } } else { format = nil } if format == .pdf, !shelf.pdfIsBook { return nil } return format } private let csvTypes: Set = ["text/csv", "text/comma-separated-values", "public.comma-separated-values-text"] /// A `.csv`, by name or by declared type: the gate on the Goodreads rule, so /// the first bytes are read for a CSV and for nothing else. public func isCSVShare(_ file: SharedFile) -> Bool { file.fileExtension == "csv" || csvTypes.contains(file.declared) } /// Whether these first bytes are a Goodreads export's: its FIRST line, a byte /// order mark aside, begins with the three columns every Goodreads library /// export (My Books › Import and export › Export library) begins with; older /// exports carry more columns after them. The way a WhatsApp export is told /// by its first line (``looksLikeChatExport(_:)``). public func looksLikeGoodreadsExport(_ head: String) -> Bool { var first = head.prefix(while: { !$0.isNewline }) if first.first == "\u{FEFF}" { first = first.dropFirst() } return first.hasPrefix("Book Id,Title,Author") } /// The Goodreads branch: a CSV whose first line is a Goodreads export's. public func isGoodreadsShare(_ file: SharedFile, head: () -> String?) -> Bool { guard isCSVShare(file), let head = head() else { return false } return looksLikeGoodreadsExport(head) } /// The types an OPML file is declared under: its own, and the XML it is. private let opmlTypes: Set = ["text/x-opml", "org.opml.opml"] private let xmlTypes: Set = ["text/xml", "application/xml", "public.xml"] /// Whether these first bytes are an OPML document's: its root element, /// ` Bool { head.range(of: " String?) -> Bool { if file.fileExtension == "opml" || opmlTypes.contains(file.declared) { return true } guard file.fileExtension == "xml" || xmlTypes.contains(file.declared), let head = head() else { return false } return looksLikeOpml(head) }