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

81 lines
2.1 KiB
Kotlin
Raw Normal View History

2019-08-19 16:50:33 +02:00
package com.github.apognu.otter.utils
import android.os.Build
import androidx.fragment.app.Fragment
2019-10-22 21:56:33 +02:00
import com.github.apognu.otter.R
2019-08-19 16:50:33 +02:00
import com.github.apognu.otter.fragments.BrowseFragment
2020-07-13 23:32:42 +02:00
import com.github.apognu.otter.models.api.DownloadInfo
2019-08-19 16:50:33 +02:00
import com.github.apognu.otter.repositories.Repository
import com.github.kittinunf.fuel.core.Request
import com.google.android.exoplayer2.offline.Download
import com.google.gson.Gson
2019-10-22 21:56:33 +02:00
import com.squareup.picasso.Picasso
import com.squareup.picasso.RequestCreator
import kotlinx.coroutines.CoroutineScope
2019-08-19 16:50:33 +02:00
import kotlinx.coroutines.Dispatchers.Main
2019-10-31 16:17:37 +01:00
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
2019-08-19 16:50:33 +02:00
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
2020-07-13 23:32:42 +02:00
inline fun <D> Flow<Repository.Response<D>>.untilNetwork(scope: CoroutineScope, context: CoroutineContext = Main, crossinline callback: (data: List<D>, page: Int, hasMore: Boolean) -> Unit) {
scope.launch(context) {
2019-10-31 16:17:37 +01:00
collect { data ->
2020-07-13 23:32:42 +02:00
callback(data.data, data.page, data.hasMore)
2019-08-19 16:50:33 +02:00
}
}
}
fun Fragment.onViewPager(block: Fragment.() -> Unit) {
for (f in activity?.supportFragmentManager?.fragments ?: listOf()) {
if (f is BrowseFragment) {
f.block()
}
}
}
fun <T> Int.onApi(block: () -> T) {
if (Build.VERSION.SDK_INT >= this) {
block()
}
}
fun <T, U> Int.onApi(block: () -> T, elseBlock: (() -> U)) {
if (Build.VERSION.SDK_INT >= this) {
block()
} else {
elseBlock()
}
}
fun <T> Int.onApiForResult(block: () -> T, elseBlock: (() -> T)): T {
2019-10-21 11:51:32 +02:00
return if (Build.VERSION.SDK_INT >= this) {
block()
2019-08-19 16:50:33 +02:00
} else {
2019-10-21 11:51:32 +02:00
elseBlock()
2019-08-19 16:50:33 +02:00
}
}
fun <T> T.applyOnApi(api: Int, block: T.() -> T): T {
2019-10-21 11:51:32 +02:00
return if (Build.VERSION.SDK_INT >= api) {
block()
2019-08-19 16:50:33 +02:00
} else {
2019-10-21 11:51:32 +02:00
this
2019-08-19 16:50:33 +02:00
}
2019-10-22 21:56:33 +02:00
}
fun Picasso.maybeLoad(url: String?): RequestCreator {
return if (url == null) load(R.drawable.cover)
else load(url)
}
fun Request.authorize(): Request {
return this.apply {
if (!Settings.isAnonymous()) {
header("Authorization", "Bearer ${Settings.getAccessToken()}")
}
}
}
fun Download.getMetadata(): DownloadInfo? = Gson().fromJson(String(this.request.data), DownloadInfo::class.java)