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

52 lines
1.8 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
import eu.kanade.tachiyomi.ui.browse.source.SourcesController
2021-12-12 23:59:29 +01:00
import eu.kanade.tachiyomi.util.lang.launchIO
import exh.smartsearch.SmartSearchEngine
import exh.ui.base.CoroutinePresenter
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableSharedFlow
2021-12-12 23:59:29 +01:00
import kotlinx.coroutines.flow.asSharedFlow
2019-07-29 08:12:30 +02:00
class SmartSearchPresenter(private val source: CatalogueSource, private val config: SourcesController.SmartSearchConfig) :
CoroutinePresenter<SmartSearchController>() {
2019-07-29 19:27:33 +02:00
2021-12-12 23:59:29 +01:00
private val _smartSearchFlow = MutableSharedFlow<SearchResults>()
val smartSearchFlow = _smartSearchFlow.asSharedFlow()
2019-07-29 19:27:33 +02:00
2020-08-24 23:25:10 +02:00
private val smartSearchEngine = SmartSearchEngine()
2019-07-31 09:39:51 +02:00
2019-07-29 19:27:33 +02:00
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
presenterScope.launchIO {
val result = try {
val resultManga = smartSearchEngine.smartSearch(source, config.origTitle)
if (resultManga != null) {
val localManga = smartSearchEngine.networkToLocalManga(resultManga, source.id)
SearchResults.Found(localManga)
} else {
SearchResults.NotFound
}
} catch (e: Exception) {
if (e is CancellationException) {
throw e
} else {
SearchResults.Error
2019-07-29 19:27:33 +02:00
}
}
2021-12-12 23:59:29 +01:00
_smartSearchFlow.emit(result)
}
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
}
}