Migrate to kotlinx.serialization for Bangumi

This commit is contained in:
arkon 2020-10-11 15:58:59 -04:00
parent f8d82cb052
commit f5aa36c787
8 changed files with 52 additions and 41 deletions

View File

@ -1,5 +1,8 @@
package eu.kanade.tachiyomi.data.track.bangumi package eu.kanade.tachiyomi.data.track.bangumi
import kotlinx.serialization.Serializable
@Serializable
data class Avatar( data class Avatar(
val large: String? = "", val large: String? = "",
val medium: String? = "", val medium: String? = "",

View File

@ -2,22 +2,21 @@ package eu.kanade.tachiyomi.data.track.bangumi
import android.content.Context import android.content.Context
import android.graphics.Color import android.graphics.Color
import com.google.gson.Gson
import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.data.track.model.TrackSearch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import rx.Completable import rx.Completable
import rx.Observable import rx.Observable
import uy.kohesive.injekt.injectLazy
class Bangumi(private val context: Context, id: Int) : TrackService(id) { class Bangumi(private val context: Context, id: Int) : TrackService(id) {
override val name = "Bangumi" override val name = "Bangumi"
private val gson: Gson by injectLazy() private val interceptor by lazy { BangumiInterceptor(this) }
private val interceptor by lazy { BangumiInterceptor(this, gson) }
private val api by lazy { BangumiApi(client, interceptor) } private val api by lazy { BangumiApi(client, interceptor) }
@ -112,13 +111,12 @@ class Bangumi(private val context: Context, id: Int) : TrackService(id) {
} }
fun saveToken(oauth: OAuth?) { fun saveToken(oauth: OAuth?) {
val json = gson.toJson(oauth) preferences.trackToken(this).set(Json.encodeToString(oauth))
preferences.trackToken(this).set(json)
} }
fun restoreToken(): OAuth? { fun restoreToken(): OAuth? {
return try { return try {
gson.fromJson(preferences.trackToken(this).get(), OAuth::class.java) Json.decodeFromString<OAuth>(preferences.trackToken(this).get())
} catch (e: Exception) { } catch (e: Exception) {
null null
} }

View File

@ -2,27 +2,28 @@ package eu.kanade.tachiyomi.data.track.bangumi
import android.net.Uri import android.net.Uri
import androidx.core.net.toUri import androidx.core.net.toUri
import com.github.salomonbrys.kotson.array
import com.github.salomonbrys.kotson.obj
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.data.track.model.TrackSearch
import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.network.asObservableSuccess
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.float
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.CacheControl import okhttp3.CacheControl
import okhttp3.FormBody import okhttp3.FormBody
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import rx.Observable import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.net.URLEncoder import java.net.URLEncoder
class BangumiApi(private val client: OkHttpClient, interceptor: BangumiInterceptor) { class BangumiApi(private val client: OkHttpClient, interceptor: BangumiInterceptor) {
private val gson: Gson by injectLazy()
private val authClient = client.newBuilder().addInterceptor(interceptor).build() private val authClient = client.newBuilder().addInterceptor(interceptor).build()
fun addLibManga(track: Track): Observable<Track> { fun addLibManga(track: Track): Observable<Track> {
@ -92,36 +93,32 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept
if (responseBody.contains("\"code\":404")) { if (responseBody.contains("\"code\":404")) {
responseBody = "{\"results\":0,\"list\":[]}" responseBody = "{\"results\":0,\"list\":[]}"
} }
val response = JsonParser.parseString(responseBody).obj["list"]?.array val response = Json.decodeFromString<JsonObject>(responseBody)["list"]?.jsonArray
response?.filter { it.obj["type"].asInt == 1 }?.map { jsonToSearch(it.obj) } response?.filter { it.jsonObject["type"]?.jsonPrimitive?.int == 1 }?.map { jsonToSearch(it.jsonObject) }
} }
} }
private fun jsonToSearch(obj: JsonObject): TrackSearch { private fun jsonToSearch(obj: JsonObject): TrackSearch {
return TrackSearch.create(TrackManager.BANGUMI).apply { return TrackSearch.create(TrackManager.BANGUMI).apply {
media_id = obj["id"].asInt media_id = obj["id"]!!.jsonPrimitive.int
title = obj["name_cn"].asString title = obj["name_cn"]!!.jsonPrimitive.content
cover_url = obj["images"].obj["common"].asString cover_url = obj["images"]!!.jsonObject["common"]!!.jsonPrimitive.content
summary = obj["name"].asString summary = obj["name"]!!.jsonPrimitive.content
tracking_url = obj["url"].asString tracking_url = obj["url"]!!.jsonPrimitive.content
} }
} }
private fun jsonToTrack(mangas: JsonObject): Track { private fun jsonToTrack(mangas: JsonObject): Track {
return Track.create(TrackManager.BANGUMI).apply { return Track.create(TrackManager.BANGUMI).apply {
title = mangas["name"].asString title = mangas["name"]!!.jsonPrimitive.content
media_id = mangas["id"].asInt media_id = mangas["id"]!!.jsonPrimitive.int
score = if (mangas["rating"] != null) { score = try {
if (mangas["rating"].isJsonObject) { mangas["rating"]!!.jsonObject["score"]!!.jsonPrimitive.float
mangas["rating"].obj["score"].asFloat } catch (_: Exception) {
} else {
0f
}
} else {
0f 0f
} }
status = Bangumi.DEFAULT_STATUS status = Bangumi.DEFAULT_STATUS
tracking_url = mangas["url"].asString tracking_url = mangas["url"]!!.jsonPrimitive.content
} }
} }
@ -137,7 +134,7 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept
.map { netResponse -> .map { netResponse ->
// get comic info // get comic info
val responseBody = netResponse.body?.string().orEmpty() val responseBody = netResponse.body?.string().orEmpty()
jsonToTrack(JsonParser.parseString(responseBody).obj) jsonToTrack(Json.decodeFromString(responseBody))
} }
} }
@ -154,7 +151,7 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept
.asObservableSuccess() .asObservableSuccess()
.map { netResponse -> .map { netResponse ->
val resp = netResponse.body?.string() val resp = netResponse.body?.string()
val coll = gson.fromJson(resp, Collection::class.java) val coll = Json.decodeFromString<Collection>(resp!!)
track.status = coll.status?.id!! track.status = coll.status?.id!!
track.last_chapter_read = coll.ep_status!! track.last_chapter_read = coll.ep_status!!
track track
@ -167,7 +164,7 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept
if (responseBody.isEmpty()) { if (responseBody.isEmpty()) {
throw Exception("Null Response") throw Exception("Null Response")
} }
gson.fromJson(responseBody, OAuth::class.java) Json.decodeFromString<OAuth>(responseBody)
} }
} }

View File

@ -1,23 +1,24 @@
package eu.kanade.tachiyomi.data.track.bangumi package eu.kanade.tachiyomi.data.track.bangumi
import com.google.gson.Gson import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.FormBody import okhttp3.FormBody
import okhttp3.Interceptor import okhttp3.Interceptor
import okhttp3.Response import okhttp3.Response
class BangumiInterceptor(val bangumi: Bangumi, val gson: Gson) : Interceptor { class BangumiInterceptor(val bangumi: Bangumi) : Interceptor {
/** /**
* OAuth object used for authenticated requests. * OAuth object used for authenticated requests.
*/ */
private var oauth: OAuth? = bangumi.restoreToken() private var oauth: OAuth? = bangumi.restoreToken()
fun addTocken(tocken: String, oidFormBody: FormBody): FormBody { fun addToken(token: String, oidFormBody: FormBody): FormBody {
val newFormBody = FormBody.Builder() val newFormBody = FormBody.Builder()
for (i in 0 until oidFormBody.size) { for (i in 0 until oidFormBody.size) {
newFormBody.add(oidFormBody.name(i), oidFormBody.value(i)) newFormBody.add(oidFormBody.name(i), oidFormBody.value(i))
} }
newFormBody.add("access_token", tocken) newFormBody.add("access_token", token)
return newFormBody.build() return newFormBody.build()
} }
@ -29,7 +30,7 @@ class BangumiInterceptor(val bangumi: Bangumi, val gson: Gson) : Interceptor {
if (currAuth.isExpired()) { if (currAuth.isExpired()) {
val response = chain.proceed(BangumiApi.refreshTokenRequest(currAuth.refresh_token!!)) val response = chain.proceed(BangumiApi.refreshTokenRequest(currAuth.refresh_token!!))
if (response.isSuccessful) { if (response.isSuccessful) {
newAuth(gson.fromJson(response.body!!.string(), OAuth::class.java)) newAuth(Json.decodeFromString<OAuth>(response.body!!.string()))
} else { } else {
response.close() response.close()
} }
@ -42,7 +43,7 @@ class BangumiInterceptor(val bangumi: Bangumi, val gson: Gson) : Interceptor {
.addQueryParameter("access_token", currAuth.access_token).build() .addQueryParameter("access_token", currAuth.access_token).build()
) )
.build() else originalRequest.newBuilder() .build() else originalRequest.newBuilder()
.post(addTocken(currAuth.access_token, originalRequest.body as FormBody)) .post(addToken(currAuth.access_token, originalRequest.body as FormBody))
.header("User-Agent", "Tachiyomi") .header("User-Agent", "Tachiyomi")
.build() .build()

View File

@ -1,5 +1,8 @@
package eu.kanade.tachiyomi.data.track.bangumi package eu.kanade.tachiyomi.data.track.bangumi
import kotlinx.serialization.Serializable
@Serializable
data class Collection( data class Collection(
val `private`: Int? = 0, val `private`: Int? = 0,
val comment: String? = "", val comment: String? = "",

View File

@ -1,5 +1,8 @@
package eu.kanade.tachiyomi.data.track.bangumi package eu.kanade.tachiyomi.data.track.bangumi
import kotlinx.serialization.Serializable
@Serializable
data class OAuth( data class OAuth(
val access_token: String, val access_token: String,
val token_type: String, val token_type: String,

View File

@ -1,5 +1,8 @@
package eu.kanade.tachiyomi.data.track.bangumi package eu.kanade.tachiyomi.data.track.bangumi
import kotlinx.serialization.Serializable
@Serializable
data class Status( data class Status(
val id: Int? = 0, val id: Int? = 0,
val name: String? = "", val name: String? = "",

View File

@ -1,5 +1,8 @@
package eu.kanade.tachiyomi.data.track.bangumi package eu.kanade.tachiyomi.data.track.bangumi
import kotlinx.serialization.Serializable
@Serializable
data class User( data class User(
val avatar: Avatar? = Avatar(), val avatar: Avatar? = Avatar(),
val id: Int? = 0, val id: Int? = 0,