Otter-App-Android-Funkwhale/app/src/main/java/com/github/apognu/otter/repositories/AlbumsRepository.kt

60 lines
1.8 KiB
Kotlin
Raw Normal View History

2019-08-19 16:50:33 +02:00
package com.github.apognu.otter.repositories
import android.content.Context
2020-07-17 16:23:49 +02:00
import androidx.lifecycle.LiveData
2020-09-26 17:26:42 +02:00
import androidx.lifecycle.asLiveData
import com.couchbase.lite.*
2020-07-13 23:32:42 +02:00
import com.github.apognu.otter.models.api.FunkwhaleAlbum
2020-07-17 16:23:49 +02:00
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
2020-09-26 17:26:42 +02:00
import com.molo17.couchbase.lite.*
import kotlinx.coroutines.GlobalScope
2019-08-19 16:50:33 +02:00
2020-09-26 17:26:42 +02:00
class AlbumsRepository(override val context: Context, private val couch: Database, artistId: Int?) : Repository<FunkwhaleAlbum>() {
2020-07-13 23:32:42 +02:00
override val upstream: Upstream<FunkwhaleAlbum> by lazy {
2019-08-19 16:50:33 +02:00
val url =
if (artistId == null) "/api/v1/albums/?playable=true&ordering=title"
else "/api/v1/albums/?playable=true&artist=$artistId&ordering=release_date"
2019-08-19 16:50:33 +02:00
2020-07-13 23:32:42 +02:00
HttpUpstream(
2019-08-19 16:50:33 +02:00
HttpUpstream.Behavior.Progressive,
url,
2020-07-13 23:32:42 +02:00
FunkwhaleAlbum.serializer()
2019-08-19 16:50:33 +02:00
)
}
2020-07-13 23:32:42 +02:00
override fun onDataFetched(data: List<FunkwhaleAlbum>): List<FunkwhaleAlbum> {
2020-09-26 17:26:42 +02:00
FunkwhaleAlbum.persist(couch, data)
2020-07-13 23:32:42 +02:00
return super.onDataFetched(data)
}
2020-07-17 16:23:49 +02:00
2020-09-26 17:26:42 +02:00
fun insert(albums: List<FunkwhaleAlbum>) = FunkwhaleAlbum.persist(couch, albums)
fun all() =
select(SelectResult.all())
.from(couch)
.where { "type" equalTo "album"}
.asFlow()
.asLiveData()
fun find(ids: List<Int>) =
select(SelectResult.all())
.from(couch)
.where { ("type" equalTo "album") and (Meta.id.`in`(*ids.map { Expression.string("album:$it") }.toTypedArray())) }
.asFlow()
.asLiveData(GlobalScope.coroutineContext)
2020-07-17 16:23:49 +02:00
2020-09-26 17:26:42 +02:00
fun ofArtist(id: Int): LiveData<ResultSet> {
2020-07-17 16:23:49 +02:00
scope.launch(Dispatchers.IO) {
fetch().collect()
}
2020-09-26 17:26:42 +02:00
return select(SelectResult.all())
.from(couch)
.where { ("type" equalTo "album") and ("artist_id" equalTo id) }
.asFlow()
.asLiveData(GlobalScope.coroutineContext)
2020-07-17 16:23:49 +02:00
}
2019-08-19 16:50:33 +02:00
}