Beam/ShareExtension/Sources/ShareExtensionViewController.swift

106 lines
3.6 KiB
Swift
Raw Normal View History

Share extension (#3506) * Setup simple share extension * Switch the app url scheme to be the full bundle identifier * Setup a share extension that show a SwiftUI view, uses rust tracing and redirects to the hosting aplication * Move media as json through the custom scheme into the main app and deep link into the media upload preview screen * Fix message forwarding and global search screen room summary provider filtering. * Tweak the message forwarding and global search screen designs. * Add a room selection screen to use after receiving a share request from the share extension * Fix share extension entitlements * Share the temporary directory between the main app and the extensions; rename the caches one. * Remove the no longer needed notification avatar flipping fix. * Extract the placeholder avatar image generator from the NSE * Nest `AvatarSize` within the new `Avatars` enum * Donate an `INSendMessageIntent` to the system every time we send a message so they appear as share suggestions * Support suggestions in the share extension itself * Improve sharing animations and fix presentation when room already on the stack * Clear all routes when sharing without a preselected room. * Fix broken unit tests * Various initial tweaks following code review. * Correctly clean up and dismiss the share extension for all paths. * Move the share extension path to a constants enum * Rename UserSessionFlowCoordinator specific share extension states and events * Add UserSession and Room flow coordinator share route tests * Tweak the share extension logic.
2024-11-13 14:02:47 +02:00
//
// Copyright 2024 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
Share extension (#3506) * Setup simple share extension * Switch the app url scheme to be the full bundle identifier * Setup a share extension that show a SwiftUI view, uses rust tracing and redirects to the hosting aplication * Move media as json through the custom scheme into the main app and deep link into the media upload preview screen * Fix message forwarding and global search screen room summary provider filtering. * Tweak the message forwarding and global search screen designs. * Add a room selection screen to use after receiving a share request from the share extension * Fix share extension entitlements * Share the temporary directory between the main app and the extensions; rename the caches one. * Remove the no longer needed notification avatar flipping fix. * Extract the placeholder avatar image generator from the NSE * Nest `AvatarSize` within the new `Avatars` enum * Donate an `INSendMessageIntent` to the system every time we send a message so they appear as share suggestions * Support suggestions in the share extension itself * Improve sharing animations and fix presentation when room already on the stack * Clear all routes when sharing without a preselected room. * Fix broken unit tests * Various initial tweaks following code review. * Correctly clean up and dismiss the share extension for all paths. * Move the share extension path to a constants enum * Rename UserSessionFlowCoordinator specific share extension states and events * Add UserSession and Room flow coordinator share route tests * Tweak the share extension logic.
2024-11-13 14:02:47 +02:00
//
import IntentsUI
import SwiftUI
class ShareExtensionViewController: UIViewController {
private let appSettings: CommonSettingsProtocol = AppSettings()
private let hostingController = UIHostingController(rootView: ShareExtensionView())
override func viewDidLoad() {
super.viewDidLoad()
addChild(hostingController)
view.addMatchedSubview(hostingController.view)
hostingController.didMove(toParent: self)
MXLog.configure(currentTarget: "shareextension", filePrefix: "shareextension", logLevel: appSettings.logLevel)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Task {
if let payload = await prepareSharePayload() {
await self.openMainApp(payload: payload)
}
self.dismiss()
}
}
// MARK: - Private
private func prepareSharePayload() async -> ShareExtensionPayload? {
guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem,
let itemProvider = extensionItem.attachments?.first else {
return nil
}
let roomID = (extensionContext?.intent as? INSendMessageIntent)?.conversationIdentifier
if let fileURL = await itemProvider.storeData() {
return .mediaFile(roomID: roomID, mediaFile: .init(url: fileURL, suggestedName: fileURL.lastPathComponent))
} else if let url = await itemProvider.loadTransferable(type: URL.self) {
return .text(roomID: roomID, text: url.absoluteString)
} else if let string = await itemProvider.loadString() {
return .text(roomID: roomID, text: string)
} else {
MXLog.error("Failed loading NSItemProvider data: \(itemProvider)")
Share extension (#3506) * Setup simple share extension * Switch the app url scheme to be the full bundle identifier * Setup a share extension that show a SwiftUI view, uses rust tracing and redirects to the hosting aplication * Move media as json through the custom scheme into the main app and deep link into the media upload preview screen * Fix message forwarding and global search screen room summary provider filtering. * Tweak the message forwarding and global search screen designs. * Add a room selection screen to use after receiving a share request from the share extension * Fix share extension entitlements * Share the temporary directory between the main app and the extensions; rename the caches one. * Remove the no longer needed notification avatar flipping fix. * Extract the placeholder avatar image generator from the NSE * Nest `AvatarSize` within the new `Avatars` enum * Donate an `INSendMessageIntent` to the system every time we send a message so they appear as share suggestions * Support suggestions in the share extension itself * Improve sharing animations and fix presentation when room already on the stack * Clear all routes when sharing without a preselected room. * Fix broken unit tests * Various initial tweaks following code review. * Correctly clean up and dismiss the share extension for all paths. * Move the share extension path to a constants enum * Rename UserSessionFlowCoordinator specific share extension states and events * Add UserSession and Room flow coordinator share route tests * Tweak the share extension logic.
2024-11-13 14:02:47 +02:00
return nil
}
}
private func openMainApp(payload: ShareExtensionPayload) async {
guard let payload = urlEncodeSharePayload(payload) else {
MXLog.error("Failed preparing share payload")
return
}
guard let url = URL(string: "\(InfoPlistReader.main.baseBundleIdentifier):/\(ShareExtensionConstants.urlPath)?\(payload)") else {
MXLog.error("Failed retrieving main application scheme")
return
}
await openURL(url)
}
private func urlEncodeSharePayload(_ payload: ShareExtensionPayload) -> String? {
let data: Data
do {
data = try JSONEncoder().encode(payload)
} catch {
MXLog.error("Failed encoding share payload with error: \(error)")
return nil
}
guard let jsonString = String(data: data, encoding: .utf8) else {
MXLog.error("Invalid payload data")
return nil
}
return jsonString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}
private func dismiss() {
extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
}
private func openURL(_ url: URL) async {
var responder: UIResponder? = self
while responder != nil {
if let application = responder as? UIApplication {
await application.open(url)
return
}
responder = responder?.next
}
}
}