Merge branch 'devel' into feature/mal
# Conflicts: # app/src/main/java/org/koitharu/kotatsu/core/prefs/AppSettings.kt # app/src/main/java/org/koitharu/kotatsu/scrobbling/ScrobblingModule.kt # app/src/main/java/org/koitharu/kotatsu/scrobbling/domain/model/ScrobblerService.kt # app/src/main/java/org/koitharu/kotatsu/settings/HistorySettingsFragment.kt # app/src/main/res/xml/pref_history.xmlpull/302/head
commit
ee2538ba7f
@ -0,0 +1,3 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
package org.koitharu.kotatsu.core.network
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.Response
|
||||||
|
import okio.Buffer
|
||||||
|
import org.koitharu.kotatsu.core.network.CommonHeaders.ACCEPT_ENCODING
|
||||||
|
|
||||||
|
class CurlLoggingInterceptor(
|
||||||
|
private val curlOptions: String? = null
|
||||||
|
) : Interceptor {
|
||||||
|
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val request = chain.request()
|
||||||
|
var isCompressed = false
|
||||||
|
|
||||||
|
val curlCmd = StringBuilder()
|
||||||
|
curlCmd.append("curl")
|
||||||
|
if (curlOptions != null) {
|
||||||
|
curlCmd.append(' ').append(curlOptions)
|
||||||
|
}
|
||||||
|
curlCmd.append(" -X ").append(request.method)
|
||||||
|
|
||||||
|
for ((name, value) in request.headers) {
|
||||||
|
if (name.equals(ACCEPT_ENCODING, ignoreCase = true) && value.equals("gzip", ignoreCase = true)) {
|
||||||
|
isCompressed = true
|
||||||
|
}
|
||||||
|
curlCmd.append(" -H \"").append(name).append(": ").append(value.escape()).append('\"')
|
||||||
|
}
|
||||||
|
|
||||||
|
val body = request.body
|
||||||
|
if (body != null) {
|
||||||
|
val buffer = Buffer()
|
||||||
|
body.writeTo(buffer)
|
||||||
|
val charset = body.contentType()?.charset() ?: Charsets.UTF_8
|
||||||
|
curlCmd.append(" --data-raw '")
|
||||||
|
.append(buffer.readString(charset).replace("\n", "\\n"))
|
||||||
|
.append("'")
|
||||||
|
}
|
||||||
|
if (isCompressed) {
|
||||||
|
curlCmd.append(" --compressed")
|
||||||
|
}
|
||||||
|
curlCmd.append(" \"").append(request.url).append('"')
|
||||||
|
|
||||||
|
log("---cURL (" + request.url + ")")
|
||||||
|
log(curlCmd.toString())
|
||||||
|
|
||||||
|
return chain.proceed(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.escape() = replace("\"", "\\\"")
|
||||||
|
|
||||||
|
private fun log(msg: String) {
|
||||||
|
Log.d("CURL", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,23 @@
|
|||||||
|
package org.koitharu.kotatsu.core.cache
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaPage
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
|
|
||||||
|
interface ContentCache {
|
||||||
|
|
||||||
|
val isCachingEnabled: Boolean
|
||||||
|
|
||||||
|
suspend fun getDetails(source: MangaSource, url: String): Manga?
|
||||||
|
|
||||||
|
fun putDetails(source: MangaSource, url: String, details: SafeDeferred<Manga>)
|
||||||
|
|
||||||
|
suspend fun getPages(source: MangaSource, url: String): List<MangaPage>?
|
||||||
|
|
||||||
|
fun putPages(source: MangaSource, url: String, pages: SafeDeferred<List<MangaPage>>)
|
||||||
|
|
||||||
|
data class Key(
|
||||||
|
val source: MangaSource,
|
||||||
|
val url: String,
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
package org.koitharu.kotatsu.core.cache
|
||||||
|
|
||||||
|
import androidx.collection.LruCache
|
||||||
|
|
||||||
|
class DeferredLruCache<T>(maxSize: Int) : LruCache<ContentCache.Key, SafeDeferred<T>>(maxSize)
|
||||||
@ -0,0 +1,59 @@
|
|||||||
|
package org.koitharu.kotatsu.core.cache
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.content.ComponentCallbacks2
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaPage
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
|
|
||||||
|
class MemoryContentCache(application: Application) : ContentCache, ComponentCallbacks2 {
|
||||||
|
|
||||||
|
init {
|
||||||
|
application.registerComponentCallbacks(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val detailsCache = DeferredLruCache<Manga>(4)
|
||||||
|
private val pagesCache = DeferredLruCache<List<MangaPage>>(4)
|
||||||
|
|
||||||
|
override val isCachingEnabled: Boolean = true
|
||||||
|
|
||||||
|
override suspend fun getDetails(source: MangaSource, url: String): Manga? {
|
||||||
|
return detailsCache[ContentCache.Key(source, url)]?.awaitOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun putDetails(source: MangaSource, url: String, details: SafeDeferred<Manga>) {
|
||||||
|
detailsCache.put(ContentCache.Key(source, url), details)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getPages(source: MangaSource, url: String): List<MangaPage>? {
|
||||||
|
return pagesCache[ContentCache.Key(source, url)]?.awaitOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun putPages(source: MangaSource, url: String, pages: SafeDeferred<List<MangaPage>>) {
|
||||||
|
pagesCache.put(ContentCache.Key(source, url), pages)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onConfigurationChanged(newConfig: Configuration) = Unit
|
||||||
|
|
||||||
|
override fun onLowMemory() = Unit
|
||||||
|
|
||||||
|
override fun onTrimMemory(level: Int) {
|
||||||
|
trimCache(detailsCache, level)
|
||||||
|
trimCache(pagesCache, level)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun trimCache(cache: DeferredLruCache<*>, level: Int) {
|
||||||
|
when (level) {
|
||||||
|
ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL,
|
||||||
|
ComponentCallbacks2.TRIM_MEMORY_COMPLETE,
|
||||||
|
ComponentCallbacks2.TRIM_MEMORY_MODERATE -> cache.evictAll()
|
||||||
|
|
||||||
|
ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN,
|
||||||
|
ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW,
|
||||||
|
ComponentCallbacks2.TRIM_MEMORY_BACKGROUND -> cache.trimToSize(1)
|
||||||
|
|
||||||
|
else -> cache.trimToSize(cache.maxSize() / 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,20 @@
|
|||||||
|
package org.koitharu.kotatsu.core.cache
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Deferred
|
||||||
|
|
||||||
|
class SafeDeferred<T>(
|
||||||
|
private val delegate: Deferred<Result<T>>,
|
||||||
|
) {
|
||||||
|
|
||||||
|
suspend fun await(): T {
|
||||||
|
return delegate.await().getOrThrow()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun awaitOrNull(): T? {
|
||||||
|
return delegate.await().getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel() {
|
||||||
|
delegate.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,18 @@
|
|||||||
|
package org.koitharu.kotatsu.core.cache
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaPage
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
|
|
||||||
|
class StubContentCache : ContentCache {
|
||||||
|
|
||||||
|
override val isCachingEnabled: Boolean = false
|
||||||
|
|
||||||
|
override suspend fun getDetails(source: MangaSource, url: String): Manga? = null
|
||||||
|
|
||||||
|
override fun putDetails(source: MangaSource, url: String, details: SafeDeferred<Manga>) = Unit
|
||||||
|
|
||||||
|
override suspend fun getPages(source: MangaSource, url: String): List<MangaPage>? = null
|
||||||
|
|
||||||
|
override fun putPages(source: MangaSource, url: String, pages: SafeDeferred<List<MangaPage>>) = Unit
|
||||||
|
}
|
||||||
@ -0,0 +1,128 @@
|
|||||||
|
package org.koitharu.kotatsu.core.logs
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.annotation.WorkerThread
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.cancelAndJoin
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runInterruptible
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
|
import org.koitharu.kotatsu.utils.ext.printStackTraceDebug
|
||||||
|
import org.koitharu.kotatsu.utils.ext.processLifecycleScope
|
||||||
|
import org.koitharu.kotatsu.utils.ext.runCatchingCancellable
|
||||||
|
import org.koitharu.kotatsu.utils.ext.subdir
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.concurrent.ConcurrentLinkedQueue
|
||||||
|
|
||||||
|
private const val DIR = "logs"
|
||||||
|
private const val FLUSH_DELAY = 2_000L
|
||||||
|
private const val MAX_SIZE_BYTES = 1024 * 1024 // 1 MB
|
||||||
|
|
||||||
|
class FileLogger(
|
||||||
|
context: Context,
|
||||||
|
private val settings: AppSettings,
|
||||||
|
name: String,
|
||||||
|
) {
|
||||||
|
|
||||||
|
val file by lazy {
|
||||||
|
val dir = context.getExternalFilesDir(DIR) ?: context.filesDir.subdir(DIR)
|
||||||
|
File(dir, "$name.log")
|
||||||
|
}
|
||||||
|
val isEnabled: Boolean
|
||||||
|
get() = settings.isLoggingEnabled
|
||||||
|
private val dateFormat = SimpleDateFormat.getDateTimeInstance(
|
||||||
|
SimpleDateFormat.SHORT,
|
||||||
|
SimpleDateFormat.SHORT,
|
||||||
|
Locale.ROOT,
|
||||||
|
)
|
||||||
|
private val buffer = ConcurrentLinkedQueue<String>()
|
||||||
|
private val mutex = Mutex()
|
||||||
|
private var flushJob: Job? = null
|
||||||
|
|
||||||
|
fun log(message: String, e: Throwable? = null) {
|
||||||
|
if (!isEnabled) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val text = buildString {
|
||||||
|
append(dateFormat.format(Date()))
|
||||||
|
append(": ")
|
||||||
|
if (e != null) {
|
||||||
|
append("E!")
|
||||||
|
}
|
||||||
|
append(message)
|
||||||
|
if (e != null) {
|
||||||
|
append(' ')
|
||||||
|
append(e.stackTraceToString())
|
||||||
|
appendLine()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buffer.add(text)
|
||||||
|
postFlush()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun flush() {
|
||||||
|
if (!isEnabled) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
flushJob?.cancelAndJoin()
|
||||||
|
flushImpl()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun postFlush() {
|
||||||
|
if (flushJob?.isActive == true) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
flushJob = processLifecycleScope.launch(Dispatchers.Default) {
|
||||||
|
delay(FLUSH_DELAY)
|
||||||
|
runCatchingCancellable {
|
||||||
|
flushImpl()
|
||||||
|
}.onFailure {
|
||||||
|
it.printStackTraceDebug()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun flushImpl() {
|
||||||
|
mutex.withLock {
|
||||||
|
if (buffer.isEmpty()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
runInterruptible(Dispatchers.IO) {
|
||||||
|
if (file.length() > MAX_SIZE_BYTES) {
|
||||||
|
rotate()
|
||||||
|
}
|
||||||
|
FileOutputStream(file, true).use {
|
||||||
|
while (true) {
|
||||||
|
val message = buffer.poll() ?: break
|
||||||
|
it.write(message.toByteArray())
|
||||||
|
it.write('\n'.code)
|
||||||
|
}
|
||||||
|
it.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@WorkerThread
|
||||||
|
private fun rotate() {
|
||||||
|
val length = file.length()
|
||||||
|
val bakFile = File(file.parentFile, file.name + ".bak")
|
||||||
|
file.renameTo(bakFile)
|
||||||
|
bakFile.inputStream().use { input ->
|
||||||
|
input.skip(length - MAX_SIZE_BYTES / 2)
|
||||||
|
file.outputStream().use { output ->
|
||||||
|
input.copyTo(output)
|
||||||
|
output.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bakFile.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
package org.koitharu.kotatsu.core.logs
|
||||||
|
|
||||||
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class TrackerLogger
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
package org.koitharu.kotatsu.core.logs
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.collection.arraySetOf
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import dagger.multibindings.ElementsIntoSet
|
||||||
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object LoggersModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@TrackerLogger
|
||||||
|
fun provideTrackerLogger(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
settings: AppSettings,
|
||||||
|
) = FileLogger(context, settings, "tracker")
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@ElementsIntoSet
|
||||||
|
fun provideAllLoggers(
|
||||||
|
@TrackerLogger trackerLogger: FileLogger,
|
||||||
|
): Set<@JvmSuppressWildcards FileLogger> = arraySetOf(
|
||||||
|
trackerLogger,
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
package org.koitharu.kotatsu.core.prefs
|
||||||
|
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
|
||||||
|
enum class NetworkPolicy(
|
||||||
|
private val key: Int,
|
||||||
|
) {
|
||||||
|
|
||||||
|
NEVER(0),
|
||||||
|
ALWAYS(1),
|
||||||
|
NON_METERED(2);
|
||||||
|
|
||||||
|
fun isNetworkAllowed(cm: ConnectivityManager) = when (this) {
|
||||||
|
NEVER -> false
|
||||||
|
ALWAYS -> true
|
||||||
|
NON_METERED -> !cm.isActiveNetworkMetered
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
fun from(key: String?, default: NetworkPolicy): NetworkPolicy {
|
||||||
|
val intKey = key?.toIntOrNull() ?: return default
|
||||||
|
return enumValues<NetworkPolicy>().find { it.key == intKey } ?: default
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,116 @@
|
|||||||
|
package org.koitharu.kotatsu.details.service
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
|
import org.koitharu.kotatsu.base.ui.CoroutineIntentService
|
||||||
|
import org.koitharu.kotatsu.core.cache.ContentCache
|
||||||
|
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
||||||
|
import org.koitharu.kotatsu.core.model.parcelable.ParcelableMangaChapters
|
||||||
|
import org.koitharu.kotatsu.core.parser.MangaRepository
|
||||||
|
import org.koitharu.kotatsu.history.domain.HistoryRepository
|
||||||
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
|
import org.koitharu.kotatsu.utils.ext.getParcelableExtraCompat
|
||||||
|
import org.koitharu.kotatsu.utils.ext.runCatchingCancellable
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class MangaPrefetchService : CoroutineIntentService() {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var mangaRepositoryFactory: MangaRepository.Factory
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var cache: ContentCache
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var historyRepository: HistoryRepository
|
||||||
|
|
||||||
|
override suspend fun processIntent(startId: Int, intent: Intent) {
|
||||||
|
when (intent.action) {
|
||||||
|
ACTION_PREFETCH_DETAILS -> prefetchDetails(
|
||||||
|
manga = intent.getParcelableExtraCompat<ParcelableManga>(EXTRA_MANGA)?.manga ?: return,
|
||||||
|
)
|
||||||
|
|
||||||
|
ACTION_PREFETCH_PAGES -> prefetchPages(
|
||||||
|
chapter = intent.getParcelableExtraCompat<ParcelableMangaChapters>(EXTRA_CHAPTER)
|
||||||
|
?.chapters?.singleOrNull() ?: return,
|
||||||
|
)
|
||||||
|
|
||||||
|
ACTION_PREFETCH_LAST -> prefetchLast()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onError(startId: Int, error: Throwable) = Unit
|
||||||
|
|
||||||
|
private suspend fun prefetchDetails(manga: Manga) {
|
||||||
|
val source = mangaRepositoryFactory.create(manga.source)
|
||||||
|
runCatchingCancellable { source.getDetails(manga) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun prefetchPages(chapter: MangaChapter) {
|
||||||
|
val source = mangaRepositoryFactory.create(chapter.source)
|
||||||
|
runCatchingCancellable { source.getPages(chapter) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun prefetchLast() {
|
||||||
|
val last = historyRepository.getLastOrNull() ?: return
|
||||||
|
if (last.source == MangaSource.LOCAL) return
|
||||||
|
val repo = mangaRepositoryFactory.create(last.source)
|
||||||
|
val details = runCatchingCancellable { repo.getDetails(last) }.getOrNull() ?: return
|
||||||
|
val chapters = details.chapters
|
||||||
|
if (chapters.isNullOrEmpty()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val history = historyRepository.getOne(last)
|
||||||
|
val chapter = if (history == null) {
|
||||||
|
chapters.firstOrNull()
|
||||||
|
} else {
|
||||||
|
chapters.find { x -> x.id == history.chapterId } ?: chapters.firstOrNull()
|
||||||
|
} ?: return
|
||||||
|
runCatchingCancellable { repo.getPages(chapter) }
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
private const val EXTRA_MANGA = "manga"
|
||||||
|
private const val EXTRA_CHAPTER = "manga"
|
||||||
|
private const val ACTION_PREFETCH_DETAILS = "details"
|
||||||
|
private const val ACTION_PREFETCH_PAGES = "pages"
|
||||||
|
private const val ACTION_PREFETCH_LAST = "last"
|
||||||
|
|
||||||
|
fun prefetchDetails(context: Context, manga: Manga) {
|
||||||
|
if (!isPrefetchAvailable(context, manga.source)) return
|
||||||
|
val intent = Intent(context, MangaPrefetchService::class.java)
|
||||||
|
intent.action = ACTION_PREFETCH_DETAILS
|
||||||
|
intent.putExtra(EXTRA_MANGA, ParcelableManga(manga, withChapters = false))
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun prefetchPages(context: Context, chapter: MangaChapter) {
|
||||||
|
if (!isPrefetchAvailable(context, chapter.source)) return
|
||||||
|
val intent = Intent(context, MangaPrefetchService::class.java)
|
||||||
|
intent.action = ACTION_PREFETCH_PAGES
|
||||||
|
intent.putExtra(EXTRA_CHAPTER, ParcelableMangaChapters(listOf(chapter)))
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun prefetchLast(context: Context) {
|
||||||
|
if (!isPrefetchAvailable(context, null)) return
|
||||||
|
val intent = Intent(context, MangaPrefetchService::class.java)
|
||||||
|
intent.action = ACTION_PREFETCH_LAST
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isPrefetchAvailable(context: Context, source: MangaSource?): Boolean {
|
||||||
|
if (source == MangaSource.LOCAL) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val entryPoint = EntryPointAccessors.fromApplication(context, PrefetchCompanionEntryPoint::class.java)
|
||||||
|
return entryPoint.contentCache.isCachingEnabled && entryPoint.settings.isContentPrefetchEnabled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,14 @@
|
|||||||
|
package org.koitharu.kotatsu.details.service
|
||||||
|
|
||||||
|
import dagger.hilt.EntryPoint
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import org.koitharu.kotatsu.core.cache.ContentCache
|
||||||
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
|
|
||||||
|
@EntryPoint
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
interface PrefetchCompanionEntryPoint {
|
||||||
|
val settings: AppSettings
|
||||||
|
val contentCache: ContentCache
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
package org.koitharu.kotatsu.favourites.ui.list
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.Menu
|
||||||
|
import android.view.MenuInflater
|
||||||
|
import android.view.MenuItem
|
||||||
|
import androidx.core.view.MenuProvider
|
||||||
|
import androidx.core.view.forEach
|
||||||
|
import org.koitharu.kotatsu.R
|
||||||
|
import org.koitharu.kotatsu.core.ui.titleRes
|
||||||
|
import org.koitharu.kotatsu.favourites.ui.categories.FavouriteCategoriesActivity
|
||||||
|
import org.koitharu.kotatsu.favourites.ui.categories.edit.FavouritesCategoryEditActivity
|
||||||
|
import org.koitharu.kotatsu.parsers.model.SortOrder
|
||||||
|
|
||||||
|
class FavouritesListMenuProvider(
|
||||||
|
private val context: Context,
|
||||||
|
private val viewModel: FavouritesListViewModel,
|
||||||
|
) : MenuProvider {
|
||||||
|
|
||||||
|
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
|
||||||
|
menuInflater.inflate(R.menu.opt_favourites, menu)
|
||||||
|
val subMenu = menu.findItem(R.id.action_order)?.subMenu ?: return
|
||||||
|
for (order in FavouriteCategoriesActivity.SORT_ORDERS) {
|
||||||
|
subMenu.add(R.id.group_order, Menu.NONE, order.ordinal, order.titleRes)
|
||||||
|
}
|
||||||
|
subMenu.setGroupCheckable(R.id.group_order, true, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPrepareMenu(menu: Menu) {
|
||||||
|
super.onPrepareMenu(menu)
|
||||||
|
val order = viewModel.sortOrder.value ?: return
|
||||||
|
menu.findItem(R.id.action_order)?.subMenu?.forEach { item ->
|
||||||
|
if (item.order == order.ordinal) {
|
||||||
|
item.isChecked = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
|
||||||
|
if (menuItem.groupId == R.id.group_order) {
|
||||||
|
val order = enumValues<SortOrder>()[menuItem.order]
|
||||||
|
viewModel.setSortOrder(order)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return when (menuItem.itemId) {
|
||||||
|
R.id.action_edit -> {
|
||||||
|
context.startActivity(
|
||||||
|
FavouritesCategoryEditActivity.newIntent(context, viewModel.categoryId),
|
||||||
|
)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
package org.koitharu.kotatsu.list.ui.adapter
|
||||||
|
|
||||||
|
import android.view.View
|
||||||
|
import org.koitharu.kotatsu.base.ui.list.OnListItemClickListener
|
||||||
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
|
|
||||||
|
interface MangaDetailsClickListener : OnListItemClickListener<Manga> {
|
||||||
|
|
||||||
|
fun onReadClick(manga: Manga, view: View)
|
||||||
|
|
||||||
|
fun onTagClick(manga: Manga, tag: MangaTag, view: View)
|
||||||
|
}
|
||||||
@ -1,15 +1,15 @@
|
|||||||
package org.koitharu.kotatsu.list.ui.model
|
package org.koitharu.kotatsu.list.ui.model
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.base.ui.widgets.ChipsView
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
|
||||||
data class MangaListDetailedModel(
|
data class MangaListDetailedModel(
|
||||||
override val id: Long,
|
override val id: Long,
|
||||||
override val title: String,
|
override val title: String,
|
||||||
val subtitle: String?,
|
val subtitle: String?,
|
||||||
val tags: String,
|
|
||||||
override val coverUrl: String,
|
override val coverUrl: String,
|
||||||
val rating: String?,
|
|
||||||
override val manga: Manga,
|
override val manga: Manga,
|
||||||
override val counter: Int,
|
override val counter: Int,
|
||||||
override val progress: Float,
|
override val progress: Float,
|
||||||
) : MangaItemModel
|
val tags: List<ChipsView.ChipModel>,
|
||||||
|
) : MangaItemModel
|
||||||
|
|||||||
@ -1,18 +0,0 @@
|
|||||||
package org.koitharu.kotatsu.local.data
|
|
||||||
|
|
||||||
import okhttp3.internal.closeQuietly
|
|
||||||
import okio.BufferedSource
|
|
||||||
import okio.Closeable
|
|
||||||
|
|
||||||
class ExtraCloseableBufferedSource(
|
|
||||||
private val delegate: BufferedSource,
|
|
||||||
vararg closeable: Closeable,
|
|
||||||
) : BufferedSource by delegate {
|
|
||||||
|
|
||||||
private val extraCloseable = closeable
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
delegate.close()
|
|
||||||
extraCloseable.forEach { x -> x.closeQuietly() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -0,0 +1,21 @@
|
|||||||
|
package org.koitharu.kotatsu.local.data
|
||||||
|
|
||||||
|
import okhttp3.internal.closeQuietly
|
||||||
|
import okio.Closeable
|
||||||
|
import okio.Source
|
||||||
|
|
||||||
|
private class ExtraCloseableSource(
|
||||||
|
private val delegate: Source,
|
||||||
|
private val extraCloseable: Closeable,
|
||||||
|
) : Source by delegate {
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
try {
|
||||||
|
delegate.close()
|
||||||
|
} finally {
|
||||||
|
extraCloseable.closeQuietly()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Source.withExtraCloseable(closeable: Closeable): Source = ExtraCloseableSource(this, closeable)
|
||||||
@ -0,0 +1,39 @@
|
|||||||
|
package org.koitharu.kotatsu.main.ui
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.AttributeSet
|
||||||
|
import android.view.View
|
||||||
|
import androidx.coordinatorlayout.widget.CoordinatorLayout
|
||||||
|
import androidx.core.view.ViewCompat
|
||||||
|
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
|
||||||
|
import org.koitharu.kotatsu.base.ui.util.ShrinkOnScrollBehavior
|
||||||
|
import org.koitharu.kotatsu.base.ui.widgets.SlidingBottomNavigationView
|
||||||
|
|
||||||
|
class MainActionButtonBehavior : ShrinkOnScrollBehavior {
|
||||||
|
|
||||||
|
constructor() : super()
|
||||||
|
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
|
||||||
|
|
||||||
|
override fun layoutDependsOn(
|
||||||
|
parent: CoordinatorLayout,
|
||||||
|
child: ExtendedFloatingActionButton,
|
||||||
|
dependency: View
|
||||||
|
): Boolean {
|
||||||
|
return dependency is SlidingBottomNavigationView || super.layoutDependsOn(parent, child, dependency)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDependentViewChanged(
|
||||||
|
parent: CoordinatorLayout,
|
||||||
|
child: ExtendedFloatingActionButton,
|
||||||
|
dependency: View
|
||||||
|
): Boolean {
|
||||||
|
val bottom = child.bottom
|
||||||
|
val bottomLine = parent.height
|
||||||
|
return if (bottom > bottomLine) {
|
||||||
|
ViewCompat.offsetTopAndBottom(child, bottomLine - bottom)
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
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 org.koitharu.kotatsu.scrobbling.data.ScrobblerStorage
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerService
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerType
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Provider
|
||||||
|
|
||||||
|
class AniListAuthenticator @Inject constructor(
|
||||||
|
@ScrobblerType(ScrobblerService.ANILIST) private val storage: ScrobblerStorage,
|
||||||
|
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,24 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.data
|
||||||
|
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.Response
|
||||||
|
import org.koitharu.kotatsu.core.network.CommonHeaders
|
||||||
|
import org.koitharu.kotatsu.scrobbling.data.ScrobblerStorage
|
||||||
|
|
||||||
|
private const val JSON = "application/json"
|
||||||
|
|
||||||
|
class AniListInterceptor(private val storage: ScrobblerStorage) : 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,263 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.data
|
||||||
|
|
||||||
|
import okhttp3.FormBody
|
||||||
|
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.toIntUp
|
||||||
|
import org.koitharu.kotatsu.scrobbling.data.ScrobblerRepository
|
||||||
|
import org.koitharu.kotatsu.scrobbling.data.ScrobblerStorage
|
||||||
|
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.scrobbling.domain.model.ScrobblerUser
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
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
|
||||||
|
private const val REQUEST_QUERY = "query"
|
||||||
|
private const val REQUEST_MUTATION = "mutation"
|
||||||
|
private const val KEY_SCORE_FORMAT = "score_format"
|
||||||
|
|
||||||
|
class AniListRepository(
|
||||||
|
private val okHttp: OkHttpClient,
|
||||||
|
private val storage: ScrobblerStorage,
|
||||||
|
private val db: MangaDatabase,
|
||||||
|
) : ScrobblerRepository {
|
||||||
|
|
||||||
|
override val oauthUrl: String
|
||||||
|
get() = "${BASE_URL}oauth/authorize?client_id=${BuildConfig.ANILIST_CLIENT_ID}&" +
|
||||||
|
"redirect_uri=${REDIRECT_URI}&response_type=code"
|
||||||
|
|
||||||
|
override val isAuthorized: Boolean
|
||||||
|
get() = storage.accessToken != null
|
||||||
|
|
||||||
|
private val shrinkRegex = Regex("\\t+")
|
||||||
|
|
||||||
|
override 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")
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun loadUser(): ScrobblerUser {
|
||||||
|
val response = doRequest(
|
||||||
|
REQUEST_QUERY,
|
||||||
|
"""
|
||||||
|
AniChartUser {
|
||||||
|
user {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
avatar {
|
||||||
|
medium
|
||||||
|
}
|
||||||
|
mediaListOptions {
|
||||||
|
scoreFormat
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
val jo = response.getJSONObject("data").getJSONObject("AniChartUser").getJSONObject("user")
|
||||||
|
storage[KEY_SCORE_FORMAT] = jo.getJSONObject("mediaListOptions").getString("scoreFormat")
|
||||||
|
return AniListUser(jo).also { storage.user = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
override val cachedUser: ScrobblerUser?
|
||||||
|
get() {
|
||||||
|
return storage.user
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun unregister(mangaId: Long) {
|
||||||
|
return db.scrobblingDao.delete(ScrobblerService.ANILIST.id, mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun logout() {
|
||||||
|
storage.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun findManga(query: String, offset: Int): List<ScrobblerManga> {
|
||||||
|
val page = (offset / MANGA_PAGE_SIZE.toFloat()).toIntUp() + 1
|
||||||
|
val response = doRequest(
|
||||||
|
REQUEST_QUERY,
|
||||||
|
"""
|
||||||
|
Page(page: $page, perPage: ${MANGA_PAGE_SIZE}) {
|
||||||
|
media(type: MANGA, sort: SEARCH_MATCH, search: ${JSONObject.quote(query)}) {
|
||||||
|
id
|
||||||
|
title {
|
||||||
|
userPreferred
|
||||||
|
native
|
||||||
|
}
|
||||||
|
coverImage {
|
||||||
|
medium
|
||||||
|
}
|
||||||
|
siteUrl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
val data = response.getJSONObject("data").getJSONObject("Page").getJSONArray("media")
|
||||||
|
return data.mapJSON { ScrobblerManga(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun createRate(mangaId: Long, scrobblerMangaId: Long) {
|
||||||
|
val response = doRequest(
|
||||||
|
REQUEST_MUTATION,
|
||||||
|
"""
|
||||||
|
SaveMediaListEntry(mediaId: $scrobblerMangaId) {
|
||||||
|
id
|
||||||
|
mediaId
|
||||||
|
status
|
||||||
|
notes
|
||||||
|
score
|
||||||
|
progress
|
||||||
|
}
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
saveRate(response.getJSONObject("data").getJSONObject("SaveMediaListEntry"), mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updateRate(rateId: Int, mangaId: Long, chapter: MangaChapter) {
|
||||||
|
val response = doRequest(
|
||||||
|
REQUEST_MUTATION,
|
||||||
|
"""
|
||||||
|
SaveMediaListEntry(id: $rateId, progress: ${chapter.number}) {
|
||||||
|
id
|
||||||
|
mediaId
|
||||||
|
status
|
||||||
|
notes
|
||||||
|
score
|
||||||
|
progress
|
||||||
|
}
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
saveRate(response.getJSONObject("data").getJSONObject("SaveMediaListEntry"), mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updateRate(rateId: Int, mangaId: Long, rating: Float, status: String?, comment: String?) {
|
||||||
|
val scoreRaw = (rating * 100f).roundToInt()
|
||||||
|
val statusString = status?.let { ", status: $it" }.orEmpty()
|
||||||
|
val notesString = comment?.let { ", notes: ${JSONObject.quote(it)}" }.orEmpty()
|
||||||
|
val response = doRequest(
|
||||||
|
REQUEST_MUTATION,
|
||||||
|
"""
|
||||||
|
SaveMediaListEntry(id: $rateId, scoreRaw: $scoreRaw$statusString$notesString) {
|
||||||
|
id
|
||||||
|
mediaId
|
||||||
|
status
|
||||||
|
notes
|
||||||
|
score
|
||||||
|
progress
|
||||||
|
}
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
saveRate(response.getJSONObject("data").getJSONObject("SaveMediaListEntry"), mangaId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getMangaInfo(id: Long): ScrobblerMangaInfo {
|
||||||
|
val response = doRequest(
|
||||||
|
REQUEST_QUERY,
|
||||||
|
"""
|
||||||
|
Media(id: $id) {
|
||||||
|
id
|
||||||
|
title {
|
||||||
|
userPreferred
|
||||||
|
}
|
||||||
|
coverImage {
|
||||||
|
large
|
||||||
|
}
|
||||||
|
description
|
||||||
|
siteUrl
|
||||||
|
}
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
return ScrobblerMangaInfo(response.getJSONObject("data").getJSONObject("Media"))
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun saveRate(json: JSONObject, mangaId: Long) {
|
||||||
|
val scoreFormat = ScoreFormat.of(storage[KEY_SCORE_FORMAT])
|
||||||
|
val entity = ScrobblingEntity(
|
||||||
|
scrobbler = ScrobblerService.ANILIST.id,
|
||||||
|
id = json.getInt("id"),
|
||||||
|
mangaId = mangaId,
|
||||||
|
targetId = json.getLong("mediaId"),
|
||||||
|
status = json.getString("status"),
|
||||||
|
chapter = json.getInt("progress"),
|
||||||
|
comment = json.getString("notes"),
|
||||||
|
rating = scoreFormat.normalize(json.getDouble("score").toFloat()),
|
||||||
|
)
|
||||||
|
db.scrobblingDao.upsert(entity)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ScrobblerManga(json: JSONObject): ScrobblerManga {
|
||||||
|
val title = json.getJSONObject("title")
|
||||||
|
return ScrobblerManga(
|
||||||
|
id = json.getLong("id"),
|
||||||
|
name = title.getString("userPreferred"),
|
||||||
|
altName = title.getStringOrNull("native"),
|
||||||
|
cover = json.getJSONObject("coverImage").getString("medium"),
|
||||||
|
url = json.getString("siteUrl"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ScrobblerMangaInfo(json: JSONObject) = ScrobblerMangaInfo(
|
||||||
|
id = json.getLong("id"),
|
||||||
|
name = json.getJSONObject("title").getString("userPreferred"),
|
||||||
|
cover = json.getJSONObject("coverImage").getString("large"),
|
||||||
|
url = json.getString("siteUrl"),
|
||||||
|
descriptionHtml = json.getString("description"),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun AniListUser(json: JSONObject) = ScrobblerUser(
|
||||||
|
id = json.getLong("id"),
|
||||||
|
nickname = json.getString("name"),
|
||||||
|
avatar = json.getJSONObject("avatar").getString("medium"),
|
||||||
|
service = ScrobblerService.ANILIST,
|
||||||
|
)
|
||||||
|
|
||||||
|
private suspend fun doRequest(type: String, payload: String): JSONObject {
|
||||||
|
val body = JSONObject()
|
||||||
|
body.put("query", "$type { ${payload.shrink()} }")
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.shrink() = replace(shrinkRegex, " ")
|
||||||
|
}
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.data
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.utils.ext.printStackTraceDebug
|
||||||
|
|
||||||
|
enum class ScoreFormat {
|
||||||
|
|
||||||
|
POINT_100, POINT_10_DECIMAL, POINT_10, POINT_5, POINT_3;
|
||||||
|
|
||||||
|
fun normalize(score: Float): Float = when (this) {
|
||||||
|
POINT_100 -> score / 100f
|
||||||
|
POINT_10_DECIMAL,
|
||||||
|
POINT_10 -> score / 10f
|
||||||
|
|
||||||
|
POINT_5 -> score / 5f
|
||||||
|
POINT_3 -> score / 3f
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
fun of(rawValue: String?): ScoreFormat {
|
||||||
|
rawValue ?: return POINT_10_DECIMAL
|
||||||
|
return runCatching { valueOf(rawValue) }
|
||||||
|
.onFailure { it.printStackTraceDebug() }
|
||||||
|
.getOrDefault(POINT_10_DECIMAL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,42 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.anilist.domain
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||||
|
import org.koitharu.kotatsu.scrobbling.anilist.data.AniListRepository
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.Scrobbler
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerService
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblingStatus
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class AniListScrobbler @Inject constructor(
|
||||||
|
private val repository: AniListRepository,
|
||||||
|
db: MangaDatabase,
|
||||||
|
) : Scrobbler(db, ScrobblerService.ANILIST, repository) {
|
||||||
|
|
||||||
|
init {
|
||||||
|
statuses[ScrobblingStatus.PLANNED] = "PLANNING"
|
||||||
|
statuses[ScrobblingStatus.READING] = "CURRENT"
|
||||||
|
statuses[ScrobblingStatus.RE_READING] = "REPEATING"
|
||||||
|
statuses[ScrobblingStatus.COMPLETED] = "COMPLETED"
|
||||||
|
statuses[ScrobblingStatus.ON_HOLD] = "PAUSED"
|
||||||
|
statuses[ScrobblingStatus.DROPPED] = "DROPPED"
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
status = statuses[status],
|
||||||
|
comment = comment,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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.domain.model.ScrobblerUser
|
||||||
|
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: ScrobblerUser?) {
|
||||||
|
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.domain.model.ScrobblerUser
|
||||||
|
|
||||||
|
class AniListSettingsViewModel @AssistedInject constructor(
|
||||||
|
private val repository: AniListRepository,
|
||||||
|
@Assisted authCode: String?,
|
||||||
|
) : BaseViewModel() {
|
||||||
|
|
||||||
|
val authorizationUrl: String
|
||||||
|
get() = repository.oauthUrl
|
||||||
|
|
||||||
|
val user = MutableLiveData<ScrobblerUser?>()
|
||||||
|
|
||||||
|
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.cachedUser?.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
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,33 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.data
|
||||||
|
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerMangaInfo
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerUser
|
||||||
|
|
||||||
|
interface ScrobblerRepository {
|
||||||
|
|
||||||
|
val oauthUrl: String
|
||||||
|
|
||||||
|
val isAuthorized: Boolean
|
||||||
|
|
||||||
|
val cachedUser: ScrobblerUser?
|
||||||
|
|
||||||
|
suspend fun authorize(code: String?)
|
||||||
|
|
||||||
|
suspend fun loadUser(): ScrobblerUser
|
||||||
|
|
||||||
|
fun logout()
|
||||||
|
|
||||||
|
suspend fun unregister(mangaId: Long)
|
||||||
|
|
||||||
|
suspend fun findManga(query: String, offset: Int): List<ScrobblerManga>
|
||||||
|
|
||||||
|
suspend fun getMangaInfo(id: Long): ScrobblerMangaInfo
|
||||||
|
|
||||||
|
suspend fun createRate(mangaId: Long, scrobblerMangaId: Long)
|
||||||
|
|
||||||
|
suspend fun updateRate(rateId: Int, mangaId: Long, chapter: MangaChapter)
|
||||||
|
|
||||||
|
suspend fun updateRate(rateId: Int, mangaId: Long, rating: Float, status: String?, comment: String?)
|
||||||
|
}
|
||||||
@ -0,0 +1,58 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.data
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.core.content.edit
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerService
|
||||||
|
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerUser
|
||||||
|
|
||||||
|
private const val KEY_ACCESS_TOKEN = "access_token"
|
||||||
|
private const val KEY_REFRESH_TOKEN = "refresh_token"
|
||||||
|
private const val KEY_USER = "user"
|
||||||
|
|
||||||
|
class ScrobblerStorage(context: Context, service: ScrobblerService) {
|
||||||
|
|
||||||
|
private val prefs = context.getSharedPreferences(service.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: ScrobblerUser?
|
||||||
|
get() = prefs.getString(KEY_USER, null)?.let {
|
||||||
|
val lines = it.lines()
|
||||||
|
if (lines.size != 4) {
|
||||||
|
return@let null
|
||||||
|
}
|
||||||
|
ScrobblerUser(
|
||||||
|
id = lines[0].toLong(),
|
||||||
|
nickname = lines[1],
|
||||||
|
avatar = lines[2],
|
||||||
|
service = ScrobblerService.valueOf(lines[3]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
set(value) = prefs.edit {
|
||||||
|
if (value == null) {
|
||||||
|
remove(KEY_USER)
|
||||||
|
return@edit
|
||||||
|
}
|
||||||
|
val str = buildString {
|
||||||
|
appendLine(value.id)
|
||||||
|
appendLine(value.nickname)
|
||||||
|
appendLine(value.avatar)
|
||||||
|
appendLine(value.service.name)
|
||||||
|
}
|
||||||
|
putString(KEY_USER, str)
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun get(key: String): String? = prefs.getString(key, null)
|
||||||
|
|
||||||
|
operator fun set(key: String, value: String?) = prefs.edit { putString(key, value) }
|
||||||
|
|
||||||
|
fun clear() = prefs.edit {
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
package org.koitharu.kotatsu.scrobbling.domain.model
|
||||||
|
|
||||||
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
@Qualifier
|
||||||
|
annotation class ScrobblerType(
|
||||||
|
val service: ScrobblerService
|
||||||
|
)
|
||||||
@ -1,40 +0,0 @@
|
|||||||
package org.koitharu.kotatsu.scrobbling.shikimori.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.shikimori.data.model.ShikimoriUser
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
private const val PREF_NAME = "shikimori"
|
|
||||||
private const val KEY_ACCESS_TOKEN = "access_token"
|
|
||||||
private const val KEY_REFRESH_TOKEN = "refresh_token"
|
|
||||||
private const val KEY_USER = "user"
|
|
||||||
|
|
||||||
@Singleton
|
|
||||||
class ShikimoriStorage @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: ShikimoriUser?
|
|
||||||
get() = prefs.getString(KEY_USER, null)?.let {
|
|
||||||
ShikimoriUser(JSONObject(it))
|
|
||||||
}
|
|
||||||
set(value) = prefs.edit {
|
|
||||||
putString(KEY_USER, value?.toJson()?.toString())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clear() = prefs.edit {
|
|
||||||
clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
package org.koitharu.kotatsu.settings.utils
|
||||||
|
|
||||||
|
import android.content.ActivityNotFoundException
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.util.AttributeSet
|
||||||
|
import androidx.preference.ListPreference
|
||||||
|
import org.koitharu.kotatsu.utils.ext.printStackTraceDebug
|
||||||
|
|
||||||
|
class ActivityListPreference : ListPreference {
|
||||||
|
|
||||||
|
var activityIntent: Intent? = null
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
context: Context,
|
||||||
|
attrs: AttributeSet?,
|
||||||
|
defStyleAttr: Int,
|
||||||
|
defStyleRes: Int
|
||||||
|
) : super(context, attrs, defStyleAttr, defStyleRes)
|
||||||
|
|
||||||
|
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
|
||||||
|
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
|
||||||
|
constructor(context: Context) : super(context)
|
||||||
|
|
||||||
|
override fun onClick() {
|
||||||
|
val intent = activityIntent
|
||||||
|
if (intent == null) {
|
||||||
|
super.onClick()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
context.startActivity(intent)
|
||||||
|
} catch (e: ActivityNotFoundException) {
|
||||||
|
e.printStackTraceDebug()
|
||||||
|
super.onClick()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue