Cleaned up error messages, added retry-count

This commit is contained in:
Robinson 2022-03-04 01:32:57 +01:00
parent 14601b43b1
commit b920e8f759
No known key found for this signature in database
GPG Key ID: 8E7DB78588BD6F5C

View File

@ -542,11 +542,12 @@ object WebUtil {
/** /**
* Runs the 'action' function when the scheme+domain+path(s) when it was successful. Runs the 'onError' function when it fails. * Runs the 'action' function when the scheme+domain+path(s) when it was successful. Runs the 'onError' function when it fails.
*/ */
suspend fun fetchData(scheme: String, domain: String, vararg paths: String, suspend fun fetchData(scheme: String, domain: String, vararg paths: String, retryCount: Int = 10,
onError: (String) ->Unit, onError: (String) ->Unit,
onSuccess: suspend (InputStream)->Unit) = withContext(Dispatchers.IO) { onSuccess: suspend (InputStream)->Unit) = withContext(Dispatchers.IO) {
val encodedPath = paths.joinToString(separator = "/") { URLEncoder.encodePathSegment(it, Charsets.UTF_8) } val encodedPath = paths.joinToString(separator = "/") { URLEncoder.encodePathSegment(it, Charsets.UTF_8) }
var location = "$scheme://$domain/$encodedPath" var location = "$scheme://$domain/$encodedPath"
var alreadyTriedOtherScheme = false
// logger.trace{ "Getting data: $location" } // logger.trace{ "Getting data: $location" }
@ -557,8 +558,8 @@ object WebUtil {
while (true) { while (true) {
visitedCount += 1 visitedCount += 1
if (visitedCount > 10) { if (visitedCount > retryCount) {
onError("Stuck in a loop for '$location' --- more than $visitedCount tries to get the domain '$location'") onError("Stuck in a loop for '$location' --- more than $visitedCount attempts")
return@withContext return@withContext
} }
@ -596,27 +597,28 @@ object WebUtil {
return@withContext return@withContext
} }
HttpsURLConnection.HTTP_NOT_FOUND -> { HttpsURLConnection.HTTP_NOT_FOUND -> {
// if we are HTTPS, retry again as HTTP. if (alreadyTriedOtherScheme) {
if (location.startsWith(scheme)) { onError("Error '$responseCode' getting location '$location' HTTPS option exhausted.")
visitedCount = 0
location = if (scheme == "http") {
"https://$domain/$encodedPath"
} else {
"http://$domain/$encodedPath"
}
// loop again with the new location
return@with
} else {
onError("Error '$responseCode' getting domain '$location' HTTPS option exhausted.")
// done // done
return@withContext return@withContext
} }
// if we are HTTPS, retry again as HTTP.
alreadyTriedOtherScheme = true
visitedCount = 0
location = if (location.startsWith("https")) {
"http://$domain/$encodedPath"
} else {
"https://$domain/$encodedPath"
}
// loop again with the new location
return@with
} }
else -> { else -> {
onError("Error '$responseCode' getting domain '$location'") onError("Error '$responseCode' getting location '$location'")
// done // done
return@withContext return@withContext