Basic AniList api implementation
parent
0e5221fa6e
commit
743098d0b0
@ -0,0 +1,53 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.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 AniListAuthenticator @Inject constructor(
|
||||||
|
private val storage: AniListStorage,
|
||||||
|
private val repositoryProvider: Provider<AniListRepository>,
|
||||||
|
) : 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,23 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.data
|
||||||
|
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.Response
|
||||||
|
import org.koitharu.kotatsu.core.network.CommonHeaders
|
||||||
|
|
||||||
|
private const val JSON = "application/json"
|
||||||
|
|
||||||
|
class AniListInterceptor(private val storage: AniListStorage) : Interceptor {
|
||||||
|
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val sourceRequest = chain.request()
|
||||||
|
val request = sourceRequest.newBuilder()
|
||||||
|
request.header(CommonHeaders.CONTENT_TYPE, JSON)
|
||||||
|
request.header(CommonHeaders.ACCEPT, JSON)
|
||||||
|
if (!sourceRequest.url.pathSegments.contains("oauth")) {
|
||||||
|
storage.accessToken?.let {
|
||||||
|
request.header(CommonHeaders.AUTHORIZATION, "Bearer $it")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return chain.proceed(request.build())
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,232 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.data
|
||||||
|
|
||||||
|
import okhttp3.FormBody
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.koitharu.kotatsu.BuildConfig
|
||||||
|
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||||
|
import org.koitharu.kotatsu.parsers.exception.GraphQLException
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
|
import org.koitharu.kotatsu.parsers.util.await
|
||||||
|
import org.koitharu.kotatsu.parsers.util.json.getStringOrNull
|
||||||
|
import org.koitharu.kotatsu.parsers.util.json.mapJSON
|
||||||
|
import org.koitharu.kotatsu.parsers.util.parseJson
|
||||||
|
import org.koitharu.kotatsu.parsers.util.parseJsonArray
|
||||||
|
import org.koitharu.kotatsu.parsers.util.toAbsoluteUrl
|
||||||
|
import org.koitharu.kotatsu.scrobbling.anilist.data.model.AniListUser
|
||||||
|
import org.koitharu.kotatsu.scrobbling.data.ScrobblingEntity
|
||||||
|
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.utils.ext.toRequestBody
|
||||||
|
|
||||||
|
private const val REDIRECT_URI = "kotatsu://anilist-auth"
|
||||||
|
private const val BASE_URL = "https://anilist.co/api/v2/"
|
||||||
|
private const val ENDPOINT = "https://graphql.anilist.co"
|
||||||
|
private const val MANGA_PAGE_SIZE = 10
|
||||||
|
|
||||||
|
class AniListRepository(
|
||||||
|
private val okHttp: OkHttpClient,
|
||||||
|
private val storage: AniListStorage,
|
||||||
|
private val db: MangaDatabase,
|
||||||
|
) {
|
||||||
|
|
||||||
|
val oauthUrl: String
|
||||||
|
get() = "${BASE_URL}oauth/authorize?client_id=${BuildConfig.ANILIST_CLIENT_ID}&" +
|
||||||
|
"redirect_uri=${REDIRECT_URI}&response_type=code"
|
||||||
|
|
||||||
|
val isAuthorized: Boolean
|
||||||
|
get() = storage.accessToken != null
|
||||||
|
|
||||||
|
suspend fun authorize(code: String?) {
|
||||||
|
val body = FormBody.Builder()
|
||||||
|
body.add("client_id", BuildConfig.ANILIST_CLIENT_ID)
|
||||||
|
body.add("client_secret", BuildConfig.ANILIST_CLIENT_SECRET)
|
||||||
|
if (code != null) {
|
||||||
|
body.add("grant_type", "authorization_code")
|
||||||
|
body.add("redirect_uri", REDIRECT_URI)
|
||||||
|
body.add("code", code)
|
||||||
|
} else {
|
||||||
|
body.add("grant_type", "refresh_token")
|
||||||
|
body.add("refresh_token", checkNotNull(storage.refreshToken))
|
||||||
|
}
|
||||||
|
val request = Request.Builder()
|
||||||
|
.post(body.build())
|
||||||
|
.url("${BASE_URL}oauth/token")
|
||||||
|
val response = okHttp.newCall(request.build()).await().parseJson()
|
||||||
|
storage.accessToken = response.getString("access_token")
|
||||||
|
storage.refreshToken = response.getString("refresh_token")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun loadUser(): AniListUser {
|
||||||
|
val response = query(
|
||||||
|
"""
|
||||||
|
AniChartUser {
|
||||||
|
user {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
avatar {
|
||||||
|
medium
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".trimIndent(),
|
||||||
|
)
|
||||||
|
val jo = response.getJSONObject("data").getJSONObject("AniChartUser").getJSONObject("user")
|
||||||
|
return AniListUser(jo).also { storage.user = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getCachedUser(): AniListUser? {
|
||||||
|
return storage.user
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun unregister(mangaId: Long) {
|
||||||
|
return db.scrobblingDao.delete(ScrobblerService.SHIKIMORI.id, mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logout() {
|
||||||
|
storage.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun findManga(query: String, offset: Int): List<ScrobblerManga> {
|
||||||
|
val page = offset / MANGA_PAGE_SIZE
|
||||||
|
val pageOffset = offset % MANGA_PAGE_SIZE
|
||||||
|
val url = BASE_URL.toHttpUrl().newBuilder()
|
||||||
|
.addPathSegment("api")
|
||||||
|
.addPathSegment("mangas")
|
||||||
|
.addEncodedQueryParameter("page", (page + 1).toString())
|
||||||
|
.addEncodedQueryParameter("limit", MANGA_PAGE_SIZE.toString())
|
||||||
|
.addEncodedQueryParameter("censored", false.toString())
|
||||||
|
.addQueryParameter("search", query)
|
||||||
|
.build()
|
||||||
|
val request = Request.Builder().url(url).get().build()
|
||||||
|
val response = okHttp.newCall(request).await().parseJsonArray()
|
||||||
|
val list = response.mapJSON { ScrobblerManga(it) }
|
||||||
|
return if (pageOffset != 0) list.drop(pageOffset) else list
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun createRate(mangaId: Long, shikiMangaId: Long) {
|
||||||
|
val user = getCachedUser() ?: loadUser()
|
||||||
|
val payload = JSONObject()
|
||||||
|
payload.put(
|
||||||
|
"user_rate",
|
||||||
|
JSONObject().apply {
|
||||||
|
put("target_id", shikiMangaId)
|
||||||
|
put("target_type", "Manga")
|
||||||
|
put("user_id", user.id)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
val url = BASE_URL.toHttpUrl().newBuilder()
|
||||||
|
.addPathSegment("api")
|
||||||
|
.addPathSegment("v2")
|
||||||
|
.addPathSegment("user_rates")
|
||||||
|
.build()
|
||||||
|
val request = Request.Builder().url(url).post(payload.toRequestBody()).build()
|
||||||
|
val response = okHttp.newCall(request).await().parseJson()
|
||||||
|
saveRate(response, mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun updateRate(rateId: Int, mangaId: Long, chapter: MangaChapter) {
|
||||||
|
val payload = JSONObject()
|
||||||
|
payload.put(
|
||||||
|
"user_rate",
|
||||||
|
JSONObject().apply {
|
||||||
|
put("chapters", chapter.number)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
val url = BASE_URL.toHttpUrl().newBuilder()
|
||||||
|
.addPathSegment("api")
|
||||||
|
.addPathSegment("v2")
|
||||||
|
.addPathSegment("user_rates")
|
||||||
|
.addPathSegment(rateId.toString())
|
||||||
|
.build()
|
||||||
|
val request = Request.Builder().url(url).patch(payload.toRequestBody()).build()
|
||||||
|
val response = okHttp.newCall(request).await().parseJson()
|
||||||
|
saveRate(response, mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun updateRate(rateId: Int, mangaId: Long, rating: Float, status: String?, comment: String?) {
|
||||||
|
val payload = JSONObject()
|
||||||
|
payload.put(
|
||||||
|
"user_rate",
|
||||||
|
JSONObject().apply {
|
||||||
|
put("score", rating.toString())
|
||||||
|
if (comment != null) {
|
||||||
|
put("text", comment)
|
||||||
|
}
|
||||||
|
if (status != null) {
|
||||||
|
put("status", status)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
val url = BASE_URL.toHttpUrl().newBuilder()
|
||||||
|
.addPathSegment("api")
|
||||||
|
.addPathSegment("v2")
|
||||||
|
.addPathSegment("user_rates")
|
||||||
|
.addPathSegment(rateId.toString())
|
||||||
|
.build()
|
||||||
|
val request = Request.Builder().url(url).patch(payload.toRequestBody()).build()
|
||||||
|
val response = okHttp.newCall(request).await().parseJson()
|
||||||
|
saveRate(response, mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun getMangaInfo(id: Long): ScrobblerMangaInfo {
|
||||||
|
val request = Request.Builder()
|
||||||
|
.get()
|
||||||
|
.url("${BASE_URL}api/mangas/$id")
|
||||||
|
val response = okHttp.newCall(request.build()).await().parseJson()
|
||||||
|
return ScrobblerMangaInfo(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun saveRate(json: JSONObject, mangaId: Long) {
|
||||||
|
val entity = ScrobblingEntity(
|
||||||
|
scrobbler = ScrobblerService.SHIKIMORI.id,
|
||||||
|
id = json.getInt("id"),
|
||||||
|
mangaId = mangaId,
|
||||||
|
targetId = json.getLong("target_id"),
|
||||||
|
status = json.getString("status"),
|
||||||
|
chapter = json.getInt("chapters"),
|
||||||
|
comment = json.getString("text"),
|
||||||
|
rating = json.getDouble("score").toFloat() / 10f,
|
||||||
|
)
|
||||||
|
db.scrobblingDao.insert(entity)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ScrobblerManga(json: JSONObject) = ScrobblerManga(
|
||||||
|
id = json.getLong("id"),
|
||||||
|
name = json.getString("name"),
|
||||||
|
altName = json.getStringOrNull("russian"),
|
||||||
|
cover = json.getJSONObject("image").getString("preview").toAbsoluteUrl("shikimori.one"),
|
||||||
|
url = json.getString("url").toAbsoluteUrl("shikimori.one"),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun ScrobblerMangaInfo(json: JSONObject) = ScrobblerMangaInfo(
|
||||||
|
id = json.getLong("id"),
|
||||||
|
name = json.getString("name"),
|
||||||
|
cover = json.getJSONObject("image").getString("preview").toAbsoluteUrl("shikimori.one"),
|
||||||
|
url = json.getString("url").toAbsoluteUrl("shikimori.one"),
|
||||||
|
descriptionHtml = json.getString("description_html"),
|
||||||
|
)
|
||||||
|
|
||||||
|
private suspend fun query(query: String): JSONObject {
|
||||||
|
val body = JSONObject()
|
||||||
|
body.put("query", "{$query}")
|
||||||
|
body.put("variables", null)
|
||||||
|
val mediaType = "application/json; charset=utf-8".toMediaType()
|
||||||
|
val requestBody = body.toString().toRequestBody(mediaType)
|
||||||
|
val request = Request.Builder()
|
||||||
|
.post(requestBody)
|
||||||
|
.url(ENDPOINT)
|
||||||
|
val json = okHttp.newCall(request.build()).await().parseJson()
|
||||||
|
json.optJSONArray("errors")?.let {
|
||||||
|
if (it.length() != 0) {
|
||||||
|
throw GraphQLException(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,40 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.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.anilist.data.model.AniListUser
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
private const val PREF_NAME = "anilist"
|
||||||
|
private const val KEY_ACCESS_TOKEN = "access_token"
|
||||||
|
private const val KEY_REFRESH_TOKEN = "refresh_token"
|
||||||
|
private const val KEY_USER = "user"
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class AniListStorage @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: AniListUser?
|
||||||
|
get() = prefs.getString(KEY_USER, null)?.let {
|
||||||
|
AniListUser(JSONObject(it))
|
||||||
|
}
|
||||||
|
set(value) = prefs.edit {
|
||||||
|
putString(KEY_USER, value?.toJson()?.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() = prefs.edit {
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,42 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.data.model
|
||||||
|
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
class AniListUser(
|
||||||
|
val id: Long,
|
||||||
|
val nickname: String,
|
||||||
|
val avatar: String,
|
||||||
|
) {
|
||||||
|
|
||||||
|
constructor(json: JSONObject) : this(
|
||||||
|
id = json.getLong("id"),
|
||||||
|
nickname = json.getString("name"),
|
||||||
|
avatar = json.getJSONObject("avatar").getString("medium"),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun toJson() = JSONObject().apply {
|
||||||
|
put("id", id)
|
||||||
|
put("name", nickname)
|
||||||
|
put("avatar", JSONObject().apply { put("medium", avatar) })
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (javaClass != other?.javaClass) return false
|
||||||
|
|
||||||
|
other as AniListUser
|
||||||
|
|
||||||
|
if (id != other.id) return false
|
||||||
|
if (nickname != other.nickname) return false
|
||||||
|
if (avatar != other.avatar) return false
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
var result = id.hashCode()
|
||||||
|
result = 31 * result + nickname.hashCode()
|
||||||
|
result = 31 * result + avatar.hashCode()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,71 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.domain
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
|
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListRepository
|
||||||
|
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 javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
private const val RATING_MAX = 10f
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class AniListScrobbler @Inject constructor(
|
||||||
|
private val repository: AniListRepository,
|
||||||
|
db: MangaDatabase,
|
||||||
|
) : Scrobbler(db, ScrobblerService.ANILIST) {
|
||||||
|
|
||||||
|
init {
|
||||||
|
statuses[ScrobblingStatus.PLANNED] = "planned"
|
||||||
|
statuses[ScrobblingStatus.READING] = "watching"
|
||||||
|
statuses[ScrobblingStatus.RE_READING] = "rewatching"
|
||||||
|
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> {
|
||||||
|
return repository.findManga(query, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun linkManga(mangaId: Long, targetId: Long) {
|
||||||
|
repository.createRate(mangaId, targetId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun scrobble(mangaId: Long, chapter: MangaChapter) {
|
||||||
|
val entity = db.scrobblingDao.find(scrobblerService.id, mangaId) ?: return
|
||||||
|
repository.updateRate(entity.id, entity.mangaId, chapter)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updateScrobblingInfo(
|
||||||
|
mangaId: Long,
|
||||||
|
rating: Float,
|
||||||
|
status: ScrobblingStatus?,
|
||||||
|
comment: String?,
|
||||||
|
) {
|
||||||
|
val entity = db.scrobblingDao.find(scrobblerService.id, mangaId)
|
||||||
|
requireNotNull(entity) { "Scrobbling info for manga $mangaId not found" }
|
||||||
|
repository.updateRate(
|
||||||
|
rateId = entity.id,
|
||||||
|
mangaId = entity.mangaId,
|
||||||
|
rating = rating * RATING_MAX,
|
||||||
|
status = statuses[status],
|
||||||
|
comment = comment,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun unregisterScrobbling(mangaId: Long) {
|
||||||
|
repository.unregister(mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getMangaInfo(id: Long): ScrobblerMangaInfo {
|
||||||
|
return repository.getMangaInfo(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,86 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.ui
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.View
|
||||||
|
import androidx.preference.Preference
|
||||||
|
import coil.ImageLoader
|
||||||
|
import coil.request.ImageRequest
|
||||||
|
import coil.transform.CircleCropTransformation
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import org.koitharu.kotatsu.R
|
||||||
|
import org.koitharu.kotatsu.base.ui.BasePreferenceFragment
|
||||||
|
import org.koitharu.kotatsu.scrobbling.anilist.data.model.AniListUser
|
||||||
|
import org.koitharu.kotatsu.utils.PreferenceIconTarget
|
||||||
|
import org.koitharu.kotatsu.utils.ext.assistedViewModels
|
||||||
|
import org.koitharu.kotatsu.utils.ext.enqueueWith
|
||||||
|
import org.koitharu.kotatsu.utils.ext.withArgs
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class AniListSettingsFragment : BasePreferenceFragment(R.string.anilist) {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var coil: ImageLoader
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var viewModelFactory: AniListSettingsViewModel.Factory
|
||||||
|
|
||||||
|
private val viewModel by assistedViewModels {
|
||||||
|
viewModelFactory.create(arguments?.getString(ARG_AUTH_CODE))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
|
||||||
|
addPreferencesFromResource(R.xml.pref_anilist)
|
||||||
|
}
|
||||||
|
|
||||||
|
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: AniListUser?) {
|
||||||
|
val pref = findPreference<Preference>(KEY_USER) ?: return
|
||||||
|
pref.isSelectable = user == null
|
||||||
|
pref.title = user?.nickname ?: getString(R.string.sign_in)
|
||||||
|
ImageRequest.Builder(requireContext())
|
||||||
|
.data(user?.avatar)
|
||||||
|
.transformations(CircleCropTransformation())
|
||||||
|
.target(PreferenceIconTarget(pref))
|
||||||
|
.enqueueWith(coil)
|
||||||
|
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 = "al_user"
|
||||||
|
private const val KEY_LOGOUT = "al_logout"
|
||||||
|
|
||||||
|
private const val ARG_AUTH_CODE = "auth_code"
|
||||||
|
|
||||||
|
fun newInstance(authCode: String?) = AniListSettingsFragment().withArgs(1) {
|
||||||
|
putString(ARG_AUTH_CODE, authCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,57 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.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.anilist.data.AniListRepository
|
||||||
|
import org.koitharu.kotatsu.scrobbling.anilist.data.model.AniListUser
|
||||||
|
|
||||||
|
class AniListSettingsViewModel @AssistedInject constructor(
|
||||||
|
private val repository: AniListRepository,
|
||||||
|
@Assisted authCode: String?,
|
||||||
|
) : BaseViewModel() {
|
||||||
|
|
||||||
|
val authorizationUrl: String
|
||||||
|
get() = repository.oauthUrl
|
||||||
|
|
||||||
|
val user = MutableLiveData<AniListUser?>()
|
||||||
|
|
||||||
|
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?): AniListSettingsViewModel
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@ -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="al_user"
|
||||||
|
android:persistent="false"
|
||||||
|
android:title="@string/loading_"
|
||||||
|
app:iconSpaceReserved="true" />
|
||||||
|
|
||||||
|
<Preference
|
||||||
|
android:key="al_logout"
|
||||||
|
android:persistent="false"
|
||||||
|
android:title="@string/logout"
|
||||||
|
app:allowDividerAbove="true" />
|
||||||
|
|
||||||
|
</PreferenceScreen>
|
||||||
Loading…
Reference in New Issue