Skip to content

Commit

Permalink
ref: use coroutines in LoginActivity.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
VaiTon committed Jun 6, 2021
1 parent bb65483 commit 5ecc126
Show file tree
Hide file tree
Showing 13 changed files with 248 additions and 222 deletions.
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Expand Up @@ -133,7 +133,7 @@
</intent-filter>
</activity>
<activity
android:name=".features.LoginActivity"
android:name=".features.login.LoginActivity"
android:parentActivityName=".features.MainActivity"
android:screenOrientation="portrait">
<meta-data
Expand Down
Expand Up @@ -24,17 +24,22 @@ import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.lifecycle.lifecycleScope
import com.afollestad.materialdialogs.MaterialDialog
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.addTo
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.customtabs.CustomTabActivityHelper
import openfoodfacts.github.scrachx.openfood.customtabs.CustomTabsHelper
import openfoodfacts.github.scrachx.openfood.customtabs.WebViewFallback
import openfoodfacts.github.scrachx.openfood.databinding.FragmentHomeBinding
import openfoodfacts.github.scrachx.openfood.features.LoginActivity.Companion.LoginContract
import openfoodfacts.github.scrachx.openfood.features.login.LoginActivity
import openfoodfacts.github.scrachx.openfood.features.login.LoginActivity.Companion.LoginContract
import openfoodfacts.github.scrachx.openfood.features.shared.NavigationBaseFragment
import openfoodfacts.github.scrachx.openfood.network.services.ProductsAPI
import openfoodfacts.github.scrachx.openfood.utils.LocaleManager
Expand Down Expand Up @@ -91,14 +96,14 @@ class HomeFragment : NavigationBaseFragment() {
mayLaunchUrl(dailyFoodFactUri, null, null)
}
val customTabsIntent = CustomTabsHelper.getCustomTabsIntent(
requireActivity(),
customTabActivityHelper.session,
requireActivity(),
customTabActivityHelper.session,
)
CustomTabActivityHelper.openCustomTab(
requireActivity(),
customTabsIntent,
dailyFoodFactUri,
WebViewFallback()
requireActivity(),
customTabsIntent,
dailyFoodFactUri,
WebViewFallback()
)
}

Expand All @@ -119,32 +124,37 @@ class HomeFragment : NavigationBaseFragment() {
return
}

productsApi.signIn(login, password, "Sign-in")
.observeOn(AndroidSchedulers.mainThread())
.doOnError { Log.e(LOG_TAG, "Cannot check user credentials.", it) }
.subscribe { response ->
val htmlBody: String = try {
response.body()!!.string()
} catch (e: IOException) {
Log.e(LOG_TAG, "I/O Exception while checking user saved credentials.", e)
return@subscribe
}
if (LoginActivity.isHtmlNotValid(htmlBody)) {
Log.w(LOG_TAG, "Cannot validate login, deleting saved credentials and asking the user to log back in.")
settings.edit {
putString("user", "")
putString("pass", "")
}
MaterialDialog.Builder(requireActivity()).let {
it.title(R.string.alert_dialog_warning_title)
it.content(R.string.alert_dialog_warning_msg_user)
it.positiveText(R.string.txtOk)
it.onPositive { _, _ -> loginLauncher.launch(Unit) }
it.show()
}

lifecycleScope.launch(Dispatchers.IO) {
val response = try {
productsApi.signIn(login, password, "Sign-in")
} catch (err: Throwable) {
Log.e(LOG_TAG, "Cannot check user credentials.", err)
null
} ?: return@launch

val htmlBody: String = try {
response.body()!!.string()
} catch (e: IOException) {
Log.e(LOG_TAG, "I/O Exception while checking user saved credentials.", e)
return@launch
}
if (LoginActivity.isHtmlNotValid(htmlBody)) {
Log.w(LOG_TAG, "Cannot validate login, deleting saved credentials and asking the user to log back in.")
settings.edit {
putString("user", "")
putString("pass", "")
}
withContext(Dispatchers.Main) {
MaterialDialog.Builder(requireActivity()).let {
it.title(R.string.alert_dialog_warning_title)
it.content(R.string.alert_dialog_warning_msg_user)
it.positiveText(R.string.txtOk)
it.onPositive { _, _ -> loginLauncher.launch(Unit) }
it.show()
}
}.addTo(disp)
}
}
}
}

