Change the clear logs task to a workmanager

This commit is contained in:
greenart7c3
2025-07-11 13:04:06 -03:00
parent 72ac146828
commit 1622a3c9f6
3 changed files with 87 additions and 82 deletions
@@ -1,14 +1,14 @@
package com.greenart7c3.nostrsigner
import android.app.AlarmManager
import android.app.Application
import android.app.PendingIntent
import android.content.Intent
import android.net.NetworkCapabilities
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import coil3.ImageLoader
import coil3.SingletonImageLoader
@@ -23,7 +23,7 @@ import com.greenart7c3.nostrsigner.okhttp.HttpClientManager
import com.greenart7c3.nostrsigner.okhttp.OkHttpWebSocket
import com.greenart7c3.nostrsigner.relays.AmberListenerSingleton
import com.greenart7c3.nostrsigner.relays.AmberRelayStats
import com.greenart7c3.nostrsigner.service.BootReceiver
import com.greenart7c3.nostrsigner.service.ClearLogsWorker
import com.greenart7c3.nostrsigner.service.ConnectivityService
import com.greenart7c3.nostrsigner.service.NotificationDataSource
import com.greenart7c3.nostrsigner.service.ProfileDataSource
@@ -44,6 +44,7 @@ import java.lang.ref.WeakReference
import java.net.InetSocketAddress
import java.net.Socket
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -134,19 +135,18 @@ class Amber : Application() {
}
private fun startCleanLogsAlarm() {
val alarmManager = this.getSystemService(ALARM_SERVICE) as AlarmManager
val intent = Intent(this, BootReceiver::class.java)
intent.action = BootReceiver.CLEAR_LOGS_ACTION
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)
val workRequest = PeriodicWorkRequestBuilder<ClearLogsWorker>(
24,
TimeUnit.HOURS,
)
.setInitialDelay(5, TimeUnit.MINUTES) // Delay first run by 5 minutes
.addTag("clearLogsWork")
.build()
val interval: Long = 24 * 60 * 60 * 1000 // 24 hours in milliseconds
val triggerAtMillis = System.currentTimeMillis() + (5 * 60 * 1000) // start after 5 minutes
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
triggerAtMillis,
interval,
pendingIntent,
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"ClearLogsWorker",
ExistingPeriodicWorkPolicy.REPLACE,
workRequest,
)
}
@@ -7,19 +7,10 @@ import android.os.Build
import android.util.Log
import com.greenart7c3.nostrsigner.Amber
import com.greenart7c3.nostrsigner.BuildConfig
import com.greenart7c3.nostrsigner.LocalPreferences
import com.vitorpamplona.quartz.utils.TimeUtils
import com.vitorpamplona.quartz.utils.TimeUtils.ONE_WEEK
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class BootReceiver : BroadcastReceiver() {
companion object {
const val CLEAR_LOGS_ACTION = "CLEAR_AMBER_LOGS"
}
override fun onReceive(context: Context, intent: Intent) {
@Suppress("KotlinConstantConditions")
if (BuildConfig.FLAVOR == "offline") return
@@ -55,64 +46,6 @@ class BootReceiver : BroadcastReceiver() {
Amber.instance.startService()
}
}
CLEAR_LOGS_ACTION -> {
Log.d(Amber.TAG, "Received CLEAR_LOGS_ACTION")
Amber.instance.applicationIOScope.launch(Dispatchers.IO) {
LocalPreferences.allSavedAccounts(Amber.instance).forEach {
Amber.instance.getDatabase(it.npub).let { database ->
try {
val oneWeek = System.currentTimeMillis() - (ONE_WEEK * 1000L)
val oneWeekAgo = TimeUtils.oneWeekAgo()
val countHistory = database.applicationDao().countOldHistory(oneWeekAgo)
Log.d(Amber.TAG, "Deleting $countHistory old history entries")
if (countHistory > 0) {
var logs = database.applicationDao().getOldHistory(oneWeekAgo)
var count = 0
while (logs.isNotEmpty()) {
count++
logs.forEach { history ->
database.applicationDao().deleteHistory(history)
}
logs = database.applicationDao().getOldHistory(oneWeekAgo)
}
}
val countNotification = database.applicationDao().countOldNotification(oneWeekAgo)
Log.d(Amber.TAG, "Deleting $countNotification old notification entries")
if (countNotification > 0) {
var logs = database.applicationDao().getOldNotification(oneWeekAgo)
var count = 0
while (logs.isNotEmpty()) {
count++
logs.forEach { history ->
database.applicationDao().deleteNotification(history)
}
logs = database.applicationDao().getOldNotification(oneWeekAgo)
}
}
val countLog = database.applicationDao().countOldLog(oneWeek)
Log.d(Amber.TAG, "Deleting $countLog old log entries from ${com.greenart7c3.nostrsigner.models.TimeUtils.formatLongToCustomDateTimeWithSeconds(oneWeek)}")
if (countLog > 0) {
var logs = database.applicationDao().getOldLog(oneWeek)
var count = 0
while (logs.isNotEmpty()) {
count++
logs.forEach { history ->
Log.d(Amber.TAG, "Deleting log entry ${com.greenart7c3.nostrsigner.models.TimeUtils.formatLongToCustomDateTimeWithSeconds(history.time)}")
database.applicationDao().deleteLog(history)
}
logs = database.applicationDao().getOldLog(oneWeek)
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
Log.e(Amber.TAG, "Error deleting old log entries", e)
}
}
}
}
}
}
}
}
@@ -0,0 +1,72 @@
package com.greenart7c3.nostrsigner.service
import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.greenart7c3.nostrsigner.Amber
import com.greenart7c3.nostrsigner.LocalPreferences
import com.vitorpamplona.quartz.utils.TimeUtils
import com.vitorpamplona.quartz.utils.TimeUtils.ONE_WEEK
import kotlin.coroutines.cancellation.CancellationException
class ClearLogsWorker(appContext: Context, workerParams: WorkerParameters) :
CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
LocalPreferences.allSavedAccounts(Amber.instance).forEach {
Amber.instance.getDatabase(it.npub).let { database ->
try {
val oneWeek = System.currentTimeMillis() - (ONE_WEEK * 1000L)
val oneWeekAgo = TimeUtils.oneWeekAgo()
val countHistory = database.applicationDao().countOldHistory(oneWeekAgo)
Log.d(Amber.TAG, "Deleting $countHistory old history entries")
if (countHistory > 0) {
var logs = database.applicationDao().getOldHistory(oneWeekAgo)
var count = 0
while (logs.isNotEmpty()) {
count++
logs.forEach { history ->
database.applicationDao().deleteHistory(history)
}
logs = database.applicationDao().getOldHistory(oneWeekAgo)
}
}
val countNotification = database.applicationDao().countOldNotification(oneWeekAgo)
Log.d(Amber.TAG, "Deleting $countNotification old notification entries")
if (countNotification > 0) {
var logs = database.applicationDao().getOldNotification(oneWeekAgo)
var count = 0
while (logs.isNotEmpty()) {
count++
logs.forEach { history ->
database.applicationDao().deleteNotification(history)
}
logs = database.applicationDao().getOldNotification(oneWeekAgo)
}
}
val countLog = database.applicationDao().countOldLog(oneWeek)
Log.d(Amber.TAG, "Deleting $countLog old log entries from ${com.greenart7c3.nostrsigner.models.TimeUtils.formatLongToCustomDateTimeWithSeconds(oneWeek)}")
if (countLog > 0) {
var logs = database.applicationDao().getOldLog(oneWeek)
var count = 0
while (logs.isNotEmpty()) {
count++
logs.forEach { history ->
Log.d(Amber.TAG, "Deleting log entry ${com.greenart7c3.nostrsigner.models.TimeUtils.formatLongToCustomDateTimeWithSeconds(history.time)}")
database.applicationDao().deleteLog(history)
}
logs = database.applicationDao().getOldLog(oneWeek)
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
Log.e(Amber.TAG, "Error deleting old log entries", e)
}
}
}
return Result.success()
}
}