Add custom header to RetroAchievements API requests

Fixes API requests returning 403
This commit is contained in:
Rafael Caetano 2023-12-22 13:20:56 +00:00
parent 9462f0c553
commit c1f35d5cae
3 changed files with 41 additions and 3 deletions

View File

@ -0,0 +1,28 @@
package me.magnum.melonds.common.network
import android.content.Context
import okhttp3.Interceptor
import okhttp3.Response
class MelonOkHttpInterceptor(private val context: Context) : Interceptor {
private companion object {
const val USER_AGENT = "User-Agent"
const val MELON_USER_AGENT_PREFIX = "melonDS-android"
}
private val userAgentVersion by lazy {
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
val appVersion = packageInfo.versionName
val userAgentSuffix = appVersion.lowercase().replace(' ', '-').replace("(", "").replace(")", "")
"$MELON_USER_AGENT_PREFIX/$userAgentSuffix"
}
override fun intercept(chain: Interceptor.Chain): Response {
val newRequest = chain.request()
.newBuilder()
.addHeader(USER_AGENT, userAgentVersion)
.build()
return chain.proceed(newRequest)
}
}

View File

@ -1,11 +1,14 @@
package me.magnum.melonds.di
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import me.magnum.melonds.common.network.MelonOkHttpInterceptor
import me.magnum.melonds.common.retroachievements.AndroidRAAchievementSignatureProvider
import me.magnum.melonds.common.retroachievements.AndroidRAUserAuthStore
import me.magnum.rcheevosapi.RAAchievementSignatureProvider
@ -19,10 +22,17 @@ import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
object RAModule {
@Provides
fun provideMelonOkHttpInterceptor(@ApplicationContext context: Context): MelonOkHttpInterceptor {
return MelonOkHttpInterceptor(context)
}
@Provides
@Named("ra-api-client")
fun provideRAApiOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder().build()
fun provideRAApiOkHttpClient(melonOkHttpInterceptor: MelonOkHttpInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(melonOkHttpInterceptor)
.build()
}
@Provides

View File

@ -47,7 +47,7 @@ class RAApi(
private const val VALUE_HARDMODE_DISABLED = "0"
private const val VALUE_HARDMODE_ENABLED = "1"
private const val REQUEST_LOGIN = "login"
private const val REQUEST_LOGIN = "login2"
private const val REQUEST_HASH_LIBRARY = "hashlibrary"
private const val REQUEST_GAME_DATA = "patch"
private const val REQUEST_USER_UNLOCKED_ACHIEVEMENTS = "unlocks"