From d5c956c691d018b9c6274c079139b2854ea885df Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Fri, 6 Nov 2026 17:39:56 -0500 Subject: [PATCH] feat(mobile): continue media screens with Apple Handoff (#74) --- apps/mobile/app.config.ts | 4 + apps/mobile/app/+native-intent.ts | 7 +- apps/mobile/app/_layout.tsx | 3 + apps/mobile/components/handoff-bridge.tsx | 81 +++++++++++++++++++ apps/mobile/lib/incoming-media-link.ts | 5 ++ .../modules/handoff/expo-module.config.json | 7 ++ .../modules/handoff/ios/Handoff.podspec | 16 ++++ .../modules/handoff/ios/HandoffModule.swift | 70 ++++++++++++++++ apps/mobile/modules/handoff/package.json | 5 ++ 9 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 apps/mobile/components/handoff-bridge.tsx create mode 100644 apps/mobile/modules/handoff/expo-module.config.json create mode 100644 apps/mobile/modules/handoff/ios/Handoff.podspec create mode 100644 apps/mobile/modules/handoff/ios/HandoffModule.swift create mode 100644 apps/mobile/modules/handoff/package.json diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 9a6f639..8aa6e7a 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -36,6 +36,10 @@ export default ({ config }: ConfigContext): ExpoConfig => { ...config.ios, bundleIdentifier: `${config.ios!.bundleIdentifier}${suffix}`, icon: `./assets/${composer}.icon`, + infoPlist: { + ...config.ios?.infoPlist, + NSUserActivityTypes: [`com.abunchofknowitalls.otunes${suffix}.media`], + }, }, android: { ...config.android, diff --git a/apps/mobile/app/+native-intent.ts b/apps/mobile/app/+native-intent.ts index 62f3efb..b06fe1c 100644 --- a/apps/mobile/app/+native-intent.ts +++ b/apps/mobile/app/+native-intent.ts @@ -1,6 +1,9 @@ import { loadServerConfig, parseServerHostname } from "@/lib/server-config" import { secureGetItem } from "@/lib/auth-storage" -import { rememberIncomingMediaLink } from "@/lib/incoming-media-link" +import { + isMediaRoute, + rememberIncomingMediaLink, +} from "@/lib/incoming-media-link" import { showError } from "@/lib/toast" export async function redirectSystemPath({ @@ -28,7 +31,7 @@ export async function redirectSystemPath({ target.username || target.password || new URL(server.serverUrl).origin !== target.origin || - !/^\/(album|artist|playlist)\/[a-zA-Z0-9_-]+$/.test(target.pathname) + !isMediaRoute(target.pathname) ) { return "/" } diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 40c8ce4..05356c6 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -9,6 +9,8 @@ import { Toaster } from "@/components/ui/toaster" import { ConvexAppProvider } from "@/contexts/convex-app" import { ServerConfigProvider, useServerConfig } from "@/contexts/server-config" +import { HandoffBridge } from "@/components/handoff-bridge" + const navigationTheme = { ...DarkTheme, colors: { ...DarkTheme.colors, background: "#000", card: "#000" }, @@ -56,6 +58,7 @@ export default function RootLayout() { + diff --git a/apps/mobile/components/handoff-bridge.tsx b/apps/mobile/components/handoff-bridge.tsx new file mode 100644 index 0000000..1f6b636 --- /dev/null +++ b/apps/mobile/components/handoff-bridge.tsx @@ -0,0 +1,81 @@ +import { useConvexAuth } from "@convex-dev/auth/react" +import { requireOptionalNativeModule, type NativeModule } from "expo" +import { usePathname } from "expo-router" +import { useEffect } from "react" +import { Platform } from "react-native" + +import { useServerConfig } from "@/contexts/server-config" +import { + isMediaRoute, + rememberIncomingMediaLink, +} from "@/lib/incoming-media-link" +import { showError } from "@/lib/toast" + +type Activity = { server: string; route: string } +declare class HandoffModule extends NativeModule<{ onActivity: () => void }> { + takeActivity(): Promise + publish(server: string | null, route: string | null): Promise +} + +const handoff = + Platform.OS === "ios" + ? requireOptionalNativeModule("Handoff") + : null + +export function HandoffBridge() { + const { config, isLoading } = useServerConfig() + const auth = useConvexAuth() + const pathname = usePathname() + + useEffect(() => { + if (!handoff || isLoading) return + let active = true + async function receive() { + const activity = await handoff!.takeActivity() + if (!active || !activity) return + try { + const source = new URL(activity.server) + if (!config || source.origin !== new URL(config.serverUrl).origin) { + showError("This activity belongs to a different oTunes server.") + return + } + if ( + !["http:", "https:"].includes(source.protocol) || + source.username || + source.password || + !isMediaRoute(activity.route) + ) + return + rememberIncomingMediaLink( + `/(app)/(tabs)/home${activity.route}`, + source.origin + ) + } catch { + // Ignore malformed activities without navigating or changing servers. + } + } + const subscription = handoff.addListener("onActivity", () => { + void receive() + }) + void receive() + return () => { + active = false + subscription.remove() + } + }, [config, isLoading]) + + useEffect(() => { + if (!handoff) return + const route = pathname.replace(/^\/(home|search|library)/, "") + const canPublish = config && auth?.isAuthenticated && isMediaRoute(route) + void handoff.publish( + canPublish ? config.serverUrl : null, + canPublish ? route : null + ) + return () => { + void handoff.publish(null, null) + } + }, [config, auth?.isAuthenticated, pathname]) + + return null +} diff --git a/apps/mobile/lib/incoming-media-link.ts b/apps/mobile/lib/incoming-media-link.ts index e2a59be..41d011b 100644 --- a/apps/mobile/lib/incoming-media-link.ts +++ b/apps/mobile/lib/incoming-media-link.ts @@ -28,3 +28,8 @@ export function rememberIncomingMediaLink(path: string, serverOrigin: string) { pendingLink = { path, serverOrigin } for (const listener of listeners) listener() } + +// Shared by native links and Handoff. Only concrete media screens are routable. +export function isMediaRoute(path: string) { + return /^\/(album|artist|playlist)\/[a-zA-Z0-9_-]+$/.test(path) +} diff --git a/apps/mobile/modules/handoff/expo-module.config.json b/apps/mobile/modules/handoff/expo-module.config.json new file mode 100644 index 0000000..53616b3 --- /dev/null +++ b/apps/mobile/modules/handoff/expo-module.config.json @@ -0,0 +1,7 @@ +{ + "platforms": ["apple"], + "apple": { + "modules": ["HandoffModule"], + "appDelegateSubscribers": ["HandoffAppDelegateSubscriber"] + } +} diff --git a/apps/mobile/modules/handoff/ios/Handoff.podspec b/apps/mobile/modules/handoff/ios/Handoff.podspec new file mode 100644 index 0000000..13f6db3 --- /dev/null +++ b/apps/mobile/modules/handoff/ios/Handoff.podspec @@ -0,0 +1,16 @@ +Pod::Spec.new do |s| + s.name = 'Handoff' + s.version = '1.0.0' + s.summary = 'Native media screen Handoff for oTunes' + s.description = s.summary + s.license = { :type => 'MIT' } + s.author = 'oTunes' + s.homepage = 'https://otunes.abunchofknowitalls.com' + s.platforms = { :ios => '16.4' } + s.swift_version = '5.9' + s.source = { :git => '' } + s.static_framework = true + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.dependency 'ExpoModulesCore' + s.source_files = '**/*.swift' +end diff --git a/apps/mobile/modules/handoff/ios/HandoffModule.swift b/apps/mobile/modules/handoff/ios/HandoffModule.swift new file mode 100644 index 0000000..d9dd6a2 --- /dev/null +++ b/apps/mobile/modules/handoff/ios/HandoffModule.swift @@ -0,0 +1,70 @@ +import ExpoModulesCore +import UIKit + +// Retain the latest continuation until JS is mounted, including cold launches. +private enum HandoffState { + static var activity: NSUserActivity? + static var pending: [String: String]? + static var notify: (() -> Void)? + + static var activityType: String { + "\(Bundle.main.bundleIdentifier!).media" + } +} + +public final class HandoffAppDelegateSubscriber: ExpoAppDelegateSubscriber { + public func application( + _ application: UIApplication, + continue userActivity: NSUserActivity, + restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void + ) -> Bool { + guard userActivity.activityType == HandoffState.activityType, + let server = userActivity.userInfo?["server"] as? String, + let route = userActivity.userInfo?["route"] as? String + else { return false } + HandoffState.pending = ["server": server, "route": route] + HandoffState.notify?() + return true + } +} + +public final class HandoffModule: Module { + public func definition() -> ModuleDefinition { + Name("Handoff") + Events("onActivity") + + OnStartObserving { + HandoffState.notify = { [weak self] in self?.sendEvent("onActivity") } + if HandoffState.pending != nil { HandoffState.notify?() } + } + OnStopObserving { HandoffState.notify = nil } + + AsyncFunction("takeActivity") { () -> [String: String]? in + defer { HandoffState.pending = nil } + return HandoffState.pending + }.runOnQueue(.main) + + AsyncFunction("publish") { (server: String?, route: String?) in + HandoffState.activity?.invalidate() + HandoffState.activity = nil + guard let server, let route else { return } + let activity = NSUserActivity(activityType: HandoffState.activityType) + activity.title = "oTunes" + activity.userInfo = ["server": server, "route": route] + activity.requiredUserInfoKeys = ["server", "route"] + activity.isEligibleForHandoff = true + activity.isEligibleForSearch = false + activity.isEligibleForPublicIndexing = false + HandoffState.activity = activity + activity.becomeCurrent() + }.runOnQueue(.main) + + OnDestroy { + DispatchQueue.main.async { + HandoffState.activity?.invalidate() + HandoffState.activity = nil + HandoffState.notify = nil + } + } + } +} diff --git a/apps/mobile/modules/handoff/package.json b/apps/mobile/modules/handoff/package.json new file mode 100644 index 0000000..1e85bd0 --- /dev/null +++ b/apps/mobile/modules/handoff/package.json @@ -0,0 +1,5 @@ +{ + "name": "otunes-handoff", + "version": "1.0.0", + "private": true +}