package audio.funkwhale.ffa.repositories import android.content.Context import audio.funkwhale.ffa.model.* import audio.funkwhale.ffa.utils.OAuth import audio.funkwhale.ffa.utils.gsonDeserializerOf import audio.funkwhale.ffa.utils.mustNormalizeUrl import com.google.android.exoplayer2.offline.DownloadManager import com.google.android.exoplayer2.upstream.cache.Cache import com.google.gson.reflect.TypeToken import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.koin.core.qualifier.named import org.koin.java.KoinJavaComponent.inject class TracksSearchRepository(override val context: Context?, var query: String) : Repository() { private val exoCache: Cache by inject(Cache::class.java, named("exoCache")) private val exoDownloadManager: DownloadManager by inject(DownloadManager::class.java) private val oAuth: OAuth by inject(OAuth::class.java) override val cacheId: String? = null override val upstream: Upstream get() = HttpUpstream( context, HttpUpstream.Behavior.AtOnce, "/api/v1/tracks/?playable=true&q=$query", object : TypeToken() {}.type, oAuth ) override fun cache(data: List) = TracksCache(data) override fun uncache(json: String) = gsonDeserializerOf(TracksCache::class.java).deserialize(json.reader()) override fun onDataFetched(data: List): List = runBlocking { val favorites = FavoritedRepository(context).fetch(Origin.Cache.origin) .map { it.data } .toList() .flatten() val downloaded = TracksRepository.getDownloadedIds(exoDownloadManager) ?: listOf() data.map { track -> track.favorite = favorites.contains(track.id) track.downloaded = downloaded.contains(track.id) track.bestUpload()?.let { upload -> val url = mustNormalizeUrl(upload.listen_url) track.cached = exoCache.isCached(url, 0, upload.duration * 1000L) } track } } } class ArtistsSearchRepository(override val context: Context?, var query: String) : Repository() { private val oAuth: OAuth by inject(OAuth::class.java) override val cacheId: String? = null override val upstream: Upstream get() = HttpUpstream( context, HttpUpstream.Behavior.AtOnce, "/api/v1/artists/?playable=true&q=$query", object : TypeToken() {}.type, oAuth ) override fun cache(data: List) = ArtistsCache(data) override fun uncache(json: String) = gsonDeserializerOf(ArtistsCache::class.java).deserialize(json.reader()) } class AlbumsSearchRepository(override val context: Context?, var query: String) : Repository() { private val oAuth: OAuth by inject(OAuth::class.java) override val cacheId: String? = null override val upstream: Upstream get() = HttpUpstream( context, HttpUpstream.Behavior.AtOnce, "/api/v1/albums/?playable=true&q=$query", object : TypeToken() {}.type, oAuth ) override fun cache(data: List) = AlbumsCache(data) override fun uncache(json: String) = gsonDeserializerOf(AlbumsCache::class.java).deserialize(json.reader()) }