VersionChecker injection

This commit is contained in:
Milos Kozak 2020-01-03 16:29:59 +01:00
parent a622bfa559
commit e1327b1e1a
6 changed files with 126 additions and 104 deletions

View file

@ -51,7 +51,7 @@ import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt;
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.setupwizard.SetupWizardActivity;
@ -76,6 +76,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
@Inject RxBusWrapper rxBus;
@Inject SP sp;
@Inject ResourceHelper resourceHelper;
@Inject VersionCheckerUtils versionCheckerUtils;
@Inject SmsCommunicatorPlugin smsCommunicatorPlugin;
@Inject LoopPlugin loopPlugin;
@Inject NSSettingsStatus nsSettingsStatus;
@ -121,7 +122,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
//Check here if loop plugin is disabled. Else check via constraints
if (!loopPlugin.isEnabled(PluginType.LOOP))
VersionCheckerUtilsKt.triggerCheckVersion();
versionCheckerUtils.triggerCheckVersion();
FabricPrivacy.getInstance().setUserStats();

View file

@ -55,6 +55,7 @@ import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin;
import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintPlugin;
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin;
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils;
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
@ -109,9 +110,6 @@ import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import io.fabric.sdk.android.Fabric;
import static info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion;
public class MainApp extends DaggerApplication {
static Logger log = LoggerFactory.getLogger(L.CORE);
@ -138,6 +136,7 @@ public class MainApp extends DaggerApplication {
@Inject ActivityMonitor activityMonitor;
@Inject FabricPrivacy fabricPrivacy;
@Inject ResourceHelper resourceHelper;
@Inject VersionCheckerUtils versionCheckersUtils;
@Inject ActionsPlugin actionsPlugin;
@Inject AutomationPlugin automationPlugin;
@ -230,7 +229,7 @@ public class MainApp extends DaggerApplication {
registerLocalBroadcastReceiver();
//trigger here to see the new version on app start after an update
triggerCheckVersion();
versionCheckersUtils.triggerCheckVersion();
if (pluginsList == null) {
pluginsList = new ArrayList<>();

View file

@ -93,6 +93,8 @@ class SignatureVerifierPlugin @Inject constructor(
try {
synchronized(lock) {
if (revokedCerts == null) return false
// TODO Change after raising min API to 28
@Suppress("DEPRECATION", "PackageManagerGetSignatures")
val signatures = mainApp.packageManager.getPackageInfo(mainApp.packageName, PackageManager.GET_SIGNATURES).signatures
if (signatures != null) {
for (signature in signatures) {
@ -117,6 +119,8 @@ class SignatureVerifierPlugin @Inject constructor(
fun shortHashes(): List<String> {
val hashes: MutableList<String> = ArrayList()
try {
// TODO Change after raising min API to 28
@Suppress("DEPRECATION", "PackageManagerGetSignatures")
val signatures = mainApp.packageManager.getPackageInfo(mainApp.packageName, PackageManager.GET_SIGNATURES).signatures
if (signatures != null) {
for (signature in signatures) {

View file

@ -10,6 +10,7 @@ import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.extensions.daysToMillis
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.concurrent.TimeUnit
@ -21,7 +22,8 @@ import kotlin.math.roundToInt
class VersionCheckerPlugin @Inject constructor(
private val rxBus: RxBusWrapper,
private val sp: SP,
private val resourceHelper: ResourceHelper
private val resourceHelper: ResourceHelper,
private val versionCheckerUtils: VersionCheckerUtils
) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.neverVisible(true)
@ -29,6 +31,11 @@ class VersionCheckerPlugin @Inject constructor(
.showInList(false)
.pluginName(R.string.versionChecker)), ConstraintsInterface {
enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) {
RELEASE(30, 60, 90),
RC(1, 7, 14)
}
private val gracePeriod: GracePeriod
get() = if ((BuildConfig.VERSION_NAME.contains("RC", ignoreCase = true))) {
GracePeriod.RC
@ -43,7 +50,7 @@ class VersionCheckerPlugin @Inject constructor(
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
checkWarning()
triggerCheckVersion()
versionCheckerUtils.triggerCheckVersion()
return if (isOldVersion(gracePeriod.veryOld.daysToMillis()))
value.set(false, resourceHelper.gs(R.string.very_old_version), this)
else
@ -88,10 +95,3 @@ class VersionCheckerPlugin @Inject constructor(
return now > sp.getLong(R.string.key_last_time_this_version_detected, 0) + gracePeriod
}
}
enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) {
RELEASE(30, 60, 90),
RC(1, 7, 14)
}
private fun Long.daysToMillis() = TimeUnit.DAYS.toMillis(this)

View file

@ -6,121 +6,134 @@ import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.slf4j.LoggerFactory
import java.io.IOException
import java.net.URL
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
// check network connection
fun isConnected(): Boolean {
val connMgr = MainApp.instance().applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connMgr.activeNetworkInfo?.isConnected ?: false
}
@Singleton
class VersionCheckerUtils @Inject constructor() {
private val log = LoggerFactory.getLogger(L.CORE)
@Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
fun triggerCheckVersion() {
if (!SP.contains(R.string.key_last_time_this_version_detected)) {
// On a new installation, set it as 30 days old in order to warn that there is a new version.
SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
// check network connection
fun isConnected(): Boolean {
val connMgr = mainApp.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connMgr.activeNetworkInfo?.isConnected ?: false
}
// If we are good, only check once every day.
if (System.currentTimeMillis() > SP.getLong(R.string.key_last_time_this_version_detected, 0) + CHECK_EVERY) {
checkVersion()
}
}
private val log = LoggerFactory.getLogger(L.CORE)
private fun checkVersion() = if (isConnected()) {
Thread {
try {
val version: String? = findVersion(URL("https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/build.gradle").readText())
compareWithCurrentVersion(version, BuildConfig.VERSION_NAME)
} catch (e: IOException) {
log.debug("Github master version check error: $e")
fun triggerCheckVersion() {
if (!sp.contains(R.string.key_last_time_this_version_detected)) {
// On a new installation, set it as 30 days old in order to warn that there is a new version.
sp.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
}
}.start()
} else
log.debug("Github master version no checked. No connectivity")
fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) {
val newVersionElements = newVersion.toNumberList()
val currentVersionElements = currentVersion.toNumberList()
if (newVersionElements == null || newVersionElements.isEmpty()) {
onVersionNotDetectable()
return
// If we are good, only check once every day.
if (System.currentTimeMillis() > sp.getLong(R.string.key_last_time_this_version_detected, 0) + CHECK_EVERY) {
checkVersion()
}
}
if (currentVersionElements == null || currentVersionElements.isEmpty()) {
// current version scrambled?!
onNewVersionDetected(currentVersion, newVersion)
return
}
private fun checkVersion() = if (isConnected()) {
Thread {
try {
val version: String? = findVersion(URL("https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/build.gradle").readText())
compareWithCurrentVersion(version, BuildConfig.VERSION_NAME)
} catch (e: IOException) {
log.debug("Github master version check error: $e")
}
}.start()
} else
log.debug("Github master version no checked. No connectivity")
newVersionElements.take(3).forEachIndexed { i, newElem ->
val currElem: Int = currentVersionElements.getOrNull(i)
?: return onNewVersionDetected(currentVersion, newVersion)
fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) {
(newElem - currElem).let {
when {
it > 0 -> return onNewVersionDetected(currentVersion, newVersion)
it < 0 -> return onOlderVersionDetected()
it == 0 -> Unit
val newVersionElements = newVersion.toNumberList()
val currentVersionElements = currentVersion.toNumberList()
if (newVersionElements == null || newVersionElements.isEmpty()) {
onVersionNotDetectable()
return
}
if (currentVersionElements == null || currentVersionElements.isEmpty()) {
// current version scrambled?!
onNewVersionDetected(currentVersion, newVersion)
return
}
newVersionElements.take(3).forEachIndexed { i, newElem ->
val currElem: Int = currentVersionElements.getOrNull(i)
?: return onNewVersionDetected(currentVersion, newVersion)
(newElem - currElem).let {
when {
it > 0 -> return onNewVersionDetected(currentVersion, newVersion)
it < 0 -> return onOlderVersionDetected()
it == 0 -> Unit
}
}
}
onSameVersionDetected()
}
onSameVersionDetected()
}
private fun onOlderVersionDetected() {
log.debug("Version newer than master. Are you developer?")
SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis())
}
fun onSameVersionDetected() {
SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis())
}
fun onVersionNotDetectable() {
log.debug("fetch failed")
}
fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
val now = System.currentTimeMillis()
if (now > SP.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
log.debug("Version ${currentVersion} outdated. Found $newVersion")
val notification = Notification(Notification.NEWVERSIONDETECTED, String.format(MainApp.gs(R.string.versionavailable), newVersion.toString()), Notification.LOW)
RxBus.INSTANCE.send(EventNewNotification(notification))
SP.putLong(R.string.key_last_versionchecker_warning, now)
private fun onOlderVersionDetected() {
log.debug("Version newer than master. Are you developer?")
sp.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis())
}
}
@Deprecated(replaceWith = ReplaceWith("numericVersionPart()"), message = "Will not work if RCs have another index number in it.")
fun String.versionStrip() = this.mapNotNull {
when (it) {
in '0'..'9' -> it
'.' -> it
else -> null
fun onSameVersionDetected() {
sp.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis())
}
}.joinToString(separator = "")
fun String.numericVersionPart(): String =
"(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1) ?: ""
fun onVersionNotDetectable() {
log.debug("fetch failed")
}
fun String?.toNumberList() =
this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }
fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
val now = System.currentTimeMillis()
if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
log.debug("Version ${currentVersion} outdated. Found $newVersion")
val notification = Notification(Notification.NEWVERSIONDETECTED, resourceHelper.gs(R.string.versionavailable, newVersion.toString()), Notification.LOW)
rxBus.send(EventNewNotification(notification))
sp.putLong(R.string.key_last_versionchecker_warning, now)
}
}
fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
@Deprecated(replaceWith = ReplaceWith("numericVersionPart()"), message = "Will not work if RCs have another index number in it.")
fun String.versionStrip() = this.mapNotNull {
when (it) {
in '0'..'9' -> it
'.' -> it
else -> null
}
}.joinToString(separator = "")
val CHECK_EVERY = TimeUnit.DAYS.toMillis(1)
val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
fun String.numericVersionPart(): String =
"(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1)
?: ""
fun String?.toNumberList() =
this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }
fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
val CHECK_EVERY = TimeUnit.DAYS.toMillis(1)
val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
}

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.utils.extensions
import java.util.concurrent.TimeUnit
fun Long.daysToMillis() = TimeUnit.DAYS.toMillis(this)