mirror of
https://github.com/streamyfin/streamyfin.git
synced 2026-07-15 17:02:58 +01:00
fix: network location settings
Fixed android location settings for wifi network connections as didn't exist Added some better wording to assist Signed-off-by: Lance Chant <13349722+lancechant@users.noreply.github.com>
This commit is contained in:
19
modules/wifi-ssid/android/build.gradle
Normal file
19
modules/wifi-ssid/android/build.gradle
Normal file
@@ -0,0 +1,19 @@
|
||||
apply plugin: 'expo-module-gradle-plugin'
|
||||
|
||||
group = 'expo.modules.wifissid'
|
||||
version = '1.0.0'
|
||||
|
||||
expoModule {
|
||||
canBePublished false
|
||||
}
|
||||
|
||||
android {
|
||||
namespace "expo.modules.wifissid"
|
||||
defaultConfig {
|
||||
versionCode 1
|
||||
versionName "1.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
}
|
||||
9
modules/wifi-ssid/android/src/main/AndroidManifest.xml
Normal file
9
modules/wifi-ssid/android/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,9 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- Reading the connected Wi-Fi SSID requires ACCESS_WIFI_STATE, and (since
|
||||
Android 8) ACCESS_FINE_LOCATION granted at runtime. Location is requested
|
||||
at runtime by the app via expo-location; the manifest declares the
|
||||
Wi-Fi/network permissions this module needs directly. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,109 @@
|
||||
package expo.modules.wifissid
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class WifiSsidModule : Module() {
|
||||
companion object {
|
||||
private const val TAG = "WifiSsid"
|
||||
private const val UNKNOWN_SSID = "<unknown ssid>"
|
||||
}
|
||||
|
||||
private val context
|
||||
get() = requireNotNull(appContext.reactContext)
|
||||
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("WifiSsid")
|
||||
|
||||
AsyncFunction("getSSID") {
|
||||
val (ssid, connectedToWifi) = readWifi()
|
||||
mapOf(
|
||||
"ssid" to ssid,
|
||||
"connectedToWifi" to connectedToWifi,
|
||||
)
|
||||
}
|
||||
|
||||
Function("getSSIDSync") {
|
||||
val (ssid, connectedToWifi) = readWifi()
|
||||
mapOf(
|
||||
"ssid" to ssid,
|
||||
"connectedToWifi" to connectedToWifi,
|
||||
)
|
||||
}
|
||||
|
||||
Function("openLocationSettings") {
|
||||
openLocationSettings()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current Wi-Fi SSID (or null when it can't be read) and whether
|
||||
* the device is connected to a Wi-Fi network. When the device is connected but
|
||||
* the SSID is null, the OS is withholding the network name — on Android this
|
||||
* typically means device Location services are off (the SSID is treated as
|
||||
* location-sensitive).
|
||||
*/
|
||||
private fun readWifi(): Pair<String?, Boolean> {
|
||||
val appContext = context.applicationContext
|
||||
var connectedToWifi = false
|
||||
var ssid: String? = null
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
try {
|
||||
val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
val caps = cm?.let { manager ->
|
||||
manager.activeNetwork?.let { net -> manager.getNetworkCapabilities(net) }
|
||||
}
|
||||
connectedToWifi = caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
|
||||
if (hasFineLocationPermission()) {
|
||||
ssid = (caps?.transportInfo as? WifiInfo)?.ssid?.sanitize()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error reading Wi-Fi via ConnectivityManager", e)
|
||||
}
|
||||
}
|
||||
|
||||
if (ssid == null && hasFineLocationPermission()) {
|
||||
try {
|
||||
val wm = appContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
@Suppress("DEPRECATION")
|
||||
ssid = wm?.connectionInfo?.ssid?.sanitize()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error reading SSID via WifiManager", e)
|
||||
}
|
||||
}
|
||||
|
||||
return Pair(ssid, connectedToWifi)
|
||||
}
|
||||
|
||||
private fun openLocationSettings() {
|
||||
try {
|
||||
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
context.applicationContext.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Unable to open Location settings", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasFineLocationPermission(): Boolean =
|
||||
context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun String.sanitize(): String? {
|
||||
val cleaned = trim('"')
|
||||
return if (cleaned.isBlank() || cleaned == UNKNOWN_SSID) null else cleaned
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
{
|
||||
"name": "wifi-ssid",
|
||||
"version": "1.0.0",
|
||||
"platforms": ["ios"],
|
||||
"platforms": ["ios", "android"],
|
||||
"ios": {
|
||||
"modules": ["WifiSsidModule"]
|
||||
},
|
||||
"android": {
|
||||
"modules": ["expo.modules.wifissid.WifiSsidModule"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +1,92 @@
|
||||
import { Platform, requireNativeModule } from "expo-modules-core";
|
||||
import { Linking } from "react-native";
|
||||
|
||||
// Only load the native module on iOS
|
||||
const WifiSsidModule =
|
||||
Platform.OS === "ios" ? requireNativeModule("WifiSsid") : null;
|
||||
export interface WifiSsidResult {
|
||||
ssid: string | null;
|
||||
/**
|
||||
* Whether the device is connected to a Wi-Fi network. When true but `ssid` is
|
||||
* null, the OS is withholding the network name — on Android this happens when
|
||||
* device Location services are off (the SSID is location-sensitive).
|
||||
*/
|
||||
connectedToWifi: boolean;
|
||||
}
|
||||
|
||||
// Load the native module on iOS and Android (not TV/web). Wrapped so a
|
||||
// missing/unlinked module degrades to null instead of crashing the bundle.
|
||||
const WifiSsidModule = (() => {
|
||||
if (Platform.OS !== "ios" && Platform.OS !== "android") return null;
|
||||
try {
|
||||
return requireNativeModule("WifiSsid");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
/**
|
||||
* Get the current WiFi SSID on iOS.
|
||||
* Returns null on Android or if not connected to WiFi.
|
||||
* Get the current WiFi SSID and whether the device is on a Wi-Fi network.
|
||||
*
|
||||
* Requires:
|
||||
* iOS requirements:
|
||||
* - Location permission granted
|
||||
* - com.apple.developer.networking.wifi-info entitlement
|
||||
* - Access WiFi Information capability enabled in Apple Developer Portal
|
||||
*
|
||||
* Android requirements:
|
||||
* - ACCESS_FINE_LOCATION granted at runtime, and device Location services on
|
||||
*/
|
||||
export async function getSSID(): Promise<string | null> {
|
||||
export async function getSSID(): Promise<WifiSsidResult> {
|
||||
if (!WifiSsidModule) {
|
||||
return null;
|
||||
return { ssid: null, connectedToWifi: false };
|
||||
}
|
||||
|
||||
try {
|
||||
const ssid = await WifiSsidModule.getSSID();
|
||||
return ssid ?? null;
|
||||
return normalize(await WifiSsidModule.getSSID());
|
||||
} catch (error) {
|
||||
console.error("[WifiSsid] Error getting SSID:", error);
|
||||
return null;
|
||||
return { ssid: null, connectedToWifi: false };
|
||||
}
|
||||
}
|
||||
|
||||
/** Synchronous version (uses the older CNCopyCurrentNetworkInfo API on iOS). */
|
||||
export function getSSIDSync(): WifiSsidResult {
|
||||
if (!WifiSsidModule) {
|
||||
return { ssid: null, connectedToWifi: false };
|
||||
}
|
||||
try {
|
||||
return normalize(WifiSsidModule.getSSIDSync());
|
||||
} catch (error) {
|
||||
console.error("[WifiSsid] Error getting SSID (sync):", error);
|
||||
return { ssid: null, connectedToWifi: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous version - uses older CNCopyCurrentNetworkInfo API
|
||||
* Open the system Location settings so the user can enable Location services
|
||||
* (required on Android for the OS to reveal the Wi-Fi SSID). Falls back to the
|
||||
* app's settings page where there is no dedicated native action (e.g. iOS).
|
||||
*/
|
||||
export function getSSIDSync(): string | null {
|
||||
if (!WifiSsidModule) {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function openLocationSettings(): void {
|
||||
try {
|
||||
return WifiSsidModule.getSSIDSync() ?? null;
|
||||
if (WifiSsidModule?.openLocationSettings) {
|
||||
WifiSsidModule.openLocationSettings();
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[WifiSsid] Error getting SSID (sync):", error);
|
||||
return null;
|
||||
console.error("[WifiSsid] Error opening location settings:", error);
|
||||
}
|
||||
Linking.openSettings();
|
||||
}
|
||||
|
||||
// Both native modules return { ssid, connectedToWifi }. The string branch is a
|
||||
// defensive fallback in case a build returns the older plain-string shape.
|
||||
function normalize(result: unknown): WifiSsidResult {
|
||||
if (typeof result === "string") {
|
||||
const ssid = result || null;
|
||||
return { ssid, connectedToWifi: ssid !== null };
|
||||
}
|
||||
if (result && typeof result === "object") {
|
||||
const obj = result as { ssid?: string | null; connectedToWifi?: boolean };
|
||||
return {
|
||||
ssid: obj.ssid ?? null,
|
||||
connectedToWifi: Boolean(obj.connectedToWifi),
|
||||
};
|
||||
}
|
||||
return { ssid: null, connectedToWifi: false };
|
||||
}
|
||||
|
||||
@@ -1,50 +1,109 @@
|
||||
import ExpoModulesCore
|
||||
#if !os(tvOS)
|
||||
import Network
|
||||
import NetworkExtension
|
||||
import SystemConfiguration.CaptiveNetwork
|
||||
#endif
|
||||
import UIKit
|
||||
|
||||
public class WifiSsidModule: Module {
|
||||
#if !os(tvOS)
|
||||
// NWPathMonitor reports whether the active path uses Wi-Fi WITHOUT requiring
|
||||
// the wifi-info entitlement, so we can tell "on Wi-Fi but can't read the SSID"
|
||||
// apart from "not connected to Wi-Fi" even when fetchCurrent returns nil.
|
||||
private let pathMonitor = NWPathMonitor()
|
||||
private let monitorQueue = DispatchQueue(label: "expo.modules.wifissid.pathmonitor")
|
||||
private let lock = NSLock()
|
||||
private var cachedOnWifi = false
|
||||
private var pathMonitorStarted = false
|
||||
|
||||
private var isOnWifi: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return cachedOnWifi
|
||||
}
|
||||
|
||||
private func startPathMonitorIfNeeded() {
|
||||
lock.lock()
|
||||
if pathMonitorStarted {
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
pathMonitorStarted = true
|
||||
lock.unlock()
|
||||
|
||||
pathMonitor.pathUpdateHandler = { [weak self] path in
|
||||
guard let self else { return }
|
||||
let onWifi = path.status == .satisfied && path.usesInterfaceType(.wifi)
|
||||
self.lock.lock()
|
||||
self.cachedOnWifi = onWifi
|
||||
self.lock.unlock()
|
||||
}
|
||||
pathMonitor.start(queue: monitorQueue)
|
||||
}
|
||||
#endif
|
||||
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("WifiSsid")
|
||||
|
||||
// Get current WiFi SSID using NEHotspotNetwork (iOS 14+)
|
||||
// Not available on tvOS
|
||||
AsyncFunction("getSSID") { () -> String? in
|
||||
AsyncFunction("getSSID") { () -> [String: Any] in
|
||||
#if os(tvOS)
|
||||
return nil
|
||||
return ["ssid": NSNull(), "connectedToWifi": false]
|
||||
#else
|
||||
return await withCheckedContinuation { continuation in
|
||||
NEHotspotNetwork.fetchCurrent { network in
|
||||
if let ssid = network?.ssid {
|
||||
print("[WifiSsid] Got SSID via NEHotspotNetwork: \(ssid)")
|
||||
continuation.resume(returning: ssid)
|
||||
} else {
|
||||
// Fallback to CNCopyCurrentNetworkInfo for older iOS
|
||||
print("[WifiSsid] NEHotspotNetwork returned nil, trying CNCopyCurrentNetworkInfo")
|
||||
let ssid = self.getSSIDViaCNCopy()
|
||||
continuation.resume(returning: ssid)
|
||||
}
|
||||
}
|
||||
self.startPathMonitorIfNeeded()
|
||||
let ssid = await self.resolveSSID()
|
||||
var result: [String: Any] = ["connectedToWifi": self.isOnWifi]
|
||||
if let ssid = ssid {
|
||||
result["ssid"] = ssid
|
||||
} else {
|
||||
result["ssid"] = NSNull()
|
||||
}
|
||||
return result
|
||||
#endif
|
||||
}
|
||||
|
||||
// Synchronous version using only CNCopyCurrentNetworkInfo
|
||||
// Not available on tvOS
|
||||
Function("getSSIDSync") { () -> String? in
|
||||
Function("getSSIDSync") { () -> [String: Any] in
|
||||
#if os(tvOS)
|
||||
return nil
|
||||
return ["ssid": NSNull(), "connectedToWifi": false]
|
||||
#else
|
||||
return self.getSSIDViaCNCopy()
|
||||
self.startPathMonitorIfNeeded()
|
||||
let ssid = self.getSSIDViaCNCopy()
|
||||
var result: [String: Any] = ["connectedToWifi": self.isOnWifi]
|
||||
if let ssid = ssid {
|
||||
result["ssid"] = ssid
|
||||
} else {
|
||||
result["ssid"] = NSNull()
|
||||
}
|
||||
return result
|
||||
#endif
|
||||
}
|
||||
|
||||
Function("openLocationSettings") {
|
||||
#if !os(tvOS)
|
||||
DispatchQueue.main.async {
|
||||
if let url = URL(string: UIApplication.openSettingsURLString) {
|
||||
UIApplication.shared.open(url)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(tvOS)
|
||||
private func resolveSSID() async -> String? {
|
||||
await withCheckedContinuation { continuation in
|
||||
NEHotspotNetwork.fetchCurrent { network in
|
||||
if let ssid = network?.ssid {
|
||||
continuation.resume(returning: ssid)
|
||||
} else {
|
||||
continuation.resume(returning: self.getSSIDViaCNCopy())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func getSSIDViaCNCopy() -> String? {
|
||||
guard let interfaces = CNCopySupportedInterfaces() as? [String] else {
|
||||
print("[WifiSsid] CNCopySupportedInterfaces returned nil")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -54,12 +113,10 @@ public class WifiSsidModule: Module {
|
||||
}
|
||||
|
||||
if let ssid = networkInfo[kCNNetworkInfoKeySSID as String] as? String {
|
||||
print("[WifiSsid] Got SSID via CNCopyCurrentNetworkInfo: \(ssid)")
|
||||
return ssid
|
||||
}
|
||||
}
|
||||
|
||||
print("[WifiSsid] No SSID found via CNCopyCurrentNetworkInfo")
|
||||
return nil
|
||||
}
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user