Cleanup rec changes

This commit is contained in:
Jobobby04 2020-11-29 17:10:42 -05:00
parent 2cefc93797
commit ede4f40133

View File

@ -10,12 +10,11 @@ import eu.kanade.tachiyomi.util.lang.asObservable
import exh.log.maybeInjectEHLogger import exh.log.maybeInjectEHLogger
import exh.util.MangaType import exh.util.MangaType
import exh.util.mangaType import exh.util.mangaType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.supervisorScope import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.serialization.decodeFromString import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonArray
@ -31,7 +30,6 @@ import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
import rx.Observable import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import timber.log.Timber import timber.log.Timber
abstract class API(_endpoint: String) { abstract class API(_endpoint: String) {
@ -39,17 +37,13 @@ abstract class API(_endpoint: String) {
val client = OkHttpClient.Builder() val client = OkHttpClient.Builder()
.maybeInjectEHLogger() .maybeInjectEHLogger()
.build() .build()
val scope = CoroutineScope(Job() + Dispatchers.Default)
abstract suspend fun getRecsBySearch(search: String): List<SMangaImpl> abstract suspend fun getRecsBySearch(search: String): List<SMangaImpl>
} }
class MyAnimeList : API("https://api.jikan.moe/v3/") { class MyAnimeList : API("https://api.jikan.moe/v3/") {
private suspend fun getRecsById(id: String): List<SMangaImpl> { private suspend fun getRecsById(id: String): List<SMangaImpl> {
val httpUrl = endpoint.toHttpUrlOrNull() val httpUrl = endpoint.toHttpUrlOrNull() ?: throw Exception("Could not convert endpoint url")
if (httpUrl == null) {
throw Exception("Could not convert endpoint url")
}
val urlBuilder = httpUrl.newBuilder() val urlBuilder = httpUrl.newBuilder()
urlBuilder.addPathSegment("manga") urlBuilder.addPathSegment("manga")
urlBuilder.addPathSegment(id) urlBuilder.addPathSegment(id)
@ -62,32 +56,28 @@ class MyAnimeList : API("https://api.jikan.moe/v3/") {
.build() .build()
val response = client.newCall(request).await() val response = client.newCall(request).await()
val body = response.body?.string().orEmpty() val body = withContext(Dispatchers.IO) { response.body?.string().orEmpty() }
if (body.isEmpty()) { if (body.isEmpty()) {
throw Exception("Null Response") throw Exception("Null Response")
} }
val data = Json.decodeFromString<JsonObject>(body) val data = Json.decodeFromString<JsonObject>(body)
val recommendations = data["recommendations"] as? JsonArray val recommendations = data["recommendations"] as? JsonArray
?: throw Exception("Unexpected response") ?: throw Exception("Unexpected response")
val recs = recommendations.map { rec -> return recommendations.map { rec ->
rec as? JsonObject ?: throw Exception("Invalid json") rec as? JsonObject ?: throw Exception("Invalid json")
Timber.tag("RECOMMENDATIONS").d("MYANIMELIST > RECOMMENDATION: %s", rec["title"]!!.jsonPrimitive.content) Timber.tag("RECOMMENDATIONS").d("MYANIMELIST > RECOMMENDATION: %s", rec["title"]!!.jsonPrimitive.content)
SMangaImpl().apply { SMangaImpl().apply {
this.title = rec["title"]!!.jsonPrimitive.content title = rec["title"]!!.jsonPrimitive.content
this.thumbnail_url = rec["image_url"]!!.jsonPrimitive.content thumbnail_url = rec["image_url"]!!.jsonPrimitive.content
this.initialized = true initialized = true
this.url = rec["url"]!!.jsonPrimitive.content this.url = rec["url"]!!.jsonPrimitive.content
} }
} }
return recs
} }
override suspend fun getRecsBySearch(search: String): List<SMangaImpl> { override suspend fun getRecsBySearch(search: String): List<SMangaImpl> {
val httpUrl = val httpUrl =
endpoint.toHttpUrlOrNull() endpoint.toHttpUrlOrNull() ?: throw Exception("Could not convert endpoint url")
if (httpUrl == null) {
throw Exception("Could not convert endpoint url")
}
val urlBuilder = httpUrl.newBuilder() val urlBuilder = httpUrl.newBuilder()
urlBuilder.addPathSegment("search") urlBuilder.addPathSegment("search")
urlBuilder.addPathSegment("manga") urlBuilder.addPathSegment("manga")
@ -100,7 +90,7 @@ class MyAnimeList : API("https://api.jikan.moe/v3/") {
.build() .build()
val response = client.newCall(request).await() val response = client.newCall(request).await()
val body = response.body?.string().orEmpty() val body = withContext(Dispatchers.IO) { response.body?.string().orEmpty() }
if (body.isEmpty()) { if (body.isEmpty()) {
throw Exception("Null Response") throw Exception("Null Response")
} }
@ -183,7 +173,7 @@ class Anilist : API("https://graphql.anilist.co/") {
.build() .build()
val response = client.newCall(request).await() val response = client.newCall(request).await()
val body = response.body?.string().orEmpty() val body = withContext(Dispatchers.IO) { response.body?.string().orEmpty() }
if (body.isEmpty()) { if (body.isEmpty()) {
throw Exception("Null Response") throw Exception("Null Response")
} }
@ -203,17 +193,16 @@ class Anilist : API("https://graphql.anilist.co/") {
) )
).last().jsonObject ).last().jsonObject
val recommendations = result["recommendations"]!!.jsonObject["edges"]!!.jsonArray val recommendations = result["recommendations"]!!.jsonObject["edges"]!!.jsonArray
val recs = recommendations.map { return recommendations.map {
val rec = it.jsonObject["node"]!!.jsonObject["mediaRecommendation"]!!.jsonObject val rec = it.jsonObject["node"]!!.jsonObject["mediaRecommendation"]!!.jsonObject
Timber.tag("RECOMMENDATIONS").d("ANILIST > RECOMMENDATION: %s", getTitle(rec)) Timber.tag("RECOMMENDATIONS").d("ANILIST > RECOMMENDATION: %s", getTitle(rec))
SMangaImpl().apply { SMangaImpl().apply {
this.title = getTitle(rec) title = getTitle(rec)
this.thumbnail_url = rec["coverImage"]!!.jsonObject["large"]!!.jsonPrimitive.content thumbnail_url = rec["coverImage"]!!.jsonObject["large"]!!.jsonPrimitive.content
this.initialized = true initialized = true
this.url = rec["siteUrl"]!!.jsonPrimitive.content url = rec["siteUrl"]!!.jsonPrimitive.content
} }
} }
return recs
} }
} }
@ -228,37 +217,33 @@ open class RecommendsPager(
val apiList = mapOf(preferredApi to API_MAP[preferredApi]!!) + API_MAP.filter { it.key != preferredApi }.toList() val apiList = mapOf(preferredApi to API_MAP[preferredApi]!!) + API_MAP.filter { it.key != preferredApi }.toList()
val recs = supervisorScope { val recs = apiList
apiList .asSequence()
.asSequence() .map { (key, api) ->
.map { (key, api) -> try {
async(Dispatchers.Default) { val recs = runBlocking { api.getRecsBySearch(manga.originalTitle) }
try { Timber.tag("RECOMMENDATIONS").d("%s > Results: %s", key, recs.count())
val recs = api.getRecsBySearch(manga.originalTitle).orEmpty() recs
Timber.tag("RECOMMENDATIONS").d("%s > Results: %s", key, recs.count()) } catch (e: Exception) {
recs Timber.tag("RECOMMENDATIONS").e("%s > Error: %s", key, e.message)
} catch (e: Exception) { listOf()
Timber.tag("RECOMMENDATIONS").e("%s > Error: %s", key, e.message)
listOf()
}
}
} }
.firstOrNull { it.await().isNotEmpty() } }
?.await().orEmpty() .firstOrNull { it.isNotEmpty() }
} .orEmpty()
val page = MangasPage(recs, false) val page = MangasPage(recs, false)
emit(page) emit(page)
} }
.asObservable() .onEach {
.observeOn(AndroidSchedulers.mainThread()) withContext(Dispatchers.Main) {
.doOnNext { if (it.mangas.isNotEmpty()) {
if (it.mangas.isNotEmpty()) { onPageReceived(it)
onPageReceived(it) } else {
} else { throw NoResultsException()
throw NoResultsException() }
} }
} }.asObservable()
} }
companion object { companion object {