2019-08-19 16:50:33 +02:00
|
|
|
package com.github.apognu.otter.repositories
|
|
|
|
|
|
|
|
import android.content.Context
|
2020-06-13 17:44:50 +02:00
|
|
|
import com.github.apognu.otter.utils.*
|
2019-08-19 16:50:33 +02:00
|
|
|
import com.github.kittinunf.fuel.gson.gsonDeserializerOf
|
2020-06-13 17:44:50 +02:00
|
|
|
import com.google.android.exoplayer2.offline.Download
|
|
|
|
import com.google.gson.Gson
|
2019-08-19 16:50:33 +02:00
|
|
|
import com.google.gson.reflect.TypeToken
|
2019-10-31 16:17:37 +01:00
|
|
|
import kotlinx.coroutines.flow.map
|
|
|
|
import kotlinx.coroutines.flow.toList
|
2019-08-19 16:50:33 +02:00
|
|
|
import kotlinx.coroutines.runBlocking
|
|
|
|
import java.io.BufferedReader
|
|
|
|
|
|
|
|
class TracksRepository(override val context: Context?, albumId: Int) : Repository<Track, TracksCache>() {
|
|
|
|
override val cacheId = "tracks-album-$albumId"
|
2019-10-29 23:41:44 +01:00
|
|
|
override val upstream = HttpUpstream<Track, FunkwhaleResponse<Track>>(HttpUpstream.Behavior.AtOnce, "/api/v1/tracks/?playable=true&album=$albumId", object : TypeToken<TracksResponse>() {}.type)
|
2019-08-19 16:50:33 +02:00
|
|
|
|
|
|
|
override fun cache(data: List<Track>) = TracksCache(data)
|
|
|
|
override fun uncache(reader: BufferedReader) = gsonDeserializerOf(TracksCache::class.java).deserialize(reader)
|
|
|
|
|
|
|
|
override fun onDataFetched(data: List<Track>): List<Track> = runBlocking {
|
2019-10-31 16:17:37 +01:00
|
|
|
val favorites = FavoritedRepository(context).fetch(Origin.Network.origin)
|
|
|
|
.map { it.data }
|
|
|
|
.toList()
|
|
|
|
.flatten()
|
2019-08-19 16:50:33 +02:00
|
|
|
|
2020-06-13 17:44:50 +02:00
|
|
|
val downloaded = getDownloadedIds() ?: listOf()
|
|
|
|
|
2019-08-19 16:50:33 +02:00
|
|
|
data.map { track ->
|
2019-10-23 20:21:18 +02:00
|
|
|
track.favorite = favorites.contains(track.id)
|
2020-06-13 17:44:50 +02:00
|
|
|
track.downloaded = downloaded.contains(track.id)
|
2019-08-19 16:50:33 +02:00
|
|
|
track
|
2019-11-22 20:24:08 +01:00
|
|
|
}.sortedBy { it.position }
|
2019-08-19 16:50:33 +02:00
|
|
|
}
|
2020-06-13 17:44:50 +02:00
|
|
|
|
|
|
|
suspend fun getDownloadedIds(): List<Int>? {
|
|
|
|
return RequestBus.send(Request.GetDownloads).wait<com.github.apognu.otter.utils.Response.Downloads>()?.let { response ->
|
|
|
|
val ids: MutableList<Int> = mutableListOf()
|
|
|
|
|
|
|
|
while (response.cursor.moveToNext()) {
|
|
|
|
val download = response.cursor.download
|
|
|
|
|
|
|
|
Gson().fromJson(String(download.request.data), DownloadInfo::class.java)?.let {
|
|
|
|
if (download.state == Download.STATE_COMPLETED) {
|
|
|
|
ids.add(it.id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ids
|
|
|
|
}
|
|
|
|
}
|
2019-08-19 16:50:33 +02:00
|
|
|
}
|