// 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.importFoundation// 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.publicstructSharedFile: Equatable, Sendable {publicvar path: Stringpublicvar fileName: String?publicvar mimeType: String?publicinit(path: String, fileName: String? = nil, mimeType: String? = nil) {self.path = pathself.fileName = fileNameself.mimeType = mimeType }/// The file a mailbox entry names, or `nil` when the entry carries no bytes.publicinit?(_ entry: ShareEntry) {guardlet path = entry.path?.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmptyelse { returnnil }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.publicvar nameOrPath: String {guardlet fileName, !shareFileExtension(fileName).isEmpty else { return path.lowercased() }return fileName.lowercased() }publicvar fileExtension: String { shareFileExtension(nameOrPath) }publicvar 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.publicenumShareFileKind: String, Sendable, CaseIterable {case photocase videocase audiocase 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.privatelet pictureExtensions: Set<String> = ["jpg", "jpeg", "png", "webp", "heic", "heif", "gif"]privatelet movieExtensions: Set<String> = ["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.privatelet audioExtensions: Set<String> = MeetingAudioFormats.extensions.subtracting(movieExtensions)/// iOS hands a UTI where Android hands a MIME type; both name the same thing.privatelet movieUTIs: Set<String> = ["public.movie", "public.video", "com.apple.quicktime-movie"]privatelet imageUTIs: Set<String> = ["public.image"]privatelet audioUTIs: Set<String> = ["public.audio"]/// A declared type that says nothing — the same as saying nothing at all.privatelet undeclaredTypes: Set<String> = ["", "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.privatelet supportedAudioExtensions: Set<String> = 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.publiclet documentContentTypes: Set<String> = ["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.privatelet 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.publicfunc shareFileExtension(_ name: String) -> String {let base = name.trimmingCharacters(in: .whitespaces) .split(whereSeparator: { $0 == "/" || $0 == "\\" }) .last .map(String.init) ?? ""guardlet dot = base.lastIndex(of: "."), dot != base.startIndex else { return"" }let after = base.index(after: dot)guard after < base.endIndex else { return"" }returnString(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.publicfunc shareFileKind(_ file: SharedFile) -> ShareFileKind {let declared = file.declaredif !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.fileExtensionif 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.publicfunc 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.publicfunc isTextShare(_ file: SharedFile) -> Bool {if shareFileExtension(file.nameOrPath) == "txt" { returntrue }let declared = file.declaredreturn 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 <name>.txt` and `WhatsApp Chat - <name>.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.publicfunc isChatExportName(_ file: SharedFile) -> Bool {guard isTextShare(file) else { returnfalse }var name = file.nameOrPath .split(whereSeparator: { $0 == "/" || $0 == "\\" }) .last .map(String.init) ?? ""// The staging prefix a share sheet writes: `1757000000000-WhatsApp Chat …`.iflet dash = name.firstIndex(of: "-"), name[name.startIndex..<dash].count >= 10, name[name.startIndex..<dash].allSatisfy(\.isNumber) { name = String(name[name.index(after: dash)...]) }guard name.hasSuffix(".txt") else { returnfalse }if name == "_chat.txt" { returntrue }return name.hasPrefix("whatsapp chat with ") || name.hasPrefix("whatsapp chat - ")}/// Whether these first bytes read as a WhatsApp transcript.////// **The FIRST line decides, and that is deliberate.** Every export begins with/// a dated header — the end-to-end-encryption notice, or the first message of a/// chat old enough to predate it — so a first line that is not a header is not/// an export, and a dated line somewhere in the middle of a log file is not one/// either. Loosening this to "any line in the first page" would claim a server/// log or a diary as somebody's chat.////// The two dialects are the adapter's own (`cotton-core/src/import/adapters//// chat_txt.rs`): iOS writes `[26/07/2025, 10:12:45 AM] Sender: body` and/// Android writes `26/07/2025, 10:12 - Sender: body`. This is a SNIFF and not a/// second parser: it reads the header's SHAPE and stops at the sender, so the/// date order, the dialect, the locale and every message stay the crate's to/// decide. Nothing here is allowed to grow an opinion about a message.publicfunc looksLikeChatExport(_ head: String) -> Bool {for line in head.split(whereSeparator: \.isNewline) {let cleaned = chatExportPlainText(String(line))if cleaned.isEmpty { continue }return startsWithChatExportHeader(cleaned) }returnfalse}/// 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.publicfunc isChatExportShare(_ file: SharedFile, head: () -> String?) -> Bool {if isZipShare(file) { returntrue }guard isTextShare(file) else { returnfalse }if isChatExportName(file) { returntrue }guardlet head = head() else { returnfalse }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.privatefunc 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}":continuedefault: out.append(CharacterSet.whitespaces.contains(scalar) ? " " : scalar) } }returnString(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.privatefunc startsWithChatExportHeader(_ line: String) -> Bool {var rest = Substring(line)let bracketed = rest.first == "["if bracketed { rest = rest.dropFirst() } rest = rest.drop(while: { $0 == " " })guardlet afterDate = chatExportDate(rest) else { returnfalse } rest = afterDateif rest.first == "," { rest = rest.dropFirst() }guard rest.first == " "else { returnfalse } rest = rest.drop(while: { $0 == " " })guardlet afterClock = chatExportClock(rest) else { returnfalse } rest = chatExportMeridiem(afterClock).drop(while: { $0 == " " })if bracketed { return rest.first == "]" }// Android's dash, in the three widths an exporting phone may write it.guardlet dash = rest.first, dash == "-" || dash == "\u{2013}" || dash == "\u{2014}"else {returnfalse }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.privatefunc chatExportDate(_ text: Substring) -> Substring? {guardlet afterFirst = chatExportDigits(text, 1...4) else { returnnil }guardlet separator = afterFirst.first, separator == "/" || separator == "." || separator == "-"else { returnnil }guardlet afterSecond = chatExportDigits(afterFirst.dropFirst(), 1...2) else { returnnil }guard afterSecond.first == separator else { returnnil }return chatExportDigits(afterSecond.dropFirst(), 1...4)}/// `10:12` or `10:12:45`. The seconds are optional — iOS writes them and/// Android does not.privatefunc chatExportClock(_ text: Substring) -> Substring? {guardlet afterHour = chatExportDigits(text, 1...2), afterHour.first == ":"else { returnnil }guardlet afterMinute = chatExportDigits(afterHour.dropFirst(), 2...2) else { returnnil }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.privatefunc chatExportMeridiem(_ text: Substring) -> Substring {var rest = text.drop(while: { $0 == " " })guardlet half = rest.first, half == "a" || half == "A" || half == "p" || half == "P"else {return text } rest = rest.dropFirst()if rest.first == "." { rest = rest.dropFirst() }guardlet 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.privatefunc chatExportDigits(_ text: Substring, _ allowed: ClosedRange<Int>) -> Substring? {let digits = text.prefix(while: { $0.isASCII && $0.isNumber })guard allowed.contains(digits.count) else { returnnil }return text.dropFirst(digits.count)}/// The extension a Cotton package's file carries (`cotton_store::cottonpkg::EXTENSION`).publiclet cottonPackageExtension = "cottonpkg"/// Branch 0 — a Cotton package, by its extension.publicfunc isPackageShare(_ file: SharedFile) -> Bool { shareFileExtension(file.nameOrPath) == cottonPackageExtension || shareFileExtension(file.path) == cottonPackageExtension}/// Branch 2 — the pictures.publicfunc 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.publicfunc isAudioShare(_ file: SharedFile) -> Bool {if isPictureShare(file) { returnfalse }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.privatelet musicOnlyExtensions: Set<String> = ["flac", "aif", "aiff"]/// Whether the share is audio only a song comes in as (`musicOnlyExtensions`).publicfunc 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.publiclet filmFileExtensions: Set<String> = ["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.publicfunc isFilmShare(_ file: SharedFile) -> Bool { filmFileExtensions.contains(file.fileExtension)}/// The containers no camera writes: a film whatever its length/// (`cotton_core::films::is_film`).privatelet filmOnlyExtensions: Set<String> = ["mkv", "avi"]/// Whether the share is a film whatever its length (`filmOnlyExtensions`).publicfunc 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.publicfunc 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.publicfunc isFolderShare(_ file: SharedFile) -> Bool {var folder: ObjCBool = falsereturnFileManager.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.publicfunc documentContentType(_ file: SharedFile) -> String {if documentContentTypes.contains(file.declared) { return file.declared }let ext = file.fileExtensioniflet 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.publicfunc pictureContentType(_ file: SharedFile) -> String {let mime = file.declaredif mime == "video/x-m4v" { return"video/mp4" }if mime.hasPrefix("image/") || mime.hasPrefix("video/") { return mime }let ext = file.fileExtensionif 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.publicprotocolShareInboxFiles: Sendable {func exists(_ path: String) -> Boolfunc 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.publicstructDiskShareInboxFiles: ShareInboxFiles {publicinit() {}publicfunc exists(_ path: String) -> Bool {FileManager.default.fileExists(atPath: path) }publicfunc 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.publicfunc head(_ path: String) -> String? {guardlet handle = FileHandle(forReadingAtPath: path) else { returnnil }defer { try? handle.close() }guardlet data = try? handle.read(upToCount: 8 * 1024), !data.isEmpty else { returnnil }returnString(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.publicfunc 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 {tryFileManager.default.moveItem(at: source, to: target) } catch {returnnil }return target.path }}// MARK: - Books/// Which reader a book is read in: the `book` table's `format`.publicenumBookFormat: String, Sendable, Equatable, CaseIterable {case epubcase pdf/// The content type a book of this format is kept under.publicvar mime: String {switchself {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(_:)``).publicstructShareShelf: Sendable, Equatable {/// A shared PDF becomes a book.publicvar 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.publicvar audioIsMusic: Bool/// Every shared video, and a shared folder, becomes films (Cotton/// Cinemas, 5 Nov 2026).publicvar 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'.publicvar videoMayBeFilm: Boolpublicinit(pdfIsBook: Bool, audioIsMusic: Bool = false, videoIsFilm: Bool = false, videoMayBeFilm: Bool = false) {self.pdfIsBook = pdfIsBookself.audioIsMusic = audioIsMusicself.videoIsFilm = videoIsFilmself.videoMayBeFilm = videoMayBeFilm }/// The flavour whose app files a PDF as a book (`project.yml`'s `books`).publicstaticlet booksFlavour = "books"/// The flavour whose app files every audio file as a song (`project.yml`'s `music`).publicstaticlet musicFlavour = "music"/// The flavour whose app files every video as a film (`project.yml`'s `cinemas`).publicstaticlet cinemasFlavour = "cinemas"/// Cotton's own flavour (`CottonManifest/flavour.json`), and Cotton Dev's.publicstaticlet cottonFlavour = "cotton"/// The shelf of the app whose manifest names `flavour`.publicstaticfunc 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>.app/PlugIns/<x>.appex`)./// A bundle with no manifest (a test host) is no app's: Cotton's shelf.publicstaticfunc ofThisApp(_ bundle: Bundle = .main) -> ShareShelf {var app = bundle.bundleURLif app.pathExtension == "appex" { app = app.deletingLastPathComponent().deletingLastPathComponent() }guardlet 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) }}privatelet epubTypes: Set<String> = ["application/epub+zip", "org.idpf.epub-container"]privatelet pdfTypes: Set<String> = ["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.publicfunc shareBookFormat(_ file: SharedFile, shelf: ShareShelf) -> BookFormat? {let declared = file.declaredlet format: BookFormat?if epubTypes.contains(declared) { format = .epub } elseif pdfTypes.contains(declared) { format = .pdf } elseif undeclaredTypes.contains(declared) {switch file.fileExtension {case"epub": format = .epubcase"pdf": format = .pdfdefault: format = nil } } else { format = nil }if format == .pdf, !shelf.pdfIsBook { returnnil }return format}privatelet csvTypes: Set<String> = ["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.publicfunc 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(_:)``).publicfunc 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.publicfunc isGoodreadsShare(_ file: SharedFile, head: () -> String?) -> Bool {guard isCSVShare(file), let head = head() else { returnfalse }return looksLikeGoodreadsExport(head)}/// The types an OPML file is declared under: its own, and the XML it is.privatelet opmlTypes: Set<String> = ["text/x-opml", "org.opml.opml"]privatelet xmlTypes: Set<String> = ["text/xml", "application/xml", "public.xml"]/// Whether these first bytes are an OPML document's: its root element,/// `<opml`, past the XML declaration and any comment before it.publicfunc looksLikeOpml(_ head: String) -> Bool { head.range(of: "<opml", options: .caseInsensitive) != nil}/// The OPML branch (Podcasts' Bring subscriptions in, 7 Nov 2026): a podcast/// app's subscription list. A `.opml`, or a file declared OPML, is one by its/// name; a plain `.xml` (Reeder and Overcast claim `.opml` under types of/// their own, so a list often arrives as XML) only when its first bytes are/// an OPML document's, else it stays a document.publicfunc isOpmlShare(_ file: SharedFile, head: () -> String?) -> Bool {if file.fileExtension == "opml" || opmlTypes.contains(file.declared) { returntrue }guard file.fileExtension == "xml" || xmlTypes.contains(file.declared), let head = head() else { returnfalse }return looksLikeOpml(head)}