Initial MyAnimeList implementation
parent
2f74633abb
commit
2b2042807b
@ -0,0 +1,54 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.data
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import okhttp3.Authenticator
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.Route
|
||||
import org.koitharu.kotatsu.BuildConfig
|
||||
import org.koitharu.kotatsu.core.network.CommonHeaders
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
class MALAuthenticator @Inject constructor(
|
||||
private val storage: MALStorage,
|
||||
private val repositoryProvider: Provider<MALRepository>,
|
||||
) : Authenticator {
|
||||
|
||||
override fun authenticate(route: Route?, response: Response): Request? {
|
||||
val accessToken = storage.accessToken ?: return null
|
||||
if (!isRequestWithAccessToken(response)) {
|
||||
return null
|
||||
}
|
||||
synchronized(this) {
|
||||
val newAccessToken = storage.accessToken ?: return null
|
||||
if (accessToken != newAccessToken) {
|
||||
return newRequestWithAccessToken(response.request, newAccessToken)
|
||||
}
|
||||
val updatedAccessToken = refreshAccessToken() ?: return null
|
||||
return newRequestWithAccessToken(response.request, updatedAccessToken)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isRequestWithAccessToken(response: Response): Boolean {
|
||||
val header = response.request.header(CommonHeaders.AUTHORIZATION)
|
||||
return header?.startsWith("Bearer") == true
|
||||
}
|
||||
|
||||
private fun newRequestWithAccessToken(request: Request, accessToken: String): Request {
|
||||
return request.newBuilder()
|
||||
.header(CommonHeaders.AUTHORIZATION, "Bearer $accessToken")
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun refreshAccessToken(): String? = runCatching {
|
||||
val repository = repositoryProvider.get()
|
||||
runBlocking { repository.authorize(null) }
|
||||
return storage.accessToken
|
||||
}.onFailure {
|
||||
if (BuildConfig.DEBUG) {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.data
|
||||
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Response
|
||||
import org.koitharu.kotatsu.core.network.CommonHeaders
|
||||
import java.io.IOException
|
||||
|
||||
class MALInterceptor(private val storage: MALStorage) : Interceptor {
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val sourceRequest = chain.request()
|
||||
val request = sourceRequest.newBuilder()
|
||||
if (!sourceRequest.url.pathSegments.contains("oauth2")) {
|
||||
storage.accessToken?.let {
|
||||
request.header(CommonHeaders.AUTHORIZATION, "Bearer $it")
|
||||
}
|
||||
}
|
||||
val response = chain.proceed(request.build())
|
||||
if (!response.isSuccessful && !response.isRedirect) {
|
||||
throw IOException("${response.code} ${response.message}")
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.data
|
||||
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||
import org.koitharu.kotatsu.parsers.util.await
|
||||
import org.koitharu.kotatsu.parsers.util.parseJson
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerService
|
||||
import org.koitharu.kotatsu.scrobbling.mal.data.model.MALUser
|
||||
import org.koitharu.kotatsu.utils.PKCEGenerator
|
||||
|
||||
private const val REDIRECT_URI = "kotatsu://mal-auth"
|
||||
private const val BASE_OAUTH_URL = "https://myanimelist.net"
|
||||
private const val BASE_API_URL = "https://api.myanimelist.net/v2"
|
||||
private const val MANGA_PAGE_SIZE = 250
|
||||
|
||||
// af16954886b040673378423f5d62cccd
|
||||
|
||||
class MALRepository(
|
||||
private val okHttp: OkHttpClient,
|
||||
private val storage: MALStorage,
|
||||
private val db: MangaDatabase,
|
||||
) {
|
||||
|
||||
private var codeVerifier: String = ""
|
||||
|
||||
val oauthUrl: String
|
||||
get() = "${BASE_OAUTH_URL}/v1/oauth2/authorize?" +
|
||||
"response_type=code" +
|
||||
"&client_id=af16954886b040673378423f5d62cccd" +
|
||||
"&redirect_uri=${REDIRECT_URI}" +
|
||||
"&code_challenge=${getPKCEChallengeCode()}" +
|
||||
"&code_challenge_method=plain"
|
||||
|
||||
val isAuthorized: Boolean
|
||||
get() = storage.accessToken != null
|
||||
|
||||
suspend fun authorize(code: String?) {
|
||||
val body = FormBody.Builder()
|
||||
if (code != null) {
|
||||
body.add("client_id", "af16954886b040673378423f5d62cccd")
|
||||
body.add("code", code)
|
||||
body.add("code_verifier", getPKCEChallengeCode())
|
||||
body.add("grant_type", "authorization_code")
|
||||
}
|
||||
val request = Request.Builder()
|
||||
.post(body.build())
|
||||
.url("${BASE_OAUTH_URL}/v1/oauth2/token")
|
||||
|
||||
val response = okHttp.newCall(request.build()).await().parseJson()
|
||||
storage.accessToken = response.getString("access_token")
|
||||
storage.refreshToken = response.getString("refresh_token")
|
||||
}
|
||||
|
||||
suspend fun loadUser(): MALUser {
|
||||
val request = Request.Builder()
|
||||
.get()
|
||||
.url("${BASE_API_URL}/users")
|
||||
val response = okHttp.newCall(request.build()).await().parseJson()
|
||||
return MALUser(response).also { storage.user = it }
|
||||
}
|
||||
|
||||
fun getCachedUser(): MALUser? {
|
||||
return storage.user
|
||||
}
|
||||
|
||||
suspend fun unregister(mangaId: Long) {
|
||||
return db.scrobblingDao.delete(ScrobblerService.MAL.id, mangaId)
|
||||
}
|
||||
|
||||
fun logout() {
|
||||
storage.clear()
|
||||
}
|
||||
|
||||
private fun getPKCEChallengeCode(): String {
|
||||
codeVerifier = PKCEGenerator.generateCodeVerifier()
|
||||
return codeVerifier
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.core.content.edit
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import org.json.JSONObject
|
||||
import org.koitharu.kotatsu.scrobbling.mal.data.model.MALUser
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val PREF_NAME = "myanimelist"
|
||||
private const val KEY_ACCESS_TOKEN = "access_token"
|
||||
private const val KEY_REFRESH_TOKEN = "refresh_token"
|
||||
private const val KEY_USER = "user"
|
||||
|
||||
@Singleton
|
||||
class MALStorage @Inject constructor(@ApplicationContext context: Context) {
|
||||
|
||||
private val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
var accessToken: String?
|
||||
get() = prefs.getString(KEY_ACCESS_TOKEN, null)
|
||||
set(value) = prefs.edit { putString(KEY_ACCESS_TOKEN, value) }
|
||||
|
||||
var refreshToken: String?
|
||||
get() = prefs.getString(KEY_REFRESH_TOKEN, null)
|
||||
set(value) = prefs.edit { putString(KEY_REFRESH_TOKEN, value) }
|
||||
|
||||
var user: MALUser?
|
||||
get() = prefs.getString(KEY_USER, null)?.let {
|
||||
MALUser(JSONObject(it))
|
||||
}
|
||||
set(value) = prefs.edit {
|
||||
putString(KEY_USER, value?.toJson()?.toString())
|
||||
}
|
||||
|
||||
fun clear() = prefs.edit {
|
||||
clear()
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.data.model
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
class MALUser(
|
||||
val id: Long,
|
||||
val nickname: String,
|
||||
) {
|
||||
|
||||
constructor(json: JSONObject) : this(
|
||||
id = json.getLong("id"),
|
||||
nickname = json.getString("name"),
|
||||
)
|
||||
|
||||
fun toJson() = JSONObject().apply {
|
||||
put("id", id)
|
||||
put("nickname", nickname)
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (javaClass != other?.javaClass) return false
|
||||
|
||||
other as MALUser
|
||||
|
||||
if (id != other.id) return false
|
||||
if (nickname != other.nickname) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = id.hashCode()
|
||||
result = 31 * result + nickname.hashCode()
|
||||
return result
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,61 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.domain
|
||||
|
||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import org.koitharu.kotatsu.scrobbling.domain.Scrobbler
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerMangaInfo
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerService
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblingStatus
|
||||
import org.koitharu.kotatsu.scrobbling.mal.data.MALRepository
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val RATING_MAX = 10f
|
||||
|
||||
@Singleton
|
||||
class MALScrobbler @Inject constructor(
|
||||
private val repository: MALRepository,
|
||||
db: MangaDatabase,
|
||||
) : Scrobbler(db, ScrobblerService.MAL) {
|
||||
|
||||
init {
|
||||
statuses[ScrobblingStatus.PLANNED] = "plan_to_read"
|
||||
statuses[ScrobblingStatus.READING] = "reading"
|
||||
statuses[ScrobblingStatus.COMPLETED] = "completed"
|
||||
statuses[ScrobblingStatus.ON_HOLD] = "on_hold"
|
||||
statuses[ScrobblingStatus.DROPPED] = "dropped"
|
||||
}
|
||||
|
||||
override val isAvailable: Boolean
|
||||
get() = repository.isAuthorized
|
||||
|
||||
override suspend fun findManga(query: String, offset: Int): List<ScrobblerManga> {
|
||||
TODO()
|
||||
}
|
||||
|
||||
override suspend fun linkManga(mangaId: Long, targetId: Long) {
|
||||
TODO()
|
||||
}
|
||||
|
||||
override suspend fun scrobble(mangaId: Long, chapter: MangaChapter) {
|
||||
TODO()
|
||||
}
|
||||
|
||||
override suspend fun updateScrobblingInfo(
|
||||
mangaId: Long,
|
||||
rating: Float,
|
||||
status: ScrobblingStatus?,
|
||||
comment: String?,
|
||||
) {
|
||||
TODO()
|
||||
}
|
||||
|
||||
override suspend fun unregisterScrobbling(mangaId: Long) {
|
||||
repository.unregister(mangaId)
|
||||
}
|
||||
|
||||
override suspend fun getMangaInfo(id: Long): ScrobblerMangaInfo {
|
||||
TODO()
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,73 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import androidx.preference.Preference
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.base.ui.BasePreferenceFragment
|
||||
import org.koitharu.kotatsu.scrobbling.mal.data.model.MALUser
|
||||
import org.koitharu.kotatsu.utils.ext.assistedViewModels
|
||||
import org.koitharu.kotatsu.utils.ext.withArgs
|
||||
import javax.inject.Inject
|
||||
|
||||
@AndroidEntryPoint
|
||||
class MALSettingsFragment : BasePreferenceFragment(R.string.mal) {
|
||||
|
||||
@Inject
|
||||
lateinit var viewModelFactory: MALSettingsViewModel.Factory
|
||||
|
||||
private val viewModel by assistedViewModels {
|
||||
viewModelFactory.create(arguments?.getString(ARG_AUTH_CODE))
|
||||
}
|
||||
|
||||
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
|
||||
addPreferencesFromResource(R.xml.pref_mal)
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
viewModel.user.observe(viewLifecycleOwner, this::onUserChanged)
|
||||
}
|
||||
|
||||
override fun onPreferenceTreeClick(preference: Preference): Boolean {
|
||||
return when (preference.key) {
|
||||
KEY_USER -> openAuthorization()
|
||||
KEY_LOGOUT -> {
|
||||
viewModel.logout()
|
||||
true
|
||||
}
|
||||
else -> super.onPreferenceTreeClick(preference)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onUserChanged(user: MALUser?) {
|
||||
val pref = findPreference<Preference>(KEY_USER) ?: return
|
||||
pref.isSelectable = user == null
|
||||
pref.title = user?.nickname ?: getString(R.string.sign_in)
|
||||
findPreference<Preference>(KEY_LOGOUT)?.isVisible = user != null
|
||||
}
|
||||
|
||||
private fun openAuthorization(): Boolean {
|
||||
return runCatching {
|
||||
val intent = Intent(Intent.ACTION_VIEW)
|
||||
intent.data = Uri.parse(viewModel.authorizationUrl)
|
||||
startActivity(intent)
|
||||
}.isSuccess
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private const val KEY_USER = "mal_user"
|
||||
private const val KEY_LOGOUT = "mal_logout"
|
||||
|
||||
private const val ARG_AUTH_CODE = "auth_code"
|
||||
|
||||
fun newInstance(authCode: String?) = MALSettingsFragment().withArgs(1) {
|
||||
putString(ARG_AUTH_CODE, authCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,59 @@
|
||||
package org.koitharu.kotatsu.scrobbling.mal.ui
|
||||
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import dagger.assisted.Assisted
|
||||
import dagger.assisted.AssistedFactory
|
||||
import dagger.assisted.AssistedInject
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import org.koitharu.kotatsu.base.ui.BaseViewModel
|
||||
import org.koitharu.kotatsu.scrobbling.mal.data.MALRepository
|
||||
import org.koitharu.kotatsu.scrobbling.mal.data.model.MALUser
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriRepository
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.model.ShikimoriUser
|
||||
|
||||
class MALSettingsViewModel @AssistedInject constructor(
|
||||
private val repository: MALRepository,
|
||||
@Assisted authCode: String?,
|
||||
) : BaseViewModel() {
|
||||
|
||||
val authorizationUrl: String
|
||||
get() = repository.oauthUrl
|
||||
|
||||
val user = MutableLiveData<MALUser?>()
|
||||
|
||||
init {
|
||||
if (authCode != null) {
|
||||
authorize(authCode)
|
||||
} else {
|
||||
loadUser()
|
||||
}
|
||||
}
|
||||
|
||||
fun logout() {
|
||||
launchJob(Dispatchers.Default) {
|
||||
repository.logout()
|
||||
user.postValue(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadUser() = launchJob(Dispatchers.Default) {
|
||||
val userModel = if (repository.isAuthorized) {
|
||||
repository.getCachedUser()?.let(user::postValue)
|
||||
repository.loadUser()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
user.postValue(userModel)
|
||||
}
|
||||
|
||||
private fun authorize(code: String) = launchJob(Dispatchers.Default) {
|
||||
repository.authorize(code)
|
||||
user.postValue(repository.loadUser())
|
||||
}
|
||||
|
||||
@AssistedFactory
|
||||
interface Factory {
|
||||
|
||||
fun create(authCode: String?): MALSettingsViewModel
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
package org.koitharu.kotatsu.utils
|
||||
|
||||
import android.util.Base64
|
||||
import java.security.SecureRandom
|
||||
|
||||
object PKCEGenerator {
|
||||
|
||||
private const val PKCE_BASE64_ENCODE_SETTINGS = Base64.NO_WRAP or Base64.NO_PADDING or Base64.URL_SAFE
|
||||
|
||||
fun generateCodeVerifier(): String {
|
||||
val codeVerifier = ByteArray(50)
|
||||
SecureRandom().nextBytes(codeVerifier)
|
||||
return Base64.encodeToString(codeVerifier, PKCE_BASE64_ENCODE_SETTINGS)
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 720 B |
Binary file not shown.
|
After Width: | Height: | Size: 432 B |
Binary file not shown.
|
After Width: | Height: | Size: 810 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 KiB |
@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<PreferenceScreen
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
app:initialExpandedChildrenCount="5">
|
||||
|
||||
<Preference
|
||||
android:key="mal_user"
|
||||
android:persistent="false"
|
||||
android:title="@string/loading_"
|
||||
app:iconSpaceReserved="true" />
|
||||
|
||||
<Preference
|
||||
android:key="mal_logout"
|
||||
android:persistent="false"
|
||||
android:title="@string/logout"
|
||||
app:allowDividerAbove="true" />
|
||||
|
||||
</PreferenceScreen>
|
||||
Loading…
Reference in New Issue