| 1 | import Foundation |
| 2 | import ImageIO |
| 3 | import UniformTypeIdentifiers |
| 4 | |
| 5 | /// POST /attachments' v1 contract (internal/attach/attach.go). /capabilities |
| 6 | /// publishes authentication/version support, not configurable upload limits. |
| 7 | public enum AttachmentLimits { |
| 8 | public static let maxBytes = 10 << 20 |
| 9 | // Bound local file reads before thumbnailing, independently of the upload cap. |
| 10 | public static let maxInputBytes = 128 << 20 |
| 11 | public static let imageLongEdge = 2560 |
| 12 | public static let maxCount = 5 |
| 13 | public static let maxSide = 12_000 |
| 14 | public static let maxPixels = 40_000_000 |
| 15 | public static func checkDimensions(width: Int, height: Int) throws { |
| 16 | guard width > 0, height > 0 else { throw AttachmentFailure.type } |
| 17 | guard width <= maxSide, height <= maxSide, width * height <= maxPixels else { throw AttachmentFailure.pixels } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | public enum AttachmentFailure: Error, Equatable, Sendable { |
| 22 | case tooLarge, pixels, type |
| 23 | |
| 24 | } |
| 25 | |
| 26 | public protocol AttachmentFileAccess: Sendable { |
| 27 | func start(_ url: URL) -> Bool |
| 28 | func stop(_ url: URL) |
| 29 | func isRegularFile(_ url: URL) throws -> Bool |
| 30 | } |
| 31 | |
| 32 | public struct SystemAttachmentFileAccess: AttachmentFileAccess { |
| 33 | public init() {} |
| 34 | public func start(_ url: URL) -> Bool { url.startAccessingSecurityScopedResource() } |
| 35 | public func stop(_ url: URL) { url.stopAccessingSecurityScopedResource() } |
| 36 | public func isRegularFile(_ url: URL) throws -> Bool { try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true } |
| 37 | } |
| 38 | |
| 39 | public struct AttachmentFile: Sendable { |
| 40 | public let data: Data |
| 41 | public let name: String |
| 42 | public let mediaType: String |
| 43 | public let width: Int |
| 44 | public let height: Int |
| 45 | |
| 46 | public static func prepare(_ data: Data, name: String) throws -> Self { |
| 47 | try prepare(data, name: name, maximumBytes: AttachmentLimits.maxBytes) |
| 48 | } |
| 49 | |
| 50 | static func prepare(_ data: Data, name: String, maximumBytes: Int) throws -> Self { |
| 51 | guard !data.isEmpty else { throw AttachmentFailure.type } |
| 52 | let name = URL(fileURLWithPath: name).lastPathComponent |
| 53 | if let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary), |
| 54 | let image = try prepareImage(source, name: name, maximumBytes: maximumBytes, original: { data }) { return image } |
| 55 | guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| 56 | if data.starts(with: Data("%PDF-".utf8)) { return Self(data: data, name: name, mediaType: "application/pdf", width: 0, height: 0) } |
| 57 | let suffix = (name as NSString).pathExtension.lowercased() |
| 58 | guard !["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "hif", "pdf"].contains(suffix), |
| 59 | let text = String(data: data, encoding: .utf8), |
| 60 | text.unicodeScalars.allSatisfy({ $0.value >= 32 && $0.value != 127 || [9, 10, 12, 13].contains($0.value) }) |
| 61 | else { throw AttachmentFailure.type } |
| 62 | // The server accepts UTF-8 source files and extensionless files too. |
| 63 | var media = ["md": "text/markdown", "markdown": "text/markdown", "csv": "text/csv"][suffix] ?? "text/plain" |
| 64 | if suffix == "json", (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)) != nil { media = "application/json" } |
| 65 | return Self(data: data, name: name, mediaType: media, width: 0, height: 0) |
| 66 | } |
| 67 | |
| 68 | static func prepareImage(_ source: CGImageSource, name: String, maximumBytes: Int, original: () throws -> Data) throws -> Self? { |
| 69 | if let typeID = CGImageSourceGetType(source) as String?, let type = UTType(typeID), type.conforms(to: .image) { |
| 70 | let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] |
| 71 | let width = (properties?[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue ?? 0 |
| 72 | let height = (properties?[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue ?? 0 |
| 73 | guard width > 0, height > 0 else { throw AttachmentFailure.type } |
| 74 | if type.conforms(to: .heic) || type.conforms(to: .heif) || type == .tiff || (type != .gif && max(width, height) > AttachmentLimits.imageLongEdge) { |
| 75 | // TIFF is the Mac clipboard's native image representation. |
| 76 | // Apply orientation and omit source metadata, including location. |
| 77 | let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: AttachmentLimits.imageLongEdge, kCGImageSourceShouldCacheImmediately: true] |
| 78 | guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { throw AttachmentFailure.type } |
| 79 | // The web canvas flattens transparency on white before JPEG encoding. |
| 80 | let flattened: CGImage |
| 81 | if (properties?[kCGImagePropertyHasAlpha] as? Bool) == false || [.none, .noneSkipFirst, .noneSkipLast].contains(image.alphaInfo) { |
| 82 | // Opaque images need no backing canvas. Avoid retaining a |
| 83 | // second 2560-pixel bitmap in the share extension. |
| 84 | flattened = image |
| 85 | } else { |
| 86 | guard let canvas = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw AttachmentFailure.type } |
| 87 | canvas.setFillColor(CGColor(gray: 1, alpha: 1)); canvas.fill(CGRect(x: 0, y: 0, width: image.width, height: image.height)) |
| 88 | canvas.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) |
| 89 | guard let opaque = canvas.makeImage() else { throw AttachmentFailure.type } |
| 90 | flattened = opaque |
| 91 | } |
| 92 | let output = NSMutableData() |
| 93 | guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { throw AttachmentFailure.type } |
| 94 | CGImageDestinationAddImage(destination, flattened, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary) |
| 95 | guard CGImageDestinationFinalize(destination) else { throw AttachmentFailure.type } |
| 96 | guard output.length <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| 97 | return Self(data: output as Data, name: (name as NSString).deletingPathExtension + ".jpg", mediaType: "image/jpeg", width: image.width, height: image.height) |
| 98 | } |
| 99 | try AttachmentLimits.checkDimensions(width: width, height: height) |
| 100 | let data = try original() |
| 101 | guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| 102 | let types: [UTType: String] = [.png: "image/png", .jpeg: "image/jpeg", .gif: "image/gif", .webP: "image/webp"] |
| 103 | guard let media = types[type] else { throw AttachmentFailure.type } |
| 104 | let suffix = type.preferredFilenameExtension ?? "png" |
| 105 | return Self(data: data, name: (name as NSString).deletingPathExtension + "." + suffix, mediaType: media, width: width, height: height) |
| 106 | } |
| 107 | return nil |
| 108 | } |
| 109 | |
| 110 | public static func checkRegularFile(_ url: URL, access: any AttachmentFileAccess) throws { |
| 111 | guard url.isFileURL else { throw AttachmentFailure.type } |
| 112 | let started = access.start(url) |
| 113 | defer { if started { access.stop(url) } } |
| 114 | guard try access.isRegularFile(url) else { throw AttachmentFailure.type } |
| 115 | } |
| 116 | |
| 117 | public static func read(_ url: URL) throws -> Data { |
| 118 | let access = url.startAccessingSecurityScopedResource() |
| 119 | defer { if access { url.stopAccessingSecurityScopedResource() } } |
| 120 | let handle = try FileHandle(forReadingFrom: url) |
| 121 | defer { try? handle.close() } |
| 122 | let data = try handle.read(upToCount: AttachmentLimits.maxInputBytes + 1) ?? Data() |
| 123 | guard data.count <= AttachmentLimits.maxInputBytes else { throw AttachmentFailure.tooLarge } |
| 124 | return data |
| 125 | } |
| 126 | } |
| 127 | |