-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLightningNodeService.kt
More file actions
188 lines (165 loc) · 7.09 KB
/
LightningNodeService.kt
File metadata and controls
188 lines (165 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package to.bitkit.androidServices
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.lightningdevkit.ldknode.Event
import to.bitkit.App
import to.bitkit.AppLifecycleListener
import to.bitkit.R
import to.bitkit.data.CacheStore
import to.bitkit.di.UiDispatcher
import to.bitkit.domain.commands.NotifyPaymentReceived
import to.bitkit.domain.commands.NotifyPaymentReceivedHandler
import to.bitkit.models.NewTransactionSheetDetails
import to.bitkit.models.NotificationDetails
import to.bitkit.repositories.LightningRepo
import to.bitkit.repositories.WalletRepo
import to.bitkit.ui.ID_NOTIFICATION_NODE
import to.bitkit.ui.MainActivity
import to.bitkit.ui.pushNotification
import to.bitkit.utils.Logger
import to.bitkit.utils.jsonLogOf
import javax.inject.Inject
@AndroidEntryPoint
class LightningNodeService : Service() {
@Inject
@UiDispatcher
lateinit var uiDispatcher: CoroutineDispatcher
private val serviceScope by lazy { CoroutineScope(SupervisorJob() + uiDispatcher) }
@Inject
lateinit var lightningRepo: LightningRepo
@Inject
lateinit var walletRepo: WalletRepo
@Inject
lateinit var notifyPaymentReceivedHandler: NotifyPaymentReceivedHandler
@Inject
lateinit var cacheStore: CacheStore
private var lifecycleListener: AppLifecycleListener? = null
override fun onCreate() {
super.onCreate()
startForeground(ID_NOTIFICATION_NODE, createNotification())
setupService()
setupLifecycleListener()
}
private fun setupLifecycleListener() {
lifecycleListener = AppLifecycleListener { isInForeground ->
Logger.debug("App lifecycle changed: isInForeground=$isInForeground", context = TAG)
serviceScope.launch {
if (isInForeground) {
lightningRepo.disableBatterySavingMode()
.onSuccess { Logger.debug("Exited battery saving mode", context = TAG) }
.onFailure { Logger.warn("Error exiting battery saving mode", it, context = TAG) }
} else {
lightningRepo.enableBatterySavingMode()
.onSuccess { Logger.debug("Entered battery saving mode", context = TAG) }
.onFailure { Logger.warn("Error entering battery saving mode", it, context = TAG) }
}
}
}.also { App.lifecycle?.addListener(it) }
}
private fun setupService() {
serviceScope.launch {
lightningRepo.start(
eventHandler = { event ->
Logger.debug("LDK-node event received in $TAG: ${jsonLogOf(event)}", context = TAG)
handlePaymentReceived(event)
}
).onSuccess {
walletRepo.setWalletExistsState()
walletRepo.refreshBip21()
walletRepo.syncBalances()
}
}
}
private suspend fun handlePaymentReceived(event: Event) {
if (event !is Event.PaymentReceived && event !is Event.OnchainTransactionReceived) return
val command = NotifyPaymentReceived.Command.from(event, includeNotification = true) ?: return
notifyPaymentReceivedHandler(command).onSuccess {
Logger.debug("Payment notification result: $it", context = TAG)
if (it !is NotifyPaymentReceived.Result.ShowNotification) return
showPaymentNotification(it.sheet, it.notification)
}
}
private fun showPaymentNotification(
sheet: NewTransactionSheetDetails,
notification: NotificationDetails,
) {
if (App.lifecycle?.activity != null) {
Logger.debug("Skipping payment notification: activity is active", context = TAG)
return
}
Logger.debug("Showing payment notification: ${notification.title}", context = TAG)
serviceScope.launch { cacheStore.setBackgroundReceive(sheet) }
pushNotification(notification.title, notification.body)
}
private fun createNotification(
contentText: String = getString(R.string.notification__service__body),
): Notification {
val notificationIntent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
// Create stop action that will close both service and app
val stopIntent = Intent(this, LightningNodeService::class.java).apply { action = ACTION_STOP_SERVICE_AND_APP }
val stopPendingIntent = PendingIntent.getService(this, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(this, CHANNEL_ID_NODE)
.setContentTitle(getString(R.string.app_name))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_bitkit_outlined)
.setColor(ContextCompat.getColor(this, R.color.brand))
.setContentIntent(pendingIntent)
.setOngoing(true)
.addAction(R.drawable.ic_x, getString(R.string.notification__service__stop), stopPendingIntent)
.build()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Logger.debug("onStartCommand", context = TAG)
when (intent?.action) {
ACTION_STOP_SERVICE_AND_APP -> {
Logger.debug("ACTION_STOP_SERVICE_AND_APP detected", context = TAG)
// Close activities gracefully without force-stopping the app
App.lifecycle?.activity?.finishAffinity()
// Stop the service
stopSelf()
return START_NOT_STICKY
}
}
return START_STICKY
}
override fun onDestroy() {
Logger.debug("onDestroy", context = TAG)
lifecycleListener?.let { App.lifecycle?.removeListener(it) }
serviceScope.launch {
lightningRepo.stop()
serviceScope.cancel()
}
super.onDestroy()
}
@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
override fun onTimeout(startId: Int, fgsType: Int) {
Logger.warn("Foreground service timeout reached", context = TAG)
serviceScope.launch {
lightningRepo.stop()
stopSelf()
}
super.onTimeout(startId, fgsType)
}
override fun onBind(intent: Intent?): IBinder? = null
companion object {
const val TAG = "LightningNodeService"
const val CHANNEL_ID_NODE = "bitkit_notification_channel_node"
const val ACTION_STOP_SERVICE_AND_APP = "to.bitkit.androidServices.action.STOP_SERVICE_AND_APP"
}
}