~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
240 lines · 11.8 KB Raw History
import AVFoundation
import Foundation
import ImageIO
import SwiftUI
import UIKit
import UniformTypeIdentifiers

extension ShareViewController {
    private struct Input {
        var text: [String]
        var images: [ImageAttachment] = []
        var videoURL: URL?
    }

    func receiveItems() async throws -> SharedComposeContent {
        if let temporaryDirectory { try? FileManager.default.removeItem(at: temporaryDirectory) }
        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
            UUID().uuidString, isDirectory: true)
        temporaryDirectory = directory
        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
        let inputItems = extensionContext?.inputItems as? [NSExtensionItem] ?? []
        var input = Input(text: inputItems.compactMap { $0.attributedContentText?.string })
        for provider in inputItems.flatMap({ $0.attachments ?? [] }) {
            try await receive(provider, into: &input, directory: directory)
        }
        guard !input.text.isEmpty || !input.images.isEmpty || input.videoURL != nil else {
            throw ShareInputError.unsupported
        }
        try Task.checkCancellation()
        let video = try await prepareVideo(input.videoURL, in: directory)
        return SharedComposeContent(text: input.text.joined(separator: "\n"), images: input.images, video: video)
    }

    private func receive(_ provider: NSItemProvider, into input: inout Input, directory: URL) async throws {
        if let type = matchingType(in: provider, conformingTo: .movie)
            ?? matchingType(in: provider, conformingTo: .video) {
            guard input.videoURL == nil, input.images.isEmpty else { throw ShareInputError.invalidMedia }
            input.videoURL = try await copyFile(provider, type: type, to: directory)
        } else if let type = matchingType(in: provider, conformingTo: .image) {
            guard input.videoURL == nil, input.images.count < 10 else { throw ShareInputError.invalidMedia }
            let data = try await receiveImage(provider, type: type, directory: directory)
            input.images.append(ImageAttachment(data: data))
        } else if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier)
            || provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {
            try await receiveURL(provider, into: &input, directory: directory)
        } else if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
            let value = try await loadText(provider)
            if !input.text.contains(value) { input.text.append(value) }
        } else {
            throw ShareInputError.unsupported
        }
    }

    private func receiveImage(_ provider: NSItemProvider, type: UTType, directory: URL) async throws -> Data {
        let file: URL
        do {
            let copied = try await copyFile(provider, type: type, to: directory)
            return try await Task.detached(priority: .userInitiated) {
                try Self.preparePhoto(copied, in: directory)
            }.value
        } catch {
            do {
                let copied = try await copyImageData(provider, type: type, to: directory)
                return try await Task.detached(priority: .userInitiated) {
                    try Self.preparePhoto(copied, in: directory)
                }.value
            } catch {
                guard provider.canLoadObject(ofClass: UIImage.self) else { throw error }
                file = try await copyImageObject(provider, to: directory)
            }
        }
        return try await Task.detached(priority: .userInitiated) {
            try Self.preparePhoto(file, in: directory)
        }.value
    }

    private func receiveURL(_ provider: NSItemProvider, into input: inout Input, directory: URL) async throws {
        let value = try await loadURL(provider)
        if value.isFileURL {
            let imported = try await importFileURL(value, into: directory)
            if let photo = imported.photo {
                guard input.videoURL == nil, input.images.count < 10 else { throw ShareInputError.invalidMedia }
                input.images.append(photo)
            } else if let video = imported.video {
                guard input.videoURL == nil, input.images.isEmpty else { throw ShareInputError.invalidMedia }
                input.videoURL = video
            }
        } else if ["http", "https"].contains(value.scheme?.lowercased() ?? "") {
            if !input.text.contains(value.absoluteString) { input.text.append(value.absoluteString) }
        } else {
            throw ShareInputError.unsupported
        }
    }

    private func prepareVideo(_ url: URL?, in directory: URL) async throws -> VideoAttachment? {
        guard let url else { return nil }
        guard url.pathExtension.lowercased() != "mp4" else { return VideoAttachment(fileURL: url) }
        let output = directory.appendingPathComponent("\(UUID().uuidString).mp4")
        guard
            let exporter = AVAssetExportSession(
                asset: AVURLAsset(url: url),
                presetName: AVAssetExportPresetHighestQuality)
        else {
            throw ShareInputError.unsupported
        }
        try await exporter.export(to: output, as: .mp4)
        return VideoAttachment(fileURL: output)
    }

    nonisolated static func preparePhoto(_ input: URL, in directory: URL) throws -> Data {
        let output = directory.appendingPathComponent("\(UUID().uuidString).jpg")
        try autoreleasepool {
            guard let source = CGImageSourceCreateWithURL(input as CFURL, nil),
                let image = CGImageSourceCreateThumbnailAtIndex(
                    source, 0,
                    [
                        kCGImageSourceCreateThumbnailFromImageAlways: true,
                        kCGImageSourceCreateThumbnailWithTransform: true,
                        kCGImageSourceThumbnailMaxPixelSize: 2048
                    ] as CFDictionary),
                let destination = CGImageDestinationCreateWithURL(
                    output as CFURL, UTType.jpeg.identifier as CFString, 1, nil)
            else {
                throw ShareInputError.unsupported
            }
            CGImageDestinationAddImage(
                destination, image, [kCGImageDestinationLossyCompressionQuality: 0.88] as CFDictionary)
            guard CGImageDestinationFinalize(destination) else { throw ShareInputError.unsupported }
        }
        return try Data(contentsOf: output, options: .mappedIfSafe)
    }

    func matchingType(in provider: NSItemProvider, conformingTo base: UTType) -> UTType? {
        provider.registeredTypeIdentifiers.compactMap(UTType.init).first { $0.conforms(to: base) }
    }

    func loadURL(_ provider: NSItemProvider) async throws -> URL {
        try await withCheckedThrowingContinuation { continuation in
            _ = provider.loadObject(ofClass: NSURL.self) { item, error in
                if let item = item as? NSURL {
                    continuation.resume(returning: item as URL)
                } else {
                    continuation.resume(throwing: error ?? ShareInputError.unsupported)
                }
            }
        }
    }

    func loadText(_ provider: NSItemProvider) async throws -> String {
        try await withCheckedThrowingContinuation { continuation in
            _ = provider.loadObject(ofClass: NSString.self) { item, error in
                if let item = item as? NSString {
                    continuation.resume(returning: item as String)
                } else {
                    continuation.resume(throwing: error ?? ShareInputError.unsupported)
                }
            }
        }
    }

    func importFileURL(_ input: URL, into directory: URL) async throws -> (photo: ImageAttachment?, video: URL?) {
        let access = input.startAccessingSecurityScopedResource()
        defer { if access { input.stopAccessingSecurityScopedResource() } }
        let contentType =
            UTType(filenameExtension: input.pathExtension)
            ?? (try? input.resourceValues(forKeys: [.contentTypeKey]).contentType)
        guard let contentType else { throw ShareInputError.unsupported }
        let isVideo = contentType.conforms(to: .movie) || contentType.conforms(to: .video)
        guard isVideo || contentType.conforms(to: .image) else { throw ShareInputError.unsupported }
        let destination = directory.appendingPathComponent("\(UUID().uuidString).\(input.pathExtension)")
        try FileManager.default.copyItem(at: input, to: destination)
        if isVideo { return (nil, destination) }
        let data = try await Task.detached(priority: .userInitiated) {
            try Self.preparePhoto(destination, in: directory)
        }.value
        return (ImageAttachment(data: data), nil)
    }

    private func copyImageData(_ provider: NSItemProvider, type: UTType, to directory: URL) async throws -> URL {
        try await withCheckedThrowingContinuation { continuation in
            provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, error in
                do {
                    guard let data else { throw error ?? ShareInputError.unsupported }
                    let destination = directory.appendingPathComponent("\(UUID().uuidString).image")
                    if data.starts(with: Data("bplist00".utf8)),
                        let url = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSURL.self, from: data),
                        url.isFileURL {
                        let source = url as URL
                        let access = source.startAccessingSecurityScopedResource()
                        defer { if access { source.stopAccessingSecurityScopedResource() } }
                        try FileManager.default.copyItem(at: source, to: destination)
                    } else {
                        try data.write(to: destination, options: .atomic)
                    }
                    continuation.resume(returning: destination)
                } catch {
                    continuation.resume(throwing: error)
                }
            }
        }
    }

    func copyImageObject(_ provider: NSItemProvider, to directory: URL) async throws -> URL {
        try await withCheckedThrowingContinuation { continuation in
            _ = provider.loadObject(ofClass: UIImage.self) { item, error in
                do {
                    guard let image = item as? UIImage, let data = image.jpegData(compressionQuality: 0.88) else {
                        throw error ?? ShareInputError.unsupported
                    }
                    let destination = directory.appendingPathComponent("\(UUID().uuidString).jpg")
                    try data.write(to: destination, options: .atomic)
                    continuation.resume(returning: destination)
                } catch {
                    continuation.resume(throwing: error)
                }
            }
        }
    }

    func copyFile(_ provider: NSItemProvider, type: UTType, to directory: URL) async throws -> URL {
        try await withCheckedThrowingContinuation { continuation in
            provider.loadFileRepresentation(forTypeIdentifier: type.identifier) { url, error in
                do {
                    guard let url else { throw error ?? ShareInputError.unsupported }
                    let suffix = type.preferredFilenameExtension ?? url.pathExtension
                    let name = suffix.isEmpty ? UUID().uuidString : "\(UUID().uuidString).\(suffix)"
                    let destination = directory.appendingPathComponent(name)
                    try FileManager.default.copyItem(at: url, to: destination)
                    continuation.resume(returning: destination)
                } catch {
                    continuation.resume(throwing: error)
                }
            }
        }
    }

    func cancel() {
        extensionContext?.cancelRequest(withError: NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError))
    }
}