Skip to content

Instantly share code, notes, and snippets.

@chientrm
Created March 1, 2023 12:52
Show Gist options
  • Save chientrm/61de41174758ff0fa24b95e5745c6898 to your computer and use it in GitHub Desktop.
Save chientrm/61de41174758ff0fa24b95e5745c6898 to your computer and use it in GitHub Desktop.
package site.chientrm.youwave.services.youwave
import com.google.firebase.auth.FirebaseAuth
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.tasks.await
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.*
import site.chientrm.youwave.BuildConfig
import site.chientrm.youwave.models.requests.CreateAudioRequest
import site.chientrm.youwave.models.requests.SetSettingsRequest
import site.chientrm.youwave.models.responses.CreateAudioResponse
import site.chientrm.youwave.models.responses.GetMyAudiosResponse
import site.chientrm.youwave.models.responses.GetPlayAudioResponse
import site.chientrm.youwave.models.responses.GetSettingsResponse
interface YouWaveWebService {
@POST("/createAudio")
suspend fun createAudio(@Body request: CreateAudioRequest): CreateAudioResponse
@POST("/processAudio/{id}")
suspend fun processAudio(@Path("id") id: Int)
@GET("/myAudios")
suspend fun getMyAudios(): GetMyAudiosResponse
@DELETE("/myAudio/{id}")
suspend fun deleteMyAudio(@Path("id") id: Int)
@GET("/audio/{id}")
suspend fun getPlayAudio(@Path("id") id: Int): GetPlayAudioResponse
@GET("/settings")
suspend fun getSettings(): GetSettingsResponse
@POST("/settings")
suspend fun setSettings(@Body body: SetSettingsRequest)
companion object {
private var service: YouWaveWebService? = null
fun getInstance(): YouWaveWebService {
if (service == null) {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val client =
OkHttpClient.Builder()
.addInterceptor {
val tokenResult =
runBlocking {
FirebaseAuth.getInstance().currentUser!!.getIdToken(false).await()
}
val idToken = tokenResult.token!!
val request =
it.request()
.newBuilder()
.addHeader("Authorization", "Bearer $idToken")
.build()
it.proceed(request)
}
.build()
service =
Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(client)
.build()
.create(YouWaveWebService::class.java)
}
return service!!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment