react-native-asleep 0.0.4 → 0.0.7

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,3 +1,6 @@
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,
3
6
  AsleepEventType,
@@ -5,9 +8,6 @@ import {
5
8
  AsleepSession,
6
9
  } from "./Asleep.types";
7
10
  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";
11
11
 
12
12
  const emitter = new EventEmitter(AsleepModule);
13
13
 
@@ -37,10 +37,11 @@ class Asleep {
37
37
  Alert.alert("Microphone permission denied");
38
38
  throw new Error("Microphone permission denied");
39
39
  }
40
+
40
41
  return AsleepModule.startTracking();
41
42
  };
42
43
 
43
- stopTracking = (): Promise<string> => {
44
+ stopTracking = async (): Promise<string> => {
44
45
  return AsleepModule.stopTracking();
45
46
  };
46
47
 
@@ -113,6 +114,7 @@ class Asleep {
113
114
 
114
115
  export const useAsleep = () => {
115
116
  const [didClose, setDidClose] = useState(false);
117
+ const [isTracking, setIsTracking] = useState(asleep.isTracking());
116
118
 
117
119
  const [error, setError] = useState<string | null>(null);
118
120
  const [userId, setUserId] = useState<string | null>(null);
@@ -133,6 +135,8 @@ export const useAsleep = () => {
133
135
  try {
134
136
  console.log("[useAsleep] startTracking");
135
137
  setDidClose(false);
138
+ setIsTracking(true);
139
+ console.log("[useAsleep] startTracking isTracking: ", isTracking);
136
140
  await asleep.startTracking();
137
141
  } catch (err: any) {
138
142
  console.error("startTracking error:", err);
@@ -143,21 +147,19 @@ export const useAsleep = () => {
143
147
  const stopTracking = useCallback(async () => {
144
148
  try {
145
149
  console.log("[useAsleep] stopTracking");
146
- await asleep.stopTracking();
150
+ const sessionId = await asleep.stopTracking();
147
151
  setDidClose(true);
152
+ setSessionId(sessionId);
153
+ setIsTracking(false);
148
154
  } catch (err: any) {
149
155
  console.error("stopTracking error:", err);
150
156
  setError(err.message);
151
157
  }
152
158
  }, []);
153
159
 
154
- const isTrackingService = useCallback(() => {
155
- return asleep.isTracking();
156
- }, []);
157
-
158
160
  const getReport = async (sessionId: string): Promise<AsleepReport | null> => {
159
161
  try {
160
- console.log("[useAsleep] getReport");
162
+ console.log("[useAsleep] getReport sessionId: ", sessionId);
161
163
  const report = await asleep.getReport(sessionId);
162
164
  return report;
163
165
  } catch (err: any) {
@@ -240,8 +242,14 @@ export const useAsleep = () => {
240
242
  setUserId(null);
241
243
  addLog(`[onUserDeleted] userId: ${data.userId}`);
242
244
  };
243
- const onTrackingCreated = () => {
244
- addLog(`[onTrackingCreated]`);
245
+ const onTrackingCreated = (data: any) => {
246
+ setIsTracking(true);
247
+ if (data && data.sessionId) {
248
+ setSessionId(data.sessionId);
249
+ }
250
+ addLog(
251
+ `[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`
252
+ );
245
253
  };
246
254
  const onTrackingUploaded = (data: any) => {
247
255
  addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
@@ -249,17 +257,21 @@ export const useAsleep = () => {
249
257
  const onTrackingClosed = (data: { sessionId: string }) => {
250
258
  setSessionId(data.sessionId);
251
259
  setDidClose(true);
260
+ setIsTracking(false);
252
261
  addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
253
262
  };
254
263
  const onTrackingFailed = (error: any) => {
255
264
  const errorString = JSON.stringify(error);
256
265
  setError(errorString);
266
+ setIsTracking(false);
257
267
  addLog(`[onTrackingFailed] error: ${errorString}`);
258
268
  };
259
269
  const onTrackingInterrupted = () => {
270
+ setIsTracking(false);
260
271
  addLog(`[onTrackingInterrupted]`);
261
272
  };
262
273
  const onTrackingResumed = () => {
274
+ setIsTracking(true);
263
275
  addLog(`[onTrackingResumed]`);
264
276
  };
265
277
  const onMicPermissionDenied = () => {
@@ -336,7 +348,7 @@ export const useAsleep = () => {
336
348
  stopTracking,
337
349
  getReport,
338
350
  getReportList,
339
- isTrackingService,
351
+ isTracking,
340
352
  };
341
353
  };
342
354
 
@@ -345,8 +357,8 @@ export default asleep;
345
357
 
346
358
  export type {
347
359
  AsleepConfig,
360
+ AsleepEventType,
348
361
  AsleepReport,
349
- AsleepStat,
350
362
  AsleepSession,
351
- AsleepEventType,
363
+ AsleepStat,
352
364
  } 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
- }
@@ -1,246 +0,0 @@
1
- package ai.asleep.reactnative.service
2
-
3
- import ai.asleep.reactnative.BuildConfig
4
- import ai.asleep.reactnative.IAsleepService
5
- import ai.asleep.reactnative.IListener
6
- import ai.asleep.reactnative.data.ErrorCode
7
- import ai.asleep.reactnative.utils.PreferenceHelper
8
- import ai.asleep.asleepsdk.Asleep
9
- import ai.asleep.asleepsdk.AsleepErrorCode
10
- import ai.asleep.asleepsdk.data.AsleepConfig
11
- import ai.asleep.asleepsdk.tracking.SleepTrackingManager
12
- import ai.asleep.asleepsdk.tracking.TrackingStatus
13
- import android.app.Application
14
- import android.os.RemoteCallbackList
15
- import android.os.RemoteException
16
- import android.util.Log
17
- import androidx.lifecycle.LifecycleService
18
- import androidx.lifecycle.LiveData
19
- import androidx.lifecycle.MutableLiveData
20
- import androidx.lifecycle.ViewModel
21
-
22
- class AsleepViewModel private constructor(
23
- private val applicationContext: Application
24
- ) : ViewModel() {
25
-
26
- private var _userId = MutableLiveData<String?>()
27
- val userId: LiveData<String?> get() = _userId
28
- private var _asleepConfig: AsleepConfig? = null
29
-
30
- private var _sleepTrackingManager: SleepTrackingManager? = null
31
- private var _sessionId: String? = null
32
- private var _sequence = MutableLiveData<Int?>(null)
33
-
34
- var isReporting = false
35
- val reportingSessionId = MutableLiveData<String>()
36
-
37
- private val listeners = RemoteCallbackList<IListener>()
38
- val binder: IAsleepService.Stub = object : IAsleepService.Stub() {
39
- @Throws(RemoteException::class)
40
- override fun registerListener(listener: IListener?) {
41
- listeners.register(listener)
42
- }
43
-
44
- @Throws(RemoteException::class)
45
- override fun unregisterListener(listener: IListener?) {
46
- listeners.unregister(listener)
47
- }
48
- }
49
-
50
- fun startSleepTracking(userId: String?, apiKey: String) {
51
- Asleep.initAsleepConfig(
52
- context = applicationContext,
53
- apiKey = apiKey,
54
- userId = userId,
55
- baseUrl = null,
56
- callbackUrl = null,
57
- service = "SleepTracking",
58
- object : Asleep.AsleepConfigListener {
59
- override fun onSuccess(userId: String?, asleepConfig: AsleepConfig?) {
60
- saveUserIdInSharedPreference(userId)
61
- _userId.value = userId
62
- _asleepConfig = asleepConfig
63
-
64
- notifyListeners(listeners) { listener ->
65
- (listener).onUserIdReceived(userId)
66
- }
67
-
68
- createSleepTrackingManager()
69
- startTracking()
70
- }
71
-
72
- override fun onFail(errorCode: Int, detail: String) {
73
- Log.d("initAsleepConfig", "onFail: $errorCode - $detail")
74
- notifyListeners(listeners) { listener ->
75
- listener.onErrorCodeReceived(ErrorCode(errorCode, detail))
76
- }
77
-
78
- }
79
- },
80
- object : Asleep.AsleepLogger {
81
- override fun d(tag: String, msg: String, throwable: Throwable?) {
82
- if (throwable == null) {
83
- Log.d(tag, msg)
84
- } else {
85
- Log.d(tag, "$msg ${throwable.localizedMessage}")
86
- }
87
- }
88
-
89
- override fun e(tag: String, msg: String, throwable: Throwable?) {
90
- if (throwable == null) {
91
- Log.e(tag, msg)
92
- } else {
93
- Log.e(tag, "$msg ${throwable.localizedMessage}")
94
- }
95
- }
96
-
97
- override fun i(tag: String, msg: String, throwable: Throwable?) {
98
- if (throwable == null) {
99
- Log.i(tag, msg)
100
- } else {
101
- Log.i(tag, "$msg ${throwable.localizedMessage}")
102
- }
103
- }
104
-
105
- override fun w(tag: String, msg: String, throwable: Throwable?) {
106
- if (throwable == null) {
107
- Log.w(tag, msg)
108
- } else {
109
- Log.w(tag, "$msg ${throwable.localizedMessage}")
110
- }
111
- }
112
- })
113
- }
114
-
115
- private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
116
-
117
- fun createSleepTrackingManager() {
118
- _sleepTrackingManager = Asleep.createSleepTrackingManager(_asleepConfig, object : SleepTrackingManager.TrackingListener {
119
- override fun onCreate() {
120
- mainHandler.post {
121
- _sessionId = getTrackingStatus()?.sessionId
122
- _sessionId?.let {
123
- notifyListeners(listeners) { listener ->
124
- listener.onSessionIdReceived(it)
125
- }
126
- }
127
- }
128
- }
129
-
130
- override fun onUpload(sequence: Int) {
131
- mainHandler.post {
132
- _sequence.value = sequence
133
-
134
- notifyListeners(listeners) { listener ->
135
- listener.onSequenceReceived(sequence)
136
- }
137
- }
138
- }
139
-
140
- override fun onClose(sessionId: String) {
141
- _sessionId = sessionId
142
-
143
- mainHandler.post {
144
- PreferenceHelper.putIsTracking(applicationContext, false)
145
-
146
- notifyListeners(listeners) { listener ->
147
- listener.onStopTrackingReceived(_sessionId)
148
- }
149
-
150
- if (isReporting) {
151
- _sessionId?.let {
152
- reportingSessionId.value = it
153
- }
154
- }
155
- }
156
- }
157
-
158
- override fun onFail(errorCode: Int, detail: String) {
159
- mainHandler.post {
160
- when (errorCode) {
161
- AsleepErrorCode.ERR_CLOSE_SERVER_ERROR,
162
- AsleepErrorCode.ERR_CLOSE_FAILED,
163
- AsleepErrorCode.ERR_CLOSE_FORBIDDEN,
164
- AsleepErrorCode.ERR_CLOSE_UNAUTHORIZED,
165
- AsleepErrorCode.ERR_CLOSE_BAD_REQUEST,
166
- AsleepErrorCode.ERR_CLOSE_NOT_FOUND ->
167
- notifyListeners(listeners) { listener ->
168
- listener.onStopTrackingReceived(_sessionId)
169
- }
170
- else ->
171
- notifyListeners(listeners) { listener ->
172
- listener.onErrorCodeReceived(ErrorCode(errorCode, detail))
173
- }
174
- }
175
- }
176
- }
177
- })
178
- }
179
-
180
- fun getTrackingStatus(): TrackingStatus? {
181
- return _sleepTrackingManager?.getTrackingStatus()
182
- }
183
-
184
- private fun startTracking() {
185
- _sleepTrackingManager?.startSleepTracking()
186
- }
187
-
188
- fun stopSleepTracking() {
189
- if (_sleepTrackingManager?.getTrackingStatus()?.sessionId != null) {
190
- _sleepTrackingManager?.stopSleepTracking()
191
- }
192
- }
193
-
194
-
195
- fun continueTracking() {
196
- if (_asleepConfig == null && Asleep.hasUnfinishedSession(applicationContext)) {
197
- val savedApiKey = PreferenceHelper.getApiKey(applicationContext)
198
- _asleepConfig = Asleep.getSavedAsleepConfig(applicationContext, savedApiKey)
199
- createSleepTrackingManager()
200
- startTracking()
201
- }
202
- }
203
-
204
- private fun saveUserIdInSharedPreference(userId: String?) {
205
- userId?.let {
206
- PreferenceHelper.putUserId(applicationContext, it)
207
- }
208
- }
209
-
210
- private fun notifyListeners(listeners: RemoteCallbackList<IListener>, onReceive: (IListener) -> Unit) {
211
- val numListeners = listeners.beginBroadcast()
212
- for (i in 0 until numListeners) {
213
- try {
214
- val listener = listeners.getBroadcastItem(i)
215
- onReceive(listener)
216
- } catch (e: RemoteException) {
217
- e.printStackTrace()
218
- }
219
- }
220
- listeners.finishBroadcast()
221
- }
222
-
223
- fun cleanup() {
224
- try {
225
- stopSleepTracking()
226
- _sleepTrackingManager = null
227
- _asleepConfig = null
228
- listeners.kill()
229
-
230
- System.gc()
231
- } catch (e: Exception) {
232
- Log.e(TAG, "Error in cleanup", e)
233
- }
234
- }
235
-
236
- companion object {
237
- @Volatile
238
- private var instance: AsleepViewModel? = null
239
-
240
- fun getInstance(application: Application): AsleepViewModel {
241
- return instance ?: synchronized(this) {
242
- instance ?: AsleepViewModel(application).also { instance = it }
243
- }
244
- }
245
- }
246
- }