UpdateChecker
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package `in`.sminnovations.attendanceapp.utils
|
||||
|
||||
import android.content.Context
|
||||
import com.google.firebase.firestore.ktx.firestore
|
||||
import com.google.firebase.ktx.Firebase
|
||||
import kotlinx.coroutines.tasks.await
|
||||
|
||||
|
||||
object UpdateChecker {
|
||||
private const val COLLECTION_NAME = "app_updates"
|
||||
private const val DOCUMENT_NAME = "latest_version"
|
||||
|
||||
suspend fun checkForUpdate(
|
||||
context: Context
|
||||
): Result<UpdateInfo> = runCatching {
|
||||
val currentVersion = getCurrentVersion(context)
|
||||
val updateInfo = getLatestVersion()
|
||||
|
||||
if (isNewerVersion(currentVersion, updateInfo.version)) {
|
||||
updateInfo.copy(isNew = true)
|
||||
} else {
|
||||
updateInfo.copy(isNew = false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getCurrentVersion(context: Context): String {
|
||||
return try {
|
||||
context.packageManager.getPackageInfo(context.packageName, 0).versionName
|
||||
} catch (e: Exception) {
|
||||
throw UpdateCheckException("Failed to get current app version", e)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getLatestVersion(): UpdateInfo {
|
||||
return try {
|
||||
val document = Firebase.firestore
|
||||
.collection(COLLECTION_NAME)
|
||||
.document(DOCUMENT_NAME)
|
||||
.get()
|
||||
.await()
|
||||
|
||||
if (!document.exists()) {
|
||||
throw UpdateCheckException("Update document does not exist")
|
||||
}
|
||||
|
||||
UpdateInfo(
|
||||
version = document.getString("version") ?: throw UpdateCheckException("Version field missing"),
|
||||
url = document.getString("url") ?: throw UpdateCheckException("URL field missing"),
|
||||
releaseNote = document.getString("ReleaseNote") ?: throw UpdateCheckException("ReleaseNote field missing")
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
throw UpdateCheckException("Failed to fetch update info", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isNewerVersion(currentVersion: String, latestVersion: String): Boolean {
|
||||
return try {
|
||||
val current = currentVersion.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
val latest = latestVersion.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
|
||||
for (i in 0 until maxOf(current.size, latest.size)) {
|
||||
val currentNum = current.getOrNull(i) ?: 0
|
||||
val latestNum = latest.getOrNull(i) ?: 0
|
||||
|
||||
when {
|
||||
latestNum > currentNum -> return true
|
||||
latestNum < currentNum -> return false
|
||||
}
|
||||
}
|
||||
false
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateCheckException(
|
||||
message: String,
|
||||
cause: Throwable? = null
|
||||
) : Exception(message, cause){
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user