This repository has been archived by the owner on Mar 5, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathexpo-config-plugin-ios-share-extension+0.0.4.patch
469 lines (450 loc) · 19.8 KB
/
expo-config-plugin-ios-share-extension+0.0.4.patch
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
diff --git a/node_modules/expo-config-plugin-ios-share-extension/build/writeShareExtensionFiles.js b/node_modules/expo-config-plugin-ios-share-extension/build/writeShareExtensionFiles.js
index 5f0e1db..e38386c 100644
--- a/node_modules/expo-config-plugin-ios-share-extension/build/writeShareExtensionFiles.js
+++ b/node_modules/expo-config-plugin-ios-share-extension/build/writeShareExtensionFiles.js
@@ -20,7 +20,7 @@ async function writeShareExtensionFiles(platformProjectRoot, scheme, appIdentifi
const storyboardContent = getShareExtensionStoryBoardContent();
await node_fs_1.default.promises.writeFile(storyboardFilePath, storyboardContent);
const viewControllerFilePath = getShareExtensionViewControllerPath(platformProjectRoot);
- const viewControllerContent = getShareExtensionViewControllerContent(scheme);
+ const viewControllerContent = getShareExtensionViewControllerContent(scheme, appIdentifier);
await node_fs_1.default.promises.writeFile(viewControllerFilePath, viewControllerContent);
}
exports.writeShareExtensionFiles = writeShareExtensionFiles;
@@ -56,6 +56,7 @@ function getShareExtensionInfoContent() {
NSExtension: {
NSExtensionAttributes: {
NSExtensionActivationRule: {
+ NSExtensionActivationSupportsText: true,
NSExtensionActivationSupportsWebURLWithMaxCount: 1,
NSExtensionActivationSupportsWebPageWithMaxCount: 1,
},
@@ -104,131 +105,344 @@ function getShareExtensionViewControllerPath(platformProjectRoot) {
return node_path_1.default.join(platformProjectRoot, constants_1.shareExtensionName, constants_1.shareExtensionViewControllerFileName);
}
exports.getShareExtensionViewControllerPath = getShareExtensionViewControllerPath;
-function getShareExtensionViewControllerContent(scheme) {
- console.debug("************ scheme", scheme);
+function getShareExtensionViewControllerContent(scheme, appIdentifier) {
+ console.debug("************ scheme", scheme, "appIdentifier", appIdentifier);
return `import UIKit
-import Social
-import MobileCoreServices
-
-class ShareViewController: UIViewController {
- // IMPORTANT: This should be your host app scheme
- let hostAppURLScheme = "${scheme}"
- let urlContentType = kUTTypeURL as String
- let textContentType = kUTTypePlainText as String
-
- override func viewDidLoad() {
-
- var strUrl:String? = nil
- DispatchQueue.global().async {
-
-
- if let content = self.extensionContext!.inputItems[0] as? NSExtensionItem {
- if let contents = content.attachments {
- for (_, attachment) in (contents).enumerated() {
- if attachment.hasItemConformingToTypeIdentifier(self.urlContentType) {
- let _strUrl = self.getStrUrlFromUrl(attachment: attachment)
- if(_strUrl != nil){
- strUrl = _strUrl
- }
- }
-
- if attachment.hasItemConformingToTypeIdentifier(self.textContentType) {
- if(strUrl != nil){
- continue;
- }
- let _strUrl = self.getStrUrlFromText(attachment: attachment)
- if(_strUrl != nil){
- strUrl = _strUrl
- }
-
- }
- }
- }
- }
-
- if(strUrl == nil){
- self.dismissWithError()
- return;
- }
- self.redirectToHostApp(sharedURL: strUrl!)
- }
- }
+ import Social
+ import MobileCoreServices
+ import Photos
+ class ShareViewController: SLComposeServiceViewController {
+ let hostAppBundleIdentifier = "${appIdentifier}"
+ let shareProtocol = "${scheme}"
+ let sharedKey = "${scheme}ShareKey"
+ var sharedMedia: [SharedMediaFile] = []
+ var sharedText: [String] = []
+ let imageContentType = kUTTypeImage as String
+ let videoContentType = kUTTypeMovie as String
+ let textContentType = kUTTypeText as String
+ let urlContentType = kUTTypeURL as String
+ let fileURLType = kUTTypeFileURL as String;
- private func getStrUrlFromUrl ( attachment: NSItemProvider) -> String? {
- var result:String? = nil
+ override func isContentValid() -> Bool {
+ return true
+ }
- let semaphore = DispatchSemaphore(value: 0)
+ override func viewDidLoad() {
+ super.viewDidLoad();
+ }
- attachment.loadItem(forTypeIdentifier: self.urlContentType, options: nil) { data, error in
+ override func viewDidAppear(_ animated: Bool) {
+ super.viewDidAppear(animated)
- if error == nil, let item = data as? URL {
- let _url = URL(string: item.absoluteString)
- if(_url != nil){
- result = item.absoluteString
- }
- }
- semaphore.signal()
- }
+ if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
+ if let contents = content.attachments {
+ for (index, attachment) in (contents).enumerated() {
+ if attachment.hasItemConformingToTypeIdentifier(imageContentType) {
+ handleImages(content: content, attachment: attachment, index: index)
+ } else if attachment.hasItemConformingToTypeIdentifier(textContentType) {
+ handleText(content: content, attachment: attachment, index: index)
+ } else if attachment.hasItemConformingToTypeIdentifier(fileURLType) {
+ handleFiles(content: content, attachment: attachment, index: index)
+ } else if attachment.hasItemConformingToTypeIdentifier(urlContentType) {
+ handleUrl(content: content, attachment: attachment, index: index)
+ } else if attachment.hasItemConformingToTypeIdentifier(videoContentType) {
+ handleVideos(content: content, attachment: attachment, index: index)
+ }
+ }
+ }
+ }
+ }
- semaphore.wait()
+ override func didSelectPost() {
+ print("didSelectPost");
+ }
- return result
- }
+ override func configurationItems() -> [Any]! {
+ // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
+ return []
+ }
- private func getStrUrlFromText ( attachment: NSItemProvider) -> String? {
- var result:String? = nil
+ private func handleText (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
+ attachment.loadItem(forTypeIdentifier: textContentType, options: nil) { [weak self] data, error in
- let semaphore = DispatchSemaphore(value: 0)
+ if error == nil, let item = data as? String, let this = self {
- attachment.loadItem(forTypeIdentifier: self.textContentType, options: nil) { data, error in
+ this.sharedText.append(item)
- if error == nil, let item = data as? String {
+ // If this is the last item, save imagesData in userDefaults and redirect to host app
+ if index == (content.attachments?.count)! - 1 {
+ let userDefaults = UserDefaults(suiteName: "group.\\(this.hostAppBundleIdentifier)")
+ userDefaults?.set(this.sharedText, forKey: this.sharedKey)
+ userDefaults?.synchronize()
+ this.redirectToHostApp(type: .text)
+ }
- let types: NSTextCheckingResult.CheckingType = [.link]
- let detector = try? NSDataDetector(types: types.rawValue)
+ } else {
+ self?.dismissWithError()
+ }
+ }
+ }
- if detector != nil && item.count > 0 && detector!.numberOfMatches(in: item, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, item.count)) > 0 {
- result = item
- }
+ private func handleUrl (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
+ attachment.loadItem(forTypeIdentifier: urlContentType, options: nil) { [weak self] data, error in
- }
- semaphore.signal()
- }
+ if error == nil, let item = data as? URL, let this = self {
- semaphore.wait()
+ this.sharedText.append(item.absoluteString)
+ // If this is the last item, save imagesData in userDefaults and redirect to host app
+ if index == (content.attachments?.count)! - 1 {
+ let userDefaults = UserDefaults(suiteName: "group.\\(this.hostAppBundleIdentifier)")
+ userDefaults?.set(this.sharedText, forKey: this.sharedKey)
+ userDefaults?.synchronize()
+ this.redirectToHostApp(type: .text)
+ }
- return result
- }
+ } else {
+ self?.dismissWithError()
+ }
+ }
+ }
+
+ private func handleImages (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
+ attachment.loadItem(forTypeIdentifier: imageContentType, options: nil) { [weak self] data, error in
+
+ if error == nil, let url = data as? URL, let this = self {
+ // this.redirectToHostApp(type: .media)
+ // Always copy
+ let fileExtension = this.getExtension(from: url, type: .video)
+ let newName = UUID().uuidString
+ let newPath = FileManager.default
+ .containerURL(forSecurityApplicationGroupIdentifier: "group.\\(this.hostAppBundleIdentifier)")!
+ .appendingPathComponent("\\(newName).\\(fileExtension)")
+ let copied = this.copyFile(at: url, to: newPath)
+ if(copied) {
+ this.sharedMedia.append(SharedMediaFile(path: newPath.absoluteString, thumbnail: nil, duration: nil, type: .image))
+ }
+
+ // If this is the last item, save imagesData in userDefaults and redirect to host app
+ if index == (content.attachments?.count)! - 1 {
+ let userDefaults = UserDefaults(suiteName: "group.\\(this.hostAppBundleIdentifier)")
+ userDefaults?.set(this.toData(data: this.sharedMedia), forKey: this.sharedKey)
+ userDefaults?.synchronize()
+ this.redirectToHostApp(type: .media)
+ }
+
+ } else {
+ self?.dismissWithError()
+ }
+ }
+ }
+
+ private func handleVideos (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
+ attachment.loadItem(forTypeIdentifier: videoContentType, options:nil) { [weak self] data, error in
+
+ if error == nil, let url = data as? URL, let this = self {
+
+ // Always copy
+ let fileExtension = this.getExtension(from: url, type: .video)
+ let newName = UUID().uuidString
+ let newPath = FileManager.default
+ .containerURL(forSecurityApplicationGroupIdentifier: "group.\\(this.hostAppBundleIdentifier)")!
+ .appendingPathComponent("\\(newName).\\(fileExtension)")
+ let copied = this.copyFile(at: url, to: newPath)
+ if(copied) {
+ guard let sharedFile = this.getSharedMediaFile(forVideo: newPath) else {
+ return
+ }
+ this.sharedMedia.append(sharedFile)
+ }
+
+ // If this is the last item, save imagesData in userDefaults and redirect to host app
+ if index == (content.attachments?.count)! - 1 {
+ let userDefaults = UserDefaults(suiteName: "group.\\(this.hostAppBundleIdentifier)")
+ userDefaults?.set(this.toData(data: this.sharedMedia), forKey: this.sharedKey)
+ userDefaults?.synchronize()
+ this.redirectToHostApp(type: .media)
+ }
+
+ } else {
+ self?.dismissWithError()
+ }
+ }
+ }
+
+ private func handleFiles (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
+ attachment.loadItem(forTypeIdentifier: fileURLType, options: nil) { [weak self] data, error in
+
+ if error == nil, let url = data as? URL, let this = self {
+
+ // Always copy
+ let newName = this.getFileName(from :url)
+ let newPath = FileManager.default
+ .containerURL(forSecurityApplicationGroupIdentifier: "group.\\(this.hostAppBundleIdentifier)")!
+ .appendingPathComponent("\\(newName)")
+ let copied = this.copyFile(at: url, to: newPath)
+ if (copied) {
+ this.sharedMedia.append(SharedMediaFile(path: newPath.absoluteString, thumbnail: nil, duration: nil, type: .file))
+ }
+
+ if index == (content.attachments?.count)! - 1 {
+ let userDefaults = UserDefaults(suiteName: "group.\\(this.hostAppBundleIdentifier)")
+ userDefaults?.set(this.toData(data: this.sharedMedia), forKey: this.sharedKey)
+ userDefaults?.synchronize()
+ this.redirectToHostApp(type: .file)
+ }
+
+ } else {
+ self?.dismissWithError()
+ }
+ }
+ }
+
+ private func dismissWithError() {
+ print("[ERROR] Error loading data!")
+ let alert = UIAlertController(title: "Error", message: "Error loading data", preferredStyle: .alert)
+
+ let action = UIAlertAction(title: "Error", style: .cancel) { _ in
+ self.dismiss(animated: true, completion: nil)
+ }
+
+ alert.addAction(action)
+ present(alert, animated: true, completion: nil)
+ extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
+ }
+
+ private func redirectToHostApp(type: RedirectType) {
+ let url = URL(string: "\\(shareProtocol)://dataUrl=\\(sharedKey)#\\(type)")
+ var responder = self as UIResponder?
+ let selectorOpenURL = sel_registerName("openURL:")
- private func dismissWithError() {
- self.dismiss(animated: true, completion: nil)
- extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
+ while (responder != nil) {
+ if (responder?.responds(to: selectorOpenURL))! {
+ let _ = responder?.perform(selectorOpenURL, with: url)
+ }
+ responder = responder!.next
+ }
+ extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
+ }
+
+ enum RedirectType {
+ case media
+ case text
+ case file
+ }
+
+ func getExtension(from url: URL, type: SharedMediaType) -> String {
+ let parts = url.lastPathComponent.components(separatedBy: ".")
+ var ex: String? = nil
+ if (parts.count > 1) {
+ ex = parts.last
+ }
+
+ if (ex == nil) {
+ switch type {
+ case .image:
+ ex = "PNG"
+ case .video:
+ ex = "MP4"
+ case .file:
+ ex = "TXT"
+ }
+ }
+ return ex ?? "Unknown"
+ }
+
+ func getFileName(from url: URL) -> String {
+ var name = url.lastPathComponent
+
+ if (name == "") {
+ name = UUID().uuidString + "." + getExtension(from: url, type: .file)
+ }
+
+ return name
+ }
+
+ func copyFile(at srcURL: URL, to dstURL: URL) -> Bool {
+ do {
+ if FileManager.default.fileExists(atPath: dstURL.path) {
+ try FileManager.default.removeItem(at: dstURL)
+ }
+ try FileManager.default.copyItem(at: srcURL, to: dstURL)
+ } catch (let error) {
+ print("Cannot copy item at \\(srcURL) to \\(dstURL): \\(error)")
+ return false
+ }
+ return true
+ }
+
+ private func getSharedMediaFile(forVideo: URL) -> SharedMediaFile? {
+ let asset = AVAsset(url: forVideo)
+ let duration = (CMTimeGetSeconds(asset.duration) * 1000).rounded()
+ let thumbnailPath = getThumbnailPath(for: forVideo)
+
+ if FileManager.default.fileExists(atPath: thumbnailPath.path) {
+ return SharedMediaFile(path: forVideo.absoluteString, thumbnail: thumbnailPath.absoluteString, duration: duration, type: .video)
+ }
+
+ var saved = false
+ let assetImgGenerate = AVAssetImageGenerator(asset: asset)
+ assetImgGenerate.appliesPreferredTrackTransform = true
+ // let scale = UIScreen.main.scale
+ assetImgGenerate.maximumSize = CGSize(width: 360, height: 360)
+ do {
+ let img = try assetImgGenerate.copyCGImage(at: CMTimeMakeWithSeconds(600, preferredTimescale: Int32(1.0)), actualTime: nil)
+ try UIImage.pngData(UIImage(cgImage: img))()?.write(to: thumbnailPath)
+ saved = true
+ } catch {
+ saved = false
+ }
+
+ return saved ? SharedMediaFile(path: forVideo.absoluteString, thumbnail: thumbnailPath.absoluteString, duration: duration, type: .video) : nil
+
+ }
+
+ private func getThumbnailPath(for url: URL) -> URL {
+ let fileName = Data(url.lastPathComponent.utf8).base64EncodedString().replacingOccurrences(of: "==", with: "")
+ let path = FileManager.default
+ .containerURL(forSecurityApplicationGroupIdentifier: "group.\\(hostAppBundleIdentifier)")!
+ .appendingPathComponent("\\(fileName).jpg")
+ return path
+ }
+
+ class SharedMediaFile: Codable {
+ var path: String; // can be image, video or url path. It can also be text content
+ var thumbnail: String?; // video thumbnail
+ var duration: Double?; // video duration in milliseconds
+ var type: SharedMediaType;
+
+
+ init(path: String, thumbnail: String?, duration: Double?, type: SharedMediaType) {
+ self.path = path
+ self.thumbnail = thumbnail
+ self.duration = duration
+ self.type = type
+ }
+
+ // Debug method to print out SharedMediaFile details in the console
+ func toString() {
+ print("[SharedMediaFile] path: \\(self.path)thumbnail: \\(self.thumbnail)duration: \\(self.duration)type: \\(self.type)")
+ }
+ }
+
+ enum SharedMediaType: Int, Codable {
+ case image
+ case video
+ case file
+ }
+
+ func toData(data: [SharedMediaFile]) -> Data {
+ let encodedData = try? JSONEncoder().encode(data)
+ return encodedData!
+ }
}
- private func redirectToHostApp(sharedURL: String) {
- var urlComponents = URLComponents()
- urlComponents.scheme = hostAppURLScheme
- urlComponents.host = "share"
- urlComponents.path = "/"
- urlComponents.queryItems = [
- URLQueryItem(name: "url", value: sharedURL),
- ]
- // urlComponents.url: \(scheme)://share/?url=\(sharedURL)
- let url = urlComponents.url
- var responder = self as UIResponder?
- let selectorOpenURL = sel_registerName("openURL:")
-
- while (responder != nil) {
- if (responder?.responds(to: selectorOpenURL))! {
- responder?.perform(selectorOpenURL, with: url)
- }
- responder = responder!.next
- }
- extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
+ extension Array {
+ subscript (safe index: UInt) -> Element? {
+ return Int(index) < count ? self[Int(index)] : nil
+ }
}
-}
`;
}
exports.getShareExtensionViewControllerContent = getShareExtensionViewControllerContent;