react-native-asleep 0.0.5 → 0.0.8

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.
package/src/index.ts CHANGED
@@ -1,13 +1,15 @@
1
+ import { EventEmitter } from "expo-modules-core";
2
+ import { useCallback, useEffect, useState } from "react";
3
+ import { Alert, Platform } from "react-native";
1
4
  import {
2
5
  AsleepConfig,
6
+ AsleepSetupConfig,
3
7
  AsleepEventType,
4
8
  AsleepReport,
5
9
  AsleepSession,
6
10
  } from "./Asleep.types";
7
11
  import AsleepModule from "./AsleepModule";
8
- import { EventEmitter } from "expo-modules-core";
9
- import { useCallback, useEffect, useState } from "react";
10
- import { Alert, Platform } from "react-native";
12
+ import { useAsleepStore, initializeAsleepListeners } from "./AsleepStore";
11
13
 
12
14
  const emitter = new EventEmitter(AsleepModule);
13
15
 
@@ -16,6 +18,21 @@ class Asleep {
16
18
  [K in keyof AsleepEventType]?: ((data: AsleepEventType[K]) => void)[];
17
19
  } = {};
18
20
 
21
+ setup = async (config: AsleepSetupConfig): Promise<void> => {
22
+ try {
23
+ await AsleepModule.setup(
24
+ config.apiKey,
25
+ config.baseUrl,
26
+ config.callbackUrl,
27
+ config.service,
28
+ config.enableODA
29
+ );
30
+ } catch (error) {
31
+ console.error("setup error:", error);
32
+ throw error;
33
+ }
34
+ };
35
+
19
36
  initAsleepConfig = async (config: AsleepConfig): Promise<void> => {
20
37
  try {
21
38
  const result = await AsleepModule.initAsleepConfig(
@@ -37,10 +54,11 @@ class Asleep {
37
54
  Alert.alert("Microphone permission denied");
38
55
  throw new Error("Microphone permission denied");
39
56
  }
57
+
40
58
  return AsleepModule.startTracking();
41
59
  };
42
60
 
43
- stopTracking = (): Promise<string> => {
61
+ stopTracking = async (): Promise<string> => {
44
62
  return AsleepModule.stopTracking();
45
63
  };
46
64
 
@@ -112,215 +130,26 @@ class Asleep {
112
130
  }
113
131
 
114
132
  export const useAsleep = () => {
115
- const [didClose, setDidClose] = useState(false);
116
-
117
- const [error, setError] = useState<string | null>(null);
118
- const [userId, setUserId] = useState<string | null>(null);
119
- const [sessionId, setSessionId] = useState<string | null>(null);
120
- const [showDebugLog, setShowDebugLog] = useState(false);
121
- const [log, setLog] = useState<string>("");
122
-
123
- const initAsleepConfig = useCallback(async (config: AsleepConfig) => {
124
- try {
125
- console.log("[useAsleep] initAsleepConfig");
126
- await asleep.initAsleepConfig(config);
127
- } catch (err: any) {
128
- setError(err.message);
129
- }
130
- }, []);
131
-
132
- const startTracking = useCallback(async () => {
133
- try {
134
- console.log("[useAsleep] startTracking");
135
- setDidClose(false);
136
- await asleep.startTracking();
137
- } catch (err: any) {
138
- console.error("startTracking error:", err);
139
- setError(err.message);
140
- }
141
- }, []);
142
-
143
- const stopTracking = useCallback(async () => {
144
- try {
145
- console.log("[useAsleep] stopTracking");
146
- await asleep.stopTracking();
147
- setDidClose(true);
148
- } catch (err: any) {
149
- console.error("stopTracking error:", err);
150
- setError(err.message);
151
- }
152
- }, []);
153
-
154
- const isTrackingService = useCallback(() => {
155
- return asleep.isTracking();
156
- }, []);
157
-
158
- const getReport = async (sessionId: string): Promise<AsleepReport | null> => {
159
- try {
160
- console.log("[useAsleep] getReport");
161
- const report = await asleep.getReport(sessionId);
162
- return report;
163
- } catch (err: any) {
164
- console.error("getReport error:", err);
165
- setError(err.message);
166
- return null;
167
- }
168
- };
169
-
170
- const getReportList = async (
171
- fromDate: string,
172
- toDate: string
173
- ): Promise<AsleepSession[]> => {
174
- try {
175
- console.log(
176
- `[useAsleep] getReportList fromDate: ${fromDate}, toDate: ${toDate}`
177
- );
178
- const reportList = await asleep.getReportList(fromDate, toDate);
179
- return reportList;
180
- } catch (err: any) {
181
- console.error("getReportList error:", err);
182
- setError(err.message);
183
- return [];
184
- }
185
- };
186
-
187
- const addEventListener = useCallback(
188
- <K extends keyof AsleepEventType>(
189
- eventType: K,
190
- listener: (data: AsleepEventType[K]) => void
191
- ) => {
192
- const subscription = asleep.addEventListener(eventType, listener);
193
- return () => subscription.remove();
194
- },
195
- []
196
- );
197
-
198
- const enableLog = (print: boolean = true) => {
199
- setShowDebugLog(print);
200
- };
201
-
202
- const setCustomNotification = useCallback(
203
- async (title: string, text: string) => {
204
- if (Platform.OS === "android") {
205
- await AsleepModule.setCustomNotification(title, text);
206
- } else {
207
- console.warn("setCustomNotification is not supported on this platform");
208
- }
209
- },
210
- []
211
- );
212
-
213
- const addLog = useCallback(
214
- (log: string) => {
215
- const now = new Date();
216
- const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
217
- .getMinutes()
218
- .toString()
219
- .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
220
-
221
- if (showDebugLog) {
222
- console.log(`[Asleep][${dateString}]${log}`);
223
- }
224
- setLog(`[${dateString}]${log}`);
225
- },
226
- [showDebugLog]
227
- );
133
+ const {
134
+ didClose,
135
+ isTracking,
136
+ error,
137
+ userId,
138
+ sessionId,
139
+ log,
140
+ setup,
141
+ initAsleepConfig,
142
+ startTracking,
143
+ stopTracking,
144
+ getReport,
145
+ getReportList,
146
+ enableLog,
147
+ setCustomNotification,
148
+ } = useAsleepStore();
228
149
 
229
150
  useEffect(() => {
230
- const onUserJoined = (data: any) => {
231
- setUserId(data.userId);
232
- addLog(`[onUserJoined] userId: ${data.userId}`);
233
- };
234
- const onUserJoinFailed = (error: any) => {
235
- const errorString = JSON.stringify(error);
236
- setError(errorString);
237
- addLog(`[onUserJoinFailed] error: ${errorString}`);
238
- };
239
- const onUserDeleted = (data: any) => {
240
- setUserId(null);
241
- addLog(`[onUserDeleted] userId: ${data.userId}`);
242
- };
243
- const onTrackingCreated = () => {
244
- addLog(`[onTrackingCreated]`);
245
- };
246
- const onTrackingUploaded = (data: any) => {
247
- addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
248
- };
249
- const onTrackingClosed = (data: { sessionId: string }) => {
250
- setSessionId(data.sessionId);
251
- setDidClose(true);
252
- addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
253
- };
254
- const onTrackingFailed = (error: any) => {
255
- const errorString = JSON.stringify(error);
256
- setError(errorString);
257
- addLog(`[onTrackingFailed] error: ${errorString}`);
258
- };
259
- const onTrackingInterrupted = () => {
260
- addLog(`[onTrackingInterrupted]`);
261
- };
262
- const onTrackingResumed = () => {
263
- addLog(`[onTrackingResumed]`);
264
- };
265
- const onMicPermissionDenied = () => {
266
- addLog(`[onMicPermissionDenied]`);
267
- };
268
- const onDebugLog = (data: any) => {
269
- addLog(`[onDebugLog] message: ${data.message}`);
270
- };
271
-
272
- const userJoinedListener = addEventListener("onUserJoined", onUserJoined);
273
- const userJoinFailedListener = addEventListener(
274
- "onUserJoinFailed",
275
- onUserJoinFailed
276
- );
277
- const userDeletedListener = addEventListener(
278
- "onUserDeleted",
279
- onUserDeleted
280
- );
281
- const trackingCreatedListener = addEventListener(
282
- "onTrackingCreated",
283
- onTrackingCreated
284
- );
285
- const trackingUploadedListener = addEventListener(
286
- "onTrackingUploaded",
287
- onTrackingUploaded
288
- );
289
- const trackingClosedListener = addEventListener(
290
- "onTrackingClosed",
291
- onTrackingClosed
292
- );
293
- const trackingFailedListener = addEventListener(
294
- "onTrackingFailed",
295
- onTrackingFailed
296
- );
297
- const trackingInterruptedListener = addEventListener(
298
- "onTrackingInterrupted",
299
- onTrackingInterrupted
300
- );
301
- const trackingResumedListener = addEventListener(
302
- "onTrackingResumed",
303
- onTrackingResumed
304
- );
305
- const micPermissionDeniedListener = addEventListener(
306
- "onMicPermissionDenied",
307
- onMicPermissionDenied
308
- );
309
- const debugLogListener = addEventListener("onDebugLog", onDebugLog);
310
-
311
- return () => {
312
- userJoinedListener();
313
- userJoinFailedListener();
314
- userDeletedListener();
315
- trackingCreatedListener();
316
- trackingUploadedListener();
317
- trackingClosedListener();
318
- trackingFailedListener();
319
- trackingInterruptedListener();
320
- trackingResumedListener();
321
- micPermissionDeniedListener();
322
- debugLogListener();
323
- };
151
+ const cleanup = initializeAsleepListeners();
152
+ return cleanup;
324
153
  }, []);
325
154
 
326
155
  return {
@@ -331,22 +160,58 @@ export const useAsleep = () => {
331
160
  log,
332
161
  enableLog,
333
162
  setCustomNotification,
163
+ setup,
334
164
  initAsleepConfig,
335
165
  startTracking,
336
166
  stopTracking,
337
167
  getReport,
338
168
  getReportList,
339
- isTrackingService,
169
+ isTracking,
340
170
  };
341
171
  };
342
172
 
173
+ export const asleepStore = useAsleepStore;
174
+
175
+ export const AsleepSDK = {
176
+ setup: (config: AsleepSetupConfig) => useAsleepStore.getState().setup(config),
177
+
178
+ initAsleepConfig: (config: AsleepConfig) =>
179
+ useAsleepStore.getState().initAsleepConfig(config),
180
+
181
+ startTracking: () => useAsleepStore.getState().startTracking(),
182
+
183
+ stopTracking: () => useAsleepStore.getState().stopTracking(),
184
+
185
+ getReport: (sessionId: string) =>
186
+ useAsleepStore.getState().getReport(sessionId),
187
+
188
+ getReportList: (fromDate: string, toDate: string) =>
189
+ useAsleepStore.getState().getReportList(fromDate, toDate),
190
+
191
+ isTracking: () => useAsleepStore.getState().isTracking,
192
+
193
+ getUserId: () => useAsleepStore.getState().userId,
194
+
195
+ getSessionId: () => useAsleepStore.getState().sessionId,
196
+
197
+ enableLog: (print: boolean) => useAsleepStore.getState().enableLog(print),
198
+
199
+ setCustomNotification: (title: string, text: string) =>
200
+ useAsleepStore.getState().setCustomNotification(title, text),
201
+
202
+ initialize: () => {
203
+ return initializeAsleepListeners();
204
+ },
205
+ };
206
+
343
207
  const asleep = new Asleep();
344
208
  export default asleep;
345
209
 
346
210
  export type {
347
211
  AsleepConfig,
212
+ AsleepSetupConfig,
213
+ AsleepEventType,
348
214
  AsleepReport,
349
- AsleepStat,
350
215
  AsleepSession,
351
- AsleepEventType,
216
+ AsleepStat,
352
217
  } from "./Asleep.types";
@@ -1,9 +0,0 @@
1
- // IAsleepService.aidl
2
- package ai.asleep.reactnative;
3
-
4
- import ai.asleep.reactnative.IListener;
5
-
6
- interface IAsleepService {
7
- void registerListener(IListener listener);
8
- void unregisterListener(IListener listener);
9
- }
@@ -1,12 +0,0 @@
1
- // IListener.aidl
2
- package ai.asleep.reactnative;
3
-
4
- import ai.asleep.reactnative.data.ErrorCode;
5
-
6
- interface IListener {
7
- void onUserIdReceived(String userId);
8
- void onSessionIdReceived(String sessionId);
9
- void onSequenceReceived(int sequence);
10
- void onErrorCodeReceived(in ErrorCode errorCode);
11
- void onStopTrackingReceived(String sessionId);
12
- }
@@ -1,4 +0,0 @@
1
- // ErrorCode.aidl
2
- package ai.asleep.reactnative.data;
3
-
4
- parcelable ErrorCode;
@@ -1,33 +0,0 @@
1
- package ai.asleep.reactnative.data
2
-
3
- import android.os.Parcel
4
- import android.os.Parcelable
5
-
6
- data class ErrorCode(
7
- val code: Int,
8
- val message: String
9
- ) : Parcelable {
10
- constructor(parcel: Parcel) : this(
11
- parcel.readInt(),
12
- parcel.readString() ?: ""
13
- )
14
-
15
- override fun writeToParcel(parcel: Parcel, flags: Int) {
16
- parcel.writeInt(code)
17
- parcel.writeString(message)
18
- }
19
-
20
- override fun describeContents(): Int {
21
- return 0
22
- }
23
-
24
- companion object CREATOR : Parcelable.Creator<ErrorCode> {
25
- override fun createFromParcel(parcel: Parcel): ErrorCode {
26
- return ErrorCode(parcel)
27
- }
28
-
29
- override fun newArray(size: Int): Array<ErrorCode?> {
30
- return arrayOfNulls(size)
31
- }
32
- }
33
- }
@@ -1,179 +0,0 @@
1
- package ai.asleep.reactnative.service
2
-
3
- import ai.asleep.reactnative.R
4
- import ai.asleep.reactnative.utils.PreferenceHelper
5
- import ai.asleep.reactnative.data.ErrorCode
6
- import android.app.ActivityManager
7
- import android.app.Notification
8
- import android.app.NotificationChannel
9
- import android.app.NotificationManager
10
- import android.app.PendingIntent
11
- import android.content.Context
12
- import android.content.Intent
13
- import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
14
- import android.os.Build
15
- import android.os.IBinder
16
- import android.util.Log
17
- import android.media.AudioManager
18
- import androidx.core.app.NotificationManagerCompat
19
- import androidx.lifecycle.LifecycleService
20
- import android.Manifest
21
- import android.content.pm.PackageManager
22
-
23
-
24
- const val TAG = ">>>>> AsleepService"
25
- class AsleepService : LifecycleService() {
26
-
27
- lateinit var asleepViewModel: AsleepViewModel
28
-
29
- companion object {
30
- private const val FOREGROUND_SERVICE_ID = 1000
31
- private const val RECORD_NOTIFICATION_CHANNEL_ID = "12344321"
32
-
33
- const val ACTION_START_TRACKING = "ACTION_START_TRACKING"
34
- const val ACTION_STOP_TRACKING = "ACTION_STOP_TRACKING"
35
-
36
- fun isAsleepServiceRunning(context: Context): Boolean {
37
- val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
38
- @Suppress("DEPRECATION")
39
- for (service in manager.getRunningServices(Int.MAX_VALUE)) {
40
- if (AsleepService::class.java.name == service.service.className) {
41
- return true
42
- }
43
- }
44
- return false
45
- }
46
- }
47
-
48
- override fun onCreate() {
49
- super.onCreate()
50
- Log.d(TAG, "AsleepService onCreate: ")
51
- createNotificationChannel()
52
-
53
- asleepViewModel = AsleepViewModel.getInstance(application)
54
- asleepViewModel.reportingSessionId.observe(this) {
55
- Log.d(TAG, "reportingSessionId : $it")
56
- stopSelf()
57
- }
58
- }
59
-
60
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
61
- super.onStartCommand(intent, flags, startId)
62
- Log.d(TAG, "onStartCommand:")
63
-
64
- if (intent == null || intent.action == null) {
65
- asleepViewModel.continueTracking()
66
- } else if (intent.action == ACTION_START_TRACKING) {
67
- startForegroundService()
68
-
69
- val storedUserId = PreferenceHelper.getUserId(applicationContext)
70
- val apiKey = PreferenceHelper.getApiKey(applicationContext)
71
- asleepViewModel.startSleepTracking(storedUserId, apiKey)
72
- } else if (intent.action == ACTION_STOP_TRACKING) {
73
- asleepViewModel.stopSleepTracking()
74
- asleepViewModel.isReporting = true
75
- stopForeground(true)
76
- stopSelf()
77
- }
78
- return START_STICKY
79
- }
80
-
81
- private fun createNotificationChannel() {
82
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
83
- val notificationChannel =
84
- NotificationChannel(
85
- RECORD_NOTIFICATION_CHANNEL_ID,
86
- "Asleep Tracking In Progress",
87
- NotificationManager.IMPORTANCE_LOW
88
- )
89
- notificationChannel.setSound(null, null)
90
- NotificationManagerCompat.from(applicationContext)
91
- .createNotificationChannel(notificationChannel)
92
- }
93
- }
94
-
95
- private fun startForegroundService() {
96
-
97
- val notification = getNotification()
98
-
99
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
100
- if (checkSelfPermission(Manifest.permission.FOREGROUND_SERVICE_MICROPHONE) == PackageManager.PERMISSION_GRANTED &&
101
- checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
102
- startForeground(FOREGROUND_SERVICE_ID, notification, FOREGROUND_SERVICE_TYPE_MICROPHONE)
103
- } else {
104
- Log.e(TAG, "Missing required permissions for foreground service with microphone")
105
- }
106
- } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
107
- startForeground(FOREGROUND_SERVICE_ID, notification, FOREGROUND_SERVICE_TYPE_MICROPHONE)
108
- } else {
109
- startForeground(FOREGROUND_SERVICE_ID, notification)
110
- }
111
-
112
- Log.d(TAG, "startForeground()")
113
- }
114
-
115
- private fun getNotification(): Notification {
116
- val notificationIntent = packageManager
117
- .getLaunchIntentForPackage(packageName)
118
- ?.apply {
119
- flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
120
- }
121
-
122
- val pendingIntent = PendingIntent.getActivity(
123
- this,
124
- 0,
125
- notificationIntent,
126
- PendingIntent.FLAG_IMMUTABLE
127
- )
128
-
129
- val notificationTitle = PreferenceHelper.getNotificationTitle(applicationContext)
130
- val notificationText = PreferenceHelper.getNotificationText(applicationContext)
131
-
132
- val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
133
- Notification.Builder(this, RECORD_NOTIFICATION_CHANNEL_ID)
134
- .setContentTitle(notificationTitle)
135
- .setContentText(notificationText)
136
- .setSmallIcon(android.R.drawable.ic_dialog_info)
137
- .setContentIntent(pendingIntent)
138
- .setOngoing(true)
139
- .build()
140
- } else {
141
- Notification.Builder(this)
142
- .setContentTitle(notificationTitle)
143
- .setContentText(notificationText)
144
- .setSmallIcon(android.R.drawable.ic_dialog_info)
145
- .setContentIntent(pendingIntent)
146
- .setOngoing(true)
147
- .build()
148
- }
149
-
150
- return notification
151
- }
152
-
153
- override fun onBind(intent: Intent): IBinder {
154
- super.onBind(intent)
155
- return asleepViewModel.binder
156
- }
157
-
158
- override fun onDestroy() {
159
- try {
160
- super.onDestroy()
161
- Log.d(TAG, "AsleepService onDestroy")
162
- asleepViewModel.cleanup()
163
- stopForeground(true)
164
-
165
-
166
- applicationContext?.let { context ->
167
- try {
168
-
169
- val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
170
- audioManager.abandonAudioFocus(null)
171
- } catch (e: Exception) {
172
- Log.e(TAG, "Error cleaning up audio resources", e)
173
- }
174
- }
175
- } catch (e: Exception) {
176
- Log.e(TAG, "Error in onDestroy", e)
177
- }
178
- }
179
- }