-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLightningNodeService.kt
More file actions
226 lines (195 loc) · 8.5 KB
/
LightningNodeService.kt
File metadata and controls
226 lines (195 loc) · 8.5 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package to.bitkit.androidServices
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
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.launch
import org.lightningdevkit.ldknode.Event
import to.bitkit.App
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.domain.commands.NotifyPendingPaymentResolved
import to.bitkit.domain.commands.NotifyPendingPaymentResolvedHandler
import to.bitkit.ext.activityManager
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
typealias Hook = (() -> Unit)?
@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 notifyPendingPaymentResolvedHandler: NotifyPendingPaymentResolvedHandler
@Inject
lateinit var cacheStore: CacheStore
private var hasStartedNode = false
private fun setupService() {
if (hasStartedNode) return
hasStartedNode = true
serviceScope.launch {
lightningRepo.start(
eventHandler = { event ->
Logger.debug("LDK-node event received in $TAG: ${jsonLogOf(event)}", context = TAG)
handlePaymentReceived(event)
handlePendingPaymentResolved(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.currentActivity?.value != 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 suspend fun handlePendingPaymentResolved(event: Event) {
val command = NotifyPendingPaymentResolved.Command.from(event) ?: return
notifyPendingPaymentResolvedHandler(command).onSuccess {
if (it !is NotifyPendingPaymentResolved.Result.ShowNotification) return
if (App.currentActivity?.value != null) {
Logger.debug("Skipping pending payment notification: activity is active", context = TAG)
return
}
Logger.debug("Showing pending payment notification for '${command.paymentHash}'", context = TAG)
pushNotification(it.notification.title, it.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 {
val action = intent?.action
Logger.debug("Received start command action '$action'", context = TAG)
when (action) {
ACTION_STOP_SERVICE_AND_APP -> {
stopForegroundService(startId) { Logger.debug("Received stop service action", context = TAG) }
activityManager.appTasks.forEach { it.finishAndRemoveTask() }
serviceScope.launch { lightningRepo.stop() }
}
ACTION_START_SERVICE -> if (promoteToForeground(startId)) setupService()
else -> stop(startId) { Logger.warn("Stopped service for unsupported action '$action'", context = TAG) }
}
return START_NOT_STICKY
}
private fun promoteToForeground(startId: Int): Boolean {
return runCatching {
ServiceCompat.startForeground(
this,
ID_NOTIFICATION_NODE,
createNotification(),
foregroundServiceTypeDataSync(),
)
}.fold(
onSuccess = { true },
onFailure = {
if (it !is RuntimeException) throw it
stop(startId) { Logger.error("Failed to promote foreground service", it, context = TAG) }
false
}
)
}
private fun foregroundServiceTypeDataSync(): Int {
return if (VERSION.SDK_INT >= VERSION_CODES.Q) ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC else 0
}
private fun stopForegroundService(startId: Int, hook: Hook = null) {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
stop(startId, hook)
}
private fun stop(startId: Int, hook: Hook = null) {
hook?.invoke()
stopSelf(startId)
}
override fun onDestroy() {
Logger.debug("onDestroy", context = TAG)
// Safe to call even if already stopped — guarded by lifecycleMutex + isStoppedOrStopping()
serviceScope.launch { lightningRepo.stop() }
super.onDestroy()
}
@RequiresApi(VERSION_CODES.VANILLA_ICE_CREAM)
override fun onTimeout(startId: Int, fgsType: Int) {
Logger.warn("Reached foreground service timeout for type '$fgsType'", context = TAG)
stopForegroundService(startId)
serviceScope.launch { lightningRepo.stop() }
super.onTimeout(startId, fgsType)
}
override fun onBind(intent: Intent?): IBinder? = null
companion object {
const val CHANNEL_ID_NODE = "bitkit_notification_channel_node"
const val TAG = "LightningNodeService"
const val ACTION_START_SERVICE = "to.bitkit.androidServices.action.START_SERVICE"
const val ACTION_STOP_SERVICE_AND_APP = "to.bitkit.androidServices.action.STOP_SERVICE_AND_APP"
}
}