From d69713e980d3a819168356820aae9a3466bb71f8 Mon Sep 17 00:00:00 2001 From: AWADEME Ronaldo Date: Fri, 11 Sep 2026 17:48:05 +0100 Subject: [PATCH] sync: rattrape phpnitro/phpnitro (android/engine) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 4 fichiers .kt resynchronisés (NativeDeviceBridge, NativeRenderPocActivity, PhpServer — préserve lib/backend/var/ à travers les relances, WebSocketService) + dépendance androidx.health.connect manquante pour Engine\Device\Health. --- engine/build.gradle.kts | 7 + .../com/phpnitro/engine/NativeDeviceBridge.kt | 179 ++++++++++++++++++ .../engine/NativeRenderPocActivity.kt | 58 ++++++ .../java/com/phpnitro/engine/PhpServer.kt | 29 +++ .../com/phpnitro/engine/WebSocketService.kt | 18 ++ 5 files changed, 291 insertions(+) diff --git a/engine/build.gradle.kts b/engine/build.gradle.kts index 6c9bc25..cdf6fbf 100644 --- a/engine/build.gradle.kts +++ b/engine/build.gradle.kts @@ -147,4 +147,11 @@ dependencies { // already made for chillerlan/php-qrcode (QR encoding) instead of // hand-rolling Reed-Solomon. api("com.vanniktech:android-image-cropper:4.7.0") + // Engine\Device\Health — Health Connect is Google's current unified + // health/fitness store (Google Fit's own APIs are deprecated), + // itself a separate app most devices don't ship with pre-installed — + // see NativeDeviceBridge.kt's healthStepCount() for the "app not + // installed" / "permission not granted" fallbacks this makes + // genuinely necessary, not hypothetical edge cases. + api("androidx.health.connect:connect-client:1.1.0-alpha07") } diff --git a/engine/src/main/java/com/phpnitro/engine/NativeDeviceBridge.kt b/engine/src/main/java/com/phpnitro/engine/NativeDeviceBridge.kt index ab6ce8c..3001aca 100644 --- a/engine/src/main/java/com/phpnitro/engine/NativeDeviceBridge.kt +++ b/engine/src/main/java/com/phpnitro/engine/NativeDeviceBridge.kt @@ -10,6 +10,7 @@ import android.hardware.camera2.CameraManager import android.media.MediaPlayer import android.media.MediaRecorder import android.net.Uri +import android.net.wifi.WifiManager import android.os.BatteryManager import android.os.Build import android.os.Handler @@ -31,6 +32,9 @@ import androidx.fragment.app.FragmentActivity import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey import com.google.android.gms.location.LocationServices +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import java.io.File /** @@ -92,6 +96,181 @@ class NativeDeviceBridge(private val context: Context) { return if (adapter.isEnabled) "on" else "off" } + /** + * Settings.Global.AIRPLANE_MODE_ON — a plain, publicly readable + * setting, no permission needed. Read-only on both platforms: + * neither Android nor iOS expose a public API to actually TOGGLE + * airplane mode from a third-party app (a real OS restriction, not + * a narrower implementation here). + */ + fun airplaneModeState(): String { + val value = Settings.Global.getInt(context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) + return if (value != 0) "on" else "off" + } + + /** + * "unsupported" | "off" | "on" | "on: " — WifiManager.isWifiEnabled + * needs only ACCESS_WIFI_STATE (a normal permission, always granted). + * The connected network's own SSID additionally needs + * ACCESS_FINE_LOCATION (an Android 27+ privacy restriction unrelated + * to WiFi itself, already declared for Engine\Device\Geofence) — + * same "check, never request" contract every other permission-gated + * read in this file follows: falls back to a bare "on" without it, + * rather than prompting. + */ + fun wifiState(): String { + val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager + ?: return "unsupported" + if (!wifiManager.isWifiEnabled) return "off" + if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) + != PackageManager.PERMISSION_GRANTED + ) { + return "on" + } + @Suppress("DEPRECATION") + val ssid = wifiManager.connectionInfo?.ssid?.trim('"') + return if (ssid.isNullOrEmpty() || ssid == "") "on" else "on: $ssid" + } + + /** + * Best-effort — "isWifiApEnabled"/"getWifiApState" have been hidden + * (`@hide`) SDK methods since day one, never part of the public + * WifiManager API at any Android version; this only works at all + * via reflection, and Android's own hidden-API restrictions + * (enforced since API 28, tightened further each release) can + * silently block that reflective call depending on OEM/version — + * "unsupported" is the honest, expected result on a growing share + * of real devices, not a bug in this wrapper. No public, + * officially-supported way to read personal-hotspot state exists + * on modern Android at all. + */ + fun hotspotState(): String { + return try { + val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager + ?: return "unsupported" + val method = wifiManager.javaClass.getDeclaredMethod("isWifiApEnabled") + method.isAccessible = true + if (method.invoke(wifiManager) as? Boolean == true) "on" else "off" + } catch (e: Exception) { + "unsupported" + } + } + + /** + * WallpaperManager.setBitmap() — SET_WALLPAPER is a normal + * permission (always granted, no runtime prompt). Downloads + * $imageUrl off the main thread (network + bitmap decode, same + * reasoning readSensor()'s own async shape has for anything that + * can't finish synchronously) and reports back through onResult on + * the main thread. + */ + fun setWallpaper(imageUrl: String, onResult: (String) -> Unit) { + val mainHandler = Handler(Looper.getMainLooper()) + Thread { + val result = try { + val bitmap = java.net.URL(imageUrl).openStream().use { android.graphics.BitmapFactory.decodeStream(it) } + if (bitmap == null) { + "Erreur : image invalide" + } else { + android.app.WallpaperManager.getInstance(context).setBitmap(bitmap) + "Fond d'écran modifié" + } + } catch (e: Exception) { + "Erreur : ${e.message}" + } + mainHandler.post { onResult(result) } + }.start() + } + + /** + * Best-effort — Health Connect is Google's current unified health/ + * fitness store, itself a separate app most devices don't ship with + * pre-installed (SDK_UNAVAILABLE in that case, reported as + * "unsupported"). Same "check, never request" contract as + * contactsCount()/upcomingEventsCount() above: a permission not yet + * granted reports "Permission requise" rather than prompting. + * Today's step count via aggregate(), the one metric every Health + * Connect-integrated app/watch reliably contributes. + */ + fun healthStepCount(onResult: (String) -> Unit) { + // connect-client itself declares minSdk 26 — this project's own + // minSdk stays 24 (see AndroidManifest.xml's own + // tools:overrideLibrary comment), so nothing below this guard + // may ever run on API < 26, keeping that override's "may lead + // to runtime failures" warning purely theoretical here. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + onResult("unsupported") + return + } + val mainHandler = Handler(Looper.getMainLooper()) + CoroutineScope(Dispatchers.IO).launch { + val result = try { + val status = androidx.health.connect.client.HealthConnectClient.getSdkStatus(context) + if (status != androidx.health.connect.client.HealthConnectClient.SDK_AVAILABLE) { + "unsupported" + } else { + val client = androidx.health.connect.client.HealthConnectClient.getOrCreate(context) + val permission = androidx.health.connect.client.permission.HealthPermission + .getReadPermission(androidx.health.connect.client.records.StepsRecord::class) + val granted = client.permissionController.getGrantedPermissions() + if (!granted.contains(permission)) { + "Permission requise" + } else { + val now = java.time.Instant.now() + val startOfDay = now.truncatedTo(java.time.temporal.ChronoUnit.DAYS) + val response = client.aggregate( + androidx.health.connect.client.request.AggregateRequest( + metrics = setOf(androidx.health.connect.client.records.StepsRecord.COUNT_TOTAL), + timeRangeFilter = androidx.health.connect.client.time.TimeRangeFilter.between(startOfDay, now), + ), + ) + val steps = response[androidx.health.connect.client.records.StepsRecord.COUNT_TOTAL] ?: 0L + "$steps pas aujourd'hui" + } + } + } catch (e: Exception) { + "unsupported" + } + mainHandler.post { onResult(result) } + } + } + + /** + * Always "unsupported" — Android has no OS-level "Reminders" + * concept at all, unlike iOS's own EventKit reminders (EKReminder, + * a genuinely separate store from Calendar events). The closest + * Android analog (a task list) only exists inside individual third- + * party apps (Google Tasks, etc.), each with its own non-standard + * API a generic device bridge can't target — a real, permanent + * platform gap, not a temporary "not implemented yet". + */ + fun remindersState(): String = "unsupported" + + /** + * Best-effort, almost always "unsupported" on a real device — + * Telephony.Carriers has required carrier privileges (not just a + * runtime permission) to read on Android 10+ for anything beyond + * this app's own APN entries, which a generic demo app has none of. + * Catches both the SecurityException a normal app gets denied with + * and a null/empty cursor the same way, rather than crashing. + */ + fun apnName(): String { + return try { + val cursor = context.contentResolver.query( + android.net.Uri.parse("content://telephony/carriers/preferapn"), + arrayOf("apn"), + null, + null, + null, + ) + cursor?.use { + if (it.moveToFirst()) it.getString(0) ?: "unsupported" else "unsupported" + } ?: "unsupported" + } catch (e: Exception) { + "unsupported" + } + } + /** Same real ConnectivityManager check WebAppInterface.getConnectionType() uses — the native replacement for Engine\Connectivity\ConnectivityBadge's JS-side navigator.onLine. */ fun isOnline(): Boolean { val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager diff --git a/engine/src/main/java/com/phpnitro/engine/NativeRenderPocActivity.kt b/engine/src/main/java/com/phpnitro/engine/NativeRenderPocActivity.kt index 7395fad..925bc23 100644 --- a/engine/src/main/java/com/phpnitro/engine/NativeRenderPocActivity.kt +++ b/engine/src/main/java/com/phpnitro/engine/NativeRenderPocActivity.kt @@ -870,6 +870,41 @@ class NativeRenderPocActivity : AppCompatActivity() { fieldValues[parts.getOrElse(1) { "bt_out" }] = deviceBridge.bluetoothState() refetch(action = null, includeFields = true) } + "airplanemode" -> { + fieldValues[parts.getOrElse(1) { "airplane_out" }] = deviceBridge.airplaneModeState() + refetch(action = null, includeFields = true) + } + "wifi" -> { + fieldValues[parts.getOrElse(1) { "wifi_out" }] = deviceBridge.wifiState() + refetch(action = null, includeFields = true) + } + "hotspot" -> { + fieldValues[parts.getOrElse(1) { "hotspot_out" }] = deviceBridge.hotspotState() + refetch(action = null, includeFields = true) + } + "wallpaper" -> { + val url = java.net.URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8") + val outputField = parts.getOrElse(2) { "wallpaper_out" } + deviceBridge.setWallpaper(url) { result -> + fieldValues[outputField] = result + refetch(action = null, includeFields = true) + } + } + "health" -> { + val outputField = parts.getOrElse(1) { "health_out" } + deviceBridge.healthStepCount { result -> + fieldValues[outputField] = result + refetch(action = null, includeFields = true) + } + } + "reminders" -> { + fieldValues[parts.getOrElse(1) { "reminders_out" }] = deviceBridge.remindersState() + refetch(action = null, includeFields = true) + } + "apn" -> { + fieldValues[parts.getOrElse(1) { "apn_out" }] = deviceBridge.apnName() + refetch(action = null, includeFields = true) + } "securestore" -> { val key = java.net.URLDecoder.decode(parts.getOrElse(1) { "demo_key" }, "UTF-8") val value = java.net.URLDecoder.decode(parts.getOrElse(2) { "" }, "UTF-8") @@ -1120,6 +1155,21 @@ class NativeRenderPocActivity : AppCompatActivity() { } startActivity(Intent(Intent.ACTION_VIEW, geoUri)) } + // Engine\Device\FilesApp — CATEGORY_APP_FILES is the + // documented Android way to jump straight to the system's + // default file manager (distinct from OpenFile above, which + // opens ONE specific file this app wrote, via a Uri + + // FileProvider). Not every OEM ships an app that registers + // for this category, hence the try/catch fallback below — + // same "no crash, just no-op" contract every other + // best-effort capability in this file follows. + "filesapp" -> { + try { + startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_FILES)) + } catch (e: android.content.ActivityNotFoundException) { + // No app on this device registers for CATEGORY_APP_FILES. + } + } // Engine\Device\FileSaver — MediaStore.Downloads needs API 29+ // (the scoped-storage way, no WRITE_EXTERNAL_STORAGE // permission); minSdk here is 24, hence the version gate. @@ -1203,6 +1253,14 @@ class NativeRenderPocActivity : AppCompatActivity() { val message = java.net.URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8") webSocketService?.send(message) } + "wsjoinroom" -> { + val room = java.net.URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8") + webSocketService?.joinRoom(room) + } + "wsleaveroom" -> { + val room = java.net.URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8") + webSocketService?.leaveRoom(room) + } "wsdisconnect" -> { webSocketService?.disconnect() if (webSocketBound) { diff --git a/engine/src/main/java/com/phpnitro/engine/PhpServer.kt b/engine/src/main/java/com/phpnitro/engine/PhpServer.kt index 68d902b..c5575bc 100644 --- a/engine/src/main/java/com/phpnitro/engine/PhpServer.kt +++ b/engine/src/main/java/com/phpnitro/engine/PhpServer.kt @@ -113,11 +113,40 @@ class PhpServer(private val context: Context) { private fun findFreePort(): Int = ServerSocket(0).use { it.localPort } + /** + * Real bug found on a physical iPhone (this method's own iOS + * counterpart, `PhpEmbedRuntime.stageWritableWwwDirectory()`, had the + * identical unconditional wipe): `lib/backend/var/data.sqlite` — + * `Engine\Preferences\Preferences`'s own backing store, meant to + * survive app restarts "like SharedPreferences" per that class's own + * docblock — used to get deleted and recreated empty on every single + * launch, because it lives INSIDE the same `www` tree this method + * wipes wholesale to pick up fresh app code. `var/` (database, + * session files, uploads — everything actually generated at runtime, + * never shipped in `assets/www` itself) is now preserved across the + * wipe: moved aside first, restored after the fresh code copy lands. + * Every other file still refreshes on every launch, same as before — + * only user/app DATA persists, not the code itself. + */ private fun copyAssets(): File { val target = File(context.filesDir, "www") + val varDir = File(target, "lib/backend/var") + val preservedVarDir = File(context.filesDir, "www-var-preserved") + + if (varDir.exists()) { + preservedVarDir.deleteRecursively() + varDir.renameTo(preservedVarDir) + } + target.deleteRecursively() copyAssetDir("www", target) + if (preservedVarDir.exists()) { + varDir.deleteRecursively() + varDir.parentFile?.mkdirs() + preservedVarDir.renameTo(varDir) + } + return target } diff --git a/engine/src/main/java/com/phpnitro/engine/WebSocketService.kt b/engine/src/main/java/com/phpnitro/engine/WebSocketService.kt index f9b0661..e313fc3 100644 --- a/engine/src/main/java/com/phpnitro/engine/WebSocketService.kt +++ b/engine/src/main/java/com/phpnitro/engine/WebSocketService.kt @@ -108,6 +108,24 @@ class WebSocketService : Service() { socket?.send(message) } + /** + * Engine\Device\WebSocket::joinRoomAction()'s own docblock: not a + * WebSocket protocol feature (RFC 6455 has no room concept at all), + * just a small JSON envelope over the already-open connection, + * matching what real backends supporting multi-room broadcast + * already expect (Socket.IO join/leave events, Reverb/Pusher channel + * subscriptions). org.json (not kotlinx.serialization) because + * that's what's already on the classpath everywhere else in this + * file's own package for tiny ad-hoc objects like this. + */ + fun joinRoom(room: String) { + send(org.json.JSONObject().put("type", "join").put("room", room).toString()) + } + + fun leaveRoom(room: String) { + send(org.json.JSONObject().put("type", "leave").put("room", room).toString()) + } + fun disconnect() { socket?.close(1000, "client disconnect") socket = null