Basic AniList api implementation
This commit is contained in:
@@ -7,6 +7,7 @@ object CommonHeaders {
|
||||
const val REFERER = "Referer"
|
||||
const val USER_AGENT = "User-Agent"
|
||||
const val ACCEPT = "Accept"
|
||||
const val CONTENT_TYPE = "Content-Type"
|
||||
const val CONTENT_DISPOSITION = "Content-Disposition"
|
||||
const val COOKIE = "Cookie"
|
||||
const val CONTENT_ENCODING = "Content-Encoding"
|
||||
|
||||
@@ -339,6 +339,7 @@ class AppSettings @Inject constructor(@ApplicationContext context: Context) {
|
||||
const val KEY_SUGGESTIONS_EXCLUDE_NSFW = "suggestions_exclude_nsfw"
|
||||
const val KEY_SUGGESTIONS_EXCLUDE_TAGS = "suggestions_exclude_tags"
|
||||
const val KEY_SHIKIMORI = "shikimori"
|
||||
const val KEY_ANILIST = "anilist"
|
||||
const val KEY_DOWNLOADS_PARALLELISM = "downloads_parallelism"
|
||||
const val KEY_DOWNLOADS_SLOWDOWN = "downloads_slowdown"
|
||||
const val KEY_ALL_FAVOURITES_VISIBLE = "all_favourites_visible"
|
||||
|
||||
@@ -5,15 +5,20 @@ import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import dagger.multibindings.ElementsIntoSet
|
||||
import javax.inject.Singleton
|
||||
import okhttp3.OkHttpClient
|
||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListAuthenticator
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListInterceptor
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListRepository
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListStorage
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.domain.AniListScrobbler
|
||||
import org.koitharu.kotatsu.scrobbling.domain.Scrobbler
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriAuthenticator
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriInterceptor
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriRepository
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriStorage
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.domain.ShikimoriScrobbler
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
@@ -33,9 +38,24 @@ object ScrobblingModule {
|
||||
return ShikimoriRepository(okHttp, storage, database)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAniListRepository(
|
||||
storage: AniListStorage,
|
||||
database: MangaDatabase,
|
||||
authenticator: AniListAuthenticator,
|
||||
): AniListRepository {
|
||||
val okHttp = OkHttpClient.Builder().apply {
|
||||
authenticator(authenticator)
|
||||
addInterceptor(AniListInterceptor(storage))
|
||||
}.build()
|
||||
return AniListRepository(okHttp, storage, database)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@ElementsIntoSet
|
||||
fun provideScrobblers(
|
||||
shikimoriScrobbler: ShikimoriScrobbler,
|
||||
): Set<@JvmSuppressWildcards Scrobbler> = setOf(shikimoriScrobbler)
|
||||
aniListScrobbler: AniListScrobbler,
|
||||
): Set<@JvmSuppressWildcards Scrobbler> = setOf(shikimoriScrobbler, aniListScrobbler)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,6 @@ enum class ScrobblerService(
|
||||
@DrawableRes val iconResId: Int,
|
||||
) {
|
||||
|
||||
SHIKIMORI(1, R.string.shikimori, R.drawable.ic_shikimori)
|
||||
}
|
||||
SHIKIMORI(1, R.string.shikimori, R.drawable.ic_shikimori),
|
||||
ANILIST(2, R.string.anilist, R.drawable.ic_anilist),
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import org.koitharu.kotatsu.core.os.ShortcutsUpdater
|
||||
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||
import org.koitharu.kotatsu.local.data.CacheDir
|
||||
import org.koitharu.kotatsu.local.data.LocalStorageManager
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListRepository
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriRepository
|
||||
import org.koitharu.kotatsu.search.domain.MangaSearchRepository
|
||||
import org.koitharu.kotatsu.tracker.domain.TrackingRepository
|
||||
@@ -40,6 +41,9 @@ class HistorySettingsFragment : BasePreferenceFragment(R.string.history_and_cach
|
||||
@Inject
|
||||
lateinit var shikimoriRepository: ShikimoriRepository
|
||||
|
||||
@Inject
|
||||
lateinit var aniListRepository: AniListRepository
|
||||
|
||||
@Inject
|
||||
lateinit var cookieJar: AndroidCookieJar
|
||||
|
||||
@@ -75,6 +79,7 @@ class HistorySettingsFragment : BasePreferenceFragment(R.string.history_and_cach
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
bindShikimoriSummary()
|
||||
bindAniListSummary()
|
||||
}
|
||||
|
||||
override fun onPreferenceTreeClick(preference: Preference): Boolean {
|
||||
@@ -122,6 +127,15 @@ class HistorySettingsFragment : BasePreferenceFragment(R.string.history_and_cach
|
||||
}
|
||||
}
|
||||
|
||||
AppSettings.KEY_ANILIST -> {
|
||||
if (!aniListRepository.isAuthorized) {
|
||||
launchAniListAuth()
|
||||
true
|
||||
} else {
|
||||
super.onPreferenceTreeClick(preference)
|
||||
}
|
||||
}
|
||||
|
||||
else -> super.onPreferenceTreeClick(preference)
|
||||
}
|
||||
}
|
||||
@@ -193,6 +207,14 @@ class HistorySettingsFragment : BasePreferenceFragment(R.string.history_and_cach
|
||||
}
|
||||
}
|
||||
|
||||
private fun bindAniListSummary() {
|
||||
findPreference<Preference>(AppSettings.KEY_ANILIST)?.summary = if (aniListRepository.isAuthorized) {
|
||||
getString(R.string.logged_in_as, aniListRepository.getCachedUser()?.nickname)
|
||||
} else {
|
||||
getString(R.string.disabled)
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchShikimoriAuth() {
|
||||
runCatching {
|
||||
val intent = Intent(Intent.ACTION_VIEW)
|
||||
@@ -202,4 +224,14 @@ class HistorySettingsFragment : BasePreferenceFragment(R.string.history_and_cach
|
||||
Snackbar.make(listView, it.getDisplayMessage(resources), Snackbar.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchAniListAuth() {
|
||||
runCatching {
|
||||
val intent = Intent(Intent.ACTION_VIEW)
|
||||
intent.data = Uri.parse(aniListRepository.oauthUrl)
|
||||
startActivity(intent)
|
||||
}.onFailure {
|
||||
Snackbar.make(listView, it.getDisplayMessage(resources), Snackbar.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import org.koitharu.kotatsu.base.ui.util.RecyclerViewOwner
|
||||
import org.koitharu.kotatsu.databinding.ActivitySettingsBinding
|
||||
import org.koitharu.kotatsu.main.ui.owners.AppBarOwner
|
||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||
import org.koitharu.kotatsu.scrobbling.anilist.ui.AniListSettingsFragment
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.ui.ShikimoriSettingsFragment
|
||||
import org.koitharu.kotatsu.settings.sources.SourcesSettingsFragment
|
||||
import org.koitharu.kotatsu.settings.tracker.TrackerSettingsFragment
|
||||
@@ -78,6 +79,7 @@ class SettingsActivity :
|
||||
startActivity(intent)
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
@@ -132,6 +134,7 @@ class SettingsActivity :
|
||||
ACTION_SOURCE -> SourceSettingsFragment.newInstance(
|
||||
intent.getSerializableExtra(EXTRA_SOURCE) as? MangaSource ?: MangaSource.LOCAL,
|
||||
)
|
||||
|
||||
ACTION_MANAGE_SOURCES -> SourcesSettingsFragment()
|
||||
else -> SettingsHeadersFragment()
|
||||
}
|
||||
@@ -145,6 +148,9 @@ class SettingsActivity :
|
||||
when (uri?.host) {
|
||||
HOST_SHIKIMORI_AUTH ->
|
||||
return ShikimoriSettingsFragment.newInstance(authCode = uri.getQueryParameter("code"))
|
||||
|
||||
HOST_ANILIST_AUTH ->
|
||||
return AniListSettingsFragment.newInstance(authCode = uri.getQueryParameter("code"))
|
||||
}
|
||||
finishAfterTransition()
|
||||
return null
|
||||
@@ -162,6 +168,7 @@ class SettingsActivity :
|
||||
private const val EXTRA_SOURCE = "source"
|
||||
|
||||
private const val HOST_SHIKIMORI_AUTH = "shikimori-auth"
|
||||
private const val HOST_ANILIST_AUTH = "anilist-auth"
|
||||
|
||||
fun newIntent(context: Context) = Intent(context, SettingsActivity::class.java)
|
||||
|
||||
|
||||
10
app/src/main/res/drawable/ic_anilist.xml
Normal file
10
app/src/main/res/drawable/ic_anilist.xml
Normal file
File diff suppressed because one or more lines are too long
@@ -273,6 +273,7 @@
|
||||
<string name="removal_completed">Removal completed</string>
|
||||
<string name="batch_manga_save_confirm">Download all selected manga and its chapters\? This can consume a lot of traffic and storage.</string>
|
||||
<string name="shikimori" translatable="false">Shikimori</string>
|
||||
<string name="anilist" translatable="false">AniList</string>
|
||||
<string name="parallel_downloads">Parallel downloads</string>
|
||||
<string name="download_slowdown">Download slowdown</string>
|
||||
<string name="download_slowdown_summary">Helps avoid blocking your IP address</string>
|
||||
|
||||
19
app/src/main/res/xml/pref_anilist.xml
Normal file
19
app/src/main/res/xml/pref_anilist.xml
Normal file
@@ -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>
|
||||
@@ -23,9 +23,16 @@
|
||||
|
||||
<PreferenceScreen
|
||||
android:fragment="org.koitharu.kotatsu.scrobbling.shikimori.ui.ShikimoriSettingsFragment"
|
||||
android:icon="@drawable/ic_shikimori"
|
||||
android:key="shikimori"
|
||||
android:title="@string/shikimori" />
|
||||
|
||||
<PreferenceScreen
|
||||
android:fragment="org.koitharu.kotatsu.scrobbling.anilist.ui.AniListSettingsFragment"
|
||||
android:icon="@drawable/ic_anilist"
|
||||
android:key="anilist"
|
||||
android:title="@string/anilist" />
|
||||
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory android:title="@string/data_deletion">
|
||||
|
||||
Reference in New Issue
Block a user