Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
86 lines
2.5 KiB
TypeScript
86 lines
2.5 KiB
TypeScript
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) {
|
|
showError("Connect to an oTunes server to continue this activity.")
|
|
return
|
|
}
|
|
if (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
|
|
}
|