package com.movesdk import android.annotation.SuppressLint import android.bluetooth.BluetoothManager import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.health.connect.client.PermissionController import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.permission.HealthPermission.Companion.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND import androidx.health.connect.client.records.StepsRecord import com.facebook.react.ReactActivity import com.facebook.react.bridge.Callback import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.WritableMap import com.google.gson.Gson import com.movesdk.extentions.PermissionUtils import com.movesdk.metadata.METADATA_PREF import com.movesdk.metadata.MetadataStorage import com.movesdk.metadata.MetadataStorageImpl import com.movesdk.shared.ARGUMENT_ERROR import com.movesdk.shared.ARGUMENT_ERRORS import com.movesdk.shared.ARGUMENT_MOVE_HEALTH import com.movesdk.shared.ARGUMENT_MOVE_SERVICES import com.movesdk.shared.ARGUMENT_STATE import com.movesdk.shared.ARGUMENT_WARNINGS import com.movesdk.shared.BATTERY_OPTIMIZATION_REQUEST_CODE import com.movesdk.shared.EVENT_AUTH_STATE import com.movesdk.shared.EVENT_ERRORS import com.movesdk.shared.EVENT_INIT_ERROR import com.movesdk.shared.EVENT_MOVE_CONFIG_UPDATE import com.movesdk.shared.EVENT_MOVE_DEVICES import com.movesdk.shared.EVENT_MOVE_SCAN_RESULT import com.movesdk.shared.EVENT_MOVE_SDK_APP import com.movesdk.shared.EVENT_MOVE_SDK_DEVICE_STATE import com.movesdk.shared.EVENT_MOVE_SDK_HEALTH import com.movesdk.shared.EVENT_MOVE_SDK_LOG import com.movesdk.shared.EVENT_MOVE_SDK_TRIP_START import com.movesdk.shared.EVENT_MOVE_STATE import com.movesdk.shared.EVENT_TRIP_STATE import com.movesdk.shared.EVENT_WARNINGS import com.movesdk.shared.LOG_TAG import com.movesdk.shared.OVERLAY_REQUEST_CODE import com.movesdk.shared.PROMISE_OK import io.dolphin.move.AuthSetupStatus import io.dolphin.move.DeviceDiscovery import io.dolphin.move.DrivingService import io.dolphin.move.MoveAssistanceCallStatus import io.dolphin.move.MoveAuth import io.dolphin.move.MoveAuthResult import io.dolphin.move.MoveAuthState import io.dolphin.move.MoveConfig import io.dolphin.move.MoveConfigurationError import io.dolphin.move.MoveDetectionService import io.dolphin.move.MoveDevice import io.dolphin.move.MoveHealthScore import io.dolphin.move.MoveInitOptions import io.dolphin.move.MoveNotification import io.dolphin.move.MoveOptions import io.dolphin.move.MoveScanResult import io.dolphin.move.MoveSdk import io.dolphin.move.MoveSdkState import io.dolphin.move.MoveServiceFailure import io.dolphin.move.MoveServiceWarning import io.dolphin.move.MoveShutdownResult import io.dolphin.move.MoveTripState import io.dolphin.move.WalkingService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.Date import java.util.Timer import java.util.UUID import java.util.TimerTask @SuppressLint("StaticFieldLeak", "MissingPermission") class NativeMoveSdkWrapper(private val context: Context) : MoveSdk.StateListener, MoveSdk.InitializeListener, MoveSdk.TripStateListener, MoveSdk.AuthStateUpdateListener, MoveSdk.MoveLogCallback, MoveSdk.MoveErrorListener, MoveSdk.MoveWarningListener, MoveSdk.DeviceDiscoveryListener, MoveSdk.RemoteConfigChangeListener, MoveSdk.TripStartListener, MoveSdk.TripMetadataProvider, MoveSdk.MoveDeviceStateListener, MoveSdk.MoveHealthScoreListener { companion object { private var instance: NativeMoveSdkWrapper? = null @JvmStatic fun getInstance(context: Context): NativeMoveSdkWrapper { if (instance == null) { instance = NativeMoveSdkWrapper(context) } return instance as NativeMoveSdkWrapper } } private val configRepository = MoveSdkConfigRepository(context) private val deviceScanner = DeviceScanner(context) private var delegate: MoveSdkModule? = null // MoveSdk.init() runs from Application.onCreate, so the SDK's first callbacks // are emitted before `delegate` exists and would be lost without buffering. private val pendingEvents = PendingEventBuffer() private val mainScope = CoroutineScope(Dispatchers.Main) private val ioContext = Dispatchers.IO private val gson = Gson() private val metadataStorage: MetadataStorage = MetadataStorageImpl( context.getSharedPreferences( METADATA_PREF, Context.MODE_PRIVATE ), gson, ) private val timersHolder = mutableMapOf() private var healthPermissionPromise: Promise? = null private val permissions = setOf( HealthPermission.getReadPermission(StepsRecord::class), PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND, ) private var requestPermissionsLauncher: ActivityResultLauncher>? = null @JvmOverloads fun init(context: Context, initOptions: MoveInitOptions? = null) { val moveSdk = MoveSdk.init(context.applicationContext, initOptions = initOptions) moveSdk.tripStateListener(this) moveSdk.authStateUpdateListener(this) moveSdk.initializationListener(this) moveSdk.setLogListener(this) moveSdk.setServiceErrorListener(this) moveSdk.setServiceWarningListener(this) moveSdk.deviceDiscoveryListener(this) moveSdk.setRemoteConfigChangeListener(this) moveSdk.setTripStartListener(this) moveSdk.metadataProvider(this) moveSdk.setDeviceStateListener(this) moveSdk.setMoveHealthScoreListener(this) } fun allowMockLocations(allowMockLocations: Boolean) { MoveSdk.get()?.allowMockLocations(allowMockLocations) } @SuppressLint("MissingPermission") fun setup( userId: String, accessToken: String, refreshToken: String, projectId: Int, // Config timelineDetectionServices: ReadableArray, drivingServices: ReadableArray, walkingServices: ReadableArray, options: ReadableMap?, // Platform config recognitionNotificationTitle: String, recognitionNotificationText: String, tripNotificationTitle: String, tripNotificationText: String, promise: Promise? ) { val timelineDetectionServicesToUse = mutableListOf() val drivingServicesToUse = mutableListOf() val walkingServicesToUse = mutableListOf() walkingServices.toArrayList().forEach { val serviceName = if (it == "WALKING_LOCATION") "LOCATION" else it try { walkingServicesToUse.add( WalkingService.valueOf( serviceName.toString().snakeToUpperCamelCase() ) ) } catch (t: Throwable) { t.printStackTrace() } } drivingServices.toArrayList().forEach { try { drivingServicesToUse.add(DrivingService.valueOf(it.toString().snakeToUpperCamelCase())) } catch (t: Throwable) { t.printStackTrace() } } timelineDetectionServices.toArrayList().forEach { service -> timelineDetectionServicesToUse.add( valueOfMoveDetectionService( service.toString(), drivingServicesToUse, walkingServicesToUse ) ) } val moveOptions = options?.let(::extractMoveOptions) try { Log.d(LOG_TAG, "MOVE SDK Version " + MoveSdk.version) val moveAuth = MoveAuth( userId = userId, accessToken = accessToken, refreshToken = refreshToken, projectId = projectId.toLong(), ) MoveSdk.get()?.setNotificationText( notification = MoveNotification( recognitionTitle = recognitionNotificationTitle, recognitionText = recognitionNotificationText, drivingTitle = tripNotificationTitle, drivingText = tripNotificationText, walkingTitle = recognitionNotificationTitle, walkingText = recognitionNotificationText ) ) val moveConfig = MoveConfig(timelineDetectionServicesToUse) MoveSdk.setup( auth = moveAuth, config = moveConfig, options = moveOptions, ) promise?.resolve(PROMISE_OK) } catch (t: Throwable) { val message = "SETUP_ERROR: ${t.message}" Log.e(LOG_TAG, message, t) emitDeviceEvent(EVENT_MOVE_SDK_APP, message) promise?.reject(Exception(message)) } } @SuppressLint("MissingPermission") fun setup( code: String, // Config timelineDetectionServices: ReadableArray, drivingServices: ReadableArray, walkingServices: ReadableArray, options: ReadableMap?, // Platform config recognitionNotificationTitle: String, recognitionNotificationText: String, tripNotificationTitle: String, tripNotificationText: String, promise: Promise? ) { val timelineDetectionServicesToUse = mutableListOf() val drivingServicesToUse = mutableListOf() val walkingServicesToUse = mutableListOf() walkingServices.toArrayList().forEach { val serviceName = if (it == "WALKING_LOCATION") "LOCATION" else it try { walkingServicesToUse.add( WalkingService.valueOf( serviceName.toString().snakeToUpperCamelCase() ) ) } catch (t: Throwable) { t.printStackTrace() } } drivingServices.toArrayList().forEach { try { drivingServicesToUse.add(DrivingService.valueOf(it.toString().snakeToUpperCamelCase())) } catch (t: Throwable) { t.printStackTrace() } } timelineDetectionServices.toArrayList().forEach { service -> timelineDetectionServicesToUse.add( valueOfMoveDetectionService( service.toString(), drivingServicesToUse, walkingServicesToUse ) ) } val featureOptions = options?.toHashMap() val moveOptions = try { val motionPermissionMandatory = featureOptions?.get("motionPermissionMandatory") as? Boolean val useBackendConfig = featureOptions?.get("useBackendConfig") as? Boolean val backgroundLocationPermissionMandatory = featureOptions?.get("backgroundLocationPermissionMandatory") as? Boolean val overlayPermissionMandatory = featureOptions?.get("overlayPermissionMandatory") as? Boolean val deviceDiscovery = featureOptions?.get("deviceDiscovery") as? Map val startDelay = deviceDiscovery?.get("startDelay") as? Double val duration = deviceDiscovery?.get("duration") as? Double val interval = deviceDiscovery?.get("interval") as? Double val stopScanOnFirstDiscovered = deviceDiscovery?.get("stopScanOnFirstDiscovered") as? Boolean MoveOptions( motionPermissionRequired = motionPermissionMandatory ?: false, useBackendConfig = useBackendConfig ?: false, backgroundLocationPermissionMandatory = backgroundLocationPermissionMandatory ?: false, overlayPermissionMandatory = overlayPermissionMandatory ?: true, deviceDiscovery = DeviceDiscovery( startDelay = startDelay?.toLong(), duration = duration?.toLong(), interval = interval?.toLong(), stopScanOnFirstDiscovered = stopScanOnFirstDiscovered ?: false, ), ) } catch (e: Exception) { Log.e(LOG_TAG, "setup: ${e.message}", e) null } try { Log.d(LOG_TAG, "MOVE SDK Version " + MoveSdk.version) MoveSdk.get()?.setNotificationText( notification = MoveNotification( recognitionTitle = recognitionNotificationTitle, recognitionText = recognitionNotificationText, drivingTitle = tripNotificationTitle, drivingText = tripNotificationText, walkingTitle = recognitionNotificationTitle, walkingText = recognitionNotificationText ) ) val moveConfig = MoveConfig(timelineDetectionServicesToUse) MoveSdk.setup( authCode = code, config = moveConfig, options = moveOptions, callback = object : MoveSdk.MoveAuthCallback { override fun onResult(result: MoveAuthResult) { when (result.status) { AuthSetupStatus.SUCCESS -> { promise?.resolve(PROMISE_OK) } AuthSetupStatus.INVALID_CODE, AuthSetupStatus.NETWORK_ERROR -> promise?.reject(Exception(result.status.name)) } } } ) } catch (t: Throwable) { val message = "SETUP_ERROR: ${t.message}" Log.e(LOG_TAG, message, t) emitDeviceEvent(EVENT_MOVE_SDK_APP, message) promise?.reject(Exception(message)) } } fun resolveError() { MoveSdk.get()?.resolveError() } fun startAutomaticDetection(): Boolean { return MoveSdk.get()?.startAutomaticDetection() == true } fun stopAutomaticDetection(): Boolean { return MoveSdk.get()?.stopAutomaticDetection() == true } fun shutdown(force: Boolean, timeout: Int?, promise: Promise?) { // Clear all properties, so we don't initialize it again on next startup configRepository.clear() val callback: (MoveShutdownResult) -> Unit = { result -> when (result) { MoveShutdownResult.SUCCESS -> promise?.resolve(result.name.toSnakeCase()) MoveShutdownResult.NETWORK_ERROR, MoveShutdownResult.UNINITIALIZED -> promise?.reject(Exception(result.name.toSnakeCase())) } } if (timeout != null) { MoveSdk.get()?.shutdown(force, timeout, callback) } else { MoveSdk.get()?.shutdown(force, callback = callback) } } fun forceTripRecognition(duration: Long?) { if (duration != null) { MoveSdk.get()?.forceTripRecognition(duration) } else { MoveSdk.get()?.forceTripRecognition() } } fun getErrors(promise: Promise?) { mainScope.launch { val errors: List withContext(ioContext) { errors = MoveSdk.get()?.getServiceErrors() ?: emptyList() } promise?.resolve(errors.failuresToArray().toWritableArray()) } } fun getWarnings(): List? { return MoveSdk.get()?.getServiceWarnings() } fun keepInForeground(enabled: Boolean) { MoveSdk.get()?.keepInForeground(enabled) } fun keepActive(enabled: Boolean) { MoveSdk.get()?.keepActive(enabled) } fun synchronizeUserData(promise: Promise) { MoveSdk.get()?.synchronizeUserData { synced -> promise.resolve(synced) } } fun ignoreCurrentTrip() { MoveSdk.get()?.ignoreCurrentTrip() } fun finishCurrentTrip() { MoveSdk.get()?.finishCurrentTrip() } fun getState(promise: Promise) { mainScope.launch { val state: MoveSdkState withContext(ioContext) { state = MoveSdk.get()?.getSdkState() ?: MoveSdkState.Uninitialised } promise.resolve(state.toString().toSnakeCase()) } } fun getTripState(promise: Promise) { val tripState = MoveSdk.get()?.getTripState() ?: MoveTripState.UNKNOWN promise.resolve(tripState.toString()) } fun initiateAssistanceCall(promise: Promise) { MoveSdk.get()?.initiateAssistanceCall(object : MoveSdk.AssistanceStateListener { override fun onAssistanceStateChanged(assistanceState: MoveAssistanceCallStatus) { if (assistanceState == MoveAssistanceCallStatus.SUCCESS) { promise.resolve(true) } else { promise.reject(Exception(assistanceState.name.toSnakeCase())) } } }) ?: promise.reject(Exception("ASSISTANCE_CALL_ERROR")) } fun setAssistanceMetaData(data: String?) { MoveSdk.get()?.setAssistanceMetaData(data) } fun geocode(latitude: Double, longitude: Double, promise: Promise) { MoveSdk.get()?.let { it.geocode(latitude, longitude) { result -> val error = result.error if (error != null) { promise.reject(Exception(error.name.toSnakeCase())) } else { val address = result.address promise.resolve(address) } } } ?: promise.reject(Exception("GEOCODE_ERROR")) } override fun onError(error: MoveConfigurationError) { val data = mutableMapOf() data[ARGUMENT_ERROR] = error.toString().toSnakeCase() emitDeviceEvent(EVENT_INIT_ERROR, data) } override fun onStateChanged(sdk: MoveSdk, state: MoveSdkState) { val data = mutableMapOf() data[ARGUMENT_STATE] = state.toString().toSnakeCase() /** * There is no SDK State Error anymore if (state is MoveSdkState.Error) { data.putString(ARGUMENT_ERROR_REASON, state.reason.toString()) }**/ emitDeviceEvent(EVENT_MOVE_STATE, data) Log.d(LOG_TAG, "Move SDK $state") } override fun onTripStateChanged(tripState: MoveTripState) { val data = mutableMapOf() data[ARGUMENT_STATE] = tripState.toString().toSnakeCase() emitDeviceEvent(EVENT_TRIP_STATE, data) } fun applyDelegate(dolphinSdkModule: MoveSdkModule) { delegate = dolphinSdkModule } fun updateAuth( contractId: String, accessToken: String, refreshToken: String, productId: Int ) { val auth = MoveAuth( projectId = productId.toLong(), userId = contractId, accessToken = accessToken, refreshToken = refreshToken, ) MoveSdk.get()?.updateAuth(auth) { configurationError -> val data = mutableMapOf() data[ARGUMENT_ERROR] = configurationError.toString() emitDeviceEvent(EVENT_INIT_ERROR, data) } } fun getAuthState(promise: Promise) { mainScope.launch { val state: MoveAuthState withContext(ioContext) { state = MoveSdk.get()?.getAuthState() ?: MoveAuthState.UNKNOWN } promise.resolve(state.toString()) } } override fun onAuthStateUpdate(state: MoveAuthState) { val data = mutableMapOf() data[ARGUMENT_STATE] = state.toString().toSnakeCase() /** * No need to store anything any more if (state is MoveAuthState.VALID) { data.putString(ARGUMENT_ACCESS_TOKEN, state.auth.accessToken) data.putString(ARGUMENT_REFRESH_TOKEN, state.auth.refreshToken) // Only store valid auth here configRepository.storeAuth(state.auth) }**/ emitDeviceEvent(EVENT_AUTH_STATE, data) } private fun emitDeviceEvent(eventName: String, eventData: Map) { bufferUntilSubscribed(eventName, eventData) delegate?.emitDeviceEvent(eventName, eventData) } fun emitDeviceEvent(eventName: String, eventData: Array) { bufferUntilSubscribed(eventName, eventData) delegate?.emitDeviceEvent(eventName, eventData) } fun emitDeviceEvent(eventName: String, eventData: String) { bufferUntilSubscribed(eventName, eventData) delegate?.emitDeviceEvent(eventName, eventData) } /** * Keeps the newest payload of an event JS has not subscribed to yet, so * [replayPendingEvent] can hand it over once it does. * * Callers still attempt the live emit too: consumers subscribing through * `DeviceEventEmitter` directly never reach [replayPendingEvent], and * withholding their events to avoid a possible duplicate is the worse trade. * Duplicates are only possible between the React instance coming up and JS * subscribing, and buffered events carry current state, so replay is * idempotent. */ private fun bufferUntilSubscribed(eventName: String, eventData: Any) { // Keyed by the name JS sees, which the emit helpers derive via toSnakeCase() // (e.g. "MoveSdk-State" -> "MOVE_SDK_STATE"). val jsEventName = eventName.toSnakeCase() if (!pendingEvents.isSubscribed(jsEventName)) { pendingEvents.record(jsEventName, eventData) } } /** * Re-emits the payload of [jsEventName] that arrived before JS subscribed. * * Callers must post this onto the JS queue rather than call it inline: * `NativeEventEmitter.addListener` invokes the native `addListener` *before* * registering the JS subscription, so an inline emit can overtake it. */ fun replayPendingEvent(jsEventName: String) { val pending = pendingEvents.markSubscribed(jsEventName) ?: return when (pending) { is Map<*, *> -> delegate?.emitDeviceEvent(jsEventName, pending) is Array<*> -> @Suppress("UNCHECKED_CAST") delegate?.emitDeviceEvent( jsEventName, pending as Array, ) is String -> delegate?.emitDeviceEvent(jsEventName, pending) else -> Log.w(LOG_TAG, "Cannot replay $jsEventName: unsupported payload type") } } override fun onLogReceived(eventName: String, value: String?) { val data = mutableMapOf() data["message"] = eventName.trim() value?.let { data["value"] = it.trim() } emitDeviceEvent(EVENT_MOVE_SDK_LOG, data) } override fun onMoveError(serviceFailures: List) { val data = mutableMapOf() data[ARGUMENT_ERRORS] = serviceFailures.failuresToArray() emitDeviceEvent(EVENT_ERRORS, data) } override fun onMoveWarning(serviceWarnings: List) { val data = mutableMapOf() data[ARGUMENT_WARNINGS] = serviceWarnings.warningsToArray() emitDeviceEvent(EVENT_WARNINGS, data) } fun getDeviceQualifier(): String? { return MoveSdk.get()?.getDeviceQualifier() } fun isAuthValid(promise: Promise) { mainScope.launch { val state: MoveAuthState withContext(ioContext) { state = MoveSdk.get()?.getAuthState() ?: MoveAuthState.UNKNOWN } promise.resolve(state is MoveAuthState.VALID) } } override fun onScanResult(results: List) { emitDeviceEvent(EVENT_MOVE_SCAN_RESULT, results.toScanResultArray()) } fun registerDevices(rawData: ArrayList>?, promise: Promise) { mainScope.launch { var isSuccess = false var failureReason: Throwable? = null withContext(ioContext) { val devices = rawData?.mapNotNull { try { val parsed = gson.fromJson(it["data"], MoveDevice::class.java) // `uuid` must be a valid UUID (the SDK throws on invalid). `id` may also be a // MAC address or other opaque identifier, so only normalize it when it happens // to parse as a UUID; otherwise pass it through untouched. val id = parsed.id?.normalizedUuidOrNull() ?: parsed.id val uuid = parsed.uuid?.normalizedUuidOrNull() val displayName = it["displayName"] parsed.copy(id = id, uuid = uuid, displayName = displayName ?: parsed.displayName) } catch (e: Exception) { null } }.orEmpty() // The MoveSDK throws (e.g. IllegalArgumentException on an empty UUID) for bad device // fields. Guard the call so invalid input surfaces as a JS rejection instead of a crash. try { val sdk = MoveSdk.get() isSuccess = sdk?.registerDevices(devices) ?: false if (!isSuccess && sdk != null && sdk.getSdkState() != MoveSdkState.Uninitialised) { val storedIds = sdk.getRegisteredDevices().map { it.id }.toSet() isSuccess = devices.all { it.id in storedIds } } } catch (t: Throwable) { failureReason = t } } if (isSuccess) { promise.resolve(true) } else { promise.reject(failureReason ?: Exception("ERROR_REGISTER_DEVICES")) } } } fun unregisterDevices(rawData: ArrayList>?, promise: Promise) { mainScope.launch { var isSuccess = false withContext(ioContext) { val devices = rawData?.mapNotNull { try { gson.fromJson(it["data"], MoveDevice::class.java) } catch (e: Exception) { null } }.orEmpty() isSuccess = MoveSdk.get()?.unregisterDevices(devices) ?: false } if (isSuccess) { promise.resolve(true) } else { promise.reject(Exception("ERROR_UNREGISTER_DEVICES")) } } } fun getRegisteredDevices(promise: Promise) { mainScope.launch { val devices = mutableListOf() withContext(ioContext) { MoveSdk.get()?.getRegisteredDevices()?.let(devices::addAll) } promise.resolve(devices.toMoveDeviceTypedArray().toWritableArray()) } } fun startScanningDevices(filters: List, manufacturerId: Int?, uuid: String?) { deviceScanner.startScanning( filters, manufacturerId.takeIf { it != -1 }, uuid, onNewDevices = { emitDeviceEvent(EVENT_MOVE_DEVICES, it.toMoveDeviceTypedArray()) }, onNewEvent = { eventName, value -> emitDeviceEvent(EVENT_MOVE_SDK_APP, "$eventName ${value ?: ""}".trim()) }, ) } fun stopScanningDevices() { deviceScanner.stopScanning() } override fun onConfigChanged(config: MoveConfig) { val services = mutableListOf() for(s in config.moveDetectionServices) { when(s) { is MoveDetectionService.Driving -> { services.add("DRIVING") s.drivingServices?.map { it.name.toSnakeCase() }?.let(services::addAll) } is MoveDetectionService.Walking -> { services.add("WALKING") if(s.walkingServices?.contains(WalkingService.Location) ?: false) { services.add("WALKING_LOCATION") } } else -> services.add(s.name().toSnakeCase()) } } emitDeviceEvent(EVENT_MOVE_CONFIG_UPDATE, mutableMapOf(ARGUMENT_MOVE_SERVICES to services)) } // TODO uncomment when will be fixed VIG1-1620 /* private fun getIconIdByName(name: String?): Int? { Log.i("MissingNotifications", "getIconIdByName name = $name") name ?: return null val packageName = context.packageName return try { val resource = context.resources.getIdentifier(name, "drawable", packageName).takeIf { it != 0 } Log.i("MissingNotifications", "getIdentifier resource = $resource") resource } catch (e: Exception) { null } }*/ override fun onTripStarted(startDate: Date) { emitDeviceEvent(EVENT_MOVE_SDK_TRIP_START, startDate.time.toString()) } fun updateConfig( timelineDetectionServices: ReadableArray, drivingServices: ReadableArray, walkingServices: ReadableArray, options: ReadableMap?, ) { val timelineDetectionServicesToUse = mutableListOf() val drivingServicesToUse = mutableListOf() val walkingServicesToUse = mutableListOf() walkingServices.toArrayList().forEach { val serviceName = if (it == "WALKING_LOCATION") "LOCATION" else it try { walkingServicesToUse.add( WalkingService.valueOf( serviceName.toString().snakeToUpperCamelCase() ) ) } catch (t: Throwable) { t.printStackTrace() } } drivingServices.toArrayList().forEach { try { drivingServicesToUse.add(DrivingService.valueOf(it.toString().snakeToUpperCamelCase())) } catch (t: Throwable) { t.printStackTrace() } } timelineDetectionServices.toArrayList().forEach { service -> timelineDetectionServicesToUse.add( valueOfMoveDetectionService( service.toString(), drivingServicesToUse, walkingServicesToUse ) ) } val moveOptions = options?.let(::extractMoveOptions) MoveSdk.get()?.updateConfig( config = MoveConfig(timelineDetectionServicesToUse), options = moveOptions, ) } override fun provideMetadata(start: Long, end: Long): Map { return metadataStorage.getTripMetadata().orEmpty() } fun setTripMetadata(metadataMap: Map?) { metadataStorage.setTripMetadata(metadataMap) } fun setLiveLocationTag(tag: String?): Boolean { return MoveSdk.get()?.setLiveLocationTag(tag) == true } override fun onStateChanged(device: MoveDevice) { emitDeviceEvent(EVENT_MOVE_SDK_DEVICE_STATE, arrayOf(device.toMoveDeviceMap())) } fun isBluetoothEnabled(): Boolean { val adapter = context.getSystemService(BluetoothManager::class.java)?.adapter if (adapter == null) { Log.i(LOG_TAG, "BluetoothManager is missing or BT adapter is null") } return adapter?.isEnabled == true } fun hasDiscoveryPermissions(): Boolean { var hasPermissions = true val hasBluetoothScanPermission = PermissionUtils.hasBluetoothScanPermission(context) Log.i( LOG_TAG, "Discovery permission check: BluetoothScanPermission = $hasBluetoothScanPermission" ) hasPermissions = hasPermissions && hasBluetoothScanPermission if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { val hasFineLocationPermission = PermissionUtils.hasFineLocationPermission(context) Log.i( LOG_TAG, "Discovery permission check: FineLocationPermission = $hasFineLocationPermission" ) hasPermissions = hasPermissions && hasFineLocationPermission } if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R || Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) { val hasBackgroundLocationPermission = PermissionUtils.hasBackgroundLocationPermission(context) Log.i( LOG_TAG, "Discovery permission check: BackgroundLocationPermission = $hasBackgroundLocationPermission" ) hasPermissions = hasPermissions && hasBackgroundLocationPermission } return hasPermissions } fun addSdkStateListener() { MoveSdk.get()?.sdkStateListener(this) } override fun onMoveHealthScoreChanged(score: MoveHealthScore) { try { val data = mutableMapOf() val health = mutableListOf() val healthItem = mutableMapOf() if (score.reason.isNotEmpty()) { healthItem["reason"] = score.reason.first() healthItem["description"] = score.toJsonString() health.add(healthItem) data[ARGUMENT_MOVE_HEALTH] = health emitDeviceEvent(EVENT_MOVE_SDK_HEALTH, data) Log.d(LOG_TAG, "onMoveHealthScoreChanged $data") } } catch (e: Exception) { Log.e(LOG_TAG, "Exception in Health listener", e) } } fun setTimer(delay: Int? = 0, key: String, callback: Callback) { try { val timer = timersHolder[key] timer?.cancel() Timer().also { timersHolder[key] = it it.schedule( object : TimerTask() { override fun run() { callback.invoke() } }, delay?.toLong() ?: 0L, ) } } catch (e: Exception) { // Do nothing } } fun cancelTimer(key: String?) { key ?: return try { timersHolder[key]?.cancel() } catch (e: Exception) { Log.i("cancelTimer", "error: ${e.message}") } } fun requestDrawOverlaysPermission(context: ReactContext) { val intent = Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}") ) context.currentActivity!!.startActivityForResult(intent, OVERLAY_REQUEST_CODE) } fun requestAppIgnoringBatteryOptimization(context: ReactContext) { val intent = Intent( Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + context.packageName) ) context.currentActivity?.startActivityForResult(intent, BATTERY_OPTIMIZATION_REQUEST_CODE) } fun registerRequestPermissionLauncher(activity: ReactActivity) { val requestPermissionActivityContract = PermissionController.createRequestPermissionResultContract() requestPermissionsLauncher = activity.registerForActivityResult(requestPermissionActivityContract) { granted -> if (granted.containsAll(permissions)) { Log.d(LOG_TAG, "Health connect permission has been granted") MoveSdk.get()?.resolveError() } else { Log.d(LOG_TAG, "Health connect permission NOT granted") } val response = createHealthPermissionsResponse( type = "permission_result", message = granted.toString() ) healthPermissionPromise?.resolve(response) healthPermissionPromise = null } } fun requestHealthPermissions(promise: Promise?) { healthPermissionPromise = promise try { requestPermissionsLauncher?.launch(permissions) } catch (e: ActivityNotFoundException) { Log.w(LOG_TAG, "No Activity found to handle Intent.\n Install Health connect") val response = createHealthPermissionsResponse( type = "health_connect_required", message = "Please install Health Connect app first" ) promise?.resolve(response) } catch (e: Exception) { Log.w(LOG_TAG, e.message, e) val response = createHealthPermissionsResponse( type = "error", message = e.toString() ) promise?.resolve(response) } } private fun createHealthPermissionsResponse(type: String, message: String): WritableMap { return mapOf( "technicalMessage" to type, "message" to message, ).toWritableMap() } fun getMoveConfig(promise: Promise?) { if(promise == null) return val sdk = MoveSdk.get() if(sdk == null) { promise.reject(IllegalStateException("move sdk not available")) return } val config = sdk.getMoveConfig() val map = mutableMapOf() val detectionServices = config.moveDetectionServices val timelineDetectionServices = mutableListOf() val drivingServices = mutableListOf() val walkingServices = mutableListOf() for(svc in detectionServices) { when (svc) { is MoveDetectionService.Driving -> { drivingServices.addAll(svc.drivingServices?.map { it.name.toSnakeCase() } ?: emptyList()) } is MoveDetectionService.Walking -> { walkingServices.addAll(svc.walkingServices?.map { it.name.toSnakeCase() } ?: emptyList()) } else -> {} } timelineDetectionServices.add(svc.javaClass.simpleName.toSnakeCase()) } map["timelineDetectionServices"] = timelineDetectionServices map["drivingServices"] = drivingServices map["walkingServices"] = walkingServices promise.resolve(map.toWritableMap()) } } fun List.failuresToArray(): Array { val data = mutableListOf() forEach { val map = mutableMapOf() val serviceName = when (val nativeService = it.service) { is MoveDetectionService.Driving -> nativeService.drivingServices?.firstOrNull()?.name?.toSnakeCase() ?: nativeService.name() .toSnakeCase() is MoveDetectionService.Walking -> { if (nativeService.walkingServices?.isNotEmpty() == true) { "WALKING_LOCATION" } else { nativeService.name().toSnakeCase() } } else -> nativeService.name().toSnakeCase() } map["service"] = serviceName map["reasons"] = it.reasons.map { reason -> reason.name.toSnakeCase() } data.add(map) } return data.toTypedArray() } fun List.warningsToArray(): Array { val data = mutableListOf() forEach { val map = mutableMapOf() val serviceName = when (val nativeService = it.service) { is MoveDetectionService.Driving -> nativeService.drivingServices?.firstOrNull()?.name?.toSnakeCase() ?: nativeService.name() .toSnakeCase() is MoveDetectionService.Walking -> { if (nativeService.walkingServices?.isNotEmpty() == true) { "WALKING_LOCATION" } else { nativeService.name().toSnakeCase() } } else -> nativeService?.name()?.toSnakeCase() } map["service"] = serviceName map["reasons"] = it.warnings.map { reason -> reason.name.toSnakeCase() } data.add(map) } return data.toTypedArray() } private fun String.normalizedUuidOrNull(): String? = try { UUID.fromString(this).toString().uppercase() } catch (_: IllegalArgumentException) { null }