override fun onResume() {
Expand All @@ -161,21 +171,21 @@ class HomeFragment : NavigationBaseFragment() {
Log.d(LOG_TAG, "Refreshing total product count...")

productsApi.getTotalProductCount(getUserAgent())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { setProductCount(oldCount) }
.doOnError {
setProductCount(oldCount)
Log.e(LOG_TAG, "Could not retrieve product count from server.", it)
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { setProductCount(oldCount) }
.doOnError {
setProductCount(oldCount)
Log.e(LOG_TAG, "Could not retrieve product count from server.", it)
}
.subscribe { resp ->
val totalProductCount = resp.count.toInt()
Log.d(LOG_TAG, "Refreshed total product count. There are $totalProductCount products on the database.")
setProductCount(totalProductCount)
sharedPrefs.edit {
putInt(PRODUCT_COUNT_KEY, totalProductCount)
apply()
}
.subscribe { resp ->
val totalProductCount = resp.count.toInt()
Log.d(LOG_TAG, "Refreshed total product count. There are $totalProductCount products on the database.")
setProductCount(totalProductCount)
sharedPrefs.edit {
putInt(PRODUCT_COUNT_KEY, totalProductCount)
apply()
}
}.addTo(disp)
}.addTo(disp)
}

/**
Expand All @@ -196,28 +206,28 @@ class HomeFragment : NavigationBaseFragment() {
*/
private fun refreshTagLine() {
productsApi.getTagline(getUserAgent())
.subscribeOn(Schedulers.io()) // io for network
.observeOn(AndroidSchedulers.mainThread()) // Move to main thread for UI changes
.doOnError { Log.w(LOG_TAG, "Could not retrieve tag-line from server.", it) }
.subscribe { tagLines ->
val appLanguage = localeManager.getLanguage()
var isLanguageFound = false
var isExactLanguageFound = false
tagLines.forEach { tag ->
if (!isExactLanguageFound && (tag.language == appLanguage || tag.language.contains(appLanguage))) {
isExactLanguageFound = tag.language == appLanguage
taglineURL = tag.tagLine.url
binding.tvTagLine.text = tag.tagLine.message
isLanguageFound = true
}
.subscribeOn(Schedulers.io()) // io for network
.observeOn(AndroidSchedulers.mainThread()) // Move to main thread for UI changes
.doOnError { Log.w(LOG_TAG, "Could not retrieve tag-line from server.", it) }
.subscribe { tagLines ->
val appLanguage = localeManager.getLanguage()
var isLanguageFound = false
var isExactLanguageFound = false
tagLines.forEach { tag ->
if (!isExactLanguageFound && (tag.language == appLanguage || tag.language.contains(appLanguage))) {
isExactLanguageFound = tag.language == appLanguage
taglineURL = tag.tagLine.url
binding.tvTagLine.text = tag.tagLine.message
isLanguageFound = true
}
if (!isLanguageFound) {
taglineURL = tagLines.last().tagLine.url
binding.tvTagLine.text = tagLines.last().tagLine.message
}
binding.tvTagLine.visibility = View.VISIBLE
}
.addTo(disp)
if (!isLanguageFound) {
taglineURL = tagLines.last().tagLine.url
binding.tvTagLine.text = tagLines.last().tagLine.message
}
binding.tvTagLine.visibility = View.VISIBLE
}
.addTo(disp)
}

companion object {
Expand Down
Expand Up @@ -46,6 +46,7 @@ import io.reactivex.rxkotlin.addTo
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.databinding.ActivityFullScreenImageBinding
import openfoodfacts.github.scrachx.openfood.features.adapters.LanguageDataAdapter
import openfoodfacts.github.scrachx.openfood.features.login.LoginActivity
import openfoodfacts.github.scrachx.openfood.features.shared.BaseActivity
import openfoodfacts.github.scrachx.openfood.images.*
import openfoodfacts.github.scrachx.openfood.models.LanguageData
Expand Down
Expand Up @@ -77,7 +77,6 @@ import openfoodfacts.github.scrachx.openfood.customtabs.CustomTabActivityHelper
import openfoodfacts.github.scrachx.openfood.customtabs.CustomTabsHelper
import openfoodfacts.github.scrachx.openfood.customtabs.WebViewFallback
import openfoodfacts.github.scrachx.openfood.databinding.ActivityMainBinding
import openfoodfacts.github.scrachx.openfood.features.LoginActivity.Companion.LoginContract
import openfoodfacts.github.scrachx.openfood.features.adapters.PhotosAdapter
import openfoodfacts.github.scrachx.openfood.features.additives.AdditiveListActivity
import openfoodfacts.github.scrachx.openfood.features.allergensalert.AllergensAlertFragment
Expand All @@ -86,6 +85,8 @@ import openfoodfacts.github.scrachx.openfood.features.changelog.ChangelogDialog
import openfoodfacts.github.scrachx.openfood.features.compare.ProductCompareActivity
import openfoodfacts.github.scrachx.openfood.features.listeners.CommonBottomListenerInstaller.installBottomNavigation
import openfoodfacts.github.scrachx.openfood.features.listeners.CommonBottomListenerInstaller.selectNavigationItem
import openfoodfacts.github.scrachx.openfood.features.login.LoginActivity
import openfoodfacts.github.scrachx.openfood.features.login.LoginActivity.Companion.LoginContract
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity
import openfoodfacts.github.scrachx.openfood.features.productlists.ProductListsActivity
import openfoodfacts.github.scrachx.openfood.features.scan.ContinuousScanActivity
Expand Down

0 comments on commit 5ecc126

Please sign in to comment.