Add adapter for Fever items call

This commit is contained in:
Shinokuni 2021-12-25 18:16:44 +01:00
parent 2396ba1f7e
commit 76cd9355f8
4 changed files with 130 additions and 0 deletions

View File

@ -0,0 +1,73 @@
package com.readrops.api.services.fever.adapters
import android.annotation.SuppressLint
import com.readrops.api.utils.exceptions.ParseException
import com.readrops.api.utils.extensions.nextNonEmptyString
import com.readrops.api.utils.extensions.nextNullableString
import com.readrops.api.utils.extensions.skipField
import com.readrops.api.utils.extensions.toBoolean
import com.readrops.db.entities.Item
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonReader
import com.squareup.moshi.ToJson
import org.joda.time.LocalDateTime
class FeverItemsAdapter {
@ToJson
fun toJson(items: List<Item>) = ""
@SuppressLint("CheckResult")
@FromJson
fun fromJson(reader: JsonReader): List<Item> = with(reader) {
return try {
val items = arrayListOf<Item>()
beginObject()
repeat(4) {
skipField()
}
nextName() // beginning of items array
beginArray()
while (hasNext()) {
beginObject()
val item = Item()
while (hasNext()) {
with(item) {
when (selectName(NAMES)) {
0 -> remoteId = nextNonEmptyString()
1 -> feedRemoteId = nextInt().toString()
2 -> title = nextNonEmptyString()
3 -> author = nextNullableString()
4 -> content = nextNullableString()
5 -> link = nextNullableString()
6 -> isRead = nextInt().toBoolean()
7 -> pubDate = LocalDateTime(nextLong() * 1000L)
else -> skipValue()
}
}
}
items += item
endObject()
}
endArray()
items
} catch (e: Exception) {
throw ParseException(e.message)
}
}
companion object {
val NAMES: JsonReader.Options = JsonReader.Options.of(
"id", "feed_id", "title", "author", "html", "url",
"is_read", "created_on_time"
)
}
}

View File

@ -24,3 +24,5 @@ fun JsonReader.skipToEnd() {
skipField() skipField()
} }
} }
fun Int.toBoolean(): Boolean = this == 1

View File

@ -0,0 +1,36 @@
package com.readrops.api.services.fever.adapters
import com.readrops.api.TestUtils
import com.readrops.db.entities.Item
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import okio.Buffer
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class FeverItemsAdapterTest {
private val adapter = Moshi.Builder()
.add(FeverItemsAdapter())
.build()
.adapter<List<Item>>(Types.newParameterizedType(List::class.java, Item::class.java))
@Test
fun validItemsTest() {
val stream = TestUtils.loadResource("services/fever/items.json")
val items = adapter.fromJson(Buffer().readFrom(stream))!!
with(items[0]) {
assertEquals(title, "FreshRSS 1.9.0")
assertEquals(author, "Alkarex")
assertEquals(link, "https://github.com/FreshRSS/FreshRSS/releases/tag/1.9.0")
assertNotNull(content)
assertEquals(isRead, true)
assertNotNull(pubDate)
assertEquals(remoteId, "1546007484154894")
assertEquals(feedRemoteId, "2")
}
}
}

File diff suppressed because one or more lines are too long