Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions App/AppleTVDiscovery.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import Foundation

struct AppleTVDevice: Identifiable, Equatable {
let id: String
let name: String
let host: String
let port: Int
}

@MainActor
final class AppleTVDiscovery: NSObject, ObservableObject {
@Published private(set) var devices: [AppleTVDevice] = []

private let browser = NetServiceBrowser()
private var services: [String: NetService] = [:]

override init() {
super.init()
browser.delegate = self
}

func start() {
guard services.isEmpty else { return }
browser.searchForServices(
ofType: "_remotepairing-manual-pairing._tcp.",
inDomain: "local.")
}

func stop() {
browser.stop()
for service in services.values {
service.stop()
}
services.removeAll()
devices.removeAll()
}

private func identifier(for service: NetService) -> String {
"\(service.name).\(service.type)\(service.domain)"
}

private func update(_ service: NetService) {
guard let host = service.hostName, service.port > 0 else { return }
let id = identifier(for: service)
let txt = service.txtRecordData().map(NetService.dictionary(fromTXTRecord:)) ?? [:]
let advertisedName = txt["name"].flatMap { String(data: $0, encoding: .utf8) }
let displayName = advertisedName.flatMap { $0.isEmpty ? nil : $0 } ?? service.name
let device = AppleTVDevice(
id: id,
name: displayName,
host: host,
port: service.port)
devices.removeAll { $0.id == id }
devices.append(device)
devices.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
}
}

extension AppleTVDiscovery: NetServiceBrowserDelegate {
nonisolated func netServiceBrowser(
_ browser: NetServiceBrowser,
didFind service: NetService,
moreComing: Bool
) {
Task { @MainActor in
let id = identifier(for: service)
services[id] = service
service.delegate = self
service.resolve(withTimeout: 6)
}
}

nonisolated func netServiceBrowser(
_ browser: NetServiceBrowser,
didRemove service: NetService,
moreComing: Bool
) {
Task { @MainActor in
let id = identifier(for: service)
services.removeValue(forKey: id)
devices.removeAll { $0.id == id }
}
}
}

extension AppleTVDiscovery: NetServiceDelegate {
nonisolated func netServiceDidResolveAddress(_ sender: NetService) {
Task { @MainActor in update(sender) }
}

nonisolated func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {
Task { @MainActor in update(sender) }
}
}
80 changes: 79 additions & 1 deletion App/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import SwiftUI

