Simplify lookup for existing MAL list item

This commit is contained in:
arkon 2021-01-14 17:36:22 -05:00
parent df166184ea
commit 189f18b112

View file

@ -163,25 +163,19 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI
} }
} }
suspend fun findListItem(track: Track, offset: Int = 0): Track? { suspend fun findListItem(track: Track): Track? {
val json = getListPage(offset) return withIOContext {
val obj = json.jsonObject val uri = "$baseApiUrl/manga".toUri().buildUpon()
val trackedManga = obj["data"]!!.jsonArray.find { data -> .appendPath(track.media_id.toString())
data.jsonObject["node"]!!.jsonObject["id"]!!.jsonPrimitive.int == track.media_id .appendQueryParameter("fields", "my_list_status{start_date,finish_date}")
.build()
authClient.newCall(GET(uri.toString()))
.await()
.parseAs<JsonObject>()
.let { obj ->
obj.jsonObject["list_status"]?.jsonObject?.let {
parseMangaItem(it, track)
} }
return when {
// Found the item in the list
trackedManga != null -> {
parseMangaItem(trackedManga.jsonObject["list_status"]!!.jsonObject, track)
}
// Check next page if there's more
!obj["paging"]!!.jsonObject["next"]?.jsonPrimitive?.contentOrNull.isNullOrBlank() -> {
findListItem(track, offset + listPaginationAmount)
}
// No more pages to check, item wasn't found
else -> {
null
} }
} }
} }
@ -216,7 +210,7 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI
private suspend fun getListPage(offset: Int): JsonObject { private suspend fun getListPage(offset: Int): JsonObject {
return withIOContext { return withIOContext {
val urlBuilder = "$baseApiUrl/users/@me/mangalist".toUri().buildUpon() val urlBuilder = "$baseApiUrl/users/@me/mangalist".toUri().buildUpon()
.appendQueryParameter("fields", "list_status") .appendQueryParameter("fields", "list_status{start_date,finish_date}")
.appendQueryParameter("limit", listPaginationAmount.toString()) .appendQueryParameter("limit", listPaginationAmount.toString())
if (offset > 0) { if (offset > 0) {
urlBuilder.appendQueryParameter("offset", offset.toString()) urlBuilder.appendQueryParameter("offset", offset.toString())