Repository Public
1// SP Notes iOS2// File: Core/AttachmentFiles.swift3// Description: Files of the attachments kept on the device (shared App Group container): import with streaming SHA-256, lookup,4// downsampled pictures for the editor, removal. The database rows live in the store; this type only owns the bytes.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import CryptoKit9import Foundation10import ImageIO11import UIKit12import UniformTypeIdentifiers1314struct ImportedFile: Sendable {15 let id: String16 let filename: String17 let mime: String18 let size: Int6419 let sha256: String20 /// Path relative to the attachments directory (`<id>/<filename>`).21 let relativePath: String22}2324final class AttachmentFiles: Sendable {25 let directory: URL26 private let cache = ImageCache()2728 init(directory: URL) {29 self.directory = directory30 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)31 // Readable after the first unlock so background sync and extensions work while the device is locked again.32 try? (directory as NSURL).setResourceValue(URLFileProtection.completeUntilFirstUserAuthentication, forKey: .fileProtectionKey)33 }3435 static func newID() -> String { UUID().uuidString.lowercased() }3637 func url(relativePath: String) -> URL { directory.appendingPathComponent(relativePath) }3839 /// Where a file with this id and name lives (same rule for imports and downloads).40 func relativePath(id: String, filename: String) -> String { "\(id)/\(Self.safeName(filename))" }4142 func exists(relativePath: String) -> Bool { FileManager.default.fileExists(atPath: url(relativePath: relativePath).path) }4344 /// Copies a file into the store under a fresh id (or the given one) and hashes it without loading it in memory.45 func importFile(at source: URL, filename: String? = nil, mime: String? = nil, id: String = AttachmentFiles.newID()) throws -> ImportedFile {46 let name = Self.safeName(filename ?? source.lastPathComponent)47 let relative = relativePath(id: id, filename: name)48 let destination = url(relativePath: relative)49 try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)50 if FileManager.default.fileExists(atPath: destination.path) { try FileManager.default.removeItem(at: destination) }51 try FileManager.default.copyItem(at: source, to: destination)52 return try describe(id: id, name: name, relative: relative, mime: mime)53 }5455 func importData(_ data: Data, filename: String, mime: String? = nil, id: String = AttachmentFiles.newID()) throws -> ImportedFile {56 let name = Self.safeName(filename)57 let relative = relativePath(id: id, filename: name)58 let destination = url(relativePath: relative)59 try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)60 try data.write(to: destination, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])61 return try describe(id: id, name: name, relative: relative, mime: mime)62 }6364 private func describe(id: String, name: String, relative: String, mime: String?) throws -> ImportedFile {65 let url = url(relativePath: relative)66 let size = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.int64Value ?? 067 return ImportedFile(id: id, filename: name, mime: mime ?? Self.mimeType(for: name), size: size, sha256: try Self.sha256(of: url), relativePath: relative)68 }6970 func remove(relativePath: String) {71 let file = url(relativePath: relativePath)72 try? FileManager.default.removeItem(at: file)73 let folder = file.deletingLastPathComponent()74 if folder != directory, (try? FileManager.default.contentsOfDirectory(atPath: folder.path))?.isEmpty == true { try? FileManager.default.removeItem(at: folder) }75 cache.remove(relativePath)76 }7778 func removeAll() {79 try? FileManager.default.removeItem(at: directory)80 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)81 cache.removeAll()82 }8384 /// Bytes used on the device.85 func totalSize() -> Int64 {86 guard let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: [.fileSizeKey]) else { return 0 }87 var total: Int64 = 088 for case let url as URL in enumerator { total += Int64((try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }89 return total90 }9192 /// A picture decoded at most `maxPixel` on its long side (never the full bitmap of a 48-megapixel photo), cached in memory.93 func image(relativePath: String, maxPixel: CGFloat = 1600) -> UIImage? {94 if let cached = cache.get(relativePath) { return cached }95 let file = url(relativePath: relativePath)96 guard let source = CGImageSourceCreateWithURL(file as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }97 let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceThumbnailMaxPixelSize: maxPixel]98 guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }99 let image = UIImage(cgImage: cgImage, scale: 2, orientation: .up) // points = pixels / 2: the editor scales pictures to the text width anyway100 cache.set(relativePath, image)101 return image102 }103104 // MARK: helpers105106 static func safeName(_ name: String) -> String {107 let cleaned = name.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: "\\", with: "-").replacingOccurrences(of: "\0", with: "")108 .trimmingCharacters(in: .whitespacesAndNewlines)109 let limited = String(cleaned.suffix(200))110 return limited.isEmpty || limited == "." || limited == ".." ? "fichier" : limited111 }112113 static func mimeType(for filename: String) -> String {114 let ext = (filename as NSString).pathExtension.lowercased()115 if ext == "pkdrawing" { return "application/octet-stream" }116 if ext == "md" { return "text/markdown" }117 return UTType(filenameExtension: ext)?.preferredMIMEType ?? "application/octet-stream"118 }119120 static func sha256(of url: URL) throws -> String {121 let handle = try FileHandle(forReadingFrom: url)122 defer { try? handle.close() }123 var hasher = SHA256()124 while true {125 let chunk = try handle.read(upToCount: 1 << 20) ?? Data()126 if chunk.isEmpty { break }127 hasher.update(data: chunk)128 }129 return hasher.finalize().map { String(format: "%02x", $0) }.joined()130 }131132 /// Attachment id of a document `src` of the form `/api/files/<uuid>`.133 static func attachmentID(fromSource src: String) -> String? {134 guard let range = src.range(of: "/api/files/") else { return nil }135 let id = String(src[range.upperBound...].prefix(36)).lowercased()136 return UUID(uuidString: id) != nil ? id : nil137 }138 static func source(forAttachmentID id: String) -> String { "/api/files/\(id)" }139}140141private final class ImageCache: @unchecked Sendable {142 private let cache: NSCache<NSString, UIImage> = { let c = NSCache<NSString, UIImage>(); c.totalCostLimit = 64 << 20; return c }()143 func get(_ key: String) -> UIImage? { cache.object(forKey: key as NSString) }144 func set(_ key: String, _ image: UIImage) { cache.setObject(image, forKey: key as NSString, cost: Int(image.size.width * image.size.height * image.scale * image.scale * 4)) }145 func remove(_ key: String) { cache.removeObject(forKey: key as NSString) }146 func removeAll() { cache.removeAllObjects() }147}148