Find existing entry in MAL list when binding

This commit is contained in:
arkon 2020-12-24 15:46:29 -05:00
parent a49adbd09c
commit 430714e67f
2 changed files with 51 additions and 2 deletions

View file

@ -71,8 +71,16 @@ class MyAnimeList(private val context: Context, id: Int) : TrackService(id) {
}
override fun bind(track: Track): Observable<Track> {
// TODO: change this to call add and update like the other trackers?
return runAsObservable({ api.getListItem(track) })
return runAsObservable({
val remoteTrack = api.findListItem(track)
if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.media_id = remoteTrack.media_id
update(track)
} else {
add(track)
}
})
}
override fun search(query: String): Observable<List<TrackSearch>> {

View file

@ -16,6 +16,7 @@ import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
@ -162,6 +163,46 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI
}
}
suspend fun findListItem(track: Track, offset: Int = 0): Track? {
return withContext(Dispatchers.IO) {
val urlBuilder = "$baseApiUrl/users/@me/mangalist".toUri().buildUpon()
.appendQueryParameter("fields", "list_status")
.appendQueryParameter("limit", "25")
if (offset > 0) {
urlBuilder.appendQueryParameter("offset", offset.toString())
}
val request = Request.Builder()
.url(urlBuilder.build().toString())
.get()
.build()
authClient.newCall(request)
.await()
.parseAs<JsonObject>()
.let {
val obj = it.jsonObject
val trackedManga = obj["data"]!!.jsonArray.find { data ->
data.jsonObject["node"]!!.jsonObject["id"]!!.jsonPrimitive.int == track.media_id
}
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 + 25)
}
// No more pages to check, item wasn't found
else -> {
null
}
}
}
}
}
private fun parseMangaItem(response: JsonObject, track: Track): Track {
val obj = response.jsonObject
return track.apply {