/* eslint-disable react-hooks/exhaustive-deps */ import RookSdk from '../../NativeRookSdk'; import { useEffect, useRef, useState } from 'react'; import { AppState, Platform } from 'react-native'; import type { RookSyncGateState } from '../../context/RookSyncGateTypes'; import { errors } from '../utils/errors'; import type { Message } from '../types/sendMessageBroadcast'; import { AppleHealthPermission } from '../../types/AppleHealthPermissions'; type StartBackgroundSync = { state: RookSyncGateState; enableBackground: boolean; enableLogs: boolean; }; const MESSAGE_TYPE = 'ROOK_BACKGROUND_ENABLED'; /** * The above TypeScript code defines a function `useRookAutoSync` that handles background * synchronization, including user ID validation and error messaging. * @property {boolean} enableBackground - The `enableBackground` property in the `useRookAutoSync` * function determines whether background synchronization should be enabled. If `enableBackground` is * set to `true`, the function will listen for changes in the app state and trigger the * `startBackgroundSync` function when the app transitions from * @property {boolean} enableLogs - The `enableLogs` property in the `useRookAutoSync` function is a * boolean value that determines whether logging should be enabled or not. If `enableLogs` is set to * `true`, logging messages will be displayed in the console to provide information about the * background synchronization process. If ` * @property {RookSyncGateState} state - The `state` property in the `useRookAutoSync` function * represents the current state of the RookSyncGate. It includes information such as whether the state * is ready, the permissions status, and the user ID associated with the state. This state is used to * determine when to start the */ export const useRookAutoSync = ({ enableBackground, enableLogs, state, }: StartBackgroundSync) => { const appState = useRef(AppState.currentState); const [changeAppState, setChangeState] = useState(0); useEffect(() => { if (!enableBackground) return; const subscription = AppState.addEventListener('change', (nextAppState) => { if ( // Check previous state to check if he app was inactive or in background // and then pass to be active appState.current?.match(/inactive|background/) && nextAppState === 'active' ) { setChangeState((prev) => prev + 1); } appState.current = nextAppState; }); return () => { subscription.remove(); }; }, []); useEffect(() => { if (!state.ready || !enableBackground) return; startBackgroundServices(); }, [state, changeAppState]); const startBackgroundServices = () => { const { clientUUID, secret, ready } = state; if (!enableBackground) return; if (!ready || !clientUUID || !secret) { return; } if (Platform.OS === 'android') { startAndroidBackgroundSync(); return; } startIOSBackgroundSync(); }; const isValidUser = async (): Promise => { try { const userID = await RookSdk.getUserID(); if (userID) return true; if (enableLogs) console.error(errors.noUserIDAndroidBackground); throw new Error(errors.noUserIDAndroidBackground); } catch (error) { sendMessageToBroadcast({ type: 'ROOK_BACKGROUND_ENABLED', message: (error as any).message || 'There is not a user id', value: false, }); return false; } }; const tryToStartBackgroundSync = async (): Promise => { try { const backgroundStatus = await RookSdk.checkHealthConnectBackgroundReadStatus(); if (backgroundStatus !== 'PERMISSION_GRANTED') throw new Error('No permission granted or not available'); const result = await RookSdk.scheduleBackgroundSync(enableLogs); return result; } catch (error) { sendMessageToBroadcast({ type: 'ROOK_BACKGROUND_ENABLED', message: (error as any).message || 'Health Connect background is not available on the device or the user does not grants permission', value: false, }); return false; } }; const tryToStartForegroundSync = async (): Promise => { try { const hasHCPermissions = await RookSdk.healthConnectHasPartialPermissions(); const hasAndroidPermissions = await RookSdk.androidHasBackgroundPermissions(); if (!hasHCPermissions || !hasAndroidPermissions) { if (enableLogs) console.error(errors.autoStartAndroidBackgroundSync); throw new Error(errors.autoStartAndroidBackgroundSync); } if (AppState.currentState === 'active' && appState.current === 'active') { await RookSdk.enableBackgroundAndroidSteps(); return true; } return false; } catch (error) { sendMessageToBroadcast({ type: 'ROOK_BACKGROUND_ENABLED', value: false, message: (error as Error).message, }); return false; } }; const tryToStartSamsungHealthSync = async (): Promise => { try { const isAvailable = await RookSdk.checkSamsungAvailability(); if (isAvailable !== 'INSTALLED') return false; await RookSdk.enableSamsungSync(); return true; } catch (error) { sendMessageToBroadcast({ type: 'ROOK_BACKGROUND_ENABLED', value: false, message: (error as Error).message, }); return false; } }; /** * The function `startAndroidBackgroundSync` in TypeScript initiates background synchronization for an * Android app, handling user ID validation and error messaging. * @returns If the `userID` is not available, an error message is logged and a message is sent to * broadcast with `value` set to `false`. If an error occurs during the process, a message is sent to * broadcast with `value` set to `false` and an error message is logged. */ const startAndroidBackgroundSync = async () => { const { clientUUID, secret, ready } = state; if (!ready || !clientUUID || !secret) { return; } try { const enabledSources = []; const isValid = await isValidUser(); if (!isValid) return; const isSamsungEnabled = await tryToStartSamsungHealthSync(); const isEnabled = await tryToStartBackgroundSync(); if (isSamsungEnabled) enabledSources.push('Samsung Health'); if (isEnabled) enabledSources.push('Health Connect'); if (!isEnabled) { const isForegroundEnabled = await tryToStartForegroundSync(); if (!isForegroundEnabled && !isSamsungEnabled) throw new Error("We couldn't start background sync"); if (isForegroundEnabled) enabledSources.push('Foreground Service'); } sendMessageToBroadcast({ type: 'ROOK_BACKGROUND_ENABLED', value: true, message: `via: ${enabledSources.join(', ')}`, }); if (enableLogs) console.log('ROOK - Background enabled successfully'); } catch (error) { sendMessageToBroadcast({ type: 'ROOK_BACKGROUND_ENABLED', message: (error as any).message, value: false, }); } }; /** * The function `startIOSBackgroundSync` in TypeScript initiates background synchronization for an * iOS app, handling user ID validation and error messaging. * @returns If the `userID` is not available, an error message is logged and a message is sent to * broadcast with `value` set to `false`. If an error occurs during the process, a message is sent to * broadcast with `value` set to `false` and an error message is logged. */ const startIOSBackgroundSync = async () => { try { const userID = await RookSdk.getUserID(); if (!userID) { if (enableLogs) console.error(errors.noUserIDAndroidBackground); sendMessageToBroadcast({ type: MESSAGE_TYPE, value: false, message: errors.noUserIDAndroidBackground, }); return; } const status = await RookSdk.appleHealthHasPermissions( AppleHealthPermission.STEP_COUNT ); if (status === 'PERMISSION_NOT_REQUESTED') throw new Error('Permissions required'); await RookSdk.enableBackGroundUpdates(); RookSdk.sync(() => { sendMessageToBroadcast({ type: MESSAGE_TYPE, value: true, message: 'Some data has already uploaded', }); }); sendMessageToBroadcast({ type: MESSAGE_TYPE, value: true, }); if (enableLogs) console.log('ROOK - Background enabled successfully'); } catch (err) { const error = err as any; sendMessageToBroadcast({ type: MESSAGE_TYPE, value: false, message: errors.autoStartIOSBackgroundSync, }); if (enableLogs) { if (error.message && (error.message as string).includes('emptyUserId')) console.error(errors.noUserIDAndroidBackground); else console.error(errors.autoStartIOSBackgroundSync); } } }; /** * The function `sendMessageToBroadcast` sends a message to be broadcasted using a Rook module. * @param {Message} message - The `message` parameter is of type `Message`, which is likely an object * containing information to be sent as a broadcast message. */ const sendMessageToBroadcast = (message: Message): void => { RookSdk.sendMessage(message); }; return { startBackgroundServices, }; };