import Foundation import ImageIO import UniformTypeIdentifiers public enum ImageStoreError: Error, Equatable { case unsupportedType(String) /// The data is no image that ImageIO can read, so it cannot become a PNG. case unreadableImage case noFreeName } /// Puts pasted and dropped images in the image folder and gives back the path of their image line. public struct ImageStore: Sendable { public static let fileExtensions: Set = ["png", "jpg", "jpeg", "gif", "heic", "webp"] public static let folderName = "images" /// The folder of the page file; image links are relative to it. public let base: URL private let now: @Sendable () -> Date private let random: @Sendable () -> UInt16 private let timeZone: TimeZone public init( base: URL = PageStore.defaultURL.deletingLastPathComponent(), now: @escaping @Sendable () -> Date = Date.init, random: @escaping @Sendable () -> UInt16 = { UInt16.random(in: .min ... .max) }, timeZone: TimeZone = .current ) { self.base = base self.now = now self.random = random self.timeZone = timeZone } public var folder: URL { base.appendingPathComponent(Self.folderName, isDirectory: true) } public static func isImageFile(_ url: URL) -> Bool { url.isFileURL && fileExtensions.contains(url.pathExtension.lowercased()) } /// Copies an image file into the image folder with its own extension. /// - Returns: the path relative to `base`, as `images/`. public func copy(file: URL) throws -> String { let ext = file.pathExtension.lowercased() guard Self.fileExtensions.contains(ext) else { throw ImageStoreError.unsupportedType(ext) } let target = try freeURL(ext: ext) try FileManager.default.copyItem(at: file, to: target) return relativePath(target) } /// Writes raw image data, as from the pasteboard, as a PNG file. /// - Returns: the path relative to `base`, as `images/`. public func write(imageData data: Data) throws -> String { let png = data.starts(with: [0x89, 0x50, 0x4E, 0x47]) ? data : try Self.pngData(data) let target = try freeURL(ext: "png") try png.write(to: target, options: .withoutOverwriting) return relativePath(target) } /// Deletes the image files in the image folder whose `images/` path is not in `used`. /// /// Only regular files directly in the folder go; a symbolic link, a folder or a hidden file stays, and a file /// that cannot be deleted is skipped. /// - Returns: the paths of the deleted files, sorted. @discardableResult public func removeUnused(keeping used: Set) -> [String] { let manager = FileManager.default let keys: Set = [.isRegularFileKey, .isSymbolicLinkKey] guard (try? manager.attributesOfItem(atPath: folder.path)[.type] as? FileAttributeType) == .typeDirectory, let urls = try? manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: Array(keys), options: .skipsHiddenFiles) else { return [] } var removed: [String] = [] for url in urls where Self.isImageFile(url) && !used.contains(relativePath(url)) { guard let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true, values.isSymbolicLink != true, (try? manager.removeItem(at: url)) != nil else { continue } removed.append(relativePath(url)) } return removed.sorted() } /// The name for an image made now: `2026-10-16-085512-a3f0`. public func name(ext: String) -> String { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = timeZone let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now()) let stamp = String(format: "%04d-%02d-%02d-%02d%02d%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0) return "\(stamp)-\(String(format: "%04x", random())).\(ext)" } private func freeURL(ext: String) throws -> URL { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) for _ in 0..<32 { let url = folder.appendingPathComponent(name(ext: ext)) if !FileManager.default.fileExists(atPath: url.path) { return url } } throw ImageStoreError.noFreeName } private func relativePath(_ url: URL) -> String { "\(Self.folderName)/\(url.lastPathComponent)" } private static func pngData(_ data: Data) throws -> Data { guard let source = CGImageSourceCreateWithData(data as CFData, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw ImageStoreError.unreadableImage } let out = NSMutableData() guard let destination = CGImageDestinationCreateWithData(out, UTType.png.identifier as CFString, 1, nil) else { throw ImageStoreError.unreadableImage } let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) CGImageDestinationAddImage(destination, image, properties) guard CGImageDestinationFinalize(destination) else { throw ImageStoreError.unreadableImage } return out as Data } }