Cotton code
95 lines · 5.5 KB · SwiftRaw
// AN ALBUM SHARED FROM THE SHARE SHEET (CONTACTS-ANSWERS 10.0, app albums): `share.do` founds a shared album named// after his album with the people picked and answers its `thing` (`space`, `album`); the phone then adds the album's// photos to it, one `albums.shared.add` each (crates/cotton-ffi/src/phone/albums_shared.rs). The shell's part: every// rendition a JPEG with no metadata (the core refuses EXIF, XMP, IPTC, MPF, comments: `metadata_left`), a full copy at// 2048 px on the long edge and a thumb, re-encoded here from the pixels, never the file. A photo only in iCloud, or// one that will not read, is left out and counted.#if os(iOS)import CottonKitimport ImageIOimport UIKitimport UniformTypeIdentifiersenum AlbumsSharedPhotos {    static let fullEdge: CGFloat = 2048    static let thumbEdge: CGFloat = 400    /// Adds each photo to the shared album; answers how many went and how many were left out.    static func add(core: any CottonCalling, thing: JSONValue, ids: [String]) async -> (added: Int, left: Int) {        guard let space = thing["space"]?.string, let album = thing["album"]?.string else { return (0, ids.count) }        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("albums-share-\(UUID().uuidString)", isDirectory: true)        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)        defer { try? FileManager.default.removeItem(at: dir) }        var added = 0        for (at, id) in ids.enumerated() {            guard let photos = AlbumsLibrary.photos else { break }            let picture = await photos.request(id, side: fullEdge, mode: .highQuality, network: true)            let image: CGImage            switch picture {            case .picture(let found, _), .small(let found, _): image = found            case .onlyInCloud, .failed: continue            }            guard let full = jpeg(image, longEdge: fullEdge), let thumb = jpeg(image, longEdge: thumbEdge) else { continue }            let fullURL = dir.appendingPathComponent("\(at)-full.jpg")            let thumbURL = dir.appendingPathComponent("\(at)-thumb.jpg")            do {                try full.data.write(to: fullURL)                try thumb.data.write(to: thumbURL)                let renditions: JSONValue = .array([                    .object(["kind": .string("full"), "path": .string(fullURL.path), "w": .number(Double(full.w)), "h": .number(Double(full.h))]),                    .object(["kind": .string("thumb"), "path": .string(thumbURL.path), "w": .number(Double(thumb.w)), "h": .number(Double(thumb.h))]),                ])                _ = try await core.callJSON("albums.shared.add", JSONValue.object(["space": .string(space), "album": .string(album), "renditions": renditions, "owner_ok": .bool(true)]))                added += 1            } catch {                Log.write("albums: a photo was not added to the shared album — \(error)")            }        }        return (added, ids.count - added)    }    /// The picture scaled to `longEdge` (never up) and encoded as a JPEG carrying no metadata at all.    static func jpeg(_ image: CGImage, longEdge: CGFloat) -> (data: Data, w: Int, h: Int)? {        let edge = CGFloat(max(image.width, image.height))        let scale = min(1, longEdge / max(edge, 1))        let w = max(1, Int((CGFloat(image.width) * scale).rounded()))        let h = max(1, Int((CGFloat(image.height) * scale).rounded()))        guard let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0,                                      space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }        context.interpolationQuality = .high        context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))        guard let drawn = context.makeImage() else { return nil }        let out = NSMutableData()        guard let destination = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }        CGImageDestinationAddImage(destination, drawn, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary)        guard CGImageDestinationFinalize(destination) else { return nil }        return (strip(out as Data), w, h)    }    /// The JPEG with every segment the core counts as metadata taken out (APP1 EXIF/XMP, APP2 MPF, APP11, APP12,    /// APP13 IPTC, comments); the picture's own segments kept as they are.    static func strip(_ data: Data) -> Data {        let bytes = [UInt8](data)        guard bytes.count > 4, bytes[0] == 0xFF, bytes[1] == 0xD8 else { return data }        var out: [UInt8] = [0xFF, 0xD8]        var at = 2        while at + 4 <= bytes.count, bytes[at] == 0xFF {            let marker = bytes[at + 1]            if marker == 0xDA {                // The scan and everything after it is the picture.                out.append(contentsOf: bytes[at...])                return Data(out)            }            let length = Int(bytes[at + 2]) << 8 | Int(bytes[at + 3])            guard length >= 2, at + 2 + length <= bytes.count else { return data }            let segment = bytes[(at + 4)..<(at + 2 + length)]            let drop = marker == 0xE1 || marker == 0xED || marker == 0xEB || marker == 0xEC || marker == 0xFE                || (marker == 0xE2 && segment.starts(with: Array("MPF\0".utf8)))            if !drop { out.append(contentsOf: bytes[at..<(at + 2 + length)]) }            at += 2 + length        }        return data    }}#endif