package com.movesdk import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.provider.Settings import android.util.Log import com.facebook.react.bridge.ActivityEventListener import com.facebook.react.bridge.Callback import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.movesdk.shared.ARGUMENT_STATE import com.movesdk.shared.BATTERY_OPTIMIZATION_REQUEST_CODE import com.movesdk.shared.EVENT_AUTH_BATTERY_PERMISSION import com.movesdk.shared.EVENT_AUTH_OVERLAY_PERMISSION import com.movesdk.shared.LOG_TAG import com.movesdk.shared.OVERLAY_REQUEST_CODE import io.dolphin.move.MoveSdk import io.dolphin.move.MoveServiceWarning class MoveSdkModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context), ActivityEventListener { companion object { const val NAME = "MoveSdk" } private val reactContext: ReactApplicationContext = context private val nativeSdkWrapper = NativeMoveSdkWrapper.getInstance(reactContext) init { nativeSdkWrapper.applyDelegate(this) // **** PERMISSIONS MODULE START ***** reactContext.addActivityEventListener(this) // **** PERMISSIONS MODULE START ***** } // **** PERMISSIONS MODULE START ***** override fun onNewIntent(intent: Intent) { // Skip, currently obsolete ActivityEventListener callback } // **** PERMISSIONS MODULE START ***** @ReactMethod fun setup( auth: ReadableMap?, config: ReadableMap?, options: ReadableMap?, platformParams: ReadableArray?, promise: Promise? ) { try { val authMap = auth?.toHashMap() ?: throw IllegalArgumentException("Auth object is null") val userId = authMap["userId"] as String val accessToken = authMap["accessToken"] as String val refreshToken = authMap["refreshToken"] as String val projectId = authMap["projectId"] as Double config ?: throw IllegalArgumentException("Config object is null") val timelineDetectionServices = config.getArray("timelineDetectionServices")!! val drivingServices = config.getArray("drivingServices")!! val walkingServices = config.getArray("walkingServices")!! val platformParamsIterator = platformParams?.toArrayList()?.iterator() ?: throw IllegalArgumentException("Platform Params object is null") val recognitionNotificationTitle = platformParamsIterator.next() as String val recognitionNotificationText = platformParamsIterator.next() as String val tripNotificationTitle = platformParamsIterator.next() as String val tripNotificationText = platformParamsIterator.next() as String nativeSdkWrapper.setup( userId = userId, accessToken = accessToken, refreshToken = refreshToken, projectId = projectId.toInt(), timelineDetectionServices = timelineDetectionServices, drivingServices = drivingServices, walkingServices = walkingServices, options = options, recognitionNotificationTitle = recognitionNotificationTitle, recognitionNotificationText = recognitionNotificationText, tripNotificationTitle = tripNotificationTitle, tripNotificationText = tripNotificationText, promise = promise ) } catch (e: Exception) { Log.e(LOG_TAG, "Error during setup", e) } } @ReactMethod fun setupWithCode( code: String?, config: ReadableMap?, options: ReadableMap?, platformParams: ReadableArray?, promise: Promise? ) { try { code ?: throw IllegalArgumentException("Code is null") config ?: throw IllegalArgumentException("Config object is null") val timelineDetectionServices = config.getArray("timelineDetectionServices")!! val drivingServices = config.getArray("drivingServices")!! val walkingServices = config.getArray("walkingServices")!! val platformParamsIterator = platformParams?.toArrayList()?.iterator() ?: throw IllegalArgumentException("Platform Params object is null") val recognitionNotificationTitle = platformParamsIterator.next() as String val recognitionNotificationText = platformParamsIterator.next() as String val tripNotificationTitle = platformParamsIterator.next() as String val tripNotificationText = platformParamsIterator.next() as String nativeSdkWrapper.setup( code = code, timelineDetectionServices = timelineDetectionServices, drivingServices = drivingServices, walkingServices = walkingServices, options = options, recognitionNotificationTitle = recognitionNotificationTitle, recognitionNotificationText = recognitionNotificationText, tripNotificationTitle = tripNotificationTitle, tripNotificationText = tripNotificationText, promise = promise ) } catch (e: Exception) { Log.e(LOG_TAG, "Error during setup", e) } } @ReactMethod fun init() { MoveSdk.init(reactContext.applicationContext) } @ReactMethod fun resolveError() { nativeSdkWrapper.resolveError() } @ReactMethod fun allowMockLocations(allowMockLocations: Boolean) { nativeSdkWrapper.allowMockLocations(allowMockLocations) } @ReactMethod fun startAutomaticDetection(promise: Promise?) { promise?.resolve(nativeSdkWrapper.startAutomaticDetection()) } @ReactMethod fun stopAutomaticDetection(promise: Promise?) { promise?.resolve(nativeSdkWrapper.stopAutomaticDetection()) } @ReactMethod fun shutdown(force: Boolean?, timeout: Double?, promise: Promise?) { nativeSdkWrapper.shutdown(force = force == true, timeout = timeout?.toInt(), promise = promise) } @ReactMethod fun forceTripRecognition(duration: Int?) { nativeSdkWrapper.forceTripRecognition(duration?.toLong()) } @ReactMethod fun keepInForeground(enabled: Boolean) { nativeSdkWrapper.keepInForeground(enabled) } @ReactMethod fun keepActive(enabled: Boolean) { nativeSdkWrapper.keepActive(enabled) } @ReactMethod fun synchronizeUserData(promise: Promise) { nativeSdkWrapper.synchronizeUserData(promise) } @ReactMethod fun ignoreCurrentTrip() { nativeSdkWrapper.ignoreCurrentTrip() } @ReactMethod fun finishCurrentTrip() { nativeSdkWrapper.finishCurrentTrip() } @ReactMethod fun getState(promise: Promise) { nativeSdkWrapper.getState(promise) } @ReactMethod fun getTripState(promise: Promise) { nativeSdkWrapper.getTripState(promise) } @ReactMethod fun geocode(latitude: Double, longitude: Double, promise: Promise) { nativeSdkWrapper.geocode(latitude, longitude, promise) } @ReactMethod fun setAssistanceMetaData(data: String) { nativeSdkWrapper.setAssistanceMetaData(data) } @ReactMethod fun initiateAssistanceCall(promise: Promise) { nativeSdkWrapper.initiateAssistanceCall(promise) } @ReactMethod fun updateAuth( contractId: String, accessToken: String, refreshToken: String, productId: Int ) { nativeSdkWrapper.updateAuth(contractId, accessToken, refreshToken, productId) } @ReactMethod fun getAuthState(promise: Promise) { nativeSdkWrapper.getAuthState(promise) } override fun getName(): String { return NAME } override fun getConstants(): MutableMap { val constants: HashMap = HashMap() constants["version"] = MoveSdk.version return constants } fun emitDeviceEvent(eventName: String, data: Array) { reactContext.emitDeviceArrayEvent(eventName, data) } fun emitDeviceEvent(eventName: String, data: Map<*, *>) { reactContext.emitDeviceMapEvent(eventName, data) } fun emitDeviceEvent(eventName: String, data: String) { reactContext.emitDeviceStringEvent(eventName, data) } @ReactMethod fun addListener(eventName: String) { // Posted, not inline: RN calls this before registering the JS subscription. reactContext.runOnJSQueueThread { nativeSdkWrapper.replayPendingEvent(eventName) } } @ReactMethod fun removeListeners(count: Int) { // Remove upstream listeners, stop unnecessary background tasks } @ReactMethod fun getErrors(promise: Promise?) { nativeSdkWrapper.getErrors(promise) } @ReactMethod fun getWarnings(promise: Promise?) { val warnings: List = nativeSdkWrapper.getWarnings() ?: emptyList() promise?.resolve(warnings.warningsToArray().toWritableArray()) } @ReactMethod fun getDeviceQualifier(promise: Promise) { promise.resolve(nativeSdkWrapper.getDeviceQualifier()) } @ReactMethod fun isAuthValid(promise: Promise) { nativeSdkWrapper.isAuthValid(promise) } @ReactMethod fun registerDevices(devices: ReadableArray, promise: Promise) { try { nativeSdkWrapper.registerDevices( rawData = devices.toArrayList() as? ArrayList>, promise = promise, ) } catch (t: Throwable) { Log.e("SDK Module", t.message, t) } } @ReactMethod fun unregisterDevices(devices: ReadableArray, promise: Promise) { try { nativeSdkWrapper.unregisterDevices( rawData = devices.toArrayList() as? ArrayList>, promise = promise, ) } catch (t: Throwable) { Log.e("SDK Module", t.message, t) } } @ReactMethod fun getRegisteredDevices(promise: Promise) { nativeSdkWrapper.getRegisteredDevices(promise) } @ReactMethod fun startScanningDevices(filter: ReadableArray?, uuid: String?, manufacturerId: Int?) { Log.i("MODULE_SCAN_DEVICE", "startScanningDevices: ${filter}") val filters = try { filter?.toArrayList()?.map { it.toString() }.orEmpty() } catch (e: Exception) { emptyList() } nativeSdkWrapper.startScanningDevices(filters, manufacturerId, uuid) } @ReactMethod fun stopScanningDevices() { nativeSdkWrapper.stopScanningDevices() } @ReactMethod fun setTimer(delay: Int? = 0, key: String, callback: Callback) { nativeSdkWrapper.setTimer( delay = delay, key = key, callback = callback ) } @ReactMethod fun cancelTimer(key: String?) { nativeSdkWrapper.cancelTimer(key = key) } @ReactMethod fun startTrip(metadata: ReadableMap?, promise: Promise?) { val metadataMap = metadata?.toHashMap()?.mapValues { it.value.toString() } promise?.resolve(MoveSdk.get()?.startTrip(metadataMap) == true) } @ReactMethod fun updateConfig( config: ReadableMap?, options: ReadableMap? ) { try { nativeSdkWrapper.updateConfig( timelineDetectionServices = config?.getArray("timelineDetectionServices")!!, drivingServices = config.getArray("drivingServices")!!, walkingServices = config.getArray("walkingServices")!!, options ) } catch (e: Exception) { Log.e(LOG_TAG, "Error updating config", e) } } @ReactMethod fun setTripMetadata(metadata: ReadableMap?) { val metadataMap = metadata?.toHashMap()?.mapValues { it.value.toString() } nativeSdkWrapper.setTripMetadata(metadataMap) } @ReactMethod fun setLiveLocationTag(tag: String?, promise: Promise) { if (nativeSdkWrapper.setLiveLocationTag(tag)) { promise.resolve(true) } else { promise.reject(Exception("Can't set location tag, check Move SDK logs for more information")) } } @ReactMethod fun getBluetoothState(promise: Promise) { promise.resolve(nativeSdkWrapper.isBluetoothEnabled()) } @ReactMethod fun getBluetoothPermission(promise: Promise) { promise.resolve(nativeSdkWrapper.hasDiscoveryPermissions()) } @ReactMethod fun startNativeSdkStateListener() { nativeSdkWrapper.addSdkStateListener() } // region PERMISSIONS MODULE @SuppressLint("NewApi") override fun onActivityResult( activity: Activity, requestCode: Int, resultCode: Int, data: Intent? ) { if (requestCode == OVERLAY_REQUEST_CODE) { val eventData = mutableMapOf() eventData[ARGUMENT_STATE] = Settings.canDrawOverlays(reactContext) emitDeviceEvent(EVENT_AUTH_OVERLAY_PERMISSION, eventData) } else if (requestCode == BATTERY_OPTIMIZATION_REQUEST_CODE) { val eventData = mutableMapOf() eventData[ARGUMENT_STATE] = reactContext.isAppIgnoringBatteryOptimization() emitDeviceEvent(EVENT_AUTH_BATTERY_PERMISSION, eventData) } } @ReactMethod fun canDrawOverlays(promise: Promise) { promise.resolve(Settings.canDrawOverlays(reactContext)) } @ReactMethod fun requestDrawOverlaysPermission() { nativeSdkWrapper.requestDrawOverlaysPermission(reactContext) } @ReactMethod fun isAppIgnoringBatteryOptimization(promise: Promise) { promise.resolve(reactContext.isAppIgnoringBatteryOptimization()) } @SuppressLint("BatteryLife") @ReactMethod fun requestAppIgnoringBatteryOptimization() { nativeSdkWrapper.requestAppIgnoringBatteryOptimization(reactContext) } @ReactMethod fun requestHealthPermissions(promise: Promise?) { nativeSdkWrapper.requestHealthPermissions(promise) } // endregion PERMISSIONS MODULE @ReactMethod fun getMoveConfig(promise: Promise?) { nativeSdkWrapper.getMoveConfig(promise) } }