react-native-visit-rn-sdk 6.0.4 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +297 -191
  2. package/android/build.gradle +4 -1
  3. package/android/gradle.properties +4 -4
  4. package/android/src/main/AndroidManifest.xml +11 -5
  5. package/android/src/main/AndroidManifestNew.xml +11 -5
  6. package/android/src/main/java/com/visitrnsdk/VisitFitnessModule.kt +642 -0
  7. package/android/src/main/java/com/visitrnsdk/VisitRnSdkPackage.kt +1 -1
  8. package/android/src/main/java/com/visitrnsdk/VisitSessionStorage.kt +50 -0
  9. package/ios/VisitRnSdkViewManager.h +23 -1
  10. package/ios/VisitRnSdkViewManager.m +1259 -8
  11. package/lib/commonjs/index.android.js +328 -205
  12. package/lib/commonjs/index.android.js.map +1 -1
  13. package/lib/commonjs/index.ios.js +159 -116
  14. package/lib/commonjs/index.ios.js.map +1 -1
  15. package/lib/module/index.android.js +328 -206
  16. package/lib/module/index.android.js.map +1 -1
  17. package/lib/module/index.ios.js +161 -117
  18. package/lib/module/index.ios.js.map +1 -1
  19. package/lib/typescript/index.android.d.ts +8 -3
  20. package/lib/typescript/index.android.d.ts.map +1 -1
  21. package/lib/typescript/index.ios.d.ts +6 -3
  22. package/lib/typescript/index.ios.d.ts.map +1 -1
  23. package/package.json +18 -26
  24. package/react-native-visit-rn-sdk.podspec +2 -1
  25. package/src/index.android.js +579 -0
  26. package/src/index.ios.js +284 -0
  27. package/android/src/main/java/com/visitrnsdk/VisitRnSdkLocationModule.kt +0 -37
  28. package/lib/commonjs/assets/video-call/connecting-lottie.gif +0 -0
  29. package/lib/commonjs/assets/video-call/end-call.png +0 -0
  30. package/lib/commonjs/assets/video-call/mic-off.png +0 -0
  31. package/lib/commonjs/assets/video-call/reconnecting.gif +0 -0
  32. package/lib/commonjs/assets/video-call/switch-camera.png +0 -0
  33. package/lib/commonjs/assets/video-call/toggle-down.png +0 -0
  34. package/lib/commonjs/assets/video-call/toggle-up.png +0 -0
  35. package/lib/commonjs/assets/video-call/video-off.png +0 -0
  36. package/lib/commonjs/components/VideoCallComponent.js +0 -1088
  37. package/lib/commonjs/components/VideoCallComponent.js.map +0 -1
  38. package/lib/commonjs/index.js +0 -6
  39. package/lib/commonjs/index.js.map +0 -1
  40. package/lib/commonjs/shims.d.js +0 -2
  41. package/lib/commonjs/shims.d.js.map +0 -1
  42. package/lib/commonjs/types.js +0 -2
  43. package/lib/commonjs/types.js.map +0 -1
  44. package/lib/module/assets/video-call/connecting-lottie.gif +0 -0
  45. package/lib/module/assets/video-call/end-call.png +0 -0
  46. package/lib/module/assets/video-call/mic-off.png +0 -0
  47. package/lib/module/assets/video-call/reconnecting.gif +0 -0
  48. package/lib/module/assets/video-call/switch-camera.png +0 -0
  49. package/lib/module/assets/video-call/toggle-down.png +0 -0
  50. package/lib/module/assets/video-call/toggle-up.png +0 -0
  51. package/lib/module/assets/video-call/video-off.png +0 -0
  52. package/lib/module/components/VideoCallComponent.js +0 -1081
  53. package/lib/module/components/VideoCallComponent.js.map +0 -1
  54. package/lib/module/index.js +0 -2
  55. package/lib/module/index.js.map +0 -1
  56. package/lib/module/shims.d.js +0 -2
  57. package/lib/module/shims.d.js.map +0 -1
  58. package/lib/module/types.js +0 -2
  59. package/lib/module/types.js.map +0 -1
  60. package/lib/typescript/components/VideoCallComponent.d.ts +0 -79
  61. package/lib/typescript/components/VideoCallComponent.d.ts.map +0 -1
  62. package/lib/typescript/index.d.ts +0 -17
  63. package/lib/typescript/index.d.ts.map +0 -1
  64. package/lib/typescript/types.d.ts +0 -24
  65. package/lib/typescript/types.d.ts.map +0 -1
  66. package/src/assets/video-call/connecting-lottie.gif +0 -0
  67. package/src/assets/video-call/end-call.png +0 -0
  68. package/src/assets/video-call/mic-off.png +0 -0
  69. package/src/assets/video-call/reconnecting.gif +0 -0
  70. package/src/assets/video-call/switch-camera.png +0 -0
  71. package/src/assets/video-call/toggle-down.png +0 -0
  72. package/src/assets/video-call/toggle-up.png +0 -0
  73. package/src/assets/video-call/video-off.png +0 -0
  74. package/src/components/VideoCallComponent.tsx +0 -1484
  75. package/src/index.android.tsx +0 -459
  76. package/src/index.ios.tsx +0 -238
  77. package/src/index.tsx +0 -25
  78. package/src/shims.d.ts +0 -49
  79. package/src/types.ts +0 -25
