π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add Photos platform health bridge
Neeraj Gupta9ca72c6566bd
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle b/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradlenew file mode 100644index 0000000000..d908db8522--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle@@ -0,0 +1,47 @@+group 'io.ente.photos.platform'+version '1.0'++buildscript {+ ext.kotlin_version = '2.1.10'+ repositories {+ google()+ mavenCentral()+ }++ dependencies {+ classpath 'com.android.tools.build:gradle:8.10.1'+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"+ }+}++rootProject.allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++apply plugin: 'com.android.library'+apply plugin: 'kotlin-android'++android {+ namespace 'io.ente.photos.platform'+ compileSdk 36++ compileOptions {+ sourceCompatibility JavaVersion.VERSION_1_8+ targetCompatibility JavaVersion.VERSION_1_8+ }++ kotlinOptions {+ jvmTarget = '1.8'+ }++ sourceSets {+ main.java.srcDirs += 'src/main/kotlin'+ }++ defaultConfig {+ minSdkVersion 23+ }+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a2f47b6057--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml@@ -0,0 +1,2 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+</manifest>diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/EntePhotosPlatformPlugin.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/EntePhotosPlatformPlugin.ktnew file mode 100644index 0000000000..e3802a2a3e--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/EntePhotosPlatformPlugin.kt@@ -0,0 +1,273 @@+package io.ente.photos.platform++import android.app.ActivityManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.os.BatteryManager+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.os.PowerManager+import io.flutter.embedding.engine.plugins.FlutterPlugin+import io.flutter.plugin.common.EventChannel+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel++class EntePhotosPlatformPlugin :+ FlutterPlugin,+ MethodChannel.MethodCallHandler,+ EventChannel.StreamHandler {+ private lateinit var context: Context+ private lateinit var methodChannel: MethodChannel+ private lateinit var eventChannel: EventChannel+ private val mainHandler = Handler(Looper.getMainLooper())+ private var eventSink: EventChannel.EventSink? = null+ private var batteryReceiverRegistered = false+ private var thermalListenerRegistered = false+ private var snapshotPending = false+ private var lastEmittedState: Map<String, Any?>? = null++ private val batteryReceiver =+ object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ emitSnapshot()+ }+ }++ private val thermalListener =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ PowerManager.OnThermalStatusChangedListener { emitSnapshot() }+ } else {+ null+ }++ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ context = binding.applicationContext+ methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)+ eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)+ methodChannel.setMethodCallHandler(this)+ eventChannel.setStreamHandler(this)+ }++ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "deviceHealth.getSnapshot" -> result.success(snapshot())+ "deviceHealth.getMemorySnapshot" -> result.success(memorySnapshot())+ else -> result.notImplemented()+ }+ }++ override fun onListen(arguments: Any?, events: EventChannel.EventSink) {+ stopObserving()+ eventSink = events+ lastEmittedState = null+ startObserving()+ emitSnapshot()+ }++ override fun onCancel(arguments: Any?) {+ eventSink = null+ lastEmittedState = null+ stopObserving()+ }++ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {+ eventSink = null+ stopObserving()+ methodChannel.setMethodCallHandler(null)+ eventChannel.setStreamHandler(null)+ }++ private fun startObserving() {+ try {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ context.registerReceiver(+ batteryReceiver,+ IntentFilter(Intent.ACTION_BATTERY_CHANGED),+ Context.RECEIVER_NOT_EXPORTED,+ )+ } else {+ @Suppress("DEPRECATION")+ context.registerReceiver(+ batteryReceiver,+ IntentFilter(Intent.ACTION_BATTERY_CHANGED),+ )+ }+ batteryReceiverRegistered = true+ } catch (_: RuntimeException) {+ batteryReceiverRegistered = false+ }++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ try {+ val powerManager = context.getSystemService(PowerManager::class.java)+ val listener = thermalListener ?: return+ powerManager.addThermalStatusListener(context.mainExecutor, listener)+ thermalListenerRegistered = true+ } catch (_: RuntimeException) {+ thermalListenerRegistered = false+ }+ }+ }++ private fun stopObserving() {+ if (batteryReceiverRegistered) {+ try {+ context.unregisterReceiver(batteryReceiver)+ } catch (_: IllegalArgumentException) {+ // Already unregistered by the platform.+ }+ batteryReceiverRegistered = false+ }++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && thermalListenerRegistered) {+ try {+ val listener = thermalListener+ if (listener != null) {+ context.getSystemService(PowerManager::class.java)+ .removeThermalStatusListener(listener)+ }+ } catch (_: RuntimeException) {+ // Engine teardown has no remaining consumer for this listener.+ }+ thermalListenerRegistered = false+ }+ }++ private fun emitSnapshot() {+ if (eventSink == null || snapshotPending) return+ snapshotPending = true+ mainHandler.post {+ snapshotPending = false+ val sink = eventSink ?: return@post+ val snapshot = snapshot()+ val state = mapOf(+ "battery" to snapshot["battery"],+ "thermal" to snapshot["thermal"],+ )+ if (state != lastEmittedState) {+ lastEmittedState = state+ sink.success(snapshot)+ }+ }+ }++ private fun snapshot(): Map<String, Any?> =+ mapOf(+ "platform" to "android",+ "observedAtMs" to System.currentTimeMillis(),+ "battery" to batterySnapshot(),+ "thermal" to thermalSnapshot(),+ )++ private fun batterySnapshot(): Map<String, Any?> {+ return try {+ val intent = stickyBatteryIntent()+ ?: return unavailable("battery_intent_missing")+ if (!intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true)) {+ return unavailable("battery_not_present")+ }+ val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)+ val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)+ if (level < 0 || scale <= 0 || level > scale) {+ return unavailable("battery_level_missing")+ }+ val levelPercent = ((level.toDouble() / scale) * 100).toInt()+ val temperature = intent.getIntExtra(+ BatteryManager.EXTRA_TEMPERATURE,+ Int.MIN_VALUE,+ )+ val values =+ mutableMapOf<String, Any?>(+ "status" to "available",+ "levelPercent" to levelPercent,+ "health" to batteryHealth(+ intent.getIntExtra(+ BatteryManager.EXTRA_HEALTH,+ BatteryManager.BATTERY_HEALTH_UNKNOWN,+ ),+ ),+ )+ if (temperature != Int.MIN_VALUE) {+ values["temperatureCelsius"] = temperature / 10.0+ }+ values+ } catch (_: SecurityException) {+ unavailable("battery_access_denied")+ } catch (_: RuntimeException) {+ unavailable("battery_read_failed")+ }+ }++ private fun stickyBatteryIntent(): Intent? {+ val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ context.registerReceiver(null, filter, Context.RECEIVER_NOT_EXPORTED)+ } else {+ @Suppress("DEPRECATION")+ context.registerReceiver(null, filter)+ }+ }++ private fun thermalSnapshot(): Map<String, Any?> {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {+ return mapOf("status" to "unsupported")+ }+ return try {+ val status = context.getSystemService(PowerManager::class.java).currentThermalStatus+ val state = thermalState(status)+ ?: return unavailable("thermal_status_unknown")+ mapOf("status" to "available", "state" to state)+ } catch (_: RuntimeException) {+ unavailable("thermal_read_failed")+ }+ }++ private fun memorySnapshot(): Map<String, Any?> {+ return try {+ val info = ActivityManager.MemoryInfo()+ context.getSystemService(ActivityManager::class.java).getMemoryInfo(info)+ if (info.totalMem <= 0) {+ unavailable("memory_total_missing")+ } else {+ mapOf("status" to "available", "totalBytes" to info.totalMem)+ }+ } catch (_: RuntimeException) {+ unavailable("memory_read_failed")+ }+ }++ private fun unavailable(errorCode: String): Map<String, Any?> =+ mapOf("status" to "unavailable", "errorCode" to errorCode)++ private fun batteryHealth(value: Int): String =+ when (value) {+ BatteryManager.BATTERY_HEALTH_GOOD -> "good"+ BatteryManager.BATTERY_HEALTH_COLD -> "cold"+ BatteryManager.BATTERY_HEALTH_OVERHEAT -> "overheating"+ BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE -> "overVoltage"+ BatteryManager.BATTERY_HEALTH_DEAD -> "dead"+ BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE -> "failure"+ else -> "unknown"+ }++ private fun thermalState(value: Int): String? =+ when (value) {+ PowerManager.THERMAL_STATUS_NONE -> "nominal"+ PowerManager.THERMAL_STATUS_LIGHT -> "light"+ PowerManager.THERMAL_STATUS_MODERATE -> "moderate"+ PowerManager.THERMAL_STATUS_SEVERE -> "serious"+ PowerManager.THERMAL_STATUS_CRITICAL -> "critical"+ PowerManager.THERMAL_STATUS_EMERGENCY -> "emergency"+ PowerManager.THERMAL_STATUS_SHUTDOWN -> "shutdown"+ else -> null+ }++ private companion object {+ private const val METHOD_CHANNEL = "io.ente.photos.platform"+ private const val EVENT_CHANNEL =+ "io.ente.photos.platform/device_health_events"+ }+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/EntePhotosPlatformPlugin.swift b/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/EntePhotosPlatformPlugin.swiftnew file mode 100644index 0000000000..c7868a1ac9--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/EntePhotosPlatformPlugin.swift@@ -0,0 +1,178 @@+import Flutter+import Foundation+import UIKit++public final class EntePhotosPlatformPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {+ private let methodChannel: FlutterMethodChannel+ private let eventChannel: FlutterEventChannel+ private var eventSink: FlutterEventSink?+ private var observerTokens: [NSObjectProtocol] = []+ private var enabledBatteryMonitoring = false++ private init(registrar: FlutterPluginRegistrar) {+ methodChannel = FlutterMethodChannel(+ name: "io.ente.photos.platform",+ binaryMessenger: registrar.messenger()+ )+ eventChannel = FlutterEventChannel(+ name: "io.ente.photos.platform/device_health_events",+ binaryMessenger: registrar.messenger()+ )+ super.init()+ }++ public static func register(with registrar: FlutterPluginRegistrar) {+ let instance = EntePhotosPlatformPlugin(registrar: registrar)+ registrar.addMethodCallDelegate(instance, channel: instance.methodChannel)+ instance.eventChannel.setStreamHandler(instance)+ registrar.publish(instance)+ }++ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {+ switch call.method {+ case "deviceHealth.getSnapshot":+ result(snapshotWithBatteryMonitoring())+ case "deviceHealth.getMemorySnapshot":+ result(memorySnapshot())+ default:+ result(FlutterMethodNotImplemented)+ }+ }++ public func onListen(+ withArguments arguments: Any?,+ eventSink events: @escaping FlutterEventSink+ ) -> FlutterError? {+ stopObserving()+ eventSink = events+ startObserving()+ emitSnapshot()+ return nil+ }++ public func onCancel(withArguments arguments: Any?) -> FlutterError? {+ eventSink = nil+ stopObserving()+ return nil+ }++ public func detachFromEngine(for registrar: FlutterPluginRegistrar) {+ eventSink = nil+ stopObserving()+ methodChannel.setMethodCallHandler(nil)+ eventChannel.setStreamHandler(nil)+ }++ private func startObserving() {+ let device = UIDevice.current+ if !device.isBatteryMonitoringEnabled {+ device.isBatteryMonitoringEnabled = true+ enabledBatteryMonitoring = true+ }++ let center = NotificationCenter.default+ observerTokens = [+ center.addObserver(+ forName: UIDevice.batteryLevelDidChangeNotification,+ object: device,+ queue: .main+ ) { [weak self] _ in self?.emitSnapshot() },+ center.addObserver(+ forName: UIDevice.batteryStateDidChangeNotification,+ object: device,+ queue: .main+ ) { [weak self] _ in self?.emitSnapshot() },+ center.addObserver(+ forName: ProcessInfo.thermalStateDidChangeNotification,+ object: ProcessInfo.processInfo,+ queue: .main+ ) { [weak self] _ in self?.emitSnapshot() },+ ]+ }++ private func stopObserving() {+ for token in observerTokens {+ NotificationCenter.default.removeObserver(token)+ }+ observerTokens.removeAll()+ if enabledBatteryMonitoring {+ UIDevice.current.isBatteryMonitoringEnabled = false+ enabledBatteryMonitoring = false+ }+ }++ private func emitSnapshot() {+ guard let sink = eventSink else { return }+ if Thread.isMainThread {+ sink(snapshot())+ } else {+ DispatchQueue.main.async { [weak self] in+ guard let self, let sink = self.eventSink else { return }+ sink(self.snapshot())+ }+ }+ }++ private func snapshotWithBatteryMonitoring() -> [String: Any] {+ let device = UIDevice.current+ let restoreMonitoring = !device.isBatteryMonitoringEnabled+ if restoreMonitoring {+ device.isBatteryMonitoringEnabled = true+ }+ defer {+ if restoreMonitoring {+ device.isBatteryMonitoringEnabled = false+ }+ }+ return snapshot()+ }++ private func snapshot() -> [String: Any] {+ [+ "platform": "ios",+ "observedAtMs": Int64(Date().timeIntervalSince1970 * 1000),+ "battery": batterySnapshot(),+ "thermal": thermalSnapshot(),+ ]+ }++ private func batterySnapshot() -> [String: Any] {+ let level = UIDevice.current.batteryLevel+ guard level >= 0, level <= 1 else {+ return unavailable("battery_level_unavailable")+ }+ return [+ "status": "available",+ "levelPercent": Int(level * 100),+ ]+ }++ private func thermalSnapshot() -> [String: Any] {+ let state: String+ switch ProcessInfo.processInfo.thermalState {+ case .nominal:+ state = "nominal"+ case .fair:+ state = "moderate"+ case .serious:+ state = "serious"+ case .critical:+ state = "critical"+ @unknown default:+ return unavailable("thermal_status_unknown")+ }+ return ["status": "available", "state": state]+ }++ private func memorySnapshot() -> [String: Any] {+ let totalBytes = ProcessInfo.processInfo.physicalMemory+ guard totalBytes > 0 else {+ return unavailable("memory_total_missing")+ }+ return ["status": "available", "totalBytes": Int64(totalBytes)]+ }++ private func unavailable(_ errorCode: String) -> [String: Any] {+ ["status": "unavailable", "errorCode": errorCode]+ }+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/ios/ente_photos_platform.podspec b/mobile/apps/photos/plugins/ente_photos_platform/ios/ente_photos_platform.podspecnew file mode 100644index 0000000000..85f43936bd--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/ente_photos_platform.podspec@@ -0,0 +1,14 @@+Pod::Spec.new do |s|+ s.name = 'ente_photos_platform'+ s.version = '0.0.1'+ s.summary = 'App-scoped native platform capabilities for Ente Photos.'+ s.homepage = 'https://ente.com'+ s.license = { :type => 'AGPL-3.0-only' }+ s.author = { 'Ente' => '[email protected]' }+ s.source = { :path => '.' }+ s.source_files = 'Classes/**/*'+ s.dependency 'Flutter'+ s.platform = :ios, '15.1'+ s.swift_version = '5.0'+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }+enddiff --git a/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart b/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dartnew file mode 100644index 0000000000..bbd6ccff1b--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart@@ -0,0 +1 @@+export 'src/device_health.dart';diff --git a/mobile/apps/photos/plugins/ente_photos_platform/lib/src/device_health.dart b/mobile/apps/photos/plugins/ente_photos_platform/lib/src/device_health.dartnew file mode 100644index 0000000000..fe5068381a--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/src/device_health.dart@@ -0,0 +1,316 @@+import 'dart:async';++import 'package:flutter/services.dart';++enum DeviceHealthPlatform { android, ios }++enum DeviceSignalStatus { available, unsupported, unavailable }++enum DeviceBatteryHealth {+ good,+ cold,+ overheating,+ overVoltage,+ dead,+ failure,+ unknown,+}++enum DeviceThermalState {+ nominal,+ light,+ moderate,+ serious,+ critical,+ emergency,+ shutdown,+}++class DeviceBatterySnapshot {+ const DeviceBatterySnapshot({+ required this.status,+ this.levelPercent,+ this.temperatureCelsius,+ this.health,+ this.errorCode,+ });++ factory DeviceBatterySnapshot.fromMap(Map<dynamic, dynamic> map) {+ final status = _enumValue(+ DeviceSignalStatus.values,+ map['status'],+ 'battery.status',+ );+ final level = _optionalInt(map['levelPercent'], 'battery.levelPercent');+ final temperature = _optionalDouble(+ map['temperatureCelsius'],+ 'battery.temperatureCelsius',+ );+ final health = map['health'] == null+ ? null+ : _enumValue(+ DeviceBatteryHealth.values,+ map['health'],+ 'battery.health',+ );+ final errorCode = _optionalString(map['errorCode'], 'battery.errorCode');+ _validateErrorCode(status, errorCode, 'battery');++ if (status == DeviceSignalStatus.available) {+ if (level == null || level < 0 || level > 100) {+ throw const FormatException(+ 'Available battery signal requires a level from 0 to 100',+ );+ }+ if (temperature != null && !temperature.isFinite) {+ throw const FormatException('Battery temperature must be finite');+ }+ } else if (level != null || temperature != null || health != null) {+ throw const FormatException(+ 'Unavailable battery signal contains observed values',+ );+ }++ return DeviceBatterySnapshot(+ status: status,+ levelPercent: level,+ temperatureCelsius: temperature,+ health: health,+ errorCode: errorCode,+ );+ }++ final DeviceSignalStatus status;+ final int? levelPercent;+ final double? temperatureCelsius;+ final DeviceBatteryHealth? health;+ final String? errorCode;+}++class DeviceThermalSnapshot {+ const DeviceThermalSnapshot({+ required this.status,+ this.state,+ this.errorCode,+ });++ factory DeviceThermalSnapshot.fromMap(Map<dynamic, dynamic> map) {+ final status = _enumValue(+ DeviceSignalStatus.values,+ map['status'],+ 'thermal.status',+ );+ final state = map['state'] == null+ ? null+ : _enumValue(DeviceThermalState.values, map['state'], 'thermal.state');+ final errorCode = _optionalString(map['errorCode'], 'thermal.errorCode');+ _validateErrorCode(status, errorCode, 'thermal');+ if ((status == DeviceSignalStatus.available) != (state != null)) {+ throw const FormatException(+ 'Thermal state must exist only when the signal is available',+ );+ }+ return DeviceThermalSnapshot(+ status: status,+ state: state,+ errorCode: errorCode,+ );+ }++ final DeviceSignalStatus status;+ final DeviceThermalState? state;+ final String? errorCode;+}++class DeviceMemorySnapshot {+ const DeviceMemorySnapshot({+ required this.status,+ this.totalBytes,+ this.errorCode,+ });++ factory DeviceMemorySnapshot.fromMap(Map<dynamic, dynamic> map) {+ final status = _enumValue(+ DeviceSignalStatus.values,+ map['status'],+ 'memory.status',+ );+ final totalBytes = _optionalInt(map['totalBytes'], 'memory.totalBytes');+ final errorCode = _optionalString(map['errorCode'], 'memory.errorCode');+ _validateErrorCode(status, errorCode, 'memory');+ if (status == DeviceSignalStatus.available) {+ if (totalBytes == null || totalBytes <= 0) {+ throw const FormatException(+ 'Available memory signal requires positive total bytes',+ );+ }+ } else if (totalBytes != null) {+ throw const FormatException(+ 'Unavailable memory signal contains observed values',+ );+ }+ return DeviceMemorySnapshot(+ status: status,+ totalBytes: totalBytes,+ errorCode: errorCode,+ );+ }++ final DeviceSignalStatus status;+ final int? totalBytes;+ final String? errorCode;+}++class DeviceHealthSnapshot {+ const DeviceHealthSnapshot({+ required this.platform,+ required this.observedAt,+ required this.battery,+ required this.thermal,+ });++ factory DeviceHealthSnapshot.fromMap(Map<dynamic, dynamic> map) {+ final observedAtMs = _requiredInt(map['observedAtMs'], 'observedAtMs');+ if (observedAtMs <= 0) {+ throw const FormatException('Observation time must be positive');+ }+ return DeviceHealthSnapshot(+ platform: _enumValue(+ DeviceHealthPlatform.values,+ map['platform'],+ 'platform',+ ),+ observedAt: DateTime.fromMillisecondsSinceEpoch(observedAtMs),+ battery: DeviceBatterySnapshot.fromMap(+ _requiredMap(map['battery'], 'battery'),+ ),+ thermal: DeviceThermalSnapshot.fromMap(+ _requiredMap(map['thermal'], 'thermal'),+ ),+ );+ }++ final DeviceHealthPlatform platform;+ final DateTime observedAt;+ final DeviceBatterySnapshot battery;+ final DeviceThermalSnapshot thermal;++ bool isFreshAt(DateTime now, Duration maximumAge) {+ if (maximumAge.isNegative) {+ throw ArgumentError.value(maximumAge, 'maximumAge', 'is negative');+ }+ final age = now.difference(observedAt);+ return !age.isNegative && age <= maximumAge;+ }+}++abstract interface class DeviceHealthSource {+ Future<DeviceHealthSnapshot> getSnapshot();++ Stream<DeviceHealthSnapshot> get updates;+}++abstract interface class DeviceMemorySource {+ Future<DeviceMemorySnapshot> getMemorySnapshot();+}++class EntePhotosDeviceHealth implements DeviceHealthSource, DeviceMemorySource {+ EntePhotosDeviceHealth({+ MethodChannel? methodChannel,+ EventChannel? eventChannel,+ }) : _methodChannel =+ methodChannel ?? const MethodChannel(_methodChannelName),+ _eventChannel = eventChannel ?? const EventChannel(_eventChannelName);++ static final instance = EntePhotosDeviceHealth();+ static const _methodChannelName = 'io.ente.photos.platform';+ static const _eventChannelName =+ 'io.ente.photos.platform/device_health_events';++ final MethodChannel _methodChannel;+ final EventChannel _eventChannel;+ Stream<DeviceHealthSnapshot>? _updates;++ @override+ Future<DeviceHealthSnapshot> getSnapshot() async {+ final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>(+ 'deviceHealth.getSnapshot',+ );+ if (result == null) {+ throw const FormatException('Device health returned no snapshot');+ }+ return DeviceHealthSnapshot.fromMap(result);+ }++ @override+ Future<DeviceMemorySnapshot> getMemorySnapshot() async {+ final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>(+ 'deviceHealth.getMemorySnapshot',+ );+ if (result == null) {+ throw const FormatException('Device memory returned no snapshot');+ }+ return DeviceMemorySnapshot.fromMap(result);+ }++ @override+ Stream<DeviceHealthSnapshot> get updates =>+ _updates ??= _eventChannel.receiveBroadcastStream().map((event) {+ if (event is! Map<dynamic, dynamic>) {+ throw const FormatException('Device health event is not a map');+ }+ return DeviceHealthSnapshot.fromMap(event);+ }).asBroadcastStream();+}++Map<dynamic, dynamic> _requiredMap(Object? value, String name) {+ if (value is! Map<dynamic, dynamic>) {+ throw FormatException('$name must be a map');+ }+ return value;+}++int _requiredInt(Object? value, String name) {+ if (value is! int) throw FormatException('$name must be an integer');+ return value;+}++int? _optionalInt(Object? value, String name) {+ if (value == null) return null;+ return _requiredInt(value, name);+}++double? _optionalDouble(Object? value, String name) {+ if (value == null) return null;+ if (value is! num) throw FormatException('$name must be numeric');+ return value.toDouble();+}++String? _optionalString(Object? value, String name) {+ if (value == null) return null;+ if (value is! String || value.isEmpty) {+ throw FormatException('$name must be a non-empty string');+ }+ return value;+}++void _validateErrorCode(+ DeviceSignalStatus status,+ String? errorCode,+ String signal,+) {+ if (status == DeviceSignalStatus.unavailable && errorCode == null) {+ throw FormatException('$signal unavailable without an error code');+ }+ if (status != DeviceSignalStatus.unavailable && errorCode != null) {+ throw FormatException('$signal error code without an unavailable status');+ }+}++T _enumValue<T extends Enum>(List<T> values, Object? value, String name) {+ if (value is! String) throw FormatException('$name must be a string');+ for (final candidate in values) {+ if (candidate.name == value) return candidate;+ }+ throw FormatException('$name has unsupported value: $value');+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/pubspec.yaml b/mobile/apps/photos/plugins/ente_photos_platform/pubspec.yamlnew file mode 100644index 0000000000..df0ce967fc--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/pubspec.yaml@@ -0,0 +1,25 @@+name: ente_photos_platform+description: App-scoped native platform capabilities for Ente Photos++resolution: workspace+environment:+ sdk: ">=3.10.0 <4.0.0"+ flutter: ">=3.38.0"++dependencies:+ flutter:+ sdk: flutter++dev_dependencies:+ flutter_lints: 6.0.0+ flutter_test:+ sdk: flutter++flutter:+ plugin:+ platforms:+ android:+ package: io.ente.photos.platform+ pluginClass: EntePhotosPlatformPlugin+ ios:+ pluginClass: EntePhotosPlatformPlugindiff --git a/mobile/apps/photos/plugins/ente_photos_platform/test/device_health_test.dart b/mobile/apps/photos/plugins/ente_photos_platform/test/device_health_test.dartnew file mode 100644index 0000000000..67264331d3--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/test/device_health_test.dart@@ -0,0 +1,147 @@+import 'package:ente_photos_platform/ente_photos_platform.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ test('parses a complete Android observation', () {+ final snapshot = DeviceHealthSnapshot.fromMap(+ _snapshotMap(platform: 'android'),+ );++ expect(snapshot.platform, DeviceHealthPlatform.android);+ expect(snapshot.battery.levelPercent, 64);+ expect(snapshot.battery.temperatureCelsius, 31.5);+ expect(snapshot.battery.health, DeviceBatteryHealth.good);+ expect(snapshot.thermal.state, DeviceThermalState.moderate);+ expect(+ snapshot.isFreshAt(+ snapshot.observedAt.add(const Duration(seconds: 30)),+ const Duration(minutes: 1),+ ),+ isTrue,+ );+ });++ test('accepts iOS battery observations without private metrics', () {+ final snapshot = DeviceHealthSnapshot.fromMap(+ _snapshotMap(+ platform: 'ios',+ battery: {'status': 'available', 'levelPercent': 80},+ ),+ );++ expect(snapshot.battery.temperatureCelsius, isNull);+ expect(snapshot.battery.health, isNull);+ });++ test('rejects available battery observations without a valid level', () {+ expect(+ () => DeviceHealthSnapshot.fromMap(+ _snapshotMap(battery: {'status': 'available'}),+ ),+ throwsFormatException,+ );+ expect(+ () => DeviceHealthSnapshot.fromMap(+ _snapshotMap(battery: {'status': 'available', 'levelPercent': 101}),+ ),+ throwsFormatException,+ );+ });++ test('rejects values attached to unavailable signals', () {+ expect(+ () => DeviceHealthSnapshot.fromMap(+ _snapshotMap(thermal: {'status': 'unsupported', 'state': 'nominal'}),+ ),+ throwsFormatException,+ );+ });++ test('requires errors only for unavailable signals', () {+ expect(+ () => DeviceHealthSnapshot.fromMap(+ _snapshotMap(battery: {'status': 'unavailable'}),+ ),+ throwsFormatException,+ );+ expect(+ () => DeviceHealthSnapshot.fromMap(+ _snapshotMap(+ thermal: {+ 'status': 'available',+ 'state': 'nominal',+ 'errorCode': 'unexpected',+ },+ ),+ ),+ throwsFormatException,+ );+ });++ test('future observations are not fresh', () {+ final snapshot = DeviceHealthSnapshot.fromMap(_snapshotMap());+ expect(+ snapshot.isFreshAt(+ snapshot.observedAt.subtract(const Duration(milliseconds: 1)),+ const Duration(minutes: 1),+ ),+ isFalse,+ );+ });++ test('source requests and parses the typed native snapshot', () async {+ const channel = MethodChannel('device-health-test');+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, (call) async {+ expect(call.method, 'deviceHealth.getSnapshot');+ return _snapshotMap();+ });+ addTearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, null),+ );++ final source = EntePhotosDeviceHealth(methodChannel: channel);+ expect((await source.getSnapshot()).battery.levelPercent, 64);+ });++ test('source requests and parses physical memory separately', () async {+ const channel = MethodChannel('device-memory-test');+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, (call) async {+ expect(call.method, 'deviceHealth.getMemorySnapshot');+ return {'status': 'available', 'totalBytes': 8 * 1024 * 1024 * 1024};+ });+ addTearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, null),+ );++ final source = EntePhotosDeviceHealth(methodChannel: channel);+ expect(+ (await source.getMemorySnapshot()).totalBytes,+ 8 * 1024 * 1024 * 1024,+ );+ });+}++Map<String, Object?> _snapshotMap({+ String platform = 'android',+ Map<String, Object?>? battery,+ Map<String, Object?>? thermal,+}) => {+ 'platform': platform,+ 'observedAtMs': 1800000000000,+ 'battery':+ battery ??+ {+ 'status': 'available',+ 'levelPercent': 64,+ 'temperatureCelsius': 31.5,+ 'health': 'good',+ },+ 'thermal': thermal ?? {'status': 'available', 'state': 'moderate'},+};diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex 183f4fdc8d..1a3a4411b5 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -12,6 +12,7 @@ workspace:- apps/photos/plugins/ente_crypto- apps/photos/plugins/ente_feature_flag- apps/photos/plugins/ente_panorama_viewer+ - apps/photos/plugins/ente_photos_platform- packages/accounts- packages/account_deletion- packages/backup_exclusion