Better error handling for the user interface

This commit is contained in:
Mylloon 2021-08-31 13:57:27 +02:00
parent 105a91371e
commit 15367bf285
4 changed files with 45 additions and 17 deletions

View file

@ -26,6 +26,10 @@ import com.google.gson.Gson
import com.google.gson.reflect.TypeToken import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import java.util.* import java.util.*
import android.widget.Toast
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
@ -158,6 +162,12 @@ class MainActivity : AppCompatActivity() {
button?.text.toString() button?.text.toString()
) )
} }
val checkedItems = booleanArrayOf(
false // get this info from the app files somewhere
)
builder.setMultiChoiceItems(arrayOf(getString(R.string.updateCheck)), checkedItems) { _, _, isChecked ->
println("Update for ${button?.text.toString()}: " + if (isChecked) "enabled" else "disabled" + "")
}
builder.setNeutralButton(R.string.cancel) { dialog, _ -> dialog.cancel() } builder.setNeutralButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
builder.show() builder.show()
true true
@ -240,7 +250,7 @@ class MainActivity : AppCompatActivity() {
if (returns[0] == "loginAttemptsExceeded") { if (returns[0] == "loginAttemptsExceeded") {
if (returns[1] == "null") callScrapper(user, password, app) if (returns[1] == "null") callScrapper(user, password, app)
val registeredAnswered: Map<String, String> = Gson().fromJson( val registeredAnswered: Map<String, String> = Gson().fromJson(
applicationContext.assets.open("captcha.json").bufferedReader() assets.open("captcha.json").bufferedReader()
.use { it.readText() }, .use { it.readText() },
object : TypeToken<Map<String, String>>() {}.type object : TypeToken<Map<String, String>>() {}.type
) )
@ -258,9 +268,15 @@ class MainActivity : AppCompatActivity() {
builder.setNeutralButton(R.string.cancel) { dialog, _ -> dialog.cancel() } builder.setNeutralButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
builder.show() builder.show()
Toast.makeText(applicationContext(), "${getString(R.string.connectionFailed)}\n${getString(R.string.credentialsDeleted)}.", Toast.makeText(instance, "${getString(R.string.connectionFailed)}\n${getString(R.string.credentialsDeleted)}.",
Toast.LENGTH_LONG).show() Toast.LENGTH_LONG).show()
} }
if (returns[0] == "noSID")
Toast.makeText(instance, R.string.noSID, Toast.LENGTH_SHORT).show()
if (returns[0] == "badSID")
Toast.makeText(instance, "${getString(R.string.badSID)}...", Toast.LENGTH_SHORT).show()
if (returns[0] == "noResults")
Toast.makeText(instance, "${getString(R.string.badSID)}...", Toast.LENGTH_SHORT).show()
} }
} }
} }

View file

