package com.rooksdk import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Callback import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.module.annotations.ReactModule import com.google.gson.Gson import com.rookmotion.rook.sdk.RookBackgroundSyncManager import com.rookmotion.rook.sdk.RookConfigurationManager import com.rookmotion.rook.sdk.RookPermissionsManager import com.rookmotion.rook.sdk.RookStepsCounter import com.rookmotion.rook.sdk.RookSyncManager import com.rookmotion.rook.sdk.RookWriteManager import com.rookmotion.rook.sdk.domain.analytics.HCRookAnalytics import com.rookmotion.rook.sdk.domain.analytics.HCRookFramework import com.rookmotion.rook.sdk.domain.annotation.ExperimentalRookApi import com.rookmotion.rook.sdk.domain.enums.BackgroundReadStatus import com.rookmotion.rook.sdk.domain.enums.HealthConnectAvailability import com.rookmotion.rook.sdk.domain.enums.HistoryReadStatus import com.rookmotion.rook.sdk.domain.enums.RequestPermissionsStatus import com.rookmotion.rook.sdk.domain.enums.SyncStatus import com.rookmotion.rook.sdk.domain.environment.RookEnvironment import com.rookmotion.rook.sdk.domain.exception.HCException import com.rookmotion.rook.sdk.domain.exception.HCRecordsNotFoundException import com.rookmotion.rook.sdk.domain.model.HCActivityEvent import com.rookmotion.rook.sdk.domain.model.HCBodySummary import com.rookmotion.rook.sdk.domain.model.HCPhysicalSummary import com.rookmotion.rook.sdk.domain.model.HCSleepSummary import com.rookmotion.rook.sdk.domain.model.RookConfiguration import com.rookmotion.rook.sdk.domain.model.SyncStatusWithData import com.rooksdk.utils.DatasourceUtils import com.rooksdk.utils.DatasourceUtils.mapToDataSourceType import com.rooksdk.utils.PermissionConversion import com.rooksdk.utils.ReadableToWritable import com.rooksdk.utils.RookDateTime import com.rooksdk.utils.RookGsonBuilder import com.rooksdk.utils.SamsungAvailability import com.rooksdk.utils.Source import com.rooksdk.utils.StringToSyncType import io.tryrook.api.sources.RookApiSources import io.tryrook.api.sources.domain.environment.ApiEnvironment import io.tryrook.api.sources.domain.exception.ApiException import io.tryrook.api.sources.domain.model.ApiConfiguration import io.tryrook.sdk.samsung.RookSamsung import io.tryrook.sdk.samsung.domain.analytics.SHRookAnalytics import io.tryrook.sdk.samsung.domain.analytics.SHRookFramework import io.tryrook.sdk.samsung.domain.enums.SHRequestPermissionsStatus import io.tryrook.sdk.samsung.domain.enums.SHSyncStatus import io.tryrook.sdk.samsung.domain.enums.SamsungHealthAvailability import io.tryrook.sdk.samsung.domain.enums.SamsungHealthPermission import io.tryrook.sdk.samsung.domain.environment.SHEnvironment import io.tryrook.sdk.samsung.domain.exception.SHException import io.tryrook.sdk.samsung.domain.model.SHActivityEvent import io.tryrook.sdk.samsung.domain.model.SHBodySummary import io.tryrook.sdk.samsung.domain.model.SHConfiguration import io.tryrook.sdk.samsung.domain.model.SHPhysicalSummary import io.tryrook.sdk.samsung.domain.model.SHSleepSummary import io.tryrook.sdk.samsung.domain.model.SHSyncStatusWithData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch @ReactModule(name = RookSdkModule.NAME) class RookSdkModule(reactContext: ReactApplicationContext) : NativeRookSdkSpec(reactContext) { override fun getName(): String { return NAME } private val rookHealthConnect by lazy { RookSyncManager(reactContext) } private var scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) private val rookSync by lazy { RookSyncManager(reactContext) } private val rookStepsCounter: RookStepsCounter by lazy { RookStepsCounter(reactContext) } private val rookPermissionsManager: RookPermissionsManager by lazy { RookPermissionsManager(reactContext) } private val rookConfigurationManager: RookConfigurationManager by lazy { RookConfigurationManager(reactContext) } private val backgroundSyncManager: RookBackgroundSyncManager by lazy { RookBackgroundSyncManager(reactContext) } private val rookSamsung: RookSamsung by lazy { RookSamsung(reactContext) } private val rookApiSources: RookApiSources by lazy { RookApiSources(reactContext) } private val gsonBuilder: Gson by lazy { RookGsonBuilder.getGsonBuilder() } private fun tryToSetSamsungUserId() { scope.launch { val result = rookConfigurationManager.getUserID() if (result != null) { val user = rookSamsung.updateUserID(result) user.getOrNull() } } } override fun initRook( options: ReadableMap?, promise: Promise? ) { if (promise == null) return if (options == null) { promise.reject(code = "1001", message = "unknown exception") return } try { val clientUUID = options.getString("clientUUID")?.trim() ?: "" val secret = options.getString("secret")?.trim() ?: "" val packageName = options.getString("packageName")?.trim() if (clientUUID.isBlank() || secret.isBlank()) { promise.reject( code ="3", message = "Requested operation needs an authorization level that your clientUUID doesn't have." ) return } var environment = RookEnvironment.SANDBOX var shEnv = SHEnvironment.SANDBOX var apiEnv = ApiEnvironment.SANDBOX if (options.getString("environment") == "production") { environment = RookEnvironment.PRODUCTION shEnv = SHEnvironment.PRODUCTION apiEnv = ApiEnvironment.PRODUCTION } val rookConfiguration = RookConfiguration( environment = environment, clientUUID = clientUUID, packageName = packageName, secret = secret ) val shConfig = SHConfiguration( environment = shEnv, clientUUID = clientUUID, packageName = packageName, secret = secret ) val apiConfig = ApiConfiguration( environment = apiEnv, clientUUID = clientUUID, packageName = packageName, secret = secret ) val enableLogs = options.getBoolean("enableLogs") if(enableLogs) { rookConfigurationManager.enableLocalLogs() rookSamsung.enableLocalLogs() rookApiSources.enableLocalLogs() } rookConfigurationManager.setConfiguration(rookConfiguration) HCRookAnalytics.setFramework(HCRookFramework.REACT_NATIVE) SHRookAnalytics.setFramework(SHRookFramework.REACT_NATIVE) scope.launch { try { val result = rookConfigurationManager.initRook() rookApiSources.initRook(apiConfig) result.getOrThrow() val availableResult = SamsungAvailability.getSamsungHealthAvailabilityOrDefault(rookSamsung) if (availableResult == SamsungHealthAvailability.INSTALLED) { rookSamsung.initRook(shConfig) tryToSetSamsungUserId() } promise.resolve(true) } catch (e: Throwable) { when (e) { is HCException -> { promise.reject(e.code.toString(), e.message, e) } is SHException -> { promise.reject(e.code.toString(), e.message, e) } else -> { promise.reject("1001", e.message, e) } } } } } catch (e: Exception) { when (e) { is HCException -> { promise.reject(e.code.toString(), e.message, e) } is SHException -> { promise.reject(e.code.toString(), e.message, e) } else -> { promise.reject("1001", e.message, e) } } } } override fun revokeDataSource( userid: String?, type: String?, promise: Promise? ) { if (promise == null) return if (type == null || type == "") { promise.reject(code = "1001", message = "the type is missing") return } if (userid == null || userid == "") { promise.reject(code = "1001", message = "the user_id is missing") return } val parsed = mapToDataSourceType(type) if(parsed == null) { promise.reject(code = "1001", message = "Invalid datasource") return } scope.launch { rookApiSources.revokeDataSource(userID = userid, dataSource = parsed).fold({ promise.resolve(true) }, { if (it is ApiException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun getDataSourceAuthorizer( props: ReadableMap?, promise: Promise? ) { if(promise == null) return if (props == null){ promise.reject(code = "1001", message = "user and datasource missing") return } val source = props.getString("dataSource") ?: "" val redirect = props.getString("redirectURL") val userid = props.getString("userID") ?: "" if (source == "" || userid == "") { promise.reject(code = "1001", message = "user and datasource missing") return } scope.launch { rookApiSources.getDataSourceAuthorizer( dataSource = source, redirectUrl = redirect, userID = userid ).fold({ value -> promise.resolve(gsonBuilder.toJson(value)) }, { if (it is ApiException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun getAuthorizedDataSourcesV2( userid: String?, promise: Promise? ) { if(promise == null) return if(userid == null || userid == "") { promise.reject(code = "1001", message = "missing user id") return } scope.launch { rookApiSources.getAuthorizedDataSourcesV2( userID = userid ).fold( { promise.resolve(gsonBuilder.toJson(it)) }, { if (it is ApiException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun getUserID(promise: Promise?) { if (promise == null) return scope.launch { try { val user = rookConfigurationManager.getUserID() promise.resolve(user) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } } override fun updateUserID(userID: String?, promise: Promise?) { if(promise == null) return if (userID == null || userID == "") { promise.reject(code = "1001", message = "Missing user id") return } scope.launch { try { if (SamsungAvailability.isSamsungAvailable(rookSamsung)) { val samsungResult = rookSamsung.updateUserID(userID) if (samsungResult.isFailure) { println("We couldn't initiate the user id in Samsung Health") } samsungResult.getOrThrow() } val healthConnectResult = rookConfigurationManager.updateUserID(userID) if (healthConnectResult.isFailure) { println("We couldn't initiate the user id in Health Connect") } healthConnectResult.getOrThrow() promise.resolve(true) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } } override fun removeUserFromRook( sources: ReadableArray?, promise: Promise? ) { if(promise == null)return if (sources == null) { promise.reject(code = "1001", message = "Missing datasource") return } scope.launch { try { val sources = DatasourceUtils.readableArrayToSourceList(sources) if(Source.HEALTH_CONNECT in sources) { val hcResult = rookConfigurationManager.deleteUserFromRook() hcResult.getOrThrow() } if(Source.SAMSUNG_HEALTH in sources && SamsungAvailability.isSamsungAvailable(rookSamsung)) { val hcResult = rookSamsung.deleteUserFromRook() hcResult.getOrThrow() } promise.resolve(true) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } } override fun syncUserTimeZone(promise: Promise?) { if(promise == null) return scope.launch { val result = rookConfigurationManager.syncUserTimeZone() result.fold({ promise.resolve(true) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun getHealthConnectDiagnosticState(promise: Promise?) { if (promise == null) return scope.launch { try { val result = rookConfigurationManager.getDiagnosticState().getOrThrow() promise.resolve(gsonBuilder.toJson(result)) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } } override fun getSamsungHealthDiagnosticState(promise: Promise?) { if (promise == null) return scope.launch { try { val result = rookSamsung.getDiagnosticState().getOrThrow() promise.resolve(gsonBuilder.toJson(result)) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } } override fun isStepsAvailable(promise: Promise?) { if (promise == null) return promise.resolve(rookStepsCounter.isStepsCounterAvailable()) } override fun enableBackgroundAndroidSteps(promise: Promise?) { if(promise == null) return rookStepsCounter.enableStepsCounter().fold({ promise.resolve(true) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } override fun disableBackgroundAndroidSteps(promise: Promise?) { if(promise == null) return rookStepsCounter .disableStepsCounter() .fold({ promise.resolve(true) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } override fun isBackgroundAndroidStepsActive(promise: Promise?) { if(promise == null) return scope.launch { val response = rookStepsCounter.isStepsCounterActive() promise.resolve(response) } } override fun syncTodayAndroidStepsCount(promise: Promise?) { if(promise == null) return scope.launch { try { val steps = rookStepsCounter.getTodayStepsCount().getOrThrow() promise.resolve(steps.toString()) } catch (e: Exception) { promise.reject("1001", e.message, e) } } } override fun androidHasBackgroundPermissions(promise: Promise?) { if(promise == null) return try { val result = rookPermissionsManager.checkAndroidPermissions() promise.resolve(result) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } override fun androidHasAlarmPermissions(promise: Promise?) { if (promise == null) return try { val result = rookPermissionsManager.checkExactAlarmPermissions() promise.resolve(result) } catch (it: Exception) { promise.reject("1001", it.message, it) } } override fun checkHealthConnectAvailability(promise: Promise?) { if(promise == null) return val r = rookPermissionsManager.checkHealthConnectAvailability() when(r) { HealthConnectAvailability.INSTALLED -> promise.resolve("INSTALLED") HealthConnectAvailability.NOT_INSTALLED -> promise.resolve("NOT_INSTALLED") HealthConnectAvailability.NOT_SUPPORTED -> promise.resolve("NOT_SUPPORTED") } } override fun checkHealthConnectBackgroundReadStatus(promise: Promise?) { if(promise == null) return scope.launch { rookPermissionsManager.checkBackgroundReadStatus().fold( { status -> when (status) { BackgroundReadStatus.UNAVAILABLE -> promise.resolve("UNAVAILABLE") BackgroundReadStatus.PERMISSION_NOT_GRANTED -> promise.resolve("PERMISSION_NOT_GRANTED") BackgroundReadStatus.PERMISSION_GRANTED -> promise.resolve("PERMISSION_GRANTED") } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun checkHistoryReadStatus(promise: Promise?) { if(promise == null) return scope.launch { rookPermissionsManager.checkHistoryReadStatus().fold( { status -> when (status) { HistoryReadStatus.UNAVAILABLE -> promise.resolve("UNAVAILABLE") HistoryReadStatus.PERMISSION_NOT_GRANTED -> promise.resolve("PERMISSION_NOT_GRANTED") HistoryReadStatus.PERMISSION_GRANTED -> promise.resolve("PERMISSION_GRANTED") } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun checkSamsungAvailability(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.checkSamsungHealthAvailability().fold( { availability -> when (availability) { SamsungHealthAvailability.INSTALLED -> promise.resolve("INSTALLED") SamsungHealthAvailability.NOT_INSTALLED -> promise.resolve("NOT_INSTALLED") SamsungHealthAvailability.OUTDATED -> promise.resolve("OUTDATED") SamsungHealthAvailability.DISABLED -> promise.resolve("DISABLED") SamsungHealthAvailability.NOT_READY -> promise.resolve("NOT_READY") } }, { promise.reject(it) }, ) } } override fun healthConnectHasPartialPermissions(promise: Promise?) { if(promise == null) return scope.launch { val result = rookPermissionsManager.checkHealthConnectPermissionsPartially() result.fold({ promise.resolve(it) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun healthConnectHasPermissions(promise: Promise?) { if(promise == null) return scope.launch { val result = rookPermissionsManager.checkHealthConnectPermissions() result.fold({ promise.resolve(it) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun samsungHealthHasPermissions(promise: Promise?) { if(promise == null) return scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)){ promise.reject(Throwable("Samsung health is not available")) return@launch } rookSamsung.checkSamsungHealthPermissions(SamsungHealthPermission.entries.toSet()).fold( { hasAllPermissions -> promise.resolve(hasAllPermissions) }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun samsungHealthHasPartialPermissions(promise: Promise?) { if(promise == null) return scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)){ promise.reject(Throwable("Samsung health is not available")) return@launch } rookSamsung.checkSamsungHealthPermissionsPartially(SamsungHealthPermission.entries.toSet()).fold( { hasAllPermissions -> promise.resolve(hasAllPermissions) }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun openHealthConnectSettings(promise: Promise?) { if (promise == null) return scope.launch { val result = rookPermissionsManager.openHealthConnectSettings() result.fold({ promise.resolve(true) },{ if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun requestAndroidAlarmPermissions(promise: Promise?) { if (promise == null) return scope.launch { try { val response = rookPermissionsManager.requestExactAlarmPermissions() if (response == RequestPermissionsStatus.REQUEST_SENT) promise.resolve("REQUEST_SENT") else promise.resolve("ALREADY_GRANTED") } catch (it: Exception) { promise.reject("1001", it.message, it) } } } override fun requestAndroidBackgroundPermissions(promise: Promise?) { if (promise == null) return try { val response = rookPermissionsManager.requestAndroidPermissions() if (response == RequestPermissionsStatus.REQUEST_SENT) promise.resolve("REQUEST_SENT") else promise.resolve("ALREADY_GRANTED") } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } override fun requestHealthConnectPermissions(promise: Promise?) { if (promise == null) return scope.launch { rookPermissionsManager.requestHealthConnectPermissions().fold({ when(it) { RequestPermissionsStatus.REQUEST_SENT -> { promise.resolve("REQUEST_SENT") } RequestPermissionsStatus .ALREADY_GRANTED -> { promise.resolve("ALREADY_GRANTED") } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun requestSamsungHealthPermissions( permissions: ReadableArray?, promise: Promise? ) { if (promise == null) return if (permissions == null){ promise.reject(code = "1001", message = "Missing permissions") return } val shPermissions = PermissionConversion.parseSamsungPermissions(permissions) scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)) { promise.reject(Throwable("Samsung Health is not available")) return@launch } rookSamsung.requestSamsungHealthPermissions(shPermissions).fold( { when (it) { SHRequestPermissionsStatus.ALREADY_GRANTED -> promise.resolve("ALREADY_GRANTED") SHRequestPermissionsStatus.REQUEST_SENT -> promise.resolve("REQUEST_SENT") } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun revokeHealthConnectPermissions(promise: Promise?) { if(promise == null) return scope.launch { rookPermissionsManager.revokeHealthConnectPermissions() .fold({ promise.resolve(true) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun shouldRequestAndroidBackgroundPermissions(promise: Promise?) { if (promise == null) return val activity = reactApplicationContext.currentActivity if (activity == null) { promise.reject(Exception("Error trying to request permissions")) return } try { val r = RookPermissionsManager.shouldRequestAndroidPermissions(activity) promise.resolve(r) } catch (it: Exception) { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } } override fun checkBatteryOptimizationsDisabled(promise: Promise) { try { val isDisabled = rookPermissionsManager.checkBatteryOptimizationsDisabled() promise.resolve(isDisabled) } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun requestDisableBatteryOptimizations(promise: Promise) { try { val response = rookPermissionsManager.requestDisableBatteryOptimizations() if (response == RequestPermissionsStatus.REQUEST_SENT) promise.resolve("REQUEST_SENT") else promise.resolve("ALREADY_GRANTED") } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun requiresOemAutoStartSetup(promise: Promise) { try { val requiresSetup = rookPermissionsManager.requiresOemAutoStartSetup() promise.resolve(requiresSetup) } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun openOemAutoStartSetup(promise: Promise) { try { rookPermissionsManager.openOemAutoStartSetup().fold({ if (it == RequestPermissionsStatus.REQUEST_SENT) promise.resolve("REQUEST_SENT") else promise.resolve("ALREADY_GRANTED") }, { promise.reject("1001", it.message, it) }) } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun getHealthConnectSleepSummary( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "Missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookHealthConnect.getSleepSummary(localDate).fold( { when (it) { SyncStatusWithData.RecordsNotFound -> { promise.reject("HealthConnectSleepSummary", "Records Not Found For Date: $date") } is SyncStatusWithData.Synced> -> { val result =gsonBuilder.toJson(it.data) promise.resolve(result) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getSamsungSleepSummary( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "Missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookSamsung.getSleepSummary(localDate).fold( { when (it) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("SamsungSleepSummary", "Records Not Found For Date: $date") } is SHSyncStatusWithData.Synced> -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getHealthConnectBodySummary( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookHealthConnect.getBodySummary(localDate).fold( { when (it) { SyncStatusWithData.RecordsNotFound -> { promise.reject("HealthConnectBodySummary", "Records Not Found For Date: $date") } is SyncStatusWithData.Synced -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getSamsungBodySummary( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookSamsung.getBodySummary(localDate).fold( { when (it) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("SamsungBodySummary", "Records Not Found For Date: $date") } is SHSyncStatusWithData.Synced -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getHealthConnectPhysicalSummary( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookHealthConnect.getPhysicalSummary(localDate).fold( { when (it) { SyncStatusWithData.RecordsNotFound -> { promise.reject("HealthConnectPhysicalSummary", "Records Not Found For Date: $date") } is SyncStatusWithData.Synced -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getSamsungPhysicalSummary( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookSamsung.getPhysicalSummary(localDate).fold( { when (it) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("SamsungPhysicalSummary", "Records Not Found For Date: $date") } is SHSyncStatusWithData.Synced -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getHealthConnectActivityEvents( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookHealthConnect.getActivityEvents(localDate).fold( { when (it) { SyncStatusWithData.RecordsNotFound -> { promise.reject("HealthConnectActivityEvents", "Records Not Found For Date: $date") } is SyncStatusWithData.Synced> -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getSamsungActivityEvents( date: String?, promise: Promise? ) { if (promise == null) return if (date == null || date == ""){ promise.reject(code = "1001", message = "missing date") return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { rookSamsung.getActivityEvents(localDate).fold( { when (it) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("SamsungActivityEvents", "Records Not Found For Date: $date") } is SHSyncStatusWithData.Synced> -> { promise.resolve(gsonBuilder.toJson(it.data)) } } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun writeHealthConnectMealData( meal: ReadableMap?, promise: Promise? ) { if (promise == null) return if (meal == null){ promise.reject(code = "1001", message = "Missing meal data") return } val mealData = ReadableToWritable.mapReadableMapToHCMealData(meal) scope.launch { RookWriteManager.writeNutritionEvent(reactApplicationContext, mealData).fold({ promise.resolve(true) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun enableSamsungSync(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.schedule(true) promise.resolve(true) } } override fun disableSamsungSync(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.cancel() promise.resolve(true) } } override fun isSamsungSyncEnabled(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.isScheduled().fold( { promise.resolve(it) }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun scheduleBackgroundSync( enableLogs: Boolean?, promise: Promise? ) { if (promise == null) return try { backgroundSyncManager.schedule(enableLogs ?: false) promise.resolve(true) } catch (e: Exception) { if (e is HCException) { promise.reject(e.code.toString(), e.message, e) } else { promise.reject("1001", e.message, e) } } } override fun cancelBackgroundSync(promise: Promise?) { if (promise == null) return scope.launch { try { backgroundSyncManager.cancel() promise.resolve(true) } catch (e: Exception) { if (e is HCException) { promise.reject(e.code.toString(), e.message, e) } else { promise.reject("1001", e.message, e) } } } } override fun isBackgroundSyncEnabled(promise: Promise?) { if (promise == null) return scope.launch { backgroundSyncManager.isScheduled().fold( { promise.resolve(it) }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun syncTodaySamsungHealthStepsCount(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.getTodayStepsCount().fold({ when (it) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("SamsungStepsCount", "Records Not Found") } is SHSyncStatusWithData.Synced -> { val steps = it.data promise.resolve(steps) } } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun syncTodayHealthConnectStepsCount(promise: Promise?) { if (promise == null) return scope.launch { rookSync.getTodayStepsCount().fold( { when (it) { SyncStatusWithData.RecordsNotFound -> { promise.reject("HealthConnectStepsCount", "Records Not Found") } is SyncStatusWithData.Synced -> { val steps = it.data promise.resolve(steps) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun syncTodayCaloriesCount(promise: Promise?) { if (promise == null) return scope.launch { rookSync.getTodayCaloriesCount().fold( { when (it) { SyncStatusWithData.RecordsNotFound -> { promise.reject("7", "The SDK could not find any health data related with calories") } is SyncStatusWithData.Synced -> { val data = Arguments.createMap().apply { putDouble("basal", it.data.basal ?: 0.0) putDouble("active", it.data.active ?: 0.0) } promise.resolve(data) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun syncSHTodayCaloriesCount(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.getTodayCaloriesCount().fold( { when (it) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("7", "The SDK could not find any health data related with calories") } is SHSyncStatusWithData.Synced -> { val data = Arguments.createMap().apply { putDouble("basal", it.data.basal ?: 0.0) putDouble("active", it.data.active ?: 0.0) } promise.resolve(data) } } }, { if (it is SHException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } } ) } } override fun getTodayHeartRate(promise: Promise?) { if (promise == null) return scope.launch { rookSync.getTodayHeartRate().fold( { syncStatus -> when (syncStatus) { SyncStatusWithData.RecordsNotFound -> { promise.reject("7", "The SDK could not find any health data related with calories") } is SyncStatusWithData.Synced -> { promise.resolve(gsonBuilder.toJson(syncStatus.data)) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun getSHTodayHeartRate(promise: Promise?) { if (promise == null) return scope.launch { rookSamsung.getTodayHeartRate().fold( { syncStatus -> when (syncStatus) { SHSyncStatusWithData.RecordsNotFound -> { promise.reject("7", "The SDK could not find any health data related with calories") } is SHSyncStatusWithData.Synced -> { promise.resolve(gsonBuilder.toJson(syncStatus.data)) } } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }, ) } } override fun isStepsCounterAvailable(promise: Promise?) { if (promise == null) return try { val available = rookStepsCounter.isStepsCounterAvailable() promise.resolve(available) } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun isStepsCounterActive(promise: Promise?) { if (promise == null) return scope.launch { try { val active = rookStepsCounter.isStepsCounterActive() promise.resolve(active) } catch (e: Exception) { promise.reject("1001", e.message, e) } } } override fun enableStepsCounter(promise: Promise?) { if (promise == null) return try { // Using getOrThrow to trigger the catch block on Result.failure rookStepsCounter.enableStepsCounter().getOrThrow() promise.resolve(null) } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun disableStepsCounter(promise: Promise?) { if (promise == null) return try { rookStepsCounter.disableStepsCounter().getOrThrow() promise.resolve(null) } catch (e: Exception) { promise.reject("1001", e.message, e) } } override fun getTodayStepsCount(promise: Promise?) { if (promise == null) return scope.launch { try { val steps = rookStepsCounter.getTodayStepsCount().getOrThrow() promise.resolve(steps.toDouble()) } catch (e: Exception) { promise.reject("1001", e.message, e) } } } override fun sync(cb: Callback?) { if (cb == null) return scope.launch { rookSync.sync(true).fold({ result -> cb.invoke(null, result) }, { val params = Arguments.createMap().apply { if (it is HCException) { putString(it.code.toString(), it.message) } else { putString("1001", it.localizedMessage ?: it.message) } } cb.invoke(params, false) }) } } override fun syncByDate(date: String?, cb: Callback?) { if(cb == null ) return if (date == null || date == "") { cb.invoke(null, false) return } val localDate = RookDateTime.stringToLocalDate(date) scope.launch { val result = rookSync.sync(localDate) try { val sleepSummaryStatus = result.sleepSummary.getOrThrow() val physicalSummaryStatus = result.physicalSummary.getOrThrow() val bodySummaryStatus = result.bodySummary.getOrThrow() val noSleepData = sleepSummaryStatus == SyncStatus.RECORDS_NOT_FOUND val noPhysicalData = physicalSummaryStatus == SyncStatus.RECORDS_NOT_FOUND val noBodyData = bodySummaryStatus == SyncStatus.RECORDS_NOT_FOUND if (noSleepData && noPhysicalData && noBodyData) { val throwable = HCRecordsNotFoundException("Sleep, Physical and Body summary") val params = Arguments.createMap().apply { putString(throwable.code.toString(), throwable.message) } cb.invoke(params, false) } else { cb.invoke(null, true) } } catch (e: Exception) { val params = Arguments.createMap().apply { if (e is HCException){ putString(e.code.toString(), e.message) } else { putString("1001", e.message ?: "Unknown error") } } cb.invoke(params, false) } } } override fun syncByDefinition( summary: String?, date: String?, cb: Callback? ) { if(cb == null ) return if (date == null || date == "" || summary == null || summary == "") { cb.invoke(null, false) return } val localDate = RookDateTime.stringToLocalDate(date) val type = StringToSyncType.stringToSummary(summary) scope.launch { val result = rookSync.sync(localDate, type) result.onSuccess { when (it) { SyncStatus.RECORDS_NOT_FOUND -> { val throwable = HCRecordsNotFoundException(type.toString()) val params = Arguments.createMap().apply { putString(throwable.code.toString(), throwable.message) } cb.invoke(params, false) } SyncStatus.SYNCED -> cb.invoke(null, true) } } result.onFailure { val params = Arguments.createMap().apply { if (it is HCException) { putString(it.code.toString(), it.message) } else { putString("1001", it.localizedMessage ?: it.message) } } cb.invoke(params, false) } } } override fun syncEvent( date: String?, event: String?, promise: Promise? ) { if (promise == null) return if (event == null || event == "" || date == null || date == "") { promise.reject(code = "1001", message = "Missing parameters") return } val localDate = RookDateTime.stringToLocalDate(date) val type = StringToSyncType.stringToEvent(event) scope.launch { rookSync.syncEvents(localDate, type).fold({ result -> when(result) { SyncStatus.RECORDS_NOT_FOUND -> { val throwable = HCRecordsNotFoundException(type.toString()) promise.reject(throwable.code.toString(), throwable.message, throwable) } SyncStatus.SYNCED -> promise.resolve(true) } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun shSync(enableLogs: Boolean, cb: Callback?) { if (cb == null) return scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)){ val params = Arguments.createMap().apply { putString("5", "Samsung health is not available") } cb.invoke(params, false) return@launch } rookSamsung.sync(enableLogs).fold( { cb(null, true) }, { val params = Arguments.createMap().apply { if (it is SHException) { putString(it.code.toString(), it.message) } else { putString("1001", it.localizedMessage ?: it.message) } } cb.invoke(params, false) } ) } } override fun shSyncByDate(date: String?, cb: Callback?) { if (cb == null) return val localDate = RookDateTime.stringToLocalDate(date ?: "") scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)){ val params = Arguments.createMap().apply { putString("5", "Samsung health is not available") } cb.invoke(params, false) return@launch } val result = rookSamsung.sync(localDate) try { val sleepSummaryStatus = result.sleepSummary.getOrThrow() val physicalSummaryStatus = result.physicalSummary.getOrThrow() val bodySummaryStatus = result.bodySummary.getOrThrow() val noSleepData = sleepSummaryStatus == SHSyncStatus.RECORDS_NOT_FOUND val noPhysicalData = physicalSummaryStatus == SHSyncStatus.RECORDS_NOT_FOUND val noBodyData = bodySummaryStatus == SHSyncStatus.RECORDS_NOT_FOUND if (noSleepData && noPhysicalData && noBodyData) { val throwable = HCRecordsNotFoundException("Sleep, Physical and Body summary") val params = Arguments.createMap().apply { putString(throwable.code.toString(), throwable.message) } cb.invoke(params, false) } else { cb.invoke(null, true) } } catch (e: Exception) { val params = Arguments.createMap().apply { if (e is HCException){ putString(e.code.toString(), e.message) } else { putString("1001", e.message ?: "Unknown error") } } cb.invoke(params, false) } } } override fun shSyncByDefinition( summary: String?, date: String?, cb: Callback? ) { if (cb == null) return if (summary == null || date == null) { cb.invoke(null, false) return } val localDate = RookDateTime.stringToLocalDate(date) val type = StringToSyncType.stringToSamsungPillar(summary) scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)){ val params = Arguments.createMap().apply { putString("5", "Samsung health is not available") } cb.invoke(params, false) return@launch } val result = rookSamsung.sync(localDate, type) result.onSuccess { when (it) { SHSyncStatus.RECORDS_NOT_FOUND -> { val throwable = HCRecordsNotFoundException(type.toString()) val params = Arguments.createMap().apply { putString(throwable.code.toString(), throwable.message) } cb.invoke(params, false) } SHSyncStatus.SYNCED -> cb.invoke(null, true) } } result.onFailure { val params = Arguments.createMap().apply { if (it is HCException) { putString(it.code.toString(), it.message) } else { putString("1001", it.localizedMessage ?: it.message) } } cb.invoke(params, false) } } } override fun shSyncEvent( date: String?, event: String?, promise: Promise? ) { if(promise == null) return if (event == null || date == null){ promise.reject(code = "1001", message = "Missing parameters") return } val localDate = RookDateTime.stringToLocalDate(date) val type = StringToSyncType.stringToSamsungEvent(event) scope.launch { if (!SamsungAvailability.isSamsungAvailable(rookSamsung)){ promise.reject( "5", "Samsung health is not available", Throwable("Samsung health is not available") ) return@launch } rookSamsung.syncEvents(localDate, type).fold({ result -> when(result) { SHSyncStatus.RECORDS_NOT_FOUND -> { val throwable = HCRecordsNotFoundException(type.toString()) promise.reject(throwable.code.toString(), throwable.message, throwable) } SHSyncStatus.SYNCED -> promise.resolve(true) } }, { if (it is HCException) { promise.reject(it.code.toString(), it.message, it) } else { promise.reject("1001", it.message, it) } }) } } override fun sendMessage( message: ReadableMap?, promise: Promise? ) { if (message == null || promise == null || !reactApplicationContext.hasActiveReactInstance()) return val hash = ReadableToWritable.readableMapToHashMap(message) val writable = ReadableToWritable.hashMapToWritableMap(hash) emitOnRookMessage(writable) promise.resolve(true) } // ios methods private fun rejectFunction(promise: Promise) { promise.reject("1001", "This method is only available in android") } override fun getDiagnosticState(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun enableBackGroundUpdates(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun disableBackGroundUpdates(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun isBackgroundUpdatesEnabled(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun appleHealthHasPermissions( param: String?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun openAppleHealthSettings(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun requestAppleHealthPermissions( permissions: ReadableArray?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun requestAppleWriteNutritionPermission(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun getAppleHealthSleepSummary( date: String?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun getAppleHealthBodySummary( date: String?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun getAppleHealthPhysicalSummary( date: String?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun getAppleHealthActivityEvents( date: String?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun writeAppleHealthMealData( meal: ReadableMap?, promise: Promise? ) { if (promise == null) return rejectFunction(promise) } override fun getTodayAppleHealthSteps(promise: Promise?) { if (promise == null) return rejectFunction(promise) } override fun getTodayAppleHealthStepCountBySource(promise: Promise?) { if (promise == null) return rejectFunction(promise) } companion object { const val NAME = "RNRookSdk" } }