Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update StoreUtils for In-App update #104

Merged
merged 10 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Stores/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,11 @@ android {
dependencies {
implementation project(path: ':Core')

standardImplementation 'com.google.android.play:core:1.10.3'
def appReviewVersion = "2.0.1"
standardImplementation "com.google.android.play:review:$appReviewVersion"
standardImplementation "com.google.android.play:review-ktx:$appReviewVersion"

def appUpdateVersion = "2.1.0"
standardImplementation "com.google.android.play:app-update:$appUpdateVersion"
standardImplementation "com.google.android.play:app-update-ktx:$appUpdateVersion"
}
44 changes: 38 additions & 6 deletions Stores/src/fdroid/java/com.infomaniak.lib.stores/StoreUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,51 @@
*/
package com.infomaniak.lib.stores

import android.content.Context
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.infomaniak.lib.core.fdroidTools.FdroidApiTools
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

fun FragmentActivity.checkUpdateIsAvailable(appId: String, versionCode: Int, onResult: (updateIsAvailable: Boolean) -> Unit) {
lifecycleScope.launch {
val lastVersionCode = FdroidApiTools().getLastRelease(appId)
object StoreUtils {

withContext(Dispatchers.Main) { onResult(versionCode < lastVersionCode) }
//region legacy App update
// TODO: Remove this when Ui for kDrive in app update will be made
fun FragmentActivity.checkUpdateIsAvailable(appId: String, versionCode: Int, onResult: (updateIsAvailable: Boolean) -> Unit) {
checkUpdateIsAvailable(appId = appId, versionCode = versionCode, inAppResultLauncher = null, onFDroidResult = onResult)
}
//endRegion

KevinBoulongne marked this conversation as resolved.
Show resolved Hide resolved
//region In-App Update
fun initAppUpdateManager(context: Context, onInstall: () -> Unit) = Unit

fun FragmentActivity.checkUpdateIsAvailable(
appId: String,
versionCode: Int,
inAppResultLauncher: ActivityResultLauncher<IntentSenderRequest>?,
onFDroidResult: (updateIsAvailable: Boolean) -> Unit,
) {
lifecycleScope.launch {
val lastVersionCode = FdroidApiTools().getLastRelease(appId)

withContext(Dispatchers.Main) { onFDroidResult(versionCode < lastVersionCode) }
}
}
}

fun FragmentActivity.launchInAppReview() = Unit
fun checkStalledUpdate() = Unit

fun installDownloadedUpdate(onFailure: (Exception) -> Unit) = Unit

fun unregisterAppUpdateListener() = Unit

fun cancelUpdate() = Unit
//endregion

//region In-App Review
fun FragmentActivity.launchInAppReview() = Unit
//endRegion
}
106 changes: 95 additions & 11 deletions Stores/src/standard/java/com.infomaniak.lib.stores/StoreUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,110 @@
*/
package com.infomaniak.lib.stores

import android.content.Context
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.fragment.app.FragmentActivity
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.appupdate.AppUpdateOptions
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.android.play.core.review.ReviewManagerFactory

fun FragmentActivity.checkUpdateIsAvailable(appId: String, versionCode: Int, onResult: (updateIsAvailable: Boolean) -> Unit) {
AppUpdateManagerFactory.create(this).appUpdateInfo.addOnSuccessListener { appUpdateInfo ->
val updateIsAvailable = appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)
object StoreUtils {

onResult(updateIsAvailable)
private const val UPDATE_TYPE = AppUpdateType.FLEXIBLE

private lateinit var appUpdateManager: AppUpdateManager
private lateinit var onInstallDownloaded: () -> Unit

// Create a listener to track request state updates.
private val installStateUpdatedListener by lazy {
InstallStateUpdatedListener { state ->
when (state.installStatus()) {
InstallStatus.DOWNLOADED -> onInstallDownloaded()
InstallStatus.INSTALLED -> unregisterAppUpdateListener()
else -> Unit
}
}
}
}

fun FragmentActivity.launchInAppReview() {
ReviewManagerFactory.create(this).apply {
val requestReviewFlow = requestReviewFlow()
requestReviewFlow.addOnCompleteListener { request ->
if (request.isSuccessful) launchReviewFlow(this@launchInAppReview, request.result)
//region legacy App update
// TODO: Remove this when Ui for kDrive in app update will be made
fun FragmentActivity.checkUpdateIsAvailable(appId: String, versionCode: Int, onResult: (updateIsAvailable: Boolean) -> Unit) {
AppUpdateManagerFactory.create(this).appUpdateInfo.addOnSuccessListener { appUpdateInfo ->
val updateIsAvailable = appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)

onResult(updateIsAvailable)
}
}
//endRegion

KevinBoulongne marked this conversation as resolved.
Show resolved Hide resolved
//region In-App Update
fun initAppUpdateManager(context: Context, onInstall: () -> Unit) {
appUpdateManager = AppUpdateManagerFactory.create(context)
onInstallDownloaded = onInstall
}

fun FragmentActivity.checkUpdateIsAvailable(
appId: String,
versionCode: Int,
inAppResultLauncher: ActivityResultLauncher<IntentSenderRequest>,
onFDroidResult: (updateIsAvailable: Boolean) -> Unit,
) {
appUpdateManager.appUpdateInfo.addOnSuccessListener { appUpdateInfo ->
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
&& appUpdateInfo.isUpdateTypeAllowed(UPDATE_TYPE)
) {
inAppResultLauncher?.let { startUpdateFlow(appUpdateInfo, it) }
}
}
}

fun checkStalledUpdate() = with(appUpdateManager) {
registerListener(installStateUpdatedListener)
appUpdateInfo.addOnSuccessListener { appUpdateInfo ->
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
// If the update is downloaded but not installed, notify the user to complete the update.
onInstallDownloaded.invoke()
}
}
}

fun installDownloadedUpdate(onFailure: (Exception) -> Unit) {
appUpdateManager.completeUpdate().addOnFailureListener(onFailure)
}

fun unregisterAppUpdateListener() {
appUpdateManager.unregisterListener(installStateUpdatedListener)
}

private fun startUpdateFlow(
appUpdateInfo: AppUpdateInfo,
downloadUpdateResultLauncher: ActivityResultLauncher<IntentSenderRequest>,
) = with(appUpdateManager) {
registerListener(installStateUpdatedListener)
startUpdateFlowForResult(
appUpdateInfo,
downloadUpdateResultLauncher,
AppUpdateOptions.newBuilder(UPDATE_TYPE).build(),
)
}
//endregion

//region In-App Review
fun FragmentActivity.launchInAppReview() {
ReviewManagerFactory.create(this).apply {
val requestReviewFlow = requestReviewFlow()
requestReviewFlow.addOnCompleteListener { request ->
if (request.isSuccessful) launchReviewFlow(this@launchInAppReview, request.result)
}
}
}
//endregion
}
2 changes: 2 additions & 0 deletions src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<string name="errorNoSupportingAppFound">Diese Datei wird von keiner installierten Anwendung unterstützt</string>
<string name="errorTitle">Fehler</string>
<string name="errorTitleLabel">Ein Fehler ist aufgetreten</string>
<string name="errorUpdateInstall">Fehler bei der Update-Installation</string>
<string name="errorUserAlreadyPresent">Fehler Benutzer bereits vorhanden</string>
<string name="noConnection">Keine Verbindung</string>
<string name="openWith">Öffnen mit</string>
Expand All @@ -43,4 +44,5 @@
<string name="updateAppTitle">Aktualisierung erforderlich</string>
<string name="updateAvailableDescription">Mit Blick auf ein optimales %s-Benutzererlebnis empfehlen wir Ihnen, Ihre Anwendung zu aktualisieren.</string>
<string name="updateAvailableTitle">Aktualisierung verfügbar!</string>
<string name="updateReadyTitle">Update bereit</string>
</resources>
2 changes: 2 additions & 0 deletions src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<string name="errorNoSupportingAppFound">No hay ninguna aplicación instalada compatible con este archivo</string>
<string name="errorTitle">Error</string>
<string name="errorTitleLabel">Se ha producido un error</string>
<string name="errorUpdateInstall">Error durante la instalación de la actualización</string>
<string name="errorUserAlreadyPresent">Error, usuario ya registrado</string>
<string name="noConnection">Sin conexión</string>
<string name="serverError">Error del servidor</string>
Expand All @@ -43,4 +44,5 @@
<string name="updateAppTitle">Es necesario actualizar</string>
<string name="updateAvailableDescription">Para disfrutar de una experiencia óptima de %s, te aconsejamos que actualices tu aplicación.</string>
<string name="updateAvailableTitle">¡Actualización disponible!</string>
<string name="updateReadyTitle">Actualización lista</string>
</resources>
2 changes: 2 additions & 0 deletions src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<string name="errorNoSupportingAppFound">Aucune application installée ne prend en charge ce fichier</string>
<string name="errorTitle">Erreur</string>
<string name="errorTitleLabel">Une erreur s’est produite</string>
<string name="errorUpdateInstall">Erreur lors de l’installation de la mise à jour</string>
<string name="errorUserAlreadyPresent">Erreur utilisateur déjà présent</string>
<string name="noConnection">Pas de connexion</string>
<string name="openWith">Ouvrir avec</string>
Expand All @@ -43,4 +44,5 @@
<string name="updateAppTitle">Mise à jour requise</string>
<string name="updateAvailableDescription">Afin de profiter d’une expérience optimale de %s, nous vous conseillons de mettre à jour votre application.</string>
<string name="updateAvailableTitle">Mise à jour disponible !</string>
<string name="updateReadyTitle">Mise à jour prête</string>
</resources>
2 changes: 2 additions & 0 deletions src/main/res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<string name="errorNoSupportingAppFound">Il file non è supportato da nessuna delle applicazioni installate</string>
<string name="errorTitle">Errore</string>
<string name="errorTitleLabel">Si è verificato un errore</string>
<string name="errorUpdateInstall">Errore durante l’installazione dell’aggiornamento</string>
<string name="errorUserAlreadyPresent">Errore utente già esistente</string>
<string name="noConnection">Nessuna connessione</string>
<string name="openWith">Apri con</string>
Expand All @@ -43,4 +44,5 @@
<string name="updateAppTitle">Aggiornamento necessario</string>
<string name="updateAvailableDescription">Per vivere la migliore esperienza con %s, ti consigliamo di aggiornare la tua applicazione.</string>
<string name="updateAvailableTitle">Aggiornamento disponibile!</string>
<string name="updateReadyTitle">Aggiornamento pronto</string>
</resources>
2 changes: 2 additions & 0 deletions src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<string name="errorNoSupportingAppFound">This file is not supported by any installed application</string>
<string name="errorTitle">Error</string>
<string name="errorTitleLabel">An error occurred</string>
<string name="errorUpdateInstall">Error during update install</string>
<string name="errorUserAlreadyPresent">Error, User already present</string>
<string name="noConnection">No connection</string>
<string name="openWith">Open with</string>
Expand All @@ -45,4 +46,5 @@
<string name="updateAppTitle">Update required</string>
<string name="updateAvailableDescription">To get the best out of %s, we recommend you update your application.</string>
<string name="updateAvailableTitle">Update available!</string>
<string name="updateReadyTitle">Update ready</string>
</resources>