@@ -0,0 +1,642 @@
1
+ package com.visitrnsdk
2
+
3
+ import android.app.Activity
4
+ import android.content.Intent
5
+ import android.net.Uri
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.util.Log
9
+ import androidx.annotation.Keep
10
+ import androidx.activity.result.ActivityResultLauncher
11
+ import androidx.activity.result.ActivityResultRegistryOwner
12
+ import androidx.health.connect.client.PermissionController
13
+ import com.facebook.react.bridge.Promise
14
+ import com.facebook.react.bridge.ReactApplicationContext
15
+ import com.facebook.react.bridge.ReactContext
16
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
17
+ import com.facebook.react.bridge.ReactMethod
18
+ import com.facebook.react.modules.core.DeviceEventManagerModule
19
+ import com.getvisitapp.visit.HealthConnectListener
20
+ import com.getvisitapp.visit.data.VisitStepSyncHelper
21
+ import com.getvisitapp.visit.healthConnect.activity.HealthConnectUtil
22
+ import com.getvisitapp.visit.healthConnect.contants.Contants.previouslyRevoked
23
+ import com.getvisitapp.visit.healthConnect.enums.HealthConnectConnectionState
24
+ import com.getvisitapp.visit.healthConnect.enums.HealthConnectConnectionState.CONNECTED
25
+ import com.getvisitapp.visit.healthConnect.enums.HealthConnectConnectionState.INSTALLED
26
+ import com.getvisitapp.visit.healthConnect.enums.HealthConnectConnectionState.NONE
27
+ import com.getvisitapp.visit.healthConnect.enums.HealthConnectConnectionState.NOT_INSTALLED
28
+ import com.getvisitapp.visit.healthConnect.enums.HealthConnectConnectionState.NOT_SUPPORTED
29
+ import kotlinx.coroutines.CancellationException
30
+ import kotlinx.coroutines.Dispatchers
31
+ import kotlinx.coroutines.launch
32
+ import kotlinx.coroutines.withContext
33
+ import timber.log.Timber
34
+
35
+ @Keep
36
+ class VisitFitnessModule(reactContext: ReactApplicationContext) :
37
+ ReactContextBaseJavaModule(reactContext), HealthConnectListener {
38
+
39
+ private companion object {
40
+ private const val HEALTH_CONNECT_PERMISSION_REQUEST_CODE = 7021
41
+ }
42
+
43
+ private val TAG = "mytag"
44
+ private val reactContext: ReactContext = reactContext
45
+ private val reactApplicationContext: ReactApplicationContext = reactContext
46
+
47
+ private var promise: Promise? = null
48
+
49
+ private var healthConnectStatusPromise: Promise? = null
50
+ private var permissionPromise: Promise? = null
51
+ private var isLoggingEnabled = false
52
+
53
+ private var visitStepSyncHelper: VisitStepSyncHelper? = null
54
+ private var healthConnectUtil: HealthConnectUtil? = null
55
+ private var syncDataWithServer = false
56
+
57
+ @Volatile
58
+ private var isSyncInProgress = false
59
+ private var mainActivity: Activity? = null
60
+
61
+ private lateinit var visitSessionStorage: VisitSessionStorage
62
+ private val requestPermissionActivityContract =
63
+ PermissionController.createRequestPermissionResultContract()
64
+ private var requestPermissionsLauncher: ActivityResultLauncher<Set<String>>? = null
65
+ private var requestPermissionsLauncherActivity: Activity? = null
66
+
67
+ init {
68
+ Log.d(TAG, "GoogleFitPermissionModule: inside constructor")
69
+ }
70
+
71
+ @ReactMethod
72
+ fun initiateSDK(isLoggingEnabled: Boolean) {
73
+ this.isLoggingEnabled = isLoggingEnabled
74
+ configureTimber(isLoggingEnabled)
75
+ Timber.d("mytag: initiateSDK %b", isLoggingEnabled)
76
+ mainActivity = reactApplicationContext.currentActivity
77
+
78
+ //don't initialise the native module if the mainActivity instance is null.
79
+ if (mainActivity == null) {
80
+ Timber.d("mytag: initiateSDK() skipped because currentActivity is null")
81
+ return
82
+ }
83
+ visitStepSyncHelper = VisitStepSyncHelper(mainActivity!!)
84
+ healthConnectUtil = HealthConnectUtil(mainActivity!!, this)
85
+ healthConnectUtil!!.initialize()
86
+ visitSessionStorage = VisitSessionStorage(mainActivity!!)
87
+
88
+ Timber.d("mytag: initiateSDK() called")
89
+ }
90
+
91
+ @ReactMethod
92
+ fun getHealthConnectStatus(healthConnectStatusPromise: Promise) {
93
+ this.healthConnectStatusPromise = healthConnectStatusPromise
94
+
95
+ Timber.d("mytag: getHealthConnectStatus called")
96
+
97
+ healthConnectUtil?.scope?.launch {
98
+ val status: HealthConnectConnectionState = healthConnectUtil!!.checkAvailability()
99
+
100
+ withContext(Dispatchers.Main) {
101
+ when (status) {
102
+ NOT_SUPPORTED -> {
103
+ healthConnectStatusPromise.resolve("NOT_SUPPORTED")
104
+ }
105
+
106
+ NOT_INSTALLED -> {
107
+ healthConnectStatusPromise.resolve("NOT_INSTALLED")
108
+ }
109
+
110
+ INSTALLED -> {
111
+ healthConnectStatusPromise.resolve("INSTALLED")
112
+ }
113
+
114
+ CONNECTED -> {
115
+ healthConnectStatusPromise.resolve("CONNECTED")
116
+ }
117
+
118
+ NONE -> {
119
+
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+
126
+ @ReactMethod
127
+ fun askForFitnessPermission(promise: Promise) {
128
+ val util = healthConnectUtil
129
+ if (util == null) {
130
+ promise.reject("SDK_NOT_INITIALIZED", "Initialize the SDK before connecting Health Connect")
131
+ return
132
+ }
133
+
134
+ util.scope.launch {
135
+ try {
136
+ val status = util.checkAvailability()
137
+ withContext(Dispatchers.Main) {
138
+ when (status) {
139
+ CONNECTED -> promise.resolve("GRANTED")
140
+ INSTALLED -> {
141
+ if (permissionPromise == null) {
142
+ permissionPromise = promise
143
+ util.requestPermission()
144
+ } else {
145
+ promise.reject("PERMISSION_IN_PROGRESS", "Health Connect permissions are already open")
146
+ }
147
+ }
148
+ NOT_INSTALLED -> {
149
+ util.requestPermission()
150
+ promise.resolve(status.name)
151
+ }
152
+ NOT_SUPPORTED, NONE -> promise.resolve(status.name)
153
+ }
154
+ }
155
+ } catch (error: CancellationException) {
156
+ throw error
157
+ } catch (error: Exception) {
158
+ promise.reject("HEALTH_CONNECT_PERMISSION_ERROR", error)
159
+ }
160
+ }
161
+ }
162
+
163
+ override fun userAcceptedHealthConnectPermission() = finishPermissionRequest("GRANTED")
164
+
165
+ override fun userDeniedHealthConnectPermission() = finishPermissionRequest("CANCELLED")
166
+
167
+ private fun finishPermissionRequest(result: String) {
168
+ Handler(Looper.getMainLooper()).post {
169
+ val pending = permissionPromise
170
+ permissionPromise = null
171
+ pending?.resolve(result)
172
+ }
173
+ }
174
+
175
+ @ReactMethod
176
+ fun requestDailyFitnessData(promise: Promise) {
177
+ loadHealthConnectGraph(promise) { it.loadDashboardGraph() }
178
+ }
179
+
180
+ @ReactMethod
181
+ fun requestActivityDataFromHealthConnect(
182
+ type: String?, frequency: String?, timestamp: Double, promise: Promise
183
+ ) {
184
+ loadHealthConnectGraph(promise, requestPermissionIfDisconnected = true) {
185
+ it.loadActivityGraph(type, frequency, Math.round(timestamp))
186
+ }
187
+ }
188
+
189
+ private fun loadHealthConnectGraph(
190
+ promise: Promise,
191
+ requestPermissionIfDisconnected: Boolean = false,
192
+ loadGraph: suspend (HealthConnectUtil) -> String?
193
+ ) {
194
+ val util = healthConnectUtil
195
+ if (util == null) {
196
+ promise.reject("SDK_NOT_INITIALIZED", "Initialize the SDK before loading Health Connect data")
197
+ return
198
+ }
199
+
200
+ util.scope.launch {
201
+ try {
202
+ if (util.healthConnectConnectionState == CONNECTED) {
203
+ promise.resolve(loadGraph(util))
204
+ } else {
205
+ if (requestPermissionIfDisconnected) {
206
+ withContext(Dispatchers.Main) {
207
+ if (permissionPromise == null) util.requestPermission()
208
+ }
209
+ }
210
+ promise.resolve(null)
211
+ }
212
+ } catch (error: CancellationException) {
213
+ throw error
214
+ } catch (error: Exception) {
215
+ promise.reject("HEALTH_CONNECT_GRAPH_ERROR", error)
216
+ }
217
+ }
218
+ }
219
+
220
+ @ReactMethod
221
+ fun updateApiBaseUrl(
222
+ apiBaseUrl: String,
223
+ authToken: String,
224
+ googleFitLastSync: Double,
225
+ gfHourlyLastSync: Double,
226
+ promise: Promise?
227
+ ) {
228
+ if (isLoggingEnabled) {
229
+ Log.d(
230
+ "mytag",
231
+ "GoogleFitPermissionModule syncDataWithServer(): baseUrl: " + apiBaseUrl + " googleFitLastSync: " + googleFitLastSync + " gfHourlyLastSync:" + gfHourlyLastSync
232
+ )
233
+ }
234
+
235
+ if (!::visitSessionStorage.isInitialized) {
236
+ promise?.resolve("Health SDK Not Initialized")
237
+ return
238
+ }
239
+
240
+ val normalizedBaseUrl = normalizeBaseUrl(apiBaseUrl)
241
+
242
+ visitSessionStorage.saveBaseUrl(normalizedBaseUrl)
243
+ visitSessionStorage.saveVisitAuthToken(authToken)
244
+ visitSessionStorage.saveDailyLastSyncTimeStamp(Math.round(googleFitLastSync))
245
+ visitSessionStorage.saveHourlyLastSyncTimeStamp(Math.round(gfHourlyLastSync))
246
+
247
+ val healthConnectUtil = healthConnectUtil
248
+ val visitStepSyncHelper = visitStepSyncHelper
249
+
250
+ if (healthConnectUtil == null || visitStepSyncHelper == null) {
251
+ promise?.resolve("Health SDK Not Initialized")
252
+ return
253
+ }
254
+
255
+ if (isSyncInProgress) {
256
+ promise?.resolve("Health Data Sync Already In Progress")
257
+ return
258
+ }
259
+
260
+ if (!syncDataWithServer) {
261
+ Timber.d("mytag: syncDataWithServer() called")
262
+ isSyncInProgress = true
263
+ visitStepSyncHelper.sendDataToVisitServer(
264
+ healthConnectUtil,
265
+ Math.round(googleFitLastSync),
266
+ Math.round(gfHourlyLastSync),
267
+ normalizedBaseUrl,
268
+ authToken,
269
+ onSuccess = { message ->
270
+ isSyncInProgress = false
271
+ Timber.d("mytag: syncDataWithServer() completed. $message")
272
+ },
273
+ onFailure = { reason ->
274
+ isSyncInProgress = false
275
+ syncDataWithServer = false
276
+ Timber.d("mytag: syncDataWithServer() failed. $reason")
277
+ }
278
+ )
279
+ syncDataWithServer = true
280
+ promise?.resolve("Health Data Sync Started")
281
+ } else {
282
+ promise?.resolve("Health Data Already Synced")
283
+ }
284
+
285
+
286
+ }
287
+
288
+ @ReactMethod
289
+ fun openHraLink(link: String?) {
290
+ try {
291
+ val i = Intent(Intent.ACTION_VIEW)
292
+ i.setData(Uri.parse(link))
293
+ currentActivityOrCached()?.startActivity(i)
294
+ } catch (e: Exception) {
295
+ e.printStackTrace()
296
+ }
297
+ }
298
+
299
+ @ReactMethod
300
+ fun fetchDailyFitnessData(timestamp: Double, promise: Promise?) {
301
+ this.promise = promise
302
+ // TODO: to be implemented in the future.
303
+ }
304
+
305
+ @ReactMethod
306
+ fun fetchHourlyFitnessData(timestamp: Double, promise: Promise?) {
307
+ this.promise = promise
308
+ // TODO: to be implemented in the future.
309
+ }
310
+
311
+ @ReactMethod
312
+ fun openHealthConnectApp(promise: Promise?) {
313
+ this.promise = promise
314
+ healthConnectUtil?.openHealthConnectApp();
315
+ }
316
+
317
+ override fun getName(): String {
318
+ return "VisitFitnessModule"
319
+ }
320
+
321
+ override fun loadVisitWebViewGraphData(webUrl: String) {
322
+ if (isLoggingEnabled) Timber.d("Health Connect graph data delivered to legacy listener")
323
+ }
324
+
325
+ override fun requestPermission() {
326
+ Timber.d("requestPermission called 218")
327
+ Handler(Looper.getMainLooper()).post {
328
+ val activity = currentActivityOrCached()
329
+ val healthConnectUtil = healthConnectUtil
330
+
331
+ if (activity == null || healthConnectUtil == null) {
332
+ Timber.d(
333
+ "requestPermission skipped. activityReady=%s, healthConnectUtilReady=%s",
334
+ activity != null,
335
+ healthConnectUtil != null
336
+ )
337
+ userDeniedHealthConnectPermission()
338
+ return@post
339
+ }
340
+
341
+ val launcher = getOrCreatePermissionLauncher(activity)
342
+ if (launcher == null) {
343
+ val exception = IllegalStateException(
344
+ "Current activity must implement ActivityResultRegistryOwner to request Health Connect permissions"
345
+ )
346
+ Timber.e(exception, "requestPermission failed")
347
+ logHealthConnectError(exception)
348
+ userDeniedHealthConnectPermission()
349
+ return@post
350
+ }
351
+
352
+ try {
353
+ launcher.launch(healthConnectUtil.PERMISSIONS)
354
+ } catch (exception: Exception) {
355
+ Timber.e(exception, "requestPermission failed")
356
+ logHealthConnectError(exception)
357
+ userDeniedHealthConnectPermission()
358
+ }
359
+ }
360
+ }
361
+
362
+ override fun updateHealthConnectConnectionStatus(
363
+ status: HealthConnectConnectionState, text: String
364
+ ) {
365
+ Timber.d("updateHealthConnectConnectionStatus: %s %s", status, text)
366
+
367
+ when (status) {
368
+ CONNECTED -> {}
369
+ NOT_SUPPORTED -> {}
370
+ NOT_INSTALLED -> {}
371
+ INSTALLED -> {}
372
+ NONE -> {}
373
+ }
374
+ }
375
+
376
+ override fun logHealthConnectError(throwable: Throwable) {
377
+ //pass it via a callback.
378
+ throwable.message?.let {
379
+ val formattedMessage = "${throwable.javaClass}: ${throwable.message}"
380
+ Timber.d("mytag: logHealthConnectError= $formattedMessage")
381
+
382
+ sendMessageToReactNative(formattedMessage)
383
+ }
384
+ }
385
+
386
+ private fun sendMessageToReactNative(message: String) {
387
+ Timber.d("mytag: sendMessageToReactNative called()")
388
+ reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
389
+ .emit("onMessage", message) // "onMessage" is the event name
390
+ }
391
+
392
+
393
+ @ReactMethod
394
+ fun getTodayStepCount(promise: Promise?) {
395
+ healthConnectUtil?.let { healthConnectUtil ->
396
+ healthConnectUtil.scope.launch {
397
+ try {
398
+ val stepsCount = healthConnectUtil.getTodayStepData()
399
+ promise?.resolve(stepsCount.toInt())
400
+ } catch (e: Exception) {
401
+ promise?.reject(e)
402
+ }
403
+ }
404
+ }
405
+ }
406
+
407
+ @ReactMethod
408
+ fun getTodaySleepMinutes(promise: Promise?) {
409
+ healthConnectUtil?.let { healthConnectUtil ->
410
+ healthConnectUtil.scope.launch {
411
+ try {
412
+ val sleepMinutes = healthConnectUtil.getTodaySleepData()
413
+ promise?.resolve(sleepMinutes.toInt())
414
+ } catch (e: Exception) {
415
+ promise?.reject(e)
416
+ }
417
+ }
418
+ }
419
+ }
420
+
421
+ @ReactMethod
422
+ fun getTodayCalorieCount(promise: Promise?) {
423
+ healthConnectUtil?.let { healthConnectUtil ->
424
+ healthConnectUtil.scope.launch {
425
+ try {
426
+ val calorieCount = healthConnectUtil.getTodayCalorieData()
427
+ promise?.resolve(calorieCount.toInt())
428
+ } catch (e: Exception) {
429
+ promise?.reject(e)
430
+ }
431
+ }
432
+ }
433
+ }
434
+
435
+
436
+ @ReactMethod
437
+ fun triggerManualSync(promise: Promise?) {
438
+
439
+ val manualSyncStartedAt = System.currentTimeMillis()
440
+
441
+ Timber.d(
442
+ "mytag: triggerManualSync() called. storageInitialized=%s, healthConnectUtilReady=%s, visitStepSyncHelperReady=%s, isSyncInProgress=%s",
443
+ ::visitSessionStorage.isInitialized,
444
+ healthConnectUtil != null,
445
+ visitStepSyncHelper != null,
446
+ isSyncInProgress
447
+ )
448
+
449
+ if (!::visitSessionStorage.isInitialized) {
450
+ Timber.d(
451
+ "mytag: triggerManualSync() rejected. code=SDK_NOT_INITIALIZED, reason=visitSessionStorage not initialized, elapsedMs=%s",
452
+ System.currentTimeMillis() - manualSyncStartedAt
453
+ )
454
+ rejectPromiseOnMainThread(promise, "SDK_NOT_INITIALIZED", "Health SDK is not initialized")
455
+ return
456
+ }
457
+
458
+ val healthConnectUtil = healthConnectUtil
459
+ val visitStepSyncHelper = visitStepSyncHelper
460
+
461
+ if (healthConnectUtil == null || visitStepSyncHelper == null) {
462
+ Timber.d(
463
+ "mytag: triggerManualSync() rejected. code=SDK_NOT_INITIALIZED, healthConnectUtilReady=%s, visitStepSyncHelperReady=%s, elapsedMs=%s",
464
+ healthConnectUtil != null,
465
+ visitStepSyncHelper != null,
466
+ System.currentTimeMillis() - manualSyncStartedAt
467
+ )
468
+ rejectPromiseOnMainThread(promise, "SDK_NOT_INITIALIZED", "Health SDK is not initialized")
469
+ return
470
+ }
471
+
472
+ if (isSyncInProgress) {
473
+ Timber.d(
474
+ "mytag: triggerManualSync() rejected. code=SYNC_IN_PROGRESS, elapsedMs=%s",
475
+ System.currentTimeMillis() - manualSyncStartedAt
476
+ )
477
+ rejectPromiseOnMainThread(
478
+ promise,
479
+ "SYNC_IN_PROGRESS",
480
+ "Health data sync is already in progress"
481
+ )
482
+ return
483
+ }
484
+
485
+ val baseUrl = visitSessionStorage.getBaseURL()
486
+ val authToken = visitSessionStorage.getVisitAuthToken()
487
+ val dailyLastSyncTimeStamp = visitSessionStorage.getDailyLastSyncTimestamp()
488
+ val hourlyLastSyncTimestamp = visitSessionStorage.getHourlyLastSyncTimeStamp()
489
+
490
+ Timber.d(
491
+ "mytag: triggerManualSync() sync inputs loaded. baseUrl=%s, authTokenPresent=%s, dailyLastSyncTimeStamp=%s, hourlyLastSyncTimestamp=%s",
492
+ baseUrl,
493
+ !authToken.isNullOrBlank(),
494
+ dailyLastSyncTimeStamp,
495
+ hourlyLastSyncTimestamp
496
+ )
497
+
498
+ if (baseUrl.isNullOrBlank() || authToken.isNullOrBlank()) {
499
+ Timber.d(
500
+ "mytag: triggerManualSync() rejected. code=MISSING_SYNC_CREDENTIALS, baseUrlPresent=%s, authTokenPresent=%s, elapsedMs=%s",
501
+ !baseUrl.isNullOrBlank(),
502
+ !authToken.isNullOrBlank(),
503
+ System.currentTimeMillis() - manualSyncStartedAt
504
+ )
505
+ rejectPromiseOnMainThread(
506
+ promise,
507
+ "MISSING_SYNC_CREDENTIALS",
508
+ "Visit sync base URL or auth token is missing"
509
+ )
510
+ return
511
+ }
512
+
513
+ if (dailyLastSyncTimeStamp < 0 || hourlyLastSyncTimestamp < 0) {
514
+ Timber.d(
515
+ "mytag: triggerManualSync() rejected. code=MISSING_SYNC_TIMESTAMPS, dailyLastSyncTimeStamp=%s, hourlyLastSyncTimestamp=%s, elapsedMs=%s",
516
+ dailyLastSyncTimeStamp,
517
+ hourlyLastSyncTimestamp,
518
+ System.currentTimeMillis() - manualSyncStartedAt
519
+ )
520
+ rejectPromiseOnMainThread(
521
+ promise,
522
+ "MISSING_SYNC_TIMESTAMPS",
523
+ "Visit sync timestamps are missing"
524
+ )
525
+ return
526
+ }
527
+
528
+ Timber.d(
529
+ "mytag: triggerManualSync() dispatching sendDataToVisitServer. baseUrl=%s, dailyLastSyncTimeStamp=%s, hourlyLastSyncTimestamp=%s",
530
+ baseUrl,
531
+ dailyLastSyncTimeStamp,
532
+ hourlyLastSyncTimestamp
533
+ )
534
+ isSyncInProgress = true
535
+ visitStepSyncHelper.sendDataToVisitServer(
536
+ healthConnectUtil = healthConnectUtil,
537
+ googleFitLastSync = dailyLastSyncTimeStamp,
538
+ gfHourlyLastSync = hourlyLastSyncTimestamp,
539
+ visitBaseUrl = baseUrl,
540
+ visitAuthToken = authToken,
541
+ onSuccess = { message ->
542
+ isSyncInProgress = false
543
+ Timber.d(
544
+ "mytag: triggerManualSync() succeeded. elapsedMs=%s, message=%s",
545
+ System.currentTimeMillis() - manualSyncStartedAt,
546
+ message
547
+ )
548
+ resolvePromiseOnMainThread(promise, message)
549
+ },
550
+ onFailure = { reason ->
551
+ isSyncInProgress = false
552
+ Timber.d(
553
+ "mytag: triggerManualSync() failed. elapsedMs=%s, reason=%s",
554
+ System.currentTimeMillis() - manualSyncStartedAt,
555
+ reason
556
+ )
557
+ rejectPromiseOnMainThread(promise, "SYNC_FAILED", reason)
558
+ }
559
+ )
560
+ }
561
+
562
+ private fun normalizeBaseUrl(baseUrl: String): String {
563
+ val trimmedBaseUrl = baseUrl.trim()
564
+ return if (trimmedBaseUrl.endsWith("/")) trimmedBaseUrl else "$trimmedBaseUrl/"
565
+ }
566
+
567
+ private fun resolvePromiseOnMainThread(promise: Promise?, value: String) {
568
+ Handler(Looper.getMainLooper()).post {
569
+ promise?.resolve(value)
570
+ }
571
+ }
572
+
573
+ private fun rejectPromiseOnMainThread(promise: Promise?, code: String, message: String) {
574
+ Handler(Looper.getMainLooper()).post {
575
+ promise?.reject(code, message)
576
+ }
577
+ }
578
+
579
+ private fun handlePermissionResult(granted: Set<String>?) {
580
+ Timber.d("handlePermissionResult: result: %s", granted)
581
+
582
+ val healthConnectUtil = healthConnectUtil
583
+ if (granted == null || healthConnectUtil == null) {
584
+ Timber.d("Lack of required permissions")
585
+ healthConnectUtil?.checkPermissionsAndRunForStar(true)
586
+ return
587
+ }
588
+
589
+ if (granted.containsAll(healthConnectUtil.PERMISSIONS)) {
590
+ previouslyRevoked = false
591
+ Timber.d("Permissions successfully granted")
592
+ } else {
593
+ Timber.d("Lack of required permissions")
594
+ }
595
+
596
+ healthConnectUtil.checkPermissionsAndRunForStar(true)
597
+ }
598
+
599
+ private fun getOrCreatePermissionLauncher(
600
+ activity: Activity
601
+ ): ActivityResultLauncher<Set<String>>? {
602
+ val existingLauncher = requestPermissionsLauncher
603
+ if (existingLauncher != null && requestPermissionsLauncherActivity === activity) {
604
+ return existingLauncher
605
+ }
606
+
607
+ val registryOwner = activity as? ActivityResultRegistryOwner ?: return null
608
+ requestPermissionsLauncher?.unregister()
609
+
610
+ requestPermissionsLauncher =
611
+ registryOwner.activityResultRegistry.register(
612
+ "visit-rn-sdk-health-connect-permissions-${System.identityHashCode(this)}",
613
+ requestPermissionActivityContract
614
+ ) { granted ->
615
+ handlePermissionResult(granted)
616
+ }
617
+ requestPermissionsLauncherActivity = activity
618
+
619
+ return requestPermissionsLauncher
620
+ }
621
+
622
+ private fun currentActivityOrCached(): Activity? {
623
+ val activity = reactApplicationContext.currentActivity
624
+ if (activity != null) {
625
+ mainActivity = activity
626
+ }
627
+ return activity ?: mainActivity
628
+ }
629
+
630
+ private fun configureTimber(loggingEnabled: Boolean) {
631
+ if (loggingEnabled && Timber.forest().isEmpty()) {
632
+ Timber.plant(Timber.DebugTree())
633
+ }
634
+ }
635
+
636
+ override fun invalidate() {
637
+ requestPermissionsLauncher?.unregister()
638
+ requestPermissionsLauncher = null
639
+ requestPermissionsLauncherActivity = null
640
+ super.invalidate()
641
+ }
642
+ }
@@ -8,7 +8,7 @@ import com.facebook.react.uimanager.ViewManager
8
8
 
9
9
  class VisitRnSdkPackage : ReactPackage {
10
10
  override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
11
- return listOf(VisitRnSdkLocationModule(reactContext))
11
+ return listOf(VisitFitnessModule(reactContext))
12
12
  }
13
13
 
14
14
  override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
@@ -0,0 +1,50 @@
1
+ package com.visitrnsdk
2
+
3
+ import android.content.Context
4
+ import android.content.SharedPreferences
5
+
6
+ class VisitSessionStorage(context: Context) {
7
+
8
+ private val BASE_URL = "baseURL"
9
+ private val DAILY_LAST_SYNC = "dailyLastSync"
10
+ private val HOURLY_LAST_SYNC = "hourlyLastSync"
11
+ private val VISIT_AUTH_TOKEN = "visitAuthToken"
12
+
13
+ private val sharedPreferences: SharedPreferences =
14
+ context.getSharedPreferences("VisitSharedPref", Context.MODE_PRIVATE)
15
+
16
+ fun saveBaseUrl(value: String) {
17
+ sharedPreferences.edit().putString(BASE_URL, value).apply()
18
+ }
19
+
20
+ fun getBaseURL(): String? {
21
+ return sharedPreferences.getString(BASE_URL, null)
22
+ }
23
+
24
+
25
+ fun saveDailyLastSyncTimeStamp(value: Long) {
26
+ sharedPreferences.edit().putLong(DAILY_LAST_SYNC, value).apply()
27
+ }
28
+
29
+
30
+ fun getDailyLastSyncTimestamp(): Long {
31
+ return sharedPreferences.getLong(DAILY_LAST_SYNC, -1L)
32
+ }
33
+
34
+ fun saveHourlyLastSyncTimeStamp(value: Long) {
35
+ sharedPreferences.edit().putLong(HOURLY_LAST_SYNC, value).apply()
36
+ }
37
+
38
+
39
+ fun getHourlyLastSyncTimeStamp(): Long {
40
+ return sharedPreferences.getLong(HOURLY_LAST_SYNC, -1L)
41
+ }
42
+
43
+ fun saveVisitAuthToken(value: String) {
44
+ sharedPreferences.edit().putString(VISIT_AUTH_TOKEN, value).apply()
45
+ }
46
+
47
+ fun getVisitAuthToken(): String? {
48
+ return sharedPreferences.getString(VISIT_AUTH_TOKEN, null)
49
+ }
50
+ }