@ -5,10 +5,11 @@ import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.httpGet import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPost import com.github.kittinunf.fuel.httpPost
import com.mylloon.mobidl.MainActivity.Companion.applicationContext import com.mylloon.mobidl.MainActivity.Companion.applicationContext
import java.lang.System.currentTimeMillis
import com.github.kittinunf.result.Result.Failure as FuelFailure import com.github.kittinunf.result.Result.Failure as FuelFailure
import com.github.kittinunf.result.Result.Success as FuelSuccess import com.github.kittinunf.result.Result.Success as FuelSuccess
var timeOfLastToast: Long = currentTimeMillis() - 2000
class Scraper( class Scraper(
private var pseudo: String, private var pseudo: String,
private var password: String, private var password: String,
@ -26,14 +27,14 @@ class Scraper(
private var loginAttemptsExceeded = "You exceeded the maximum allowed number of login attempts." private var loginAttemptsExceeded = "You exceeded the maximum allowed number of login attempts."
private var searchNotLogged = "Sorry but you are not permitted to use the search system. If you're not logged in please" private var searchNotLogged = "Sorry but you are not permitted to use the search system. If you're not logged in please"
private fun errorFormat( private fun errorFormat( // Pretty error message.
code: Int? = null, code: Int? = null,
message: String = "" message: String = ""
): String { // Pretty error message. ): String {
return "${if (code != null) "[$code]" else ""}${if ((message.isNotEmpty()) and (code is Int)) " " else ""}$message." return "${if (code != null) "[$code]" else ""}${if ((message.isNotEmpty()) and (code is Int)) " " else ""}$message."
} }
private fun connect(): MutableList<String>? { private fun connect(): MutableList<String>? { // Login to the forum using credentials.
if (debug) println("Connection attempt...") if (debug) println("Connection attempt...")
retry++ retry++
FuelManager.instance.basePath = url FuelManager.instance.basePath = url
@ -63,35 +64,39 @@ class Scraper(
return search() return search()
} }
private fun error(htmlPage: String): MutableList<String>? { private fun error(htmlPage: String): MutableList<String>? { // Handle connection errors
var message = "" var message = ""
var array: MutableList<String>? = null var array: MutableList<String>? = null
var lengthTime = Toast.LENGTH_LONG var lengthTime = Toast.LENGTH_LONG
if (errorNotConnected in htmlPage) { if (errorNotConnected in htmlPage) {
if (loginAttemptsExceeded in htmlPage) { if (loginAttemptsExceeded in htmlPage) {
message = "${applicationContext().getString(R.string.knownCaptcha)}..." message = "${applicationContext().getString(R.string.knownCaptcha)}..."
lengthTime = Toast.LENGTH_LONG lengthTime = Toast.LENGTH_SHORT
val qaConfirmID = "(?<=qa_confirm_id\" value=\")(.{32})".toRegex().find(htmlPage)?.value val qaConfirmID = "(?<=qa_confirm_id\" value=\")(.{32})".toRegex().find(htmlPage)?.value
var answer = "(?<=answer\">)(.*)</l".toRegex().find(htmlPage)?.value var question = "(?<=answer\">)(.*)</l".toRegex().find(htmlPage)?.value
answer = answer?.dropLast(3) question = question?.dropLast(3)
array = mutableListOf("loginAttemptsExceeded", answer.toString(), qaConfirmID.toString()) array = if (question == null) null else mutableListOf("loginAttemptsExceeded", question.toString(), qaConfirmID.toString())
} else { } else {
message = "${applicationContext().getString(R.string.connectionFailed)}\n${applicationContext().getString(R.string.credentialsDeleted)}." message = "${applicationContext().getString(R.string.connectionFailed)}\n${applicationContext().getString(R.string.credentialsDeleted)}."
Credentials().delete() Credentials().delete()
array = mutableListOf("errorNotConnected") array = mutableListOf("errorNotConnected")
} }
} }
println(errorFormat(message = message)) val now = currentTimeMillis()
fun sendToast() {
Toast.makeText(applicationContext(), message, lengthTime) Toast.makeText(applicationContext(), message, lengthTime)
.show() .show()
timeOfLastToast = now
}
println(errorFormat(message = message))
if ((now - timeOfLastToast) >= 2000) sendToast()
return array return array
} }
fun search(): MutableList<String>? { // Do the research. fun search(): MutableList<String>? { // Do the research.
if (sid == null) { if (sid == null) {
println(errorFormat(message = "SID not found")) println(errorFormat(message = "SID not found"))
return if (retry < 3) connect() else null return if (retry < 3) connect() else mutableListOf("noSID")
} else { } else {
if (debug) println("SID recovered") if (debug) println("SID recovered")
retry = 0 retry = 0
@ -115,15 +120,16 @@ class Scraper(
val data = session.join().data.decodeToString() val data = session.join().data.decodeToString()
return if (searchNotLogged in data) { return if (searchNotLogged in data) {
println(errorFormat(message = "The SID doesn't work, new attempt...")) println(errorFormat(message = "The SID doesn't work, new attempt..."))
if (retry < 3) connect() else null if (retry < 3) connect() else mutableListOf("badSID")
} else parse(data) } else parse(data)
} }
private fun parse(htmlPage: String): MutableList<String>? { private fun parse(htmlPage: String): MutableList<String>? { // Parse HTML response to a clean list.
if (debug) println("Fetching results for $app...") if (debug) println("Fetching results for $app...")
Toast.makeText(applicationContext(), "Fetching results for $app...", Toast.LENGTH_SHORT) Toast.makeText(applicationContext(), "Fetching results for $app...", Toast.LENGTH_SHORT)
.show() .show()
// println(htmlPage) // println(htmlPage)
if ("No suitable matches were found." in htmlPage) return mutableListOf("noResults")
return null return null
} }

View file

@ -23,4 +23,7 @@
<string name="loginAttemptsExceeded">Vous avez dépassé le nombre maximum de tentatives de connexion, veuillez compléter les captchas</string> <string name="loginAttemptsExceeded">Vous avez dépassé le nombre maximum de tentatives de connexion, veuillez compléter les captchas</string>
<string name="notConnected">Vous n\'êtes pas connecté, redirection vers la page de connexion</string> <string name="notConnected">Vous n\'êtes pas connecté, redirection vers la page de connexion</string>
<string name="knownCaptcha">Résolution des captchas</string> <string name="knownCaptcha">Résolution des captchas</string>
<string name="noSID">Aucun SID n\'a été trouvé</string>
<string name="badSID">Le SID ne fonctionne pas, nouvel essaie</string>
<string name="updateCheck">Vérification des mises à jour</string>
</resources> </resources>

View file

@ -14,6 +14,7 @@
<string name="validate">Validate</string> <string name="validate">Validate</string>
<string name="remove">Remove</string> <string name="remove">Remove</string>
<string name="cancel">Cancel</string> <string name="cancel">Cancel</string>
<string name="updateCheck">Update check</string>
<string name="notConnected">You are not logged in, redirection to the login page</string> <string name="notConnected">You are not logged in, redirection to the login page</string>
<string name="dropBro">drop bro</string> <string name="dropBro">drop bro</string>
@ -30,4 +31,6 @@
<string name="credentialsDeleted">Your credentials have been deleted</string> <string name="credentialsDeleted">Your credentials have been deleted</string>
<string name="loginAttemptsExceeded">You have exceeded the maximum number of connection attempts, please complete captchas</string> <string name="loginAttemptsExceeded">You have exceeded the maximum number of connection attempts, please complete captchas</string>
<string name="knownCaptcha">Resolving captchas</string> <string name="knownCaptcha">Resolving captchas</string>
<string name="noSID">No SID was found</string>
<string name="badSID">The SID does not work, new attempt</string>
</resources> </resources>