mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
Step one of [mobile diagnostic reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md), first piece: the reporting module, plus capture of crashes and uncaught errors. A build given a `BUZZ_SENTRY_DSN` now reports native crashes, Flutter framework errors and uncaught asynchronous Dart errors to that Sentry project, attributed to the signed-in member's public key. A build without one (every build made from this repository alone) uses a do-nothing reporter and never initializes the SDK, as [ADR 0007](https://github.com/block/buzz/blob/main/docs/adr/0007-diagnostic-reporting-follows-the-destination.md) requires. A destination the SDK cannot parse is treated as none, so a configuration mistake never stops the app from starting. ### What's in it - **One interface** in `mobile/lib/shared/diagnostics/`: report an error, count a networking event, leave a breadcrumb, and set the member. It has a Sentry-backed and a do-nothing implementation. Only this folder imports the SDK. The explicit error reports and the networking counts that use it come in the next PRs. - **Startup** wraps `runBuzzApp` and installs the SDK's crash and error handlers only when a usable destination is set: one with an HTTP(S) host, a public key and a project, which the native SDKs also require. On Android, the manifest removes the SDK's startup performance provider, which would otherwise run before that check. - **Member:** set from the active community's key, changed when the account switches, cleared on sign-out. Adding the Builderlab origin and account subject is left to a later PR. Every report also carries a random per-install identifier the app creates on first launch, as its own `install.id` tag, signed in or not, so a device's reports can be matched to its members. It lives in a file that device backups and transfers skip, so a phone restored from another gets its own: on Android in the app's files directory, excluded in both backup rule sets; on iOS in an Application Support folder that a small native call marks as excluded from backup (not the caches folder, which iOS can clear when storage runs low). Set on the SDK scope, it also reaches native crash and hang reports. With no member set (before sign-in or after sign-out), the SDK also fills the report's user with its own random per-install identifier, on Dart and native reports alike. - **One filter** runs on every Dart report, breadcrumb and count before it leaves the device: - It replaces every error's own text with fixed wording, since an error can quote its input, a server's response body or a URL. The error keeps its type, mechanism type and stack trace. - It drops what the SDK adds about the failing platform call (`mechanism.data`) and the failing widget (`flutter_error_details`), which can quote what is on screen. - It removes URL query strings and fragments, and keeps only tags and count attributes on the allowed list. - It drops every breadcrumb except networking events and the SDK's foreground/background entries. - **SDK options:** personal data, screenshots, view hierarchy, replay and tracing stay off. The SDK's session records stay on, for a crash-free rate. A session begins each time the app starts or returns after 30 seconds or more in the background; the SDK sends a record when it begins, an update each time an error is counted, and a last one when it ends, carrying the start time, error count, outcome, time from start to end, release, environment and the random per-install identifier. Native auto-breadcrumbs, Android's network-change breadcrumbs (VPN state, signal strength, bandwidth; turned off in the manifest, since the Flutter bridge leaves them on), Cocoa's network breadcrumbs (which keep each request's query and reach native crash reports) and print breadcrumbs are off. With print breadcrumbs on, the SDK would replace `debugPrint` in non-debug builds with one that prints nothing. - **Main-thread hangs:** iOS app hang tracking, Android ANR detection and iOS watchdog-termination tracking are set on explicitly, at the SDK's default thresholds. iOS reports the main thread blocked, fully or mostly, for 2 s or more while the app is active, including freezes it recovers from; a hang still going when the system kills the app is sent on the next launch as a fatal hang, and watchdog-termination tracking reports a foreground run that ended with nothing else to explain it. Android reports only system-declared ANRs: on Android 11 and later, the most recent one that ended the process (read on the next launch, when the system kept a thread dump); before 11, after 5 s once the system marks the app not responding. So recoverable freezes are reported on iOS, and on Android only before 11 once the system marks the app not responding. Dart runs on the main thread, so blocking Dart work shows up with the main thread's stack; Dart frames need the Dart debug symbols at the destination, as crashes do. The spec now has a bullet and a user story for this. - **What the filter does not cover:** native crashes and app hangs are captured and sent by the native SDKs, which never call the Dart filter. They carry stack traces and, for a native exception, its reason text. No app code puts content in a native exception today. The spec now says this. - **Reporting never blocks the app or reaches it with an error:** every call returns at once, and a failure inside reporting is dropped with a `debugPrint`. ### Regressions None for builds without a destination, which includes every build from this repository: they run the same startup with one extra synchronous check, and the SDK is never initialized. The SDK still adds to the app's binary size on both platforms. With a destination, the first frame waits for the SDK to start, native SDK included, and for the install ID to be read from (or, on first launch, written to) a small file. On a debug simulator build the first frame came about 0.3 s later (median of 6 cold launches: 768 ms with a destination, 431 ms without), measured before the install ID was added. Device builds will differ. Uncaught errors still reach Flutter's default handling, and the SDK sends in the background. ### Validation Added tests (`test/shared/diagnostics/diagnostic_reporting_test.dart`): - A table of inputs run through the production Sentry options callbacks: SDK HTTP and navigation breadcrumbs are dropped, network breadcrumbs keep only their four attributes, URLs lose their query string and fragment, unknown tags and count attributes are dropped, and the privacy and breadcrumb options stay off. - Errors sent through a real SDK hub, with the SDK's own platform-error processor and Flutter error integration, into an in-memory transport: for a parse failure, a bad argument, a server response and a platform failure, the serialized event keeps the type and stack but none of the error's text; a real framework build error leaves out the widget text. - A release-mode check that `debugPrint` keeps printing with reporting on. - A build with no destination, one the SDK cannot parse, one without a public key or one without an HTTP(S) host starts the do-nothing reporter and the SDK stays disabled. - Reporting calls whose SDK calls throw, either synchronously or asynchronously, never reach the caller. - Hang detection is on and its thresholds equal the SDK's defaults. - An installation keeps one install ID across launches, a new installation gets a new one, and the filter keeps the `install.id` tag. - Signing in, switching accounts and signing out change the member that later reports are attributed to. I checked that each guard is real by removing it: the print-breadcrumb setting, the destination check, the error-text replacement, the `mechanism.data` and `flutter_error_details` removal, the network-breadcrumb setting, the dropped-failure catch and the tag filter each made a test fail. End to end on an iPhone 17 Pro simulator, with a local server standing in as the destination and a throwaway probe (not committed) that made an HTTPS request with a secret in its query, then raised an uncaught Dart error and a framework error with secrets in their text, then crashed natively: - All four reports arrived (two Dart, one framework, one native crash on the next launch), and none of the secrets appeared in any envelope. - Dart reports carried only the foreground/background breadcrumb; the native crash carried none. - As a control, a build with Cocoa's network breadcrumbs switched back on put the request's secret query and fragment into the native crash report, so that setting is what keeps them out. - `debugPrint` lines still appeared in the device log. Hangs, on a fresh iPhone 17 Pro simulator with no debugger attached and the same local server: a throwaway probe busy-looped the main isolate for 5 s after the first frame. The SDK sent an `App Hang Fully Blocked` event ("App hanging between 5.7 and 6.5 seconds", mechanism `AppHang`) carrying the main thread's stack: Flutter engine frames around 12 frames of Dart code. This was a debug build, where Dart is compiled just in time, so those frames have no image to symbolicate against; in release builds they fall in the app's compiled Dart framework and need its debug symbols at the destination. Install ID, rechecked after moving it to its own file, on a fresh simulator with the same local server, launched twice with a probe that raised a Dart error and then crashed natively: both Dart errors and the native crash carried the same `install.id`, while the signed-out user was the SDK's own identifier. The ID file was in the backup-excluded `Library/Application Support/Diagnostics` folder, not in the app's preferences. The merged Android debug manifest has neither of the SDK's startup providers and has the network-change setting off. The NDK preload provider is still merged in, but it does nothing unless its own manifest flag is set, and it isn't. Full mobile suite passes. Dart errors are captured in the main Flutter engine only; the iOS sheets that start their own engine are out of scope for this PR (native crashes while they are open are still caught), as the spec now says. iOS simulator and Android debug builds with a destination set both build; on iOS the SDK resolves through Swift Package Manager. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
1238 lines
43 KiB
Swift
1238 lines
43 KiB
Swift
import AuthenticationServices
|
|
import AVFoundation
|
|
import BuzzPushKit
|
|
import DeclaredAgeRange
|
|
import Flutter
|
|
import UIKit
|
|
import UserNotifications
|
|
import os.log
|
|
|
|
@main
|
|
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
|
private var nativeMessagePresentationCoordinator: NativeMessagePresentationCoordinator?
|
|
private var mediaUploadChannel: FlutterMethodChannel?
|
|
private var pushChannel: FlutterMethodChannel?
|
|
private let apnsRegistrationBuffer = APNsRegistrationBuffer()
|
|
private let pushNavigationBuffer = BuzzPushNavigationBuffer()
|
|
private var apnsDeviceToken: Data?
|
|
private lazy var endpointGrantStore = BuzzPushEndpointGrantKeychainStore(
|
|
accessGroup: Bundle.main.object(forInfoDictionaryKey: "BuzzKeychainAccessGroup") as? String
|
|
)
|
|
private var enrollmentTask: Task<Void, Never>?
|
|
private lazy var notificationReplyBridge = BuzzNotificationReplyBridge(
|
|
appGroupIdentifier: appGroupIdentifier)
|
|
var appGroupIdentifier: String? {
|
|
Bundle.main.object(forInfoDictionaryKey: "BuzzAppGroupIdentifier") as? String
|
|
}
|
|
private var pushKeychainAccessGroup: String? {
|
|
Bundle.main.object(forInfoDictionaryKey: "BuzzKeychainAccessGroup") as? String
|
|
}
|
|
private lazy var pushSnapshotBridge = BuzzPushSnapshotBridge(
|
|
appGroupIdentifier: appGroupIdentifier,
|
|
endpointGrantStore: endpointGrantStore,
|
|
keychainAccessGroup: pushKeychainAccessGroup
|
|
)
|
|
private var communityKeyboardChannel: FlutterMethodChannel?
|
|
private var communityKeyboardObserver: NSObjectProtocol?
|
|
private var hapticsChannel: FlutterMethodChannel?
|
|
private var appGroupChannel: FlutterMethodChannel?
|
|
private var diagnosticsChannel: FlutterMethodChannel?
|
|
private var shareSuggestions: ShareSuggestions?
|
|
private var qrScannerChannel: FlutterMethodChannel?
|
|
private var inlinePhotoPickerSupportChannel: FlutterMethodChannel?
|
|
private var ageSignalChannel: FlutterMethodChannel?
|
|
var requestPlatformAgeSignal: @MainActor (UIViewController) async throws -> [String: Any] =
|
|
AppDelegate.platformAgeSignal
|
|
private var ageSignalTask: Task<Void, Never>?
|
|
private var ageSignalRequestID: UUID?
|
|
private var ageSignalResult: FlutterResult?
|
|
private var concentricSheetSurfaceChannel: FlutterMethodChannel?
|
|
private var nativePhotoZoomCoordinator: NativePhotoZoomCoordinator?
|
|
private var nativeAttachmentPopoverCoordinator: NativeAttachmentPopoverCoordinator?
|
|
private var nativeEmojiPickerCoordinator: NativeEmojiPickerCoordinator?
|
|
private var nativeCreateChannelSheetCoordinator: NativeCreateChannelSheetCoordinator?
|
|
private var nativeChannelActionsSheetCoordinator: NativeChannelActionsSheetCoordinator?
|
|
private var nativeAddMembersSheetCoordinator: NativeAddMembersSheetCoordinator?
|
|
private var nativeConfirmationDialogCoordinator: NativeConfirmationDialogCoordinator?
|
|
private var nativeProfileSetupCoordinator: NativeProfileSetupCoordinator?
|
|
private var nativeCommunityEntryCoordinator: NativeCommunityEntryCoordinator?
|
|
private var nativeProfileTextEditorCoordinator: NativeProfileTextEditorCoordinator?
|
|
private var identityFilePlugin: IdentityFilePlugin?
|
|
private var photoLibrarySaver: PhotoLibrarySaver?
|
|
private var hostedHpkeChannel: FlutterMethodChannel?
|
|
private var browserAuthBridge: BuzzBrowserAuthBridge?
|
|
private var huddleMediaPlugin: HuddleMediaPlugin?
|
|
|
|
override func application(
|
|
_ application: UIApplication,
|
|
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
|
|
) -> Bool {
|
|
// Age checking and notification restoration run asynchronously from
|
|
// Flutter. No age-related storage or platform request may delay launch.
|
|
UNUserNotificationCenter.current().delegate = self
|
|
BuzzNotificationReplyBridge.registerCategory()
|
|
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
|
}
|
|
|
|
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
|
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
|
engineBridge.pluginRegistry.registrar(forPlugin: "BuzzToastLayer")?.register(
|
|
ToastLayerFactory(), withId: "buzz/toast_layer")
|
|
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "BuzzIosMediaCarousel") {
|
|
registrar.register(IosMediaCarouselFactory(messenger: registrar.messenger()), withId: "buzz/ios_media_carousel")
|
|
}
|
|
|
|
let messenger = engineBridge.applicationRegistrar.messenger()
|
|
let keyboardChannel = FlutterMethodChannel(
|
|
name: "buzz/community_keyboard", binaryMessenger: messenger)
|
|
communityKeyboardChannel = keyboardChannel
|
|
if let observer = communityKeyboardObserver {
|
|
NotificationCenter.default.removeObserver(observer)
|
|
}
|
|
communityKeyboardObserver = NotificationCenter.default.addObserver(
|
|
forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main
|
|
) { _ in
|
|
// Deliver after UIKit finishes preparing the keyboard in this run-loop turn.
|
|
DispatchQueue.main.async {
|
|
keyboardChannel.invokeMethod("willShow", arguments: nil)
|
|
}
|
|
}
|
|
identityFilePlugin = IdentityFilePlugin(messenger: messenger)
|
|
photoLibrarySaver = PhotoLibrarySaver(messenger: messenger)
|
|
HomeScreenShortcuts.shared.attach(messenger: messenger)
|
|
shareSuggestions = ShareSuggestions { [weak self] in
|
|
self?.appGroupIdentifier.flatMap {
|
|
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: $0)
|
|
}
|
|
}
|
|
shareSuggestions?.attach(messenger: messenger)
|
|
QuickSendBridge.shared.attach(messenger: messenger)
|
|
browserAuthBridge = BuzzBrowserAuthBridge(messenger: messenger)
|
|
hostedHpkeChannel = FlutterMethodChannel(name: "buzz/hosted_hpke", binaryMessenger: messenger)
|
|
hostedHpkeChannel?.setMethodCallHandler { call, result in
|
|
if call.method == "isSupported" {
|
|
if #available(iOS 17.0, *) { result(true) } else { result(false) }
|
|
return
|
|
}
|
|
guard call.method == "seal" else { result(FlutterMethodNotImplemented); return }
|
|
guard #available(iOS 17.0, *) else {
|
|
result(FlutterError(code: "unsupported", message: "Backup requires iOS 17 or later", details: nil)); return
|
|
}
|
|
guard let args = call.arguments as? [String: Any],
|
|
let recipient = args["recipient"] as? FlutterStandardTypedData,
|
|
let plaintext = args["plaintext"] as? FlutterStandardTypedData,
|
|
let aad = args["aad"] as? FlutterStandardTypedData else {
|
|
result(FlutterError(code: "invalid_input", message: nil, details: nil)); return
|
|
}
|
|
do {
|
|
let sealed = try HostedHpkeBackup.seal(recipient: recipient.data, plaintext: plaintext.data, aad: aad.data)
|
|
result(["enc": FlutterStandardTypedData(bytes: sealed.enc), "ciphertext": FlutterStandardTypedData(bytes: sealed.ciphertext)])
|
|
} catch {
|
|
result(FlutterError(code: "backup_unavailable", message: nil, details: nil))
|
|
}
|
|
}
|
|
huddleMediaPlugin = HuddleMediaPlugin(messenger: messenger)
|
|
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "BuzzIosNavigationBar") {
|
|
registrar.register(IosNavigationBarFactory(messenger: messenger, parent: registrar.viewController), withId: "buzz/ios_navigation_bar")
|
|
}
|
|
mediaUploadChannel = FlutterMethodChannel(
|
|
name: "buzz/media_upload",
|
|
binaryMessenger: messenger
|
|
)
|
|
mediaUploadChannel?.setMethodCallHandler { [weak self] call, result in
|
|
self?.handleMediaUploadMethodCall(call, result: result)
|
|
}
|
|
pushChannel = FlutterMethodChannel(
|
|
name: "buzz/push",
|
|
binaryMessenger: messenger
|
|
)
|
|
pushChannel?.setMethodCallHandler { [weak self] call, result in
|
|
self?.handlePushMethodCall(call, result: result)
|
|
}
|
|
apnsRegistrationBuffer.attach { [weak self] update in
|
|
self?.pushChannel?.invokeMethod(update.method, arguments: update.arguments)
|
|
}
|
|
notificationReplyBridge.notifyFlutter = { [weak self] in
|
|
self?.pushChannel?.invokeMethod("notificationReplyAvailable", arguments: nil)
|
|
}
|
|
appGroupChannel = FlutterMethodChannel(
|
|
name: "buzz/app_group",
|
|
binaryMessenger: messenger
|
|
)
|
|
appGroupChannel?.setMethodCallHandler { [weak self] call, result in
|
|
let container = self?.appGroupIdentifier.flatMap {
|
|
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: $0)
|
|
}
|
|
switch call.method {
|
|
case "cachesDirectory":
|
|
// Caches the app's extensions can read too. The OS may purge it.
|
|
result(container?.appendingPathComponent("Library/Caches", isDirectory: true).path)
|
|
case "pendingSharesDirectory":
|
|
// Where the share extension leaves items for the app to pick up.
|
|
result(container?.appendingPathComponent("PendingShares", isDirectory: true).path)
|
|
default:
|
|
result(FlutterMethodNotImplemented)
|
|
}
|
|
}
|
|
diagnosticsChannel = FlutterMethodChannel(
|
|
name: "buzz/diagnostics",
|
|
binaryMessenger: messenger
|
|
)
|
|
diagnosticsChannel?.setMethodCallHandler { call, result in
|
|
guard call.method == "installIdDirectory" else {
|
|
result(FlutterMethodNotImplemented)
|
|
return
|
|
}
|
|
result(Self.diagnosticsInstallIdDirectory())
|
|
}
|
|
hapticsChannel = FlutterMethodChannel(
|
|
name: "buzz/haptics",
|
|
binaryMessenger: messenger
|
|
)
|
|
hapticsChannel?.setMethodCallHandler { call, result in
|
|
guard call.method == "success" || call.method == "error" else {
|
|
result(FlutterMethodNotImplemented)
|
|
return
|
|
}
|
|
let generator = UINotificationFeedbackGenerator()
|
|
generator.prepare()
|
|
generator.notificationOccurred(call.method == "error" ? .error : .success)
|
|
result(nil)
|
|
}
|
|
qrScannerChannel = FlutterMethodChannel(
|
|
name: "buzz/qr_scanner",
|
|
binaryMessenger: messenger
|
|
)
|
|
qrScannerChannel?.setMethodCallHandler { call, result in
|
|
Self.handleQrScannerMethodCall(call, result: result)
|
|
}
|
|
inlinePhotoPickerSupportChannel = FlutterMethodChannel(
|
|
name: "buzz/inline_photo_picker",
|
|
binaryMessenger: messenger
|
|
)
|
|
inlinePhotoPickerSupportChannel?.setMethodCallHandler { call, result in
|
|
guard call.method == "isSupported" else {
|
|
result(FlutterMethodNotImplemented)
|
|
return
|
|
}
|
|
if #available(iOS 17.0, *) {
|
|
result(true)
|
|
} else {
|
|
result(false)
|
|
}
|
|
}
|
|
|
|
ageSignalChannel = FlutterMethodChannel(
|
|
name: "buzz/age_signal",
|
|
binaryMessenger: messenger
|
|
)
|
|
let ageSignalRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzAgeSignal"
|
|
)
|
|
ageSignalChannel?.setMethodCallHandler { [weak self] call, result in
|
|
self?.handleAgeSignalMethodCall(
|
|
call,
|
|
viewController: ageSignalRegistrar?.viewController,
|
|
result: result
|
|
)
|
|
}
|
|
|
|
if let inlinePhotoPickerRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzInlinePhotoPicker"
|
|
) {
|
|
inlinePhotoPickerRegistrar.register(
|
|
InlinePhotoPickerFactory(
|
|
messenger: messenger,
|
|
parentViewController: inlinePhotoPickerRegistrar.viewController
|
|
),
|
|
withId: "buzz/inline_photo_picker"
|
|
)
|
|
}
|
|
|
|
if let concentricSheetRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzConcentricSheetSurface"
|
|
) {
|
|
concentricSheetRegistrar.register(
|
|
ConcentricSheetSurfaceFactory(messenger: messenger),
|
|
withId: "buzz/concentric_sheet_surface"
|
|
)
|
|
concentricSheetSurfaceChannel = FlutterMethodChannel(
|
|
name: "buzz/concentric_sheet_surface",
|
|
binaryMessenger: messenger
|
|
)
|
|
concentricSheetSurfaceChannel?.setMethodCallHandler { call, result in
|
|
guard call.method == "isSupported" else {
|
|
result(FlutterMethodNotImplemented)
|
|
return
|
|
}
|
|
if #available(iOS 26.0, *) {
|
|
result(true)
|
|
} else {
|
|
result(false)
|
|
}
|
|
}
|
|
}
|
|
|
|
if let jumpToLatestGlassRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzJumpToLatestGlassButton"
|
|
) {
|
|
jumpToLatestGlassRegistrar.register(
|
|
JumpToLatestGlassButtonFactory(messenger: messenger),
|
|
withId: "buzz/jump_to_latest_glass"
|
|
)
|
|
}
|
|
|
|
if let navigationGlassRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNavigationGlassButton"
|
|
) {
|
|
navigationGlassRegistrar.register(
|
|
NavigationGlassButtonFactory(messenger: messenger),
|
|
withId: "buzz/navigation_glass"
|
|
)
|
|
}
|
|
|
|
if let segmentedControlRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeSegmentedControl"
|
|
) {
|
|
segmentedControlRegistrar.register(
|
|
NativeSegmentedControlFactory(messenger: messenger),
|
|
withId: "buzz/native_segmented_control"
|
|
)
|
|
}
|
|
|
|
if let skinToneRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeSkinToneControl"
|
|
) {
|
|
skinToneRegistrar.register(
|
|
NativeSkinToneControlFactory(messenger: messenger),
|
|
withId: "buzz/native_skin_tone_control"
|
|
)
|
|
}
|
|
|
|
if let stickyDateGlassRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzStickyDateGlassHeader"
|
|
) {
|
|
stickyDateGlassRegistrar.register(
|
|
StickyDateGlassHeaderFactory(messenger: messenger),
|
|
withId: "buzz/sticky_date_glass"
|
|
)
|
|
}
|
|
|
|
if let themePaginationGlassRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzThemePaginationGlassControl"
|
|
) {
|
|
themePaginationGlassRegistrar.register(
|
|
ThemePaginationGlassControlFactory(messenger: messenger),
|
|
withId: "buzz/theme_pagination_glass"
|
|
)
|
|
}
|
|
nativeMessagePresentationCoordinator = NativeMessagePresentationCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeMessagePresentation"
|
|
)?.viewController
|
|
)
|
|
|
|
nativePhotoZoomCoordinator = NativePhotoZoomCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativePhotoZoom"
|
|
)?.viewController
|
|
)
|
|
|
|
let nativeAttachmentRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeAttachmentPopover"
|
|
)
|
|
nativeAttachmentPopoverCoordinator = NativeAttachmentPopoverCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: nativeAttachmentRegistrar?.viewController
|
|
)
|
|
|
|
let nativeEmojiPickerRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeEmojiPicker"
|
|
)
|
|
nativeEmojiPickerCoordinator = NativeEmojiPickerCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: nativeEmojiPickerRegistrar?.viewController
|
|
)
|
|
|
|
engineBridge.pluginRegistry.registrar(forPlugin: "BuzzNativePresenceMenu")?.register(
|
|
NativePresenceMenuFactory(messenger: messenger), withId: "buzz/presence_menu"
|
|
)
|
|
|
|
nativeCreateChannelSheetCoordinator = NativeCreateChannelSheetCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeCreateChannelSheet"
|
|
)?.viewController
|
|
)
|
|
|
|
nativeChannelActionsSheetCoordinator = NativeChannelActionsSheetCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: engineBridge.pluginRegistry.registrar(forPlugin: "BuzzNativeChannelActionsSheet")?.viewController
|
|
)
|
|
|
|
nativeAddMembersSheetCoordinator = NativeAddMembersSheetCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeAddMembersSheet"
|
|
)?.viewController
|
|
)
|
|
|
|
nativeConfirmationDialogCoordinator = NativeConfirmationDialogCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeConfirmationDialog"
|
|
)?.viewController
|
|
)
|
|
|
|
nativeProfileSetupCoordinator = NativeProfileSetupCoordinator(messenger: messenger) { [weak self] engine in
|
|
let channel = FlutterMethodChannel(name: "buzz/media_upload", binaryMessenger: engine.binaryMessenger)
|
|
channel.setMethodCallHandler { [weak self] call, result in self?.handleMediaUploadMethodCall(call, result: result) }
|
|
}
|
|
nativeCommunityEntryCoordinator = NativeCommunityEntryCoordinator(messenger: messenger)
|
|
|
|
let nativeProfileTextEditorRegistrar = engineBridge.pluginRegistry.registrar(
|
|
forPlugin: "BuzzNativeProfileTextEditor"
|
|
)
|
|
nativeProfileTextEditorCoordinator = NativeProfileTextEditorCoordinator(
|
|
messenger: messenger,
|
|
parentViewController: nativeProfileTextEditorRegistrar?.viewController
|
|
)
|
|
}
|
|
|
|
func handleAgeSignalMethodCall(
|
|
_ call: FlutterMethodCall,
|
|
viewController: UIViewController?,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
// iOS can retire the request in process. The generation fence prevents
|
|
// a late result from the cancelled task from completing a fresh request.
|
|
if call.method == "cancelAgeSignalRequest" || call.method == "restartForAgeSignal" {
|
|
cancelAgeSignalRequest()
|
|
result(true)
|
|
return
|
|
}
|
|
guard call.method == "requestAgeSignal" else {
|
|
result(FlutterMethodNotImplemented)
|
|
return
|
|
}
|
|
guard #available(iOS 26.0, *) else {
|
|
result(Self.noAgeSignalResponse)
|
|
return
|
|
}
|
|
guard let viewController else {
|
|
result(
|
|
FlutterError(
|
|
code: "age_signal_unavailable",
|
|
message: "The age signal presenter is unavailable.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
let requestID = UUID()
|
|
ageSignalRequestID = requestID
|
|
ageSignalResult = result
|
|
let request = requestPlatformAgeSignal
|
|
ageSignalTask = Task { @MainActor [weak self] in
|
|
do {
|
|
let payload = try await request(viewController)
|
|
self?.completeAgeSignalRequest(requestID, value: payload)
|
|
} catch {
|
|
self?.completeAgeSignalRequest(
|
|
requestID,
|
|
value:
|
|
FlutterError(
|
|
code: "age_signal_unavailable",
|
|
message: "The age signal request failed.",
|
|
details: String(describing: type(of: error))
|
|
)
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private static func platformAgeSignal(_ viewController: UIViewController) async throws -> [String: Any] {
|
|
guard #available(iOS 26.0, *) else { return noAgeSignalResponse }
|
|
let response = try await AgeRangeService.shared.requestAgeRange(ageGates: 18, in: viewController)
|
|
switch response {
|
|
case .declinedSharing:
|
|
return noAgeSignalResponse
|
|
case .sharing(let range):
|
|
return BuzzAgeSignalPayload.sharing(
|
|
exclusiveUpperBound: range.upperBound, lowerBound: range.lowerBound)
|
|
@unknown default:
|
|
throw NSError(domain: "BuzzAgeSignal", code: 1,
|
|
userInfo: [NSLocalizedDescriptionKey: "Unsupported age signal response"])
|
|
}
|
|
}
|
|
|
|
private func completeAgeSignalRequest(_ requestID: UUID, value: Any?) {
|
|
guard ageSignalRequestID == requestID, let result = ageSignalResult else { return }
|
|
ageSignalRequestID = nil
|
|
ageSignalResult = nil
|
|
ageSignalTask = nil
|
|
result(value)
|
|
}
|
|
|
|
private func cancelAgeSignalRequest() {
|
|
let result = ageSignalResult
|
|
ageSignalRequestID = nil
|
|
ageSignalResult = nil
|
|
ageSignalTask?.cancel()
|
|
ageSignalTask = nil
|
|
result?(
|
|
FlutterError(
|
|
code: "age_signal_cancelled",
|
|
message: "The age signal request was cancelled.",
|
|
details: nil
|
|
)
|
|
)
|
|
}
|
|
|
|
private static let noAgeSignalResponse: [String: Any] = [
|
|
"status": "noSignal",
|
|
"ageUpper": NSNull(),
|
|
]
|
|
|
|
/// Where diagnostic reporting keeps this installation's ID: Application
|
|
/// Support, which the system never purges, excluded from backups so a
|
|
/// phone restored from another gets its own ID. Nil if it can't be made.
|
|
private static func diagnosticsInstallIdDirectory() -> String? {
|
|
guard
|
|
var directory = FileManager.default.urls(
|
|
for: .applicationSupportDirectory, in: .userDomainMask
|
|
).first?.appendingPathComponent("Diagnostics", isDirectory: true)
|
|
else { return nil }
|
|
do {
|
|
try FileManager.default.createDirectory(
|
|
at: directory, withIntermediateDirectories: true)
|
|
var values = URLResourceValues()
|
|
values.isExcludedFromBackup = true
|
|
try directory.setResourceValues(values)
|
|
return directory.path
|
|
} catch {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
private static func handleQrScannerMethodCall(
|
|
_ call: FlutterMethodCall,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
switch call.method {
|
|
case "cameraCutoutFrame":
|
|
#if canImport(UIKit, _version: 9127.0.85)
|
|
if #available(iOS 27.1, *),
|
|
let scene = UIApplication.shared.connectedScenes
|
|
.compactMap({ $0 as? UIWindowScene })
|
|
.first(where: { $0.activationState == .foregroundActive }),
|
|
let window = scene.windows.first(where: { $0.isKeyWindow }) {
|
|
if window.reservedRegions(kind: .division).contains(where: { $0.isActive }) {
|
|
result(nil)
|
|
return
|
|
}
|
|
let bounds = window.bounds
|
|
// Closed Duo displays may omit Flutter display features. UIKit still
|
|
// owns the physical occlusion; remove its interactive clearance.
|
|
for region in window.reservedRegions(kind: .occlusion) where region.isActive {
|
|
let rect = region.frame.inset(by: region.margins)
|
|
let isCamera = abs(rect.width - rect.height) < 1
|
|
&& rect.minX > 0 && rect.minY > 0
|
|
&& rect.maxX < bounds.width && rect.maxY < bounds.height
|
|
&& rect.width < bounds.width / 4
|
|
guard rect.width > 0, rect.height > 0, isCamera else { continue }
|
|
let values: [Double] = [
|
|
Double(rect.minX), Double(rect.minY), Double(rect.width),
|
|
Double(rect.height), Double(bounds.width), Double(bounds.height)
|
|
]
|
|
result(values)
|
|
return
|
|
}
|
|
}
|
|
#endif
|
|
result(nil)
|
|
case "previewRotationQuarterTurns":
|
|
// The plugin reads connectedScenes.first, which can be the inactive
|
|
// cover scene on Duo. Resolve the angle against the visible preview host.
|
|
if #available(iOS 17.0, *),
|
|
let scene = UIApplication.shared.connectedScenes
|
|
.compactMap({ $0 as? UIWindowScene })
|
|
.first(where: { $0.activationState == .foregroundActive }),
|
|
let window = scene.windows.first(where: { $0.isKeyWindow }),
|
|
let camera = AVCaptureDevice.DiscoverySession(
|
|
deviceTypes: [.builtInTripleCamera, .builtInDualCamera, .builtInWideAngleCamera],
|
|
mediaType: .video, position: .back
|
|
).devices.first {
|
|
let coordinator = AVCaptureDevice.RotationCoordinator(device: camera, previewLayer: window.layer)
|
|
let angle = coordinator.videoRotationAngleForHorizonLevelPreview
|
|
let orientation = call.arguments as? String
|
|
let legacyAngle: CGFloat
|
|
switch orientation {
|
|
case "landscapeLeft": legacyAngle = 180
|
|
case "landscapeRight": legacyAngle = 0
|
|
case "portraitDown": legacyAngle = 270
|
|
default: legacyAngle = 90
|
|
}
|
|
result(Int(((angle - legacyAngle) / 90).rounded()))
|
|
return
|
|
}
|
|
result(0)
|
|
case "usesDynamicIslandQrScannerPortal":
|
|
#if canImport(UIKit, _version: 9127.0.85)
|
|
if #available(iOS 27.1, *),
|
|
let scene = UIApplication.shared.connectedScenes
|
|
.compactMap({ $0 as? UIWindowScene })
|
|
.first(where: { $0.activationState == .foregroundActive }),
|
|
let window = scene.windows.first(where: { $0.isKeyWindow }),
|
|
window.reservedRegions(kind: .division).contains(where: { $0.isActive }) {
|
|
result(false)
|
|
return
|
|
}
|
|
#endif
|
|
result(
|
|
UIDevice.current.userInterfaceIdiom == .phone
|
|
&& usesDynamicIslandQrScannerPortal(
|
|
safeAreaTopInset: activeWindowSafeAreaTopInset()
|
|
)
|
|
)
|
|
case "setDynamicIslandScannerStatusBarHidden":
|
|
guard let hidden = call.arguments as? Bool else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Expected a Bool status-bar visibility value.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
let controller = UIApplication.shared.connectedScenes
|
|
.compactMap { $0 as? UIWindowScene }
|
|
.flatMap(\.windows)
|
|
.compactMap { $0.rootViewController as? BuzzFlutterViewController }
|
|
.first
|
|
controller?.setScannerStatusBarHidden(hidden)
|
|
result(nil)
|
|
case "performDynamicIslandQrScanSuccessHaptic":
|
|
let generator = UINotificationFeedbackGenerator()
|
|
generator.prepare()
|
|
generator.notificationOccurred(.success)
|
|
result(nil)
|
|
default:
|
|
result(FlutterMethodNotImplemented)
|
|
}
|
|
}
|
|
|
|
static func usesDynamicIslandQrScannerPortal(
|
|
safeAreaTopInset: CGFloat
|
|
) -> Bool {
|
|
safeAreaTopInset > 50
|
|
}
|
|
|
|
private static func activeWindowSafeAreaTopInset() -> CGFloat {
|
|
UIApplication.shared.connectedScenes
|
|
.compactMap { $0 as? UIWindowScene }
|
|
.filter { $0.activationState == .foregroundActive }
|
|
.flatMap(\.windows)
|
|
.first(where: \.isKeyWindow)?
|
|
.safeAreaInsets.top ?? 0
|
|
}
|
|
|
|
override func application(
|
|
_ application: UIApplication,
|
|
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
|
|
) {
|
|
super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
|
|
apnsDeviceToken = deviceToken
|
|
apnsRegistrationBuffer.recordToken(deviceToken)
|
|
}
|
|
|
|
override func application(
|
|
_ application: UIApplication,
|
|
didFailToRegisterForRemoteNotificationsWithError error: Error
|
|
) {
|
|
super.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
|
|
apnsRegistrationBuffer.recordError(error.localizedDescription)
|
|
}
|
|
|
|
override func userNotificationCenter(
|
|
_ center: UNUserNotificationCenter,
|
|
didReceive response: UNNotificationResponse,
|
|
withCompletionHandler completionHandler: @escaping () -> Void
|
|
) {
|
|
if notificationReplyBridge.handle(response, center: center, completion: completionHandler) {
|
|
return
|
|
}
|
|
BuzzPushNotificationResponseCoordinator.handle(
|
|
actionIdentifier: response.actionIdentifier,
|
|
userInfo: response.notification.request.content.userInfo,
|
|
onTarget: { target in
|
|
pushNavigationBuffer.record(target)
|
|
deliverPushNavigationTarget(target)
|
|
},
|
|
forwardToFlutter: { pluginCompletion in
|
|
self.forwardPushNotificationResponseToFlutter(
|
|
center,
|
|
response: response,
|
|
completion: pluginCompletion
|
|
)
|
|
},
|
|
completion: completionHandler
|
|
)
|
|
}
|
|
|
|
private func forwardPushNotificationResponseToFlutter(
|
|
_ center: UNUserNotificationCenter,
|
|
response: UNNotificationResponse,
|
|
completion: @escaping () -> Void
|
|
) {
|
|
super.userNotificationCenter(
|
|
center,
|
|
didReceive: response,
|
|
withCompletionHandler: completion
|
|
)
|
|
}
|
|
|
|
private func deliverPushNavigationTarget(_ target: BuzzPushNavigationTarget) {
|
|
pushChannel?.invokeMethod(
|
|
"notificationOpened",
|
|
arguments: target.flutterArguments
|
|
) { [weak self] result in
|
|
guard result as? String == "handled" else { return }
|
|
self?.pushNavigationBuffer.remove(ifMatching: target)
|
|
}
|
|
}
|
|
|
|
private func handlePushMethodCall(
|
|
_ call: FlutterMethodCall,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
if pushSnapshotBridge.handle(call, result: result)
|
|
|| notificationReplyBridge.handle(call, result: result)
|
|
{
|
|
return
|
|
}
|
|
switch call.method {
|
|
case "startRegistration":
|
|
startPushRegistration(result: result)
|
|
case "takePendingNotificationResponse":
|
|
result(pushNavigationBuffer.take()?.flutterArguments)
|
|
case "endpointGrants":
|
|
do {
|
|
guard let arguments = call.arguments as? [String: Any],
|
|
let gatewayText = arguments["gatewayUrl"] as? String,
|
|
let gatewayURL = URL(string: gatewayText)
|
|
else { throw BuzzDevPushEnrollmentError.invalidGatewayURL }
|
|
let driver = try BuzzDevPushEnrollmentDriver(
|
|
gatewayBaseURL: gatewayURL,
|
|
store: endpointGrantStore,
|
|
appAttestKeychainAccessGroup: pushKeychainAccessGroup
|
|
)
|
|
result(try driver.endpointGrants().map(\.flutterArguments))
|
|
} catch {
|
|
result(
|
|
FlutterError(
|
|
code: "endpoint_grant_read_failed",
|
|
message: "Unable to read persisted push endpoint grants.",
|
|
details: error.localizedDescription
|
|
)
|
|
)
|
|
}
|
|
case "enrollPush":
|
|
handleDevPushEnrollment(call, result: result)
|
|
default:
|
|
result(FlutterMethodNotImplemented)
|
|
}
|
|
}
|
|
|
|
private func startPushRegistration(result: @escaping FlutterResult) {
|
|
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) {
|
|
_, error in
|
|
if let error {
|
|
os_log(
|
|
"Buzz notification authorization request failed: %{public}@",
|
|
type: .error,
|
|
error.localizedDescription
|
|
)
|
|
}
|
|
}
|
|
// APNs token registration is independent from display authorization. A
|
|
// denied or failed prompt must not prevent gateway enrollment and leases.
|
|
UIApplication.shared.registerForRemoteNotifications()
|
|
result(nil)
|
|
}
|
|
|
|
private func handleDevPushEnrollment(
|
|
_ call: FlutterMethodCall,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
guard enrollmentTask == nil else {
|
|
result(
|
|
FlutterError(
|
|
code: "enrollment_in_progress",
|
|
message: "Development push enrollment is already running.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
guard let deviceToken = apnsDeviceToken else {
|
|
result(
|
|
FlutterError(
|
|
code: "missing_apns_token",
|
|
message: "APNs has not supplied a device token.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
guard !deviceToken.isEmpty else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_apns_token",
|
|
message: "APNs supplied an empty device token.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
guard let arguments = call.arguments as? [String: Any],
|
|
let relayText = arguments["relayUrl"] as? String,
|
|
let relayURL = URL(string: relayText),
|
|
let gatewayText = arguments["gatewayUrl"] as? String,
|
|
let gatewayURL = URL(string: gatewayText)
|
|
else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Development push enrollment requires relayUrl and gatewayUrl.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
do {
|
|
let driver = try BuzzDevPushEnrollmentDriver(
|
|
gatewayBaseURL: gatewayURL,
|
|
store: endpointGrantStore,
|
|
appAttestKeychainAccessGroup: Bundle.main.object(
|
|
forInfoDictionaryKey: "BuzzKeychainAccessGroup"
|
|
) as? String
|
|
)
|
|
enrollmentTask = Task { [weak self] in
|
|
defer { self?.enrollmentTask = nil }
|
|
do {
|
|
let record = try await driver.enroll(
|
|
deviceToken: deviceToken,
|
|
relayURL: relayURL
|
|
)
|
|
await MainActor.run { result(record.flutterArguments) }
|
|
} catch {
|
|
await MainActor.run {
|
|
result(
|
|
FlutterError(
|
|
code: "dev_enrollment_failed",
|
|
message: "Development push enrollment failed.",
|
|
details: error.localizedDescription
|
|
)
|
|
)
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
result(
|
|
FlutterError(
|
|
code: "dev_enrollment_configuration_failed",
|
|
message: "Development push enrollment is not configured.",
|
|
details: error.localizedDescription
|
|
)
|
|
)
|
|
}
|
|
}
|
|
|
|
private func handleMediaUploadMethodCall(
|
|
_ call: FlutterMethodCall,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
switch call.method {
|
|
case "sanitizeImageForUpload":
|
|
guard
|
|
let arguments = call.arguments as? [String: Any],
|
|
let typedData = arguments["bytes"] as? FlutterStandardTypedData,
|
|
let mimeType = arguments["mimeType"] as? String
|
|
else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Expected image bytes and mime type.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
guard let image = UIImage(data: typedData.data) else {
|
|
result(
|
|
FlutterError(
|
|
code: "sanitize_failed",
|
|
message: "Unable to decode picked image.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
do {
|
|
guard let sanitizedData = try MediaSanitizer.sanitizeImage(image, mimeType: mimeType) else {
|
|
result(
|
|
FlutterError(
|
|
code: "sanitize_failed",
|
|
message: "Unable to sanitize picked image.",
|
|
details: mimeType
|
|
)
|
|
)
|
|
return
|
|
}
|
|
result(FlutterStandardTypedData(bytes: sanitizedData))
|
|
} catch {
|
|
result(
|
|
FlutterError(
|
|
code: "sanitize_failed",
|
|
message: "Unable to sanitize picked image.",
|
|
details: mimeType
|
|
)
|
|
)
|
|
}
|
|
case "transcodeImageToJpeg":
|
|
guard let typedData = call.arguments as? FlutterStandardTypedData else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Expected raw image bytes.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
guard let image = UIImage(data: typedData.data) else {
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: "Unable to convert picked image to JPEG.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
do {
|
|
guard let jpegData = try MediaSanitizer.encodeJpeg(image) else {
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: "Unable to convert picked image to JPEG.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
result(FlutterStandardTypedData(bytes: jpegData))
|
|
} catch {
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: "Unable to convert picked image to JPEG.",
|
|
details: nil
|
|
)
|
|
)
|
|
}
|
|
case "transcodeVideoToMp4":
|
|
guard let sourcePath = call.arguments as? String else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Expected source file path as String.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
transcodeVideoToMp4(sourcePath: sourcePath, result: result)
|
|
case "packageVoiceNoteForUpload":
|
|
guard let sourcePath = call.arguments as? String else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Expected source file path as String.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
VoiceNotePackager.package(sourcePath: sourcePath, result: result)
|
|
case "generateVideoPoster":
|
|
guard let sourcePath = call.arguments as? String else {
|
|
result(
|
|
FlutterError(
|
|
code: "invalid_arguments",
|
|
message: "Expected source file path as String.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
generateVideoPoster(sourcePath: sourcePath, result: result)
|
|
case "clipboardHasImage":
|
|
result(UIPasteboard.general.hasImages)
|
|
case "readClipboardImage":
|
|
guard let imageData = Self.clipboardImageData(from: UIPasteboard.general) else {
|
|
result(nil)
|
|
return
|
|
}
|
|
result(FlutterStandardTypedData(bytes: imageData))
|
|
default:
|
|
result(FlutterMethodNotImplemented)
|
|
}
|
|
}
|
|
|
|
static func clipboardImageData(from pasteboard: UIPasteboard) -> Data? {
|
|
if let pngData = pasteboard.data(forPasteboardType: "public.png") {
|
|
return pngData
|
|
}
|
|
if let jpegData = pasteboard.data(forPasteboardType: "public.jpeg") {
|
|
return jpegData
|
|
}
|
|
for imageType in ["public.heic", "public.heif", "org.webmproject.webp", "com.compuserve.gif"] {
|
|
if let imageData = pasteboard.data(forPasteboardType: imageType) {
|
|
return imageData
|
|
}
|
|
}
|
|
guard let image = pasteboard.image else {
|
|
return nil
|
|
}
|
|
return image.pngData()
|
|
}
|
|
|
|
private func transcodeVideoToMp4(
|
|
sourcePath: String,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
let sourceURL = URL(fileURLWithPath: sourcePath)
|
|
let asset = AVURLAsset(url: sourceURL)
|
|
|
|
// Do not export the source asset directly. An iPhone video can carry GPS,
|
|
// spatial-video, and other data tracks even when its user-visible metadata
|
|
// is cleared. A fresh composition copies only one video and one audio
|
|
// track, so those private channels cannot reach the relay.
|
|
let composition = AVMutableComposition()
|
|
guard
|
|
let sourceVideo = asset.tracks(withMediaType: .video).first,
|
|
let destinationVideo = composition.addMutableTrack(
|
|
withMediaType: .video,
|
|
preferredTrackID: kCMPersistentTrackID_Invalid
|
|
)
|
|
else {
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: "The selected file does not contain a video track.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
do {
|
|
let sourceAudio = asset.tracks(withMediaType: .audio).first
|
|
let insertionTimes = Self.relativeTrackInsertionTimes(
|
|
videoStart: sourceVideo.timeRange.start,
|
|
audioStart: sourceAudio?.timeRange.start
|
|
)
|
|
try destinationVideo.insertTimeRange(
|
|
sourceVideo.timeRange,
|
|
of: sourceVideo,
|
|
at: insertionTimes.video
|
|
)
|
|
destinationVideo.preferredTransform = sourceVideo.preferredTransform
|
|
|
|
if let sourceAudio,
|
|
let destinationAudio = composition.addMutableTrack(
|
|
withMediaType: .audio,
|
|
preferredTrackID: kCMPersistentTrackID_Invalid
|
|
)
|
|
{
|
|
try destinationAudio.insertTimeRange(
|
|
sourceAudio.timeRange,
|
|
of: sourceAudio,
|
|
at: insertionTimes.audio ?? .zero
|
|
)
|
|
}
|
|
} catch {
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: error.localizedDescription,
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
guard
|
|
let exportSession = AVAssetExportSession(
|
|
asset: composition,
|
|
// Passthrough preserves the source's HEVC codec and container
|
|
// metadata. Buzz accepts only canonical H.264/AAC MP4s with no
|
|
// metadata channels, so re-encode instead of copying the movie.
|
|
presetName: AVAssetExportPresetMediumQuality
|
|
)
|
|
else {
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: "Unable to create export session.",
|
|
details: nil
|
|
)
|
|
)
|
|
return
|
|
}
|
|
|
|
let outputURL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("mp4")
|
|
|
|
exportSession.outputURL = outputURL
|
|
exportSession.outputFileType = .mp4
|
|
exportSession.shouldOptimizeForNetworkUse = true
|
|
// `forSharing()` intentionally retains playback metadata. The relay
|
|
// rejects every descriptive metadata channel to avoid leaking location or
|
|
// other private information, so write no source metadata at all.
|
|
exportSession.metadata = []
|
|
exportSession.metadataItemFilter = nil
|
|
|
|
exportSession.exportAsynchronously {
|
|
switch exportSession.status {
|
|
case .completed:
|
|
do {
|
|
// AVFoundation writes a standard sample-dependency table (`sdtp`).
|
|
// Older Buzz relays mistook that playback-only box for metadata. Keep
|
|
// its size and payload in a `free` box so chunk offsets stay valid and
|
|
// uploads work before those relays receive the validator fix.
|
|
try MP4Canonicalizer.neutralizeSampleDependencyBoxes(at: outputURL)
|
|
result(outputURL.path)
|
|
} catch {
|
|
try? FileManager.default.removeItem(at: outputURL)
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: "Unable to canonicalize transcoded video.",
|
|
details: error.localizedDescription
|
|
)
|
|
)
|
|
}
|
|
default:
|
|
let errorMessage =
|
|
exportSession.error?.localizedDescription
|
|
?? "Video transcoding failed with status \(exportSession.status.rawValue)."
|
|
result(
|
|
FlutterError(
|
|
code: "transcode_failed",
|
|
message: errorMessage,
|
|
details: nil
|
|
)
|
|
)
|
|
// Clean up partial output on failure.
|
|
try? FileManager.default.removeItem(at: outputURL)
|
|
}
|
|
}
|
|
}
|
|
|
|
static func relativeTrackInsertionTimes(
|
|
videoStart: CMTime,
|
|
audioStart: CMTime?
|
|
) -> (video: CMTime, audio: CMTime?) {
|
|
guard let audioStart else {
|
|
return (video: .zero, audio: nil)
|
|
}
|
|
|
|
let timelineStart =
|
|
CMTimeCompare(audioStart, videoStart) < 0 ? audioStart : videoStart
|
|
return (
|
|
video: CMTimeSubtract(videoStart, timelineStart),
|
|
audio: CMTimeSubtract(audioStart, timelineStart)
|
|
)
|
|
}
|
|
|
|
private func generateVideoPoster(
|
|
sourcePath: String,
|
|
result: @escaping FlutterResult
|
|
) {
|
|
DispatchQueue.global(qos: .userInitiated).async {
|
|
let asset = AVURLAsset(url: URL(fileURLWithPath: sourcePath))
|
|
let generator = AVAssetImageGenerator(asset: asset)
|
|
generator.appliesPreferredTrackTransform = true
|
|
generator.maximumSize = CGSize(width: 720, height: 720)
|
|
generator.requestedTimeToleranceBefore = .positiveInfinity
|
|
generator.requestedTimeToleranceAfter = .positiveInfinity
|
|
|
|
do {
|
|
let durationSeconds = CMTimeGetSeconds(asset.duration)
|
|
let middleTime =
|
|
durationSeconds.isFinite && durationSeconds > 0
|
|
? min(durationSeconds / 2, 1)
|
|
: 0
|
|
let candidateTimes = [0, 0.1, middleTime]
|
|
var posterImage: CGImage?
|
|
var lastError: Error?
|
|
|
|
for seconds in candidateTimes {
|
|
do {
|
|
posterImage = try generator.copyCGImage(
|
|
at: CMTime(seconds: seconds, preferredTimescale: 600),
|
|
actualTime: nil
|
|
)
|
|
if posterImage != nil { break }
|
|
} catch {
|
|
lastError = error
|
|
}
|
|
}
|
|
|
|
guard let posterImage else {
|
|
throw lastError
|
|
?? NSError(
|
|
domain: "BuzzVideoPoster",
|
|
code: 1,
|
|
userInfo: [NSLocalizedDescriptionKey: "Unable to decode a video frame."]
|
|
)
|
|
}
|
|
guard let jpegData = try MediaSanitizer.encodeJpeg(UIImage(cgImage: posterImage)) else {
|
|
throw NSError(
|
|
domain: "BuzzVideoPoster",
|
|
code: 2,
|
|
userInfo: [NSLocalizedDescriptionKey: "Unable to encode video poster."]
|
|
)
|
|
}
|
|
DispatchQueue.main.async {
|
|
result(FlutterStandardTypedData(bytes: jpegData))
|
|
}
|
|
} catch {
|
|
DispatchQueue.main.async {
|
|
result(
|
|
FlutterError(
|
|
code: "poster_failed",
|
|
message: "Unable to create a video preview.",
|
|
details: error.localizedDescription
|
|
)
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|