Skip to content

Commit

Permalink
initial repo background updater
Browse files Browse the repository at this point in the history
  • Loading branch information
DerGoogler committed Oct 13, 2024
1 parent 6d6c74a commit ff2dd51
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 1 deletion.
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ dependencies {
implementation(libs.rikka.shizuku.api)
implementation(libs.rikka.shizuku.provider)

implementation(libs.androidx.work.runtime.ktx)
implementation(libs.androidx.runtime.android)
implementation(libs.androidx.annotation)
implementation(libs.androidx.activity.compose)
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
<activity
android:name=".ui.activity.ModConfActivity"
android:exported="true"
android:label="@string/modconf_activity"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ class MainActivity : MMRLComponentActivity() {
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)

startRepoUpdateService()

splashScreen.setKeepOnScreenCondition { isLoading }

setBaseContent {
Expand Down
113 changes: 113 additions & 0 deletions app/src/main/kotlin/com/dergoogler/mmrl/worker/RepoUpdateWorker.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package com.dergoogler.mmrl.worker

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.room.Room
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
import com.dergoogler.mmrl.R
import com.dergoogler.mmrl.database.AppDatabase
import com.dergoogler.mmrl.stub.IRepoManager
import timber.log.Timber

class RepoUpdateWorker(
private val context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params) {

override suspend fun doWork(): Result {
setForeground(createForegroundInfo())

return try {
val updated = updateRepositories()

if (updated) {
createNotification(
title = context.getString(R.string.repo_update_service),
message = context.getString(R.string.repo_update_service_desc)
)
} else {
createNotification(
title = context.getString(R.string.repo_update_service_failed),
message = context.getString(R.string.repo_update_service_failed_desc)
)
}
Result.success()
} catch (e: Exception) {
Result.failure()
}
}

private suspend fun updateRepositories(): Boolean {

val database: AppDatabase = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"mmrl"
).build()

val repoDao = database.repoDao()
val repos = database.repoDao().getAll()


repos.forEach { repo ->
val repoManager = IRepoManager.build(repo.url)

try {
val response =
repoManager.modules.execute()

if (response.isSuccessful && response.body() != null) {
val modulesJson = response.body()!!

if (repo.metadata.timestamp != modulesJson.metadata.timestamp) {
val updatedRepo = repo.copy(modulesJson = modulesJson)
repoDao.insert(updatedRepo)
}
} else {
Timber.e("Failed to fetch data for repo: ${repo.url}")
return false
}
} catch (e: Exception) {
Timber.e(e, "Error while updating repo: ${repo.url}")
return false
}
}

return true
}

private fun createNotification(title: String, message: String) {
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager


val channel = NotificationChannel(
"RepoUpdateChannel",
"Repo Updates",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)

val notification = NotificationCompat.Builder(context, "RepoUpdateChannel")
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.box)
.build()

notificationManager.notify(1, notification)
}

private fun createForegroundInfo(): ForegroundInfo {
val notification = NotificationCompat.Builder(applicationContext, "repo_update_channel")
.setContentTitle("Updating Repositories")
.setSmallIcon(R.drawable.box)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()

return ForegroundInfo(1, notification)
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
package ext.dergoogler.mmrl.activity

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.dergoogler.mmrl.R
import com.dergoogler.mmrl.repository.LocalRepository
import com.dergoogler.mmrl.repository.UserPreferencesRepository
Expand All @@ -21,7 +28,9 @@ import com.dergoogler.mmrl.ui.activity.InstallActivity
import com.dergoogler.mmrl.ui.activity.ModConfActivity
import com.dergoogler.mmrl.ui.providable.LocalUserPreferences
import com.dergoogler.mmrl.ui.theme.AppTheme
import com.dergoogler.mmrl.worker.RepoUpdateWorker
import dagger.hilt.android.AndroidEntryPoint
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.system.exitProcess

Expand Down Expand Up @@ -70,6 +79,23 @@ open class MMRLComponentActivity : ComponentActivity() {
}
}

fun startRepoUpdateService() {
val updateRequest = PeriodicWorkRequestBuilder<RepoUpdateWorker>(6, TimeUnit.HOURS)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()

WorkManager.getInstance(this)
.enqueueUniquePeriodicWork(
"RepoUpdateWork",
ExistingPeriodicWorkPolicy.UPDATE,
updateRequest
)
}

companion object {
fun startModConfActivity(context: Context, modId: String) {
val intent = Intent(context, ModConfActivity::class.java)
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -209,5 +209,9 @@
<string name="stack_trace_truncated">%s\n… %d more</string>
<string name="additional_notes">Additional Notes</string>
<string name="repo_added">Repo added</string>
<string name="repo_update_service">Repositories updated successfully</string>
<string name="repo_update_service_desc">Don\'t worry, MMRL updated your installed repos for you. 😋</string>
<string name="repo_update_service_failed">No updates found for repositories</string>
<string name="repo_update_service_failed_desc">There are no updates for repositories</string>

</resources>
1 change: 1 addition & 0 deletions app/src/main/res/values/strings_untranslatable.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<resources>
<string name="app_name" translatable="false">MMRL</string>
<string name="install_activity" translatable="false">@string/module_install</string>
<string name="modconf_activity" translatable="false">ModConf</string>

<!-- Setup -->
<string name="setup_shizuku_title" translatable="false">Shizuku</string>
Expand Down
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ squareRetrofit = "2.11.0"
squareOkhttp = "4.12.0"
squareMoshi = "1.15.1"
runtimeAndroid = "1.7.3"
workRuntimeKtx = "2.8.0"

[libraries]
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "androidxActivity" }
Expand Down Expand Up @@ -66,6 +67,7 @@ androidx-room-compiler = { group = "androidx.room", name = "room-compiler", vers
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "androidxRoom" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "androidxRoom" }
androidx-ui = { module = "androidx.compose.ui:ui" }
androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" }
coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" }
compose-markdown = { module = "com.github.jeziellago:compose-markdown", version.ref = "composeMarkdown" }
hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
Expand Down

0 comments on commit ff2dd51

Please sign in to comment.