struct ContentView: View {
@StateObject private var controller = PairingController.shared
@State private var appleTVPin = ""

var body: some View {
VStack(spacing: 28) {
Expand Down Expand Up @@ -29,7 +30,17 @@ struct ContentView: View {
Button {
controller.start()
} label: {
Text("Pair")
Text("Pair iPhone or iPad")
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.glass)
.controlSize(.large)

Button {
controller.browseForAppleTVs()
} label: {
Text("Pair Apple TV")
.font(.headline)
.frame(maxWidth: .infinity)
}
Expand Down Expand Up @@ -78,6 +89,73 @@ struct ContentView: View {
ProgressView()
}

case .browsingAppleTV:
VStack(spacing: 16) {
Text("Choose an Apple TV")
.font(.headline)
Text("On Apple TV, open **Settings › Remotes and Devices › Remote App and Devices**.")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)

if controller.appleTVs.isEmpty {
ProgressView("Looking for Apple TVs…")
} else {
ForEach(controller.appleTVs) { device in
Button {
appleTVPin = ""
controller.pairAppleTV(device)
} label: {
Label(device.name, systemImage: "appletv")
.frame(maxWidth: .infinity)
}
.buttonStyle(.glass)
.controlSize(.large)
}
}

Button("Cancel") { controller.cancelAppleTVPairing() }
.buttonStyle(.glass)
}

case .enteringAppleTVPin(let device):
VStack(spacing: 16) {
Text("Pair with \(device.name)")
.font(.headline)
Text("Enter the six-digit code shown on your Apple TV.")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
TextField("000000", text: $appleTVPin)
.keyboardType(.numberPad)
.textContentType(.oneTimeCode)
.multilineTextAlignment(.center)
.font(.system(size: 32, weight: .bold, design: .rounded))
.monospacedDigit()
.onChange(of: appleTVPin) { _, value in
appleTVPin = String(value.filter(\.isNumber).prefix(6))
}
.padding()
.glassEffect(.regular, in: .rect(cornerRadius: 16))
Button("Pair") {
controller.submitAppleTVPin(appleTVPin)
}
.buttonStyle(.glass)
.controlSize(.large)
.disabled(appleTVPin.count != 6)
Button("Cancel") { controller.cancelAppleTVPairing() }
.buttonStyle(.glass)
}

case .pairingAppleTV(let name):
VStack(spacing: 16) {
ProgressView()
Text("Pairing with \(name)…")
.foregroundStyle(.secondary)
Button("Cancel") { controller.cancelAppleTVPairing() }
.buttonStyle(.glass)
}

case .success(let device):
VStack(spacing: 12) {
Label("Paired", systemImage: "checkmark.seal.fill")
Expand Down
3 changes: 2 additions & 1 deletion App/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSLocalNetworkUsageDescription</key>
<string>StikPair advertises a pairing service so this device can pair with it.</string>
<string>StikPair uses your local network to discover devices and complete pairing.</string>
<key>NSBonjourServices</key>
<array>
<string>_remotepairing-pairable-host._tcp</string>
<string>_remotepairing-manual-pairing._tcp</string>
<!-- Throwaway type used only to trigger the Local Network prompt. -->
<string>_stikpairprobe._tcp</string>
</array>
Expand Down
120 changes: 119 additions & 1 deletion App/PairingController.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import BackgroundTasks
import Combine
import Foundation
import StikPairFFI
import UserNotifications
Expand All @@ -13,6 +14,9 @@ final class PairingController: ObservableObject {
case idle
case waiting
case showPin(String)
case browsingAppleTV
case enteringAppleTVPin(AppleTVDevice)
case pairingAppleTV(String)
case success(PairedDevice)
case failed(String)
}
Expand All @@ -25,6 +29,7 @@ final class PairingController: ObservableObject {
}

@Published var phase: Phase = .idle
@Published private(set) var appleTVs: [AppleTVDevice] = []

@Published var keepAliveAudio: Bool = UserDefaults.standard.bool(forKey: "keepAlive.audio") {
didSet { UserDefaults.standard.set(keepAliveAudio, forKey: "keepAlive.audio") }
Expand All @@ -39,18 +44,29 @@ final class PairingController: ObservableObject {
private var netService: NetService?
private let localNetwork = LocalNetworkAuthorization()
private let keepAlive = KeepAlive()
private let appleTVDiscovery = AppleTVDiscovery()
private var discoverySubscription: AnyCancellable?
private var appleTVSession: OpaquePointer?
private var activeAppleTV: AppleTVDevice?
private var appleTVCancelled = false

private var bgTask: BGContinuedProcessingTask?
private var pairingStarted = false
private var taskFinished = false

var isRunning: Bool {
if pairingStarted { return true }
switch phase {
case .waiting, .showPin: return true
case .waiting, .showPin, .enteringAppleTVPin, .pairingAppleTV: return true
default: return false
}
}

private init() {
discoverySubscription = appleTVDiscovery.$devices
.sink { [weak self] devices in self?.appleTVs = devices }
}

nonisolated func registerBackgroundTask() {
BGTaskScheduler.shared.register(
forTaskWithIdentifier: PairingController.taskIdentifier,
Expand Down Expand Up @@ -82,8 +98,97 @@ final class PairingController: ObservableObject {
}
}

func browseForAppleTVs() {
guard !isRunning else { return }
phase = .browsingAppleTV
Task {
let authorized = await localNetwork.request()
guard case .browsingAppleTV = phase else { return }
guard authorized else {
phase = .failed("Local Network permission is required. Enable it in Settings › StikPair › Local Network, then try again.")
return
}
appleTVDiscovery.start()
}
}

func pairAppleTV(_ device: AppleTVDevice) {
guard !pairingStarted, let session = stikpair_apple_tv_session_new() else { return }
appleTVDiscovery.stop()
appleTVSession = session
activeAppleTV = device
appleTVCancelled = false
pairingStarted = true
phase = .pairingAppleTV(device.name)

let name = hostName
let outPath = Self.pairingFilePath()
let sessionBits = UInt(bitPattern: session)
let ctxBits = UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque())
DispatchQueue.global(qos: .userInitiated).async {
guard let session = OpaquePointer(bitPattern: sessionBits) else { return }
let ctx = UnsafeMutableRawPointer(bitPattern: ctxBits)
var result = StikPairResult()
let rc = device.host.withCString { hostC in
name.withCString { nameC in
outPath.withCString { outC in
stikpair_apple_tv_session_run(
session, hostC, UInt16(device.port), nameC, outC,
appleTVPinCallback, ctx, &result)
}
}
}

let outcome: Phase
if rc == 0 {
outcome = .success(PairedDevice(
name: cString(result.device_name),
model: cString(result.device_model),
udid: cString(result.device_udid),
pairingFilePath: cString(result.pairing_file_path)))
} else {
let message = cString(result.error)
outcome = .failed(message.isEmpty ? "Apple TV pairing failed (code \(rc))" : message)
}
stikpair_result_free(&result)

DispatchQueue.main.async {
let cancelled = self.appleTVCancelled
if self.appleTVSession == session {
self.appleTVSession = nil
}
stikpair_apple_tv_session_free(session)
self.activeAppleTV = nil
self.pairingStarted = false
guard !cancelled else { return }
self.phase = outcome
if case .success = outcome {
self.postReturnNotification()
}
}
}
}

func submitAppleTVPin(_ pin: String) {
guard pin.count == 6, pin.allSatisfy(\.isNumber), let session = appleTVSession else { return }
let rc = pin.withCString { stikpair_apple_tv_session_submit_pin(session, $0) }
if rc == 0, let device = activeAppleTV {
phase = .pairingAppleTV(device.name)
}
}

func cancelAppleTVPairing() {
appleTVCancelled = true
if let session = appleTVSession {
stikpair_apple_tv_session_cancel(session)
}
appleTVDiscovery.stop()
phase = .idle
}

func reset() {
guard !isRunning else { return }
appleTVDiscovery.stop()
phase = .idle
}

Expand Down Expand Up @@ -200,6 +305,11 @@ final class PairingController: ObservableObject {
}
}

fileprivate func presentAppleTVPin() {
guard !appleTVCancelled, let device = activeAppleTV else { return }
phase = .enteringAppleTVPin(device)
}

private func stopAdvertising() {
netService?.stop()
netService = nil
Expand Down Expand Up @@ -253,6 +363,14 @@ private let pinCallback: StikPairPinCb = { pin, ctx in
}
}

private let appleTVPinCallback: StikPairAppleTvPinCb = { ctx in
guard let ctx = ctx else { return }
let controller = Unmanaged<PairingController>.fromOpaque(ctx).takeUnretainedValue()
DispatchQueue.main.async {
controller.presentAppleTVPin()
}
}

private func cString(_ ptr: UnsafeMutablePointer<CChar>?) -> String {
guard let ptr = ptr else { return "" }
return String(cString: ptr)
Expand Down
Loading
Loading