feat(mobile): continue media screens with Apple Handoff (#74)
This commit was merged in pull request #74.
This commit is contained in:
1 parent
85a2dd5c88
commit
d5c956c691
9 files changed
+196
-2
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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 "/"
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
<ConvexAppProvider>
|
||||
<StatusBar style={isDark ? "light" : "dark"} />
|
||||
<ThemeProvider value={navigationTheme}>
|
||||
<HandoffBridge />
|
||||
<RootNavigator />
|
||||
</ThemeProvider>
|
||||
<Toaster />
|
||||
|
||||
@@ -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<Activity | null>
|
||||
publish(server: string | null, route: string | null): Promise<void>
|
||||
}
|
||||
|
||||
const handoff =
|
||||
Platform.OS === "ios"
|
||||
? requireOptionalNativeModule<HandoffModule>("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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["HandoffModule"],
|
||||
"appDelegateSubscribers": ["HandoffAppDelegateSubscriber"]
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "otunes-handoff",
|
||||
"version": "1.0.0",
|
||||
"private": true
|
||||
}
|
||||
Reference in new issue
Block a user