diff --git a/apps/mobile/README.md b/apps/mobile/README.md index 7fb65bd..8e33bc2 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -42,3 +42,34 @@ Native sharing supplies media titles and artwork through iOS link metadata and A thumbnail, while sharing the original HTTPS URL. Receiving apps control whether they display previews. If artwork cannot load, the URL is still shared. Existing builds without the native sharing module fall back to URL-only sharing. + +### Apple Handoff + +The native app advertises the current album, artist, or playlist screen using +`NSUserActivity`, with the custom activity type `.media`. +Leaving these screens or signing out invalidates the activity. Only the media +route and source server address travel with it, with no playback, queue, tokens, +or web URL. Receiving compares the source with the configured server and uses +the existing navigation and sign-in flow. A missing or different configured +server shows "This activity belongs to a different oTunes server." Setup is +never prefilled or switched by Handoff. + +This repository has one UIKit-based Expo app, not a separate AppKit or Mac +Catalyst target. On macOS this implementation covers the iPhone/iPad app running +on Apple silicon, if the signed app is made available there. The same native +subscriber publishes and receives on that runtime. Intel Macs and a standalone +AppKit app are not supported by this app architecture. + +Install a new native build on each device. Apps must be signed with the same +Apple developer Team ID and declare the same activity type. Variants deliberately +use different activity types so development, preview, and production do not +continue each other's activities. Self-hosters need no associated domains, AASA +files, per-server signing configuration, or web Handoff. Server addresses are +used only for comparison on receipt. + +Apple also requires nearby devices signed into the same Apple Account, Handoff +enabled, and Wi-Fi and Bluetooth enabled. See Apple's +[Handoff implementation requirements](https://developer.apple.com/documentation/foundation/implementing-handoff-in-your-app). +Verify on physical devices in both directions, including a cold launch, signed-out +receipt, a different configured server, and leaving a media screen. A simulator +or a TypeScript check cannot establish that cross-device Handoff works. 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 +}