komikku/app/src/main/java/exh/ui/smartsearch/SmartSearchPresenter.kt

64 lines
2.1 KiB
Kotlin
Raw Normal View History

package exh.ui.smartsearch
2019-07-29 08:12:30 +02:00
2019-07-29 19:27:33 +02:00
import android.os.Bundle
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.source.CatalogueSource
2019-07-29 08:12:30 +02:00
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
2020-05-04 00:34:46 +02:00
import eu.kanade.tachiyomi.ui.browse.source.SourceController
import exh.smartsearch.SmartSearchEngine
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
2019-07-29 19:27:33 +02:00
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
2019-07-29 08:12:30 +02:00
class SmartSearchPresenter(private val source: CatalogueSource?, private val config: SourceController.SmartSearchConfig?) :
2020-08-05 01:32:36 +02:00
BasePresenter<SmartSearchController>() {
2019-07-29 19:27:33 +02:00
2020-08-05 01:32:36 +02:00
val scope = CoroutineScope(Job() + Dispatchers.Main)
2019-07-29 19:27:33 +02:00
val smartSearchChannel = Channel<SearchResults>()
2020-08-05 01:32:36 +02:00
private val smartSearchEngine = SmartSearchEngine(scope.coroutineContext)
2019-07-31 09:39:51 +02:00
2019-07-29 19:27:33 +02:00
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
if (source != null && config != null) {
2020-08-05 01:32:36 +02:00
scope.launch(Dispatchers.Default) {
2019-07-29 19:27:33 +02:00
val result = try {
2019-07-31 09:39:51 +02:00
val resultManga = smartSearchEngine.smartSearch(source, config.origTitle)
2019-07-29 19:27:33 +02:00
if (resultManga != null) {
2019-07-31 09:39:51 +02:00
val localManga = smartSearchEngine.networkToLocalManga(resultManga, source.id)
2019-07-29 19:27:33 +02:00
SearchResults.Found(localManga)
} else {
SearchResults.NotFound
}
} catch (e: Exception) {
if (e is CancellationException) {
throw e
} else {
SearchResults.Error
}
}
smartSearchChannel.send(result)
}
}
}
override fun onDestroy() {
super.onDestroy()
2020-08-05 01:32:36 +02:00
scope.cancel()
2019-07-29 19:27:33 +02:00
}
sealed class SearchResults {
data class Found(val manga: Manga) : SearchResults()
object NotFound : SearchResults()
object Error : SearchResults()
2019-07-29 19:27:33 +02:00
}
}