@mentra/glasses-media 3.4.0-dev.999 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/android/build.gradle +1 -0
- package/android/src/main/java/com/mentra/glassesmedia/GlassesMediaRelayModule.kt +12 -10
- package/android/src/main/java/com/mentra/glassesmedia/network/InternetHold.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkChangeDetector.kt +3 -1
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkObserver.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/publisher/PhoneWhipPublisher.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/CloudflareWhepSource.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/DecodedFrameTap.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/DecodedTrackRelay.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/GlassesMediaSource.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/LocalWhipIngestSource.kt +4 -4
- package/android/src/main/java/com/mentra/glassesmedia/source/SelectedIcePair.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/SoftApIceDiagnosis.kt +3 -2
- package/android/src/main/java/com/mentra/glassesmedia/source/SoftApSdpGuard.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/SyntheticI420Source.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/VideoSourceArm.kt +2 -0
- package/android/src/main/java/com/mentra/glassesmedia/source/WhipIngestServer.kt +3 -3
- package/android/src/main/java/com/mentra/glassesmedia/telemetry/AvSyncProbe.kt +1 -1
- package/android/src/main/java/com/mentra/glassesmedia/trace/MediaLog.kt +35 -0
- package/index.d.ts +6 -0
- package/index.js +21 -0
- package/ios/CoreKit/Sources/GlassesMediaCore/HotspotJoinFailure.swift +4 -0
- package/ios/CoreKit/Sources/GlassesMediaCore/HotspotReapplyPolicy.swift +26 -0
- package/ios/CoreKit/Sources/GlassesMediaCore/LocalNetworkAccessRequest.swift +33 -7
- package/ios/CoreKit/Sources/GlassesMediaCore/MacHotspotAssociation.swift +146 -18
- package/ios/GlassesHotspotNetwork.swift +90 -33
- package/ios/GlassesMediaRelayModule.swift +19 -2
- package/ios/LocalWhipIngestSource.swift +2 -2
- package/ios/MediaLog.swift +13 -0
- package/ios/WhepVideoSource.swift +8 -8
- package/package.json +4 -1
- package/android/src/main/java/com/mentra/glassesmedia/network/Ipv4Prefix.kt +0 -51
- package/android/src/main/java/com/mentra/glassesmedia/network/NetworkFacts.kt +0 -81
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkError.kt +0 -109
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkReadiness.kt +0 -103
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkRequestSpec.kt +0 -53
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkState.kt +0 -127
- package/android/src/main/java/com/mentra/glassesmedia/network/ScopedSoftApNetwork.kt +0 -573
- package/android/src/main/java/com/mentra/glassesmedia/trace/SoftApTrace.kt +0 -143
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Native receivers, WHIP publishers and network helpers shared by the Mentra App.
|
|
|
4
4
|
|
|
5
5
|
- Android: the existing `GlassesMediaSource`, local WHIP and WHEP receivers, scoped SoftAP networking, decoded I420/PCM delivery, and transport diagnostics moved here. The ACS session and raw outgoing streams remain in `acs-meeting`.
|
|
6
6
|
- iOS: `DecodedGlassesMediaSource` delivers `CVPixelBuffer` video and interleaved PCM16. `LocalWhipIngestSource` answers the glasses' existing WHIP client; `WhepVideoSource` retains the cloud subscription path.
|
|
7
|
-
- `GlassesHotspotNetwork` owns hotspot association for OTA, gallery transfers and media. iPhone uses persistent `NEHotspotConfiguration
|
|
7
|
+
- `GlassesHotspotNetwork` owns hotspot association for OTA, gallery transfers and media. iPhone uses persistent `NEHotspotConfiguration`, and keeps only the one it is joining: every join first removes the app's configurations for other hotspots, and each launch removes leftovers, so a phone near many pairs never rejoins another pair by itself; iOS-on-Mac uses public CoreWLAN in the app process and the standard Location permission needed to identify Wi-Fi networks. Wi-Fi carries the glasses link; cellular carries the call. The owner verifies the requested SSID and actual Wi-Fi interface address, retains that interface for loss checks and ACS binding, and serializes network writers across consumers. Cancellation retains custody until blocking native work and cleanup finish. Cleanup preserves a network the user joined afterward; a failed release rejects and retains ownership for a later cleanup attempt.
|
|
8
8
|
|
|
9
9
|
The publisher owns its outgoing encoders, audio policy, and destination. Receivers do not open the phone microphone or play the glasses microphone locally. iOS uses a receive-only audio device to drive decoded PCM delivery without changing the app's audio session.
|
|
10
10
|
|
package/android/build.gradle
CHANGED
|
@@ -66,6 +66,7 @@ afterEvaluate {
|
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
dependencies {
|
|
69
|
+
implementation project(':mentra-bluetooth-sdk')
|
|
69
70
|
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.4'
|
|
70
71
|
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
|
71
72
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1'
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
package com.mentra.glassesmedia
|
|
2
2
|
|
|
3
|
+
import com.mentra.bluetoothsdk.hotspot.ScopedSoftApNetwork
|
|
4
|
+
import com.mentra.bluetoothsdk.hotspot.ScopedNetworkError
|
|
3
5
|
import android.content.Intent
|
|
4
6
|
import android.os.Handler
|
|
5
7
|
import android.os.Looper
|
|
6
8
|
import android.os.PowerManager
|
|
7
9
|
import android.provider.Settings
|
|
8
10
|
import android.util.Base64
|
|
9
|
-
import
|
|
11
|
+
import com.mentra.glassesmedia.trace.MediaLog
|
|
12
|
+
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
10
13
|
import com.mentra.glassesmedia.network.*
|
|
11
14
|
import com.mentra.glassesmedia.publisher.PhoneWhipPublisher
|
|
12
15
|
import com.mentra.glassesmedia.publisher.RelayPcmInput
|
|
@@ -29,7 +32,9 @@ class GlassesMediaRelayModule : Module() {
|
|
|
29
32
|
|
|
30
33
|
override fun definition() = ModuleDefinition {
|
|
31
34
|
Name("MentraGlassesMediaRelay")
|
|
32
|
-
Events("onRelayState")
|
|
35
|
+
Events("onRelayState", "onNativeLog")
|
|
36
|
+
|
|
37
|
+
OnCreate { MediaLog.sink = { message -> sendEvent("onNativeLog", mapOf("message" to message)) } }
|
|
33
38
|
|
|
34
39
|
AsyncFunction("prepare") { options: Map<String, Any?>, promise: Promise ->
|
|
35
40
|
worker.execute {
|
|
@@ -57,13 +62,7 @@ class GlassesMediaRelayModule : Module() {
|
|
|
57
62
|
override fun onAvailable(network: android.net.Network, localIpv4: String) = Unit
|
|
58
63
|
override fun onLost(error: ScopedNetworkError) { emit(id, "failed", "Glasses hotspot connection was lost") }
|
|
59
64
|
}
|
|
60
|
-
|
|
61
|
-
scoped.join(ssid, password, listener)
|
|
62
|
-
} catch (error: ScopedNetworkError.Unavailable) {
|
|
63
|
-
// Same recovery as ACS: the first specifier can reject while leaving office Wi-Fi.
|
|
64
|
-
Thread.sleep(ScopedSoftApNetwork.UNAVAILABLE_RETRY_SETTLE_MS)
|
|
65
|
-
scoped.join(ssid, password, listener)
|
|
66
|
-
}
|
|
65
|
+
scoped.join(ssid, password, listener)
|
|
67
66
|
ScopedNetworkChangeDetector.registerRelayNetwork(scoped)
|
|
68
67
|
val outgoing = PhoneWhipPublisher(context, endpoint, options["captureAudio"] != false,
|
|
69
68
|
(options["bitrate"] as? Number)?.toInt() ?: 2_000_000) { state, reason -> emit(id, state, reason) }
|
|
@@ -108,7 +107,10 @@ class GlassesMediaRelayModule : Module() {
|
|
|
108
107
|
}
|
|
109
108
|
}
|
|
110
109
|
|
|
111
|
-
OnDestroy {
|
|
110
|
+
OnDestroy {
|
|
111
|
+
MediaLog.sink = null
|
|
112
|
+
worker.execute { runCatching { cleanup() }; worker.shutdown() }
|
|
113
|
+
}
|
|
112
114
|
}
|
|
113
115
|
|
|
114
116
|
private fun emit(id: String, state: String, reason: String) {
|
|
@@ -8,7 +8,7 @@ import android.net.NetworkCapabilities
|
|
|
8
8
|
import android.net.NetworkRequest
|
|
9
9
|
import android.net.wifi.WifiManager
|
|
10
10
|
import android.os.SystemClock
|
|
11
|
-
import com.mentra.
|
|
11
|
+
import com.mentra.bluetoothsdk.hotspot.SoftApTrace
|
|
12
12
|
import java.net.Inet4Address
|
|
13
13
|
import java.util.concurrent.CountDownLatch
|
|
14
14
|
import java.util.concurrent.TimeUnit
|
package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkChangeDetector.kt
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
package com.mentra.glassesmedia.network
|
|
2
2
|
|
|
3
|
+
import com.mentra.bluetoothsdk.hotspot.ScopedSoftApNetwork
|
|
4
|
+
import com.mentra.bluetoothsdk.hotspot.NetworkFacts
|
|
3
5
|
import android.content.Context
|
|
4
6
|
import android.net.ConnectivityManager
|
|
5
|
-
import com.mentra.
|
|
7
|
+
import com.mentra.bluetoothsdk.hotspot.SoftApTrace
|
|
6
8
|
import java.net.Inet4Address
|
|
7
9
|
import org.webrtc.NetworkChangeDetector
|
|
8
10
|
import org.webrtc.NetworkMonitor
|
|
@@ -5,7 +5,7 @@ import android.net.ConnectivityManager
|
|
|
5
5
|
import android.os.Handler
|
|
6
6
|
import android.os.HandlerThread
|
|
7
7
|
import com.mentra.glassesmedia.network.InternetHold
|
|
8
|
-
import com.mentra.
|
|
8
|
+
import com.mentra.bluetoothsdk.hotspot.SoftApTrace
|
|
9
9
|
import com.mentra.glassesmedia.source.I420Planes
|
|
10
10
|
import java.io.IOException
|
|
11
11
|
import java.util.concurrent.CountDownLatch
|
|
@@ -2,7 +2,7 @@ package com.mentra.glassesmedia.source
|
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
4
|
import android.media.AudioAttributes
|
|
5
|
-
import
|
|
5
|
+
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
6
6
|
import com.mentra.glassesmedia.telemetry.PipelineStats
|
|
7
7
|
import com.mentra.glassesmedia.video.I420Packer
|
|
8
8
|
import okhttp3.MediaType.Companion.toMediaType
|
|
@@ -2,12 +2,12 @@ package com.mentra.glassesmedia.source
|
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
4
|
import android.media.AudioAttributes
|
|
5
|
-
import
|
|
6
|
-
import com.mentra.
|
|
5
|
+
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
6
|
+
import com.mentra.bluetoothsdk.hotspot.NetworkFacts
|
|
7
7
|
import com.mentra.glassesmedia.network.ScopedNetworkChangeDetector
|
|
8
|
-
import com.mentra.
|
|
8
|
+
import com.mentra.bluetoothsdk.hotspot.ScopedSoftApNetwork
|
|
9
9
|
import com.mentra.glassesmedia.telemetry.PipelineStats
|
|
10
|
-
import com.mentra.
|
|
10
|
+
import com.mentra.bluetoothsdk.hotspot.SoftApTrace
|
|
11
11
|
import org.webrtc.AudioTrack
|
|
12
12
|
import org.webrtc.DefaultVideoDecoderFactory
|
|
13
13
|
import org.webrtc.DefaultVideoEncoderFactory
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
package com.mentra.glassesmedia.source
|
|
2
2
|
|
|
3
|
-
import com.mentra.
|
|
3
|
+
import com.mentra.bluetoothsdk.hotspot.NetworkFacts
|
|
4
|
+
import com.mentra.bluetoothsdk.hotspot.Ipv4Prefix
|
|
4
5
|
import com.mentra.glassesmedia.network.ScopedNetworkChangeDetector.PublishedEntry
|
|
5
6
|
|
|
6
7
|
/**
|
|
@@ -64,7 +65,7 @@ object SoftApIceDiagnosis {
|
|
|
64
65
|
get() = candidates.filterNot { it.onHotspot }
|
|
65
66
|
|
|
66
67
|
/**
|
|
67
|
-
* Flattened for [SoftApTrace][com.mentra.
|
|
68
|
+
* Flattened for [SoftApTrace][com.mentra.bluetoothsdk.hotspot.SoftApTrace] and the analyzer.
|
|
68
69
|
* Field names are the contract `softap-call-proof.mjs` reads, so they are stable.
|
|
69
70
|
*/
|
|
70
71
|
fun fields(): Array<Pair<String, Any?>> =
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
package com.mentra.glassesmedia.source
|
|
2
2
|
|
|
3
|
-
import
|
|
4
|
-
import com.mentra.
|
|
3
|
+
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
4
|
+
import com.mentra.bluetoothsdk.hotspot.SoftApTrace
|
|
5
5
|
import java.io.BufferedInputStream
|
|
6
6
|
import java.io.BufferedOutputStream
|
|
7
7
|
import java.io.IOException
|
|
@@ -92,7 +92,7 @@ class WhipIngestServer(
|
|
|
92
92
|
* Binds and begins accepting.
|
|
93
93
|
*
|
|
94
94
|
* @param address the phone's own address on the SoftAP, from
|
|
95
|
-
* [com.mentra.
|
|
95
|
+
* [com.mentra.bluetoothsdk.hotspot.ScopedSoftApNetwork.localIpv4]
|
|
96
96
|
* @param port 0 to let the OS choose, which is what production does; the fixed-port form exists
|
|
97
97
|
* for tests
|
|
98
98
|
*/
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.trace
|
|
2
|
+
|
|
3
|
+
import android.util.Log
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Logcat plus the app's JavaScript console, which bug reports upload. glasses-media and
|
|
7
|
+
* acs-meeting import it as `Log`, so the relay, ingest, SoftAP and ACS traces reach a report.
|
|
8
|
+
*/
|
|
9
|
+
object MediaLog {
|
|
10
|
+
/** Set by [com.mentra.glassesmedia.GlassesMediaRelayModule] while it exists. */
|
|
11
|
+
@Volatile
|
|
12
|
+
var sink: ((String) -> Unit)? = null
|
|
13
|
+
|
|
14
|
+
fun i(tag: String, message: String): Int = write(Log.INFO, tag, message, null)
|
|
15
|
+
|
|
16
|
+
fun w(tag: String, message: String, error: Throwable? = null): Int = write(Log.WARN, tag, message, error)
|
|
17
|
+
|
|
18
|
+
fun e(tag: String, message: String, error: Throwable? = null): Int = write(Log.ERROR, tag, message, error)
|
|
19
|
+
|
|
20
|
+
private fun write(priority: Int, tag: String, message: String, error: Throwable?): Int {
|
|
21
|
+
val text = if (error == null) message else "$message\n${Log.getStackTraceString(error)}"
|
|
22
|
+
val result = Log.println(priority, tag, text)
|
|
23
|
+
val level = when (priority) {
|
|
24
|
+
Log.ERROR -> "E"
|
|
25
|
+
Log.WARN -> "W"
|
|
26
|
+
else -> "I"
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
sink?.invoke("[$level/$tag] $text")
|
|
30
|
+
} catch (_: Throwable) {
|
|
31
|
+
// A log line must never break the media path that wrote it.
|
|
32
|
+
}
|
|
33
|
+
return result
|
|
34
|
+
}
|
|
35
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
/** Print glasses-media's and acs-meeting's native logs to the console, which bug reports upload. Idempotent. */
|
|
2
|
+
export function installNativeLogConsole(): void
|
|
3
|
+
|
|
1
4
|
/** Shared native association owner for the local glasses hotspot. */
|
|
2
5
|
export const glassesHotspot: {
|
|
3
6
|
join(
|
|
@@ -8,4 +11,7 @@ export const glassesHotspot: {
|
|
|
8
11
|
purpose?: "outgoing-client" | "incoming-server",
|
|
9
12
|
): Promise<string>
|
|
10
13
|
leave(id: string, waitForInternet?: boolean): Promise<void>
|
|
14
|
+
/** A join with this id has waited a few seconds for Local Network access, which the person may have denied.
|
|
15
|
+
* `systemAnswer` is the connection state and path reason that left it waiting, for logs. */
|
|
16
|
+
onPermissionRequired(listener: (id: string, systemAnswer: string) => void): {remove(): void}
|
|
11
17
|
}
|
package/index.js
CHANGED
|
@@ -3,8 +3,29 @@
|
|
|
3
3
|
// Load only when this transport is requested. Importing the package does not
|
|
4
4
|
// start a native session or require Expo's application entry point.
|
|
5
5
|
const native = () => require("expo-modules-core").requireNativeModule("MentraGlassesMediaRelay")
|
|
6
|
+
|
|
7
|
+
// Native relay, ingest, SoftAP and ACS traces go to the console, which bug reports upload.
|
|
8
|
+
// The module survives Fast Refresh, so a reload replaces the previous subscription.
|
|
9
|
+
const logSubscriptionKey = Symbol.for("mentra.glasses-media.native-log-console")
|
|
10
|
+
const credential =
|
|
11
|
+
/(?<![A-Za-z0-9])(?:token|password|passphrase|secret|authorization|key)(?![A-Za-z0-9])\s*["']?\s*[:=]\s*["']?\S+|(?<![A-Za-z0-9])bearer\s+\S+/i
|
|
12
|
+
// The host calls this at startup: with Metro's inline requires, importing this package
|
|
13
|
+
// does not run its body until something here is used.
|
|
14
|
+
export function installNativeLogConsole() {
|
|
15
|
+
const logSource = require("expo-modules-core").requireOptionalNativeModule("MentraGlassesMediaRelay")
|
|
16
|
+
if (!logSource) return
|
|
17
|
+
logSource[logSubscriptionKey]?.remove()
|
|
18
|
+
logSource[logSubscriptionKey] = logSource.addListener("onNativeLog", ({message}) => {
|
|
19
|
+
console.log("[native:glasses-media]", credential.test(message) ? "[REDACTED]" : message.slice(0, 16_384))
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
6
23
|
export const glassesHotspot = Object.freeze({
|
|
7
24
|
join: (id, ssid, password, gateway, purpose = "outgoing-client") =>
|
|
8
25
|
native().joinLocalHotspot(id, ssid, password, gateway ?? null, purpose),
|
|
9
26
|
leave: (id, waitForInternet = false) => native().leaveLocalHotspot(id, waitForInternet),
|
|
27
|
+
onPermissionRequired: (listener) =>
|
|
28
|
+
native().addListener("onLocalHotspotPermissionRequired", (event) =>
|
|
29
|
+
listener(event.id, event.systemAnswer ?? "unknown"),
|
|
30
|
+
),
|
|
10
31
|
})
|
|
@@ -13,6 +13,10 @@ public struct HotspotJoinFailure {
|
|
|
13
13
|
code = "ERR_HOTSPOT_JOIN"
|
|
14
14
|
// These messages are authored by the owned hotspot implementation, not NSError.
|
|
15
15
|
message = String(local.message.filter { !$0.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) }.prefix(512))
|
|
16
|
+
} else if (error as NSError).domain == "NEHotspotConfigurationErrorDomain", (error as NSError).code == 7 {
|
|
17
|
+
// NEHotspotConfigurationError.userDenied: the person declined the join prompt.
|
|
18
|
+
code = "ERR_HOTSPOT_USER_DENIED"
|
|
19
|
+
message = "The glasses hotspot join was declined"
|
|
16
20
|
} else {
|
|
17
21
|
code = "ERR_HOTSPOT_NATIVE"
|
|
18
22
|
let native = error as NSError
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// When to ask iOS again to join the glasses hotspot.
|
|
4
|
+
///
|
|
5
|
+
/// iOS accepts a hotspot configuration and then makes one short directed scan for it. When that
|
|
6
|
+
/// scan misses the glasses' beacon, iOS shows "Unable to join the network", stays on the current
|
|
7
|
+
/// Wi-Fi and still reports the configuration as applied. Only the phone's current network shows
|
|
8
|
+
/// that the join failed, so a request that has not put the phone on the hotspot after a few
|
|
9
|
+
/// seconds is made again, a bounded number of times, within the join's overall deadline.
|
|
10
|
+
public struct HotspotReapplyPolicy {
|
|
11
|
+
/// Polls of the current network, half a second apart, before a request counts as missed.
|
|
12
|
+
public let pollsBeforeReapply: Int
|
|
13
|
+
/// Requests in one join, the first included.
|
|
14
|
+
public let maxApplies: Int
|
|
15
|
+
|
|
16
|
+
public init(pollsBeforeReapply: Int = 16, maxApplies: Int = 3) {
|
|
17
|
+
self.pollsBeforeReapply = pollsBeforeReapply
|
|
18
|
+
self.maxApplies = maxApplies
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// Whether to request the join again, with the phone not on the hotspot after `pollsSinceApply`
|
|
22
|
+
/// polls of the `applies`-th request.
|
|
23
|
+
public func shouldReapply(applies: Int, pollsSinceApply: Int) -> Bool {
|
|
24
|
+
applies < maxApplies && pollsSinceApply >= pollsBeforeReapply
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -11,8 +11,12 @@ protocol LocalNetworkAccessConnection: AnyObject {
|
|
|
11
11
|
/// Connect to the glasses' existing gallery HTTP endpoint to prove local access (TN3179).
|
|
12
12
|
/// Network.framework retries when access is granted. A denied path can also mean that the
|
|
13
13
|
/// alert is still open, so it must not be treated as a terminal error or given a media timeout.
|
|
14
|
+
/// macOS also reports a denied path for about a second and a half right after the Mac joins the
|
|
15
|
+
/// glasses' hotspot, with access granted, while it re-applies its policies to the new network.
|
|
16
|
+
/// The caller is told only when the path stays denied for `permissionGrace`.
|
|
14
17
|
/// Ordinary connection setup has a 30-second budget, paused while permission is required.
|
|
15
18
|
public final class LocalNetworkAccessRequest {
|
|
19
|
+
static let permissionGrace: TimeInterval = 5
|
|
16
20
|
private let queue: DispatchQueue
|
|
17
21
|
private let connection: LocalNetworkAccessConnection
|
|
18
22
|
private let now: () -> TimeInterval
|
|
@@ -21,7 +25,8 @@ public final class LocalNetworkAccessRequest {
|
|
|
21
25
|
private var timeoutDeadline: TimeInterval?
|
|
22
26
|
private var timeoutWork: DispatchWorkItem?
|
|
23
27
|
private var completion: ((Result<Void, Error>) -> Void)?
|
|
24
|
-
private var waiting: (() -> Void)?
|
|
28
|
+
private var waiting: ((String) -> Void)?
|
|
29
|
+
private var permissionWork: DispatchWorkItem?
|
|
25
30
|
private var finished = false
|
|
26
31
|
private var reportedPermission = false
|
|
27
32
|
|
|
@@ -39,7 +44,10 @@ public final class LocalNetworkAccessRequest {
|
|
|
39
44
|
self.scheduleTimeout = scheduleTimeout ?? { delay, work in queue.asyncAfter(deadline: .now() + delay, execute: work) }
|
|
40
45
|
}
|
|
41
46
|
|
|
42
|
-
|
|
47
|
+
/// `onPermissionRequired` gets the system's answer, for logs, once the path has stayed denied.
|
|
48
|
+
public func start(onPermissionRequired: @escaping (_ systemAnswer: String) -> Void,
|
|
49
|
+
completion: @escaping (Result<Void, Error>) -> Void)
|
|
50
|
+
{
|
|
43
51
|
queue.async {
|
|
44
52
|
guard !self.finished, self.completion == nil else { return }
|
|
45
53
|
self.completion = completion
|
|
@@ -50,13 +58,12 @@ public final class LocalNetworkAccessRequest {
|
|
|
50
58
|
case .ready: self.finish(.success(()))
|
|
51
59
|
case .waiting where reason == .localNetworkDenied:
|
|
52
60
|
self.pauseConnectivityTimeout()
|
|
53
|
-
|
|
54
|
-
self.reportedPermission = true
|
|
55
|
-
self.waiting?()
|
|
56
|
-
}
|
|
61
|
+
self.reportPermissionIfStillDenied(state)
|
|
57
62
|
// Waiting errors are nonfatal; NWConnection retries when its path recovers.
|
|
58
63
|
// A nil path is not proof of denied permission, but must not fail immediately.
|
|
59
|
-
case .setup, .preparing, .waiting:
|
|
64
|
+
case .setup, .preparing, .waiting:
|
|
65
|
+
self.cancelPermissionReport()
|
|
66
|
+
self.resumeConnectivityTimeout()
|
|
60
67
|
case let .failed(error): self.finish(.failure(error))
|
|
61
68
|
case .cancelled: self.finish(.failure(CancellationError()))
|
|
62
69
|
@unknown default: break
|
|
@@ -71,6 +78,24 @@ public final class LocalNetworkAccessRequest {
|
|
|
71
78
|
queue.async { self.finish(.failure(CancellationError())) }
|
|
72
79
|
}
|
|
73
80
|
|
|
81
|
+
private func reportPermissionIfStillDenied(_ state: NWConnection.State) {
|
|
82
|
+
guard !reportedPermission, permissionWork == nil else { return }
|
|
83
|
+
let grace = Self.permissionGrace
|
|
84
|
+
let work = DispatchWorkItem { [weak self] in
|
|
85
|
+
guard let self, !self.finished, self.permissionWork != nil else { return }
|
|
86
|
+
self.permissionWork = nil
|
|
87
|
+
self.reportedPermission = true
|
|
88
|
+
self.waiting?("NWConnection \(state) unsatisfiedReason=localNetworkDenied for \(Int(grace))s")
|
|
89
|
+
}
|
|
90
|
+
permissionWork = work
|
|
91
|
+
scheduleTimeout(grace, work)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private func cancelPermissionReport() {
|
|
95
|
+
permissionWork?.cancel()
|
|
96
|
+
permissionWork = nil
|
|
97
|
+
}
|
|
98
|
+
|
|
74
99
|
private func resumeConnectivityTimeout() {
|
|
75
100
|
guard timeoutDeadline == nil else { return }
|
|
76
101
|
let deadline = now() + remainingConnectivityTime
|
|
@@ -94,6 +119,7 @@ public final class LocalNetworkAccessRequest {
|
|
|
94
119
|
guard !finished else { return }
|
|
95
120
|
finished = true
|
|
96
121
|
pauseConnectivityTimeout()
|
|
122
|
+
cancelPermissionReport()
|
|
97
123
|
connection.onState = nil
|
|
98
124
|
connection.cancel()
|
|
99
125
|
let reply = completion
|