1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
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))
}
}