Fix showing SSL errors if no scheme was specified

This commit is contained in:
Kirill Kamakin
2022-12-21 22:25:03 +01:00
parent 0ed45f72d3
commit 99fcbaa899

View File

@@ -12,6 +12,7 @@ import gq.kirmanak.mealient.logging.Logger
import gq.kirmanak.mealient.ui.OperationUiState import gq.kirmanak.mealient.ui.OperationUiState
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
import javax.net.ssl.SSLHandshakeException
@HiltViewModel @HiltViewModel
class BaseURLViewModel @Inject constructor( class BaseURLViewModel @Inject constructor(
@@ -27,24 +28,38 @@ class BaseURLViewModel @Inject constructor(
fun saveBaseUrl(baseURL: String) { fun saveBaseUrl(baseURL: String) {
logger.v { "saveBaseUrl() called with: baseURL = $baseURL" } logger.v { "saveBaseUrl() called with: baseURL = $baseURL" }
_uiState.value = OperationUiState.Progress() _uiState.value = OperationUiState.Progress()
val hasPrefix = ALLOWED_PREFIXES.any { baseURL.startsWith(it) } viewModelScope.launch { checkBaseURL(baseURL) }
var url = baseURL.takeIf { hasPrefix } ?: WITH_PREFIX_FORMAT.format(baseURL)
url = url.trimStart().trimEnd { it == '/' || it.isWhitespace() }
viewModelScope.launch { checkBaseURL(url) }
} }
private suspend fun checkBaseURL(baseURL: String) { private suspend fun checkBaseURL(baseURL: String) {
logger.v { "checkBaseURL() called with: baseURL = $baseURL" } logger.v { "checkBaseURL() called with: baseURL = $baseURL" }
if (baseURL == serverInfoRepo.getUrl()) {
val hasPrefix = ALLOWED_PREFIXES.any { baseURL.startsWith(it) }
val urlWithPrefix = baseURL.takeIf { hasPrefix } ?: WITH_PREFIX_FORMAT.format(baseURL)
val url = urlWithPrefix.trimStart().trimEnd { it == '/' || it.isWhitespace() }
logger.d { "checkBaseURL: Created URL = $url, with prefix = $urlWithPrefix" }
if (url == serverInfoRepo.getUrl()) {
logger.d { "checkBaseURL: new URL matches current" } logger.d { "checkBaseURL: new URL matches current" }
_uiState.value = OperationUiState.fromResult(Result.success(Unit)) _uiState.value = OperationUiState.fromResult(Result.success(Unit))
return return
} }
val result = serverInfoRepo.tryBaseURL(baseURL)
val result: Result<Unit> = serverInfoRepo.tryBaseURL(url).recoverCatching {
logger.e(it) { "checkBaseURL: trying to recover" }
if (hasPrefix.not() && it.cause is SSLHandshakeException) {
val unencryptedUrl = url.replace("https", "http")
serverInfoRepo.tryBaseURL(unencryptedUrl).getOrThrow()
} else {
throw it
}
}
if (result.isSuccess) { if (result.isSuccess) {
authRepo.logout() authRepo.logout()
recipeRepo.clearLocalData() recipeRepo.clearLocalData()
} }
logger.i { "checkBaseURL: result is $result" } logger.i { "checkBaseURL: result is $result" }
_uiState.value = OperationUiState.fromResult(result) _uiState.value = OperationUiState.fromResult(result)
} }