react-native-asleep 0.0.2
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/.eslintrc.js +5 -0
- package/License.md +117 -0
- package/README.md +36 -0
- package/android/.gradle/8.9/checksums/checksums.lock +0 -0
- package/android/.gradle/8.9/dependencies-accessors/gc.properties +0 -0
- package/android/.gradle/8.9/fileChanges/last-build.bin +0 -0
- package/android/.gradle/8.9/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/8.9/gc.properties +0 -0
- package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
- package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
- package/android/build.gradle +77 -0
- package/android/libs/AsleepSDK.aar +0 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/aidl/ai/asleep/reactnative/IAsleepService.aidl +9 -0
- package/android/src/main/aidl/ai/asleep/reactnative/IListener.aidl +12 -0
- package/android/src/main/aidl/ai/asleep/reactnative/data/ErrorCode.aidl +4 -0
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +396 -0
- package/android/src/main/java/ai/asleep/reactnative/data/ErrorCode.kt +33 -0
- package/android/src/main/java/ai/asleep/reactnative/service/AsleepService.kt +179 -0
- package/android/src/main/java/ai/asleep/reactnative/service/AsleepViewModel.kt +246 -0
- package/android/src/main/java/ai/asleep/reactnative/utils/PreferenceHelper.kt +119 -0
- package/android/src/main/java/ai/asleep/reactnative/utils/Utils.kt +48 -0
- package/build/Asleep.types.d.ts +90 -0
- package/build/Asleep.types.d.ts.map +1 -0
- package/build/Asleep.types.js +2 -0
- package/build/Asleep.types.js.map +1 -0
- package/build/AsleepModule.d.ts +3 -0
- package/build/AsleepModule.d.ts.map +1 -0
- package/build/AsleepModule.js +3 -0
- package/build/AsleepModule.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/index.ts +352 -0
- package/ios/Asleep.podspec +23 -0
- package/ios/AsleepModule.swift +202 -0
- package/package.json +42 -0
- package/src/Asleep.types.ts +87 -0
- package/src/AsleepModule.ts +3 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
package ai.asleep.reactnative
|
|
2
|
+
|
|
3
|
+
import ai.asleep.asleepsdk.Asleep
|
|
4
|
+
import ai.asleep.asleepsdk.data.AsleepConfig
|
|
5
|
+
import ai.asleep.asleepsdk.data.Report
|
|
6
|
+
import ai.asleep.asleepsdk.data.SleepSession
|
|
7
|
+
import ai.asleep.reactnative.service.AsleepService
|
|
8
|
+
import ai.asleep.asleepsdk.tracking.Reports
|
|
9
|
+
import ai.asleep.asleepsdk.tracking.SleepTrackingManager
|
|
10
|
+
import com.google.gson.Gson
|
|
11
|
+
import com.google.gson.reflect.TypeToken
|
|
12
|
+
import expo.modules.kotlin.exception.CodedException
|
|
13
|
+
import expo.modules.kotlin.modules.Module
|
|
14
|
+
import expo.modules.kotlin.modules.ModuleDefinition
|
|
15
|
+
import expo.modules.kotlin.Promise
|
|
16
|
+
import android.Manifest
|
|
17
|
+
import android.app.Activity
|
|
18
|
+
import android.app.Notification
|
|
19
|
+
import android.app.NotificationChannel
|
|
20
|
+
import android.app.NotificationManager
|
|
21
|
+
import android.app.PendingIntent
|
|
22
|
+
import android.content.ComponentName
|
|
23
|
+
import android.content.Context
|
|
24
|
+
import android.content.Intent
|
|
25
|
+
import android.content.pm.PackageManager
|
|
26
|
+
import android.content.ServiceConnection
|
|
27
|
+
import android.os.Build
|
|
28
|
+
import android.os.IBinder
|
|
29
|
+
import androidx.core.app.ActivityCompat
|
|
30
|
+
import androidx.core.app.NotificationCompat
|
|
31
|
+
import androidx.core.content.ContextCompat
|
|
32
|
+
import androidx.lifecycle.LiveData
|
|
33
|
+
import androidx.lifecycle.MutableLiveData
|
|
34
|
+
import androidx.lifecycle.ViewModel
|
|
35
|
+
import androidx.lifecycle.viewModelScope
|
|
36
|
+
import android.app.Application
|
|
37
|
+
import kotlinx.coroutines.*
|
|
38
|
+
import kotlin.coroutines.resume
|
|
39
|
+
import kotlin.coroutines.resumeWithException
|
|
40
|
+
import ai.asleep.reactnative.IAsleepService
|
|
41
|
+
import ai.asleep.reactnative.IListener
|
|
42
|
+
import ai.asleep.reactnative.data.ErrorCode
|
|
43
|
+
import ai.asleep.reactnative.utils.PreferenceHelper
|
|
44
|
+
import android.os.DeadObjectException
|
|
45
|
+
import android.util.Log
|
|
46
|
+
|
|
47
|
+
class AsleepModule : Module() {
|
|
48
|
+
private val gson = Gson()
|
|
49
|
+
|
|
50
|
+
private var _asleepConfig: AsleepConfig? = null
|
|
51
|
+
|
|
52
|
+
private var _sessionId = MutableLiveData<String?>(null)
|
|
53
|
+
val sessionId: LiveData<String?> get() = _sessionId
|
|
54
|
+
|
|
55
|
+
private var _sequence = MutableLiveData<Int?>(null)
|
|
56
|
+
val sequence: LiveData<Int?> get() = _sequence
|
|
57
|
+
|
|
58
|
+
private var _reportManager: Reports? = null
|
|
59
|
+
|
|
60
|
+
private var asleepService: IAsleepService? = null
|
|
61
|
+
private var isBound = false
|
|
62
|
+
|
|
63
|
+
val trackingState: LiveData<TrackingState> get() = _trackingState
|
|
64
|
+
private var _trackingState = MutableLiveData(TrackingState.STATE_TRACKING_STOPPED)
|
|
65
|
+
enum class TrackingState { STATE_TRACKING_STOPPED, STATE_TRACKING_STARTING, STATE_TRACKING_STARTED, STATE_TRACKING_STOPPING}
|
|
66
|
+
|
|
67
|
+
companion object {
|
|
68
|
+
public const val MICROPHONE_PERMISSION_REQUEST_CODE = 1001
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
private val listener = object : IListener.Stub() {
|
|
73
|
+
override fun onUserIdReceived(userId: String) {
|
|
74
|
+
sendEvent("onDebugLog", mapOf("message" to "onUserIdReceived: $userId"))
|
|
75
|
+
sendEvent("onUserJoined", mapOf("userId" to userId))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
override fun onSessionIdReceived(sessionId: String) {
|
|
79
|
+
sendEvent("onDebugLog", mapOf("message" to "onSessionIdReceived: $sessionId"))
|
|
80
|
+
sendEvent("onTrackingClosed", mapOf("sessionId" to sessionId))
|
|
81
|
+
_sessionId.postValue(sessionId)
|
|
82
|
+
_trackingState.postValue(TrackingState.STATE_TRACKING_STARTED)
|
|
83
|
+
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
override fun onSequenceReceived(sequence: Int) {
|
|
87
|
+
sendEvent("onDebugLog", mapOf("message" to "onSequenceReceived: $sequence"))
|
|
88
|
+
sendEvent("onTrackingUploaded", mapOf("sequence" to sequence))
|
|
89
|
+
_sequence.postValue(sequence)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
override fun onErrorCodeReceived(errorCode: ErrorCode) {
|
|
93
|
+
sendEvent("onDebugLog", mapOf("message" to "onErrorCodeReceived: ${errorCode.code}"))
|
|
94
|
+
sendEvent("onTrackingFailed", mapOf("errorCode" to errorCode.code))
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
override fun onStopTrackingReceived(sessionId: String) {
|
|
98
|
+
sendEvent("onDebugLog", mapOf("message" to "onStopTrackingReceived: $sessionId"))
|
|
99
|
+
sendEvent("onTrackingClosed", mapOf("sessionId" to sessionId))
|
|
100
|
+
_sessionId.postValue(sessionId)
|
|
101
|
+
_trackingState.postValue(TrackingState.STATE_TRACKING_STOPPED)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private val connection = object : ServiceConnection {
|
|
106
|
+
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
|
|
107
|
+
try {
|
|
108
|
+
asleepService = IAsleepService.Stub.asInterface(service)
|
|
109
|
+
asleepService?.registerListener(listener)
|
|
110
|
+
isBound = true
|
|
111
|
+
} catch (e: Exception) {
|
|
112
|
+
Log.e("AsleepModule", "Service connection failed", e)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
override fun onServiceDisconnected(name: ComponentName?) {
|
|
117
|
+
try {
|
|
118
|
+
if (isBound) {
|
|
119
|
+
asleepService?.unregisterListener(listener)
|
|
120
|
+
asleepService = null
|
|
121
|
+
isBound = false
|
|
122
|
+
|
|
123
|
+
appContext.currentActivity?.let { activity ->
|
|
124
|
+
if (!activity.isFinishing) {
|
|
125
|
+
sendEvent("onServiceDisconnected", mapOf("message" to "Service disconnected"))
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch (e: Exception) {
|
|
130
|
+
Log.e("AsleepModule", "Service disconnection error", e)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
fun bindService() {
|
|
137
|
+
try {
|
|
138
|
+
if (!isBound) {
|
|
139
|
+
val intent = Intent(appContext.reactContext, AsleepService::class.java)
|
|
140
|
+
appContext.reactContext?.bindService(intent, connection, Context.BIND_AUTO_CREATE)
|
|
141
|
+
}
|
|
142
|
+
} catch (e: Exception) {
|
|
143
|
+
Log.e("AsleepModule", "bindService failed", e)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fun unbindService() {
|
|
148
|
+
try {
|
|
149
|
+
if (isBound) {
|
|
150
|
+
appContext.reactContext?.unbindService(connection)
|
|
151
|
+
asleepService = null
|
|
152
|
+
isBound = false
|
|
153
|
+
}
|
|
154
|
+
} catch (e: Exception) {
|
|
155
|
+
Log.e("AsleepModule", "unbindService failed", e)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
override fun definition() = ModuleDefinition {
|
|
160
|
+
Name("Asleep")
|
|
161
|
+
|
|
162
|
+
Events("onTrackingCreated", "onTrackingUploaded", "onTrackingClosed", "onTrackingFailed", "onUserJoined", "onUserJoinFailed", "onDebugLog")
|
|
163
|
+
|
|
164
|
+
AsyncFunction("initAsleepConfig") { apiKey: String, userId: String?, baseUrl: String?, callbackUrl: String?, promise: Promise ->
|
|
165
|
+
try {
|
|
166
|
+
val context = appContext.reactContext!!.applicationContext as Application
|
|
167
|
+
val isTracking = PreferenceHelper.isTracking(context)
|
|
168
|
+
val savedApiKey = PreferenceHelper.getApiKey(context)
|
|
169
|
+
val savedUserId = PreferenceHelper.getUserId(context)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
if (isTracking && savedApiKey == apiKey && savedUserId == userId) {
|
|
173
|
+
|
|
174
|
+
if (AsleepService.isAsleepServiceRunning(context)) {
|
|
175
|
+
|
|
176
|
+
bindService()
|
|
177
|
+
promise.resolve("Service reconnected")
|
|
178
|
+
sendEvent("onDebugLog", mapOf("message" to "Service reconnected"))
|
|
179
|
+
return@AsyncFunction
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
PreferenceHelper.putApiKey(context, apiKey)
|
|
185
|
+
|
|
186
|
+
Asleep.initAsleepConfig(
|
|
187
|
+
context = appContext.reactContext!!.applicationContext as Application,
|
|
188
|
+
apiKey = apiKey,
|
|
189
|
+
userId = userId,
|
|
190
|
+
baseUrl = baseUrl,
|
|
191
|
+
callbackUrl = callbackUrl,
|
|
192
|
+
service = "SleepTracking",
|
|
193
|
+
object : Asleep.AsleepConfigListener {
|
|
194
|
+
override fun onSuccess(userId: String?, asleepConfig: AsleepConfig?) {
|
|
195
|
+
if (userId != null) {
|
|
196
|
+
PreferenceHelper.putUserId(appContext.reactContext!!.applicationContext as Application, userId)
|
|
197
|
+
}
|
|
198
|
+
_asleepConfig = asleepConfig
|
|
199
|
+
|
|
200
|
+
if (_asleepConfig != null) {
|
|
201
|
+
_reportManager = Asleep.createReports(_asleepConfig)
|
|
202
|
+
} else {
|
|
203
|
+
sendEvent("onDebugLog", mapOf("message" to "AsleepConfig is null"))
|
|
204
|
+
promise.reject("CONFIG_ERROR", "AsleepConfig is null", null)
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
bindService()
|
|
209
|
+
|
|
210
|
+
promise.resolve("Initialization successful")
|
|
211
|
+
try {
|
|
212
|
+
sendEvent("onDebugLog", mapOf("message" to "Initialization successful"))
|
|
213
|
+
} catch (e: Exception) {
|
|
214
|
+
println("Error sending debug log: ${e.message}")
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
override fun onFail(errorCode: Int, detail: String) {
|
|
219
|
+
sendEvent("onDebugLog", mapOf("message" to "Initialization failed: $errorCode - $detail"))
|
|
220
|
+
promise.reject("INITIALIZATION_FAILED", "Initialization failed: $errorCode - $detail", null)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
} catch (e: Exception) {
|
|
226
|
+
sendEvent("onDebugLog", mapOf("message" to "Initialization failed: ${e.message}"))
|
|
227
|
+
promise.reject("UNEXPECTED_ERROR", "Initialization failed: ${e.message}", e)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
AsyncFunction("startTracking") { promise: Promise ->
|
|
232
|
+
val activity = appContext.currentActivity
|
|
233
|
+
val context = appContext.reactContext!!.applicationContext as Application
|
|
234
|
+
PreferenceHelper.putIsTracking(context, true)
|
|
235
|
+
if (activity != null) {
|
|
236
|
+
val intent = Intent(activity, AsleepService::class.java)
|
|
237
|
+
intent.action = AsleepService.ACTION_START_TRACKING
|
|
238
|
+
|
|
239
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
240
|
+
activity.startForegroundService(intent)
|
|
241
|
+
} else {
|
|
242
|
+
activity.startService(intent)
|
|
243
|
+
}
|
|
244
|
+
promise.resolve("Tracking started")
|
|
245
|
+
} else {
|
|
246
|
+
promise.reject("ACTIVITY_NOT_FOUND", "Activity not found", null)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
Function("isTracking") {
|
|
251
|
+
val context = appContext.reactContext!!.applicationContext as Application
|
|
252
|
+
return@Function PreferenceHelper.isTracking(context)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
AsyncFunction("stopTracking") { promise: Promise ->
|
|
256
|
+
val activity = appContext.currentActivity
|
|
257
|
+
val context = appContext.reactContext!!.applicationContext as Application
|
|
258
|
+
PreferenceHelper.putIsTracking(context, false)
|
|
259
|
+
if (activity != null) {
|
|
260
|
+
val intent = Intent(activity, AsleepService::class.java)
|
|
261
|
+
intent.action = AsleepService.ACTION_STOP_TRACKING
|
|
262
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
263
|
+
activity.startForegroundService(intent)
|
|
264
|
+
} else {
|
|
265
|
+
activity.startService(intent)
|
|
266
|
+
}
|
|
267
|
+
promise.resolve("Tracking stopped")
|
|
268
|
+
} else {
|
|
269
|
+
promise.reject("ACTIVITY_NOT_FOUND", "Activity not found", null)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
AsyncFunction("getReport") { sessionId: String, promise: Promise ->
|
|
275
|
+
try {
|
|
276
|
+
if (_reportManager == null) {
|
|
277
|
+
promise.reject("UNINITIALIZED_REPORT_MANAGER", "Report manager is not initialized", null)
|
|
278
|
+
}
|
|
279
|
+
_reportManager?.getReport(sessionId, object : Reports.ReportListener {
|
|
280
|
+
override fun onSuccess(report: Report?) {
|
|
281
|
+
sendEvent("onDebugLog", mapOf("message" to "Report retrieval successful: ${report?.serializeToMap()}"))
|
|
282
|
+
promise.resolve(report?.serializeToMap())
|
|
283
|
+
}
|
|
284
|
+
override fun onFail(errorCode: Int, detail: String) {
|
|
285
|
+
val errorMessage = "Report retrieval failed: errorCode=$errorCode, detail=$detail"
|
|
286
|
+
sendEvent("onDebugLog", mapOf("message" to errorMessage))
|
|
287
|
+
promise.reject("REPORT_ERROR", errorMessage, null)
|
|
288
|
+
}
|
|
289
|
+
})
|
|
290
|
+
} catch (e: Exception) {
|
|
291
|
+
val errorMessage = "Report retrieval failed: ${e.message}"
|
|
292
|
+
sendEvent("onDebugLog", mapOf("message" to errorMessage))
|
|
293
|
+
promise.reject("UNEXPECTED_ERROR", errorMessage, e)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
AsyncFunction("getReportList") { fromDate: String, toDate: String, promise: Promise ->
|
|
300
|
+
try {
|
|
301
|
+
if (_reportManager == null) {
|
|
302
|
+
promise.reject("UNINITIALIZED_REPORT_MANAGER", "Report manager is not initialized", null)
|
|
303
|
+
}
|
|
304
|
+
_reportManager?.getReports(
|
|
305
|
+
fromDate,
|
|
306
|
+
toDate,
|
|
307
|
+
orderBy = "DESC",
|
|
308
|
+
offset = 0,
|
|
309
|
+
limit = 100,
|
|
310
|
+
object : Reports.ReportsListener {
|
|
311
|
+
override fun onSuccess(reports: List<SleepSession>?) {
|
|
312
|
+
sendEvent("onDebugLog", mapOf("message" to "Get report list success: ${reports?.map { it.serializeToMap() } ?: emptyList()}"))
|
|
313
|
+
promise.resolve(reports?.map { it.serializeToMap() } ?: emptyList<Map<String, Any>>())
|
|
314
|
+
}
|
|
315
|
+
override fun onFail(errorCode: Int, detail: String) {
|
|
316
|
+
val errorMessage = "Get report list failed: errorCode=$errorCode, detail=$detail"
|
|
317
|
+
sendEvent("onDebugLog", mapOf("message" to errorMessage))
|
|
318
|
+
}
|
|
319
|
+
})
|
|
320
|
+
} catch (e: Exception) {
|
|
321
|
+
val errorMessage = "Get report list failed: ${e.message}"
|
|
322
|
+
sendEvent("onDebugLog", mapOf("message" to errorMessage))
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
AsyncFunction("requestMicrophonePermission") { promise: Promise ->
|
|
327
|
+
CoroutineScope(Dispatchers.Main).launch {
|
|
328
|
+
try {
|
|
329
|
+
val audioPermission = ContextCompat.checkSelfPermission(appContext.reactContext!!, Manifest.permission.RECORD_AUDIO)
|
|
330
|
+
val fgsPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
331
|
+
ContextCompat.checkSelfPermission(appContext.reactContext!!, Manifest.permission.FOREGROUND_SERVICE_MICROPHONE)
|
|
332
|
+
} else {
|
|
333
|
+
PackageManager.PERMISSION_GRANTED
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (audioPermission != PackageManager.PERMISSION_GRANTED || fgsPermission != PackageManager.PERMISSION_GRANTED) {
|
|
337
|
+
ActivityCompat.requestPermissions(
|
|
338
|
+
appContext.currentActivity!!,
|
|
339
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
340
|
+
arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.FOREGROUND_SERVICE_MICROPHONE)
|
|
341
|
+
} else {
|
|
342
|
+
arrayOf(Manifest.permission.RECORD_AUDIO)
|
|
343
|
+
},
|
|
344
|
+
MICROPHONE_PERMISSION_REQUEST_CODE
|
|
345
|
+
)
|
|
346
|
+
promise.resolve(false)
|
|
347
|
+
} else {
|
|
348
|
+
promise.resolve(true)
|
|
349
|
+
}
|
|
350
|
+
} catch (e: Exception) {
|
|
351
|
+
promise.reject("PERMISSION_ERROR", "Error requesting microphone permission: ${e.message}", e)
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
AsyncFunction("setCustomNotification") { title: String, text: String, promise: Promise ->
|
|
357
|
+
try {
|
|
358
|
+
val context = appContext.reactContext!!.applicationContext as Application
|
|
359
|
+
PreferenceHelper.putNotificationTitle(context, title)
|
|
360
|
+
PreferenceHelper.putNotificationText(context, text)
|
|
361
|
+
promise.resolve(null)
|
|
362
|
+
} catch (e: Exception) {
|
|
363
|
+
promise.reject("NOTIFICATION_ERROR", "Failed to set custom notification: ${e.message}", e)
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
private fun <T> T.serializeToMap(): Map<String, Any> {
|
|
370
|
+
return convert()
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private inline fun <reified T> Map<String, Any>.toDataClass(): T {
|
|
374
|
+
return convert()
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
private inline fun <I, reified O> I.convert(): O {
|
|
378
|
+
val json = gson.toJson(this)
|
|
379
|
+
return gson.fromJson(json, object : TypeToken<O>() {}.type)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private suspend fun requestMicrophonePermission(): Boolean = suspendCancellableCoroutine { cont ->
|
|
383
|
+
val activity = appContext.currentActivity
|
|
384
|
+
if (activity != null) {
|
|
385
|
+
val permission = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
|
|
386
|
+
if (permission != PackageManager.PERMISSION_GRANTED) {
|
|
387
|
+
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.RECORD_AUDIO), MICROPHONE_PERMISSION_REQUEST_CODE)
|
|
388
|
+
cont.resume(false)
|
|
389
|
+
} else {
|
|
390
|
+
cont.resume(true)
|
|
391
|
+
}
|
|
392
|
+
} else {
|
|
393
|
+
cont.resumeWithException(Exception("Activity is null, cannot request microphone permission"))
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
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
|
+
}
|