Merge branch 'devel' into feature/nextgen
# Conflicts: # app/src/main/java/org/koitharu/kotatsu/utils/ext/AndroidExt.ktpull/163/head
commit
b4f2b82a0d
@ -0,0 +1,29 @@
|
||||
**PLEASE READ THIS**
|
||||
|
||||
I acknowledge that:
|
||||
|
||||
- I have updated to the latest version of the app (https://github.com/KotatsuApp/Kotatsu/releases/latest)
|
||||
- If this is an issue with a parser, that I should be opening an issue in https://github.com/KotatsuApp/kotatsu-parsers
|
||||
- I have searched the existing issues and this is new ticket **NOT** a duplicate or related to another open or closed issue
|
||||
- I will fill out the title and the information in this template
|
||||
|
||||
Note that the issue will be automatically closed if you do not fill out the title or requested information.
|
||||
|
||||
**DELETE THIS SECTION IF YOU HAVE READ AND ACKNOWLEDGED IT**
|
||||
|
||||
---
|
||||
|
||||
## Device information
|
||||
* Kotatsu version: ?
|
||||
* Android version: ?
|
||||
* Device: ?
|
||||
|
||||
## Steps to reproduce
|
||||
1. First step
|
||||
2. Second step
|
||||
|
||||
## Issue/Request
|
||||
?
|
||||
|
||||
## Other details
|
||||
Additional details and attachments.
|
||||
@ -1,5 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: ⚠️ Source issue
|
||||
url: https://github.com/nv95/kotatsu-parsers/issues/new
|
||||
url: https://github.com/KotatsuApp/kotatsu-parsers/issues/new
|
||||
about: Issues and requests for sources should be opened in the kotatsu-parsers repository instead
|
||||
@ -0,0 +1,29 @@
|
||||
name: Issue moderator
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited, reopened]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
moderate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Moderate issues
|
||||
uses: tachiyomiorg/issue-moderator-action@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
auto-close-rules: |
|
||||
[
|
||||
{
|
||||
"type": "body",
|
||||
"regex": ".*DELETE THIS SECTION IF YOU HAVE READ AND ACKNOWLEDGED IT.*",
|
||||
"message": "The acknowledgment section was not removed."
|
||||
},
|
||||
{
|
||||
"type": "body",
|
||||
"regex": ".*\\* (Kotatsu version|Android version|Device): \\?.*",
|
||||
"message": "Requested information in the template was not filled out."
|
||||
}
|
||||
]
|
||||
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RenderSettings">
|
||||
<option name="quality" value="0.25" />
|
||||
</component>
|
||||
</project>
|
||||
@ -1,89 +0,0 @@
|
||||
package org.koitharu.kotatsu.base.ui.dialog
|
||||
|
||||
import android.content.Context
|
||||
import android.content.DialogInterface
|
||||
import android.text.InputFilter
|
||||
import android.view.LayoutInflater
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import org.koitharu.kotatsu.databinding.DialogInputBinding
|
||||
|
||||
class TextInputDialog private constructor(
|
||||
private val delegate: AlertDialog,
|
||||
) : DialogInterface by delegate {
|
||||
|
||||
fun show() = delegate.show()
|
||||
|
||||
class Builder(context: Context) {
|
||||
|
||||
private val binding = DialogInputBinding.inflate(LayoutInflater.from(context))
|
||||
|
||||
private val delegate = MaterialAlertDialogBuilder(context)
|
||||
.setView(binding.root)
|
||||
|
||||
fun setTitle(@StringRes titleResId: Int): Builder {
|
||||
delegate.setTitle(titleResId)
|
||||
return this
|
||||
}
|
||||
|
||||
fun setTitle(title: CharSequence): Builder {
|
||||
delegate.setTitle(title)
|
||||
return this
|
||||
}
|
||||
|
||||
fun setHint(@StringRes hintResId: Int): Builder {
|
||||
binding.inputEdit.hint = binding.root.context.getString(hintResId)
|
||||
return this
|
||||
}
|
||||
|
||||
fun setMaxLength(maxLength: Int, strict: Boolean): Builder {
|
||||
with(binding.inputLayout) {
|
||||
counterMaxLength = maxLength
|
||||
isCounterEnabled = maxLength > 0
|
||||
}
|
||||
if (strict && maxLength > 0) {
|
||||
binding.inputEdit.filters += InputFilter.LengthFilter(maxLength)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
fun setInputType(inputType: Int): Builder {
|
||||
binding.inputEdit.inputType = inputType
|
||||
return this
|
||||
}
|
||||
|
||||
fun setText(text: String): Builder {
|
||||
binding.inputEdit.setText(text)
|
||||
binding.inputEdit.setSelection(text.length)
|
||||
return this
|
||||
}
|
||||
|
||||
fun setPositiveButton(
|
||||
@StringRes textId: Int,
|
||||
listener: (DialogInterface, String) -> Unit
|
||||
): Builder {
|
||||
delegate.setPositiveButton(textId) { dialog, _ ->
|
||||
listener(dialog, binding.inputEdit.text?.toString().orEmpty())
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
fun setNegativeButton(
|
||||
@StringRes textId: Int,
|
||||
listener: DialogInterface.OnClickListener? = null
|
||||
): Builder {
|
||||
delegate.setNegativeButton(textId, listener)
|
||||
return this
|
||||
}
|
||||
|
||||
fun setOnCancelListener(listener: DialogInterface.OnCancelListener): Builder {
|
||||
delegate.setOnCancelListener(listener)
|
||||
return this
|
||||
}
|
||||
|
||||
fun create() =
|
||||
TextInputDialog(delegate.create())
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package org.koitharu.kotatsu.core.db.migrations
|
||||
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
|
||||
class Migration11To12 : Migration(11, 12) {
|
||||
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
database.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS `scrobblings` (
|
||||
`scrobbler` INTEGER NOT NULL,
|
||||
`id` INTEGER NOT NULL,
|
||||
`manga_id` INTEGER NOT NULL,
|
||||
`target_id` INTEGER NOT NULL,
|
||||
`status` TEXT,
|
||||
`chapter` INTEGER NOT NULL,
|
||||
`comment` TEXT,
|
||||
`rating` REAL NOT NULL,
|
||||
PRIMARY KEY(`scrobbler`, `id`, `manga_id`)
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
database.execSQL("ALTER TABLE history ADD COLUMN `percent` REAL NOT NULL DEFAULT -1")
|
||||
database.execSQL("ALTER TABLE bookmarks ADD COLUMN `percent` REAL NOT NULL DEFAULT -1")
|
||||
}
|
||||
}
|
||||
@ -1,8 +1,6 @@
|
||||
package org.koitharu.kotatsu.core.exceptions
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import okio.IOException
|
||||
import org.koitharu.kotatsu.R
|
||||
|
||||
class CloudFlareProtectedException(
|
||||
val url: String
|
||||
|
||||
@ -0,0 +1,150 @@
|
||||
package org.koitharu.kotatsu.details.ui.scrobbling
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.text.method.LinkMovementMethod
|
||||
import android.view.LayoutInflater
|
||||
import android.view.MenuItem
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.AdapterView
|
||||
import android.widget.RatingBar
|
||||
import android.widget.Toast
|
||||
import androidx.appcompat.widget.PopupMenu
|
||||
import androidx.core.net.toUri
|
||||
import androidx.fragment.app.FragmentManager
|
||||
import coil.ImageLoader
|
||||
import coil.request.ImageRequest
|
||||
import coil.size.Scale
|
||||
import org.koin.android.ext.android.inject
|
||||
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.base.ui.BaseBottomSheet
|
||||
import org.koitharu.kotatsu.databinding.SheetScrobblingBinding
|
||||
import org.koitharu.kotatsu.details.ui.DetailsViewModel
|
||||
import org.koitharu.kotatsu.image.ui.ImageActivity
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblingInfo
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblingStatus
|
||||
import org.koitharu.kotatsu.scrobbling.ui.selector.ScrobblingSelectorBottomSheet
|
||||
import org.koitharu.kotatsu.utils.ext.enqueueWith
|
||||
import org.koitharu.kotatsu.utils.ext.getDisplayMessage
|
||||
|
||||
class ScrobblingInfoBottomSheet :
|
||||
BaseBottomSheet<SheetScrobblingBinding>(),
|
||||
AdapterView.OnItemSelectedListener,
|
||||
RatingBar.OnRatingBarChangeListener,
|
||||
View.OnClickListener,
|
||||
PopupMenu.OnMenuItemClickListener {
|
||||
|
||||
private val viewModel by sharedViewModel<DetailsViewModel>()
|
||||
private val coil by inject<ImageLoader>(mode = LazyThreadSafetyMode.NONE)
|
||||
private var menu: PopupMenu? = null
|
||||
|
||||
override fun onInflateView(inflater: LayoutInflater, container: ViewGroup?): SheetScrobblingBinding {
|
||||
return SheetScrobblingBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
viewModel.scrobblingInfo.observe(viewLifecycleOwner, ::onScrobblingInfoChanged)
|
||||
viewModel.onError.observe(viewLifecycleOwner) {
|
||||
Toast.makeText(view.context, it.getDisplayMessage(view.resources), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
binding.spinnerStatus.onItemSelectedListener = this
|
||||
binding.ratingBar.onRatingBarChangeListener = this
|
||||
binding.buttonMenu.setOnClickListener(this)
|
||||
binding.imageViewCover.setOnClickListener(this)
|
||||
binding.textViewDescription.movementMethod = LinkMovementMethod.getInstance()
|
||||
|
||||
menu = PopupMenu(view.context, binding.buttonMenu).apply {
|
||||
inflate(R.menu.opt_scrobbling)
|
||||
setOnMenuItemClickListener(this@ScrobblingInfoBottomSheet)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
menu = null
|
||||
}
|
||||
|
||||
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
|
||||
viewModel.updateScrobbling(
|
||||
rating = binding.ratingBar.rating / binding.ratingBar.numStars,
|
||||
status = enumValues<ScrobblingStatus>().getOrNull(position),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
|
||||
|
||||
override fun onRatingChanged(ratingBar: RatingBar, rating: Float, fromUser: Boolean) {
|
||||
if (fromUser) {
|
||||
viewModel.updateScrobbling(
|
||||
rating = rating / ratingBar.numStars,
|
||||
status = enumValues<ScrobblingStatus>().getOrNull(binding.spinnerStatus.selectedItemPosition),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClick(v: View) {
|
||||
when (v.id) {
|
||||
R.id.button_menu -> menu?.show()
|
||||
R.id.imageView_cover -> {
|
||||
val coverUrl = viewModel.scrobblingInfo.value?.coverUrl ?: return
|
||||
val options = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.width, v.height)
|
||||
startActivity(ImageActivity.newIntent(v.context, coverUrl), options.toBundle())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onScrobblingInfoChanged(scrobbling: ScrobblingInfo?) {
|
||||
if (scrobbling == null) {
|
||||
dismissAllowingStateLoss()
|
||||
return
|
||||
}
|
||||
binding.textViewTitle.text = scrobbling.title
|
||||
binding.ratingBar.rating = scrobbling.rating * binding.ratingBar.numStars
|
||||
binding.textViewDescription.text = scrobbling.description
|
||||
binding.spinnerStatus.setSelection(scrobbling.status?.ordinal ?: -1)
|
||||
ImageRequest.Builder(context ?: return)
|
||||
.target(binding.imageViewCover)
|
||||
.data(scrobbling.coverUrl)
|
||||
.crossfade(true)
|
||||
.lifecycle(viewLifecycleOwner)
|
||||
.placeholder(R.drawable.ic_placeholder)
|
||||
.fallback(R.drawable.ic_placeholder)
|
||||
.error(R.drawable.ic_placeholder)
|
||||
.scale(Scale.FILL)
|
||||
.enqueueWith(coil)
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private const val TAG = "ScrobblingInfoBottomSheet"
|
||||
|
||||
fun show(fm: FragmentManager) = ScrobblingInfoBottomSheet().show(fm, TAG)
|
||||
}
|
||||
|
||||
override fun onMenuItemClick(item: MenuItem): Boolean {
|
||||
when (item.itemId) {
|
||||
R.id.action_browser -> {
|
||||
val url = viewModel.scrobblingInfo.value?.externalUrl ?: return false
|
||||
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
|
||||
startActivity(
|
||||
Intent.createChooser(intent, getString(R.string.open_in_browser))
|
||||
)
|
||||
}
|
||||
R.id.action_unregister -> {
|
||||
viewModel.unregisterScrobbling()
|
||||
dismiss()
|
||||
}
|
||||
R.id.action_edit -> {
|
||||
val manga = viewModel.manga.value ?: return false
|
||||
ScrobblingSelectorBottomSheet.show(parentFragmentManager, manga)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@ -1,12 +1,13 @@
|
||||
package org.koitharu.kotatsu.history.data
|
||||
|
||||
import java.util.*
|
||||
import org.koitharu.kotatsu.core.model.MangaHistory
|
||||
import java.util.*
|
||||
|
||||
fun HistoryEntity.toMangaHistory() = MangaHistory(
|
||||
createdAt = Date(createdAt),
|
||||
updatedAt = Date(updatedAt),
|
||||
chapterId = chapterId,
|
||||
page = page,
|
||||
scroll = scroll.toInt()
|
||||
scroll = scroll.toInt(),
|
||||
percent = percent,
|
||||
)
|
||||
@ -0,0 +1,151 @@
|
||||
package org.koitharu.kotatsu.history.ui.util
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.*
|
||||
import android.graphics.drawable.Drawable
|
||||
import androidx.annotation.StyleRes
|
||||
import androidx.appcompat.content.res.AppCompatResources
|
||||
import androidx.core.graphics.ColorUtils
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.history.domain.PROGRESS_NONE
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class ReadingProgressDrawable(
|
||||
context: Context,
|
||||
@StyleRes styleResId: Int,
|
||||
) : Drawable() {
|
||||
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val checkDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_check)
|
||||
private val lineColor: Int
|
||||
private val outlineColor: Int
|
||||
private val backgroundColor: Int
|
||||
private val textColor: Int
|
||||
private val textPattern = context.getString(R.string.percent_string_pattern)
|
||||
private val textBounds = Rect()
|
||||
private val tempRect = Rect()
|
||||
private val hasBackground: Boolean
|
||||
private val hasOutline: Boolean
|
||||
private val hasText: Boolean
|
||||
private val desiredHeight: Int
|
||||
private val desiredWidth: Int
|
||||
private val autoFitTextSize: Boolean
|
||||
|
||||
var progress: Float = PROGRESS_NONE
|
||||
set(value) {
|
||||
field = value
|
||||
text = textPattern.format((value * 100f).toInt().toString())
|
||||
paint.getTextBounds(text, 0, text.length, textBounds)
|
||||
invalidateSelf()
|
||||
}
|
||||
private var text = ""
|
||||
|
||||
init {
|
||||
val ta = context.obtainStyledAttributes(styleResId, R.styleable.ProgressDrawable)
|
||||
desiredHeight = ta.getDimensionPixelSize(R.styleable.ProgressDrawable_android_height, -1)
|
||||
desiredWidth = ta.getDimensionPixelSize(R.styleable.ProgressDrawable_android_width, -1)
|
||||
autoFitTextSize = ta.getBoolean(R.styleable.ProgressDrawable_autoFitTextSize, false)
|
||||
lineColor = ta.getColor(R.styleable.ProgressDrawable_android_strokeColor, Color.BLACK)
|
||||
outlineColor = ta.getColor(R.styleable.ProgressDrawable_outlineColor, Color.TRANSPARENT)
|
||||
backgroundColor = ColorUtils.setAlphaComponent(
|
||||
ta.getColor(R.styleable.ProgressDrawable_android_fillColor, Color.TRANSPARENT),
|
||||
(255 * ta.getFloat(R.styleable.ProgressDrawable_android_fillAlpha, 0f)).toInt(),
|
||||
)
|
||||
textColor = ta.getColor(R.styleable.ProgressDrawable_android_textColor, lineColor)
|
||||
paint.strokeCap = Paint.Cap.ROUND
|
||||
paint.textAlign = Paint.Align.CENTER
|
||||
paint.textSize = ta.getDimension(R.styleable.ProgressDrawable_android_textSize, paint.textSize)
|
||||
paint.strokeWidth = ta.getDimension(R.styleable.ProgressDrawable_strokeWidth, 1f)
|
||||
ta.recycle()
|
||||
hasBackground = Color.alpha(backgroundColor) != 0
|
||||
hasOutline = Color.alpha(outlineColor) != 0
|
||||
hasText = Color.alpha(textColor) != 0 && paint.textSize > 0
|
||||
checkDrawable?.setTint(textColor)
|
||||
}
|
||||
|
||||
override fun onBoundsChange(bounds: Rect) {
|
||||
super.onBoundsChange(bounds)
|
||||
if (autoFitTextSize) {
|
||||
val innerWidth = bounds.width() - (paint.strokeWidth * 2f)
|
||||
paint.textSize = getTextSizeForWidth(innerWidth, "100%")
|
||||
paint.getTextBounds(text, 0, text.length, textBounds)
|
||||
invalidateSelf()
|
||||
}
|
||||
}
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
if (progress < 0f) {
|
||||
return
|
||||
}
|
||||
val cx = bounds.exactCenterX()
|
||||
val cy = bounds.exactCenterY()
|
||||
val radius = minOf(bounds.width(), bounds.height()) / 2f
|
||||
if (hasBackground) {
|
||||
paint.style = Paint.Style.FILL
|
||||
paint.color = backgroundColor
|
||||
canvas.drawCircle(cx, cy, radius, paint)
|
||||
}
|
||||
val innerRadius = radius - paint.strokeWidth / 2f
|
||||
paint.style = Paint.Style.STROKE
|
||||
if (hasOutline) {
|
||||
paint.color = outlineColor
|
||||
canvas.drawCircle(cx, cy, innerRadius, paint)
|
||||
}
|
||||
paint.color = lineColor
|
||||
canvas.drawArc(
|
||||
cx - innerRadius,
|
||||
cy - innerRadius,
|
||||
cx + innerRadius,
|
||||
cy + innerRadius,
|
||||
-90f,
|
||||
360f * progress,
|
||||
false,
|
||||
paint,
|
||||
)
|
||||
if (hasText) {
|
||||
if (checkDrawable != null && progress >= 1f - Math.ulp(progress)) {
|
||||
tempRect.set(bounds)
|
||||
tempRect *= 0.6
|
||||
checkDrawable.bounds = tempRect
|
||||
checkDrawable.draw(canvas)
|
||||
} else {
|
||||
paint.style = Paint.Style.FILL
|
||||
paint.color = textColor
|
||||
val ty = bounds.height() / 2f + textBounds.height() / 2f - textBounds.bottom
|
||||
canvas.drawText(text, cx, ty, paint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
paint.alpha = alpha
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||
paint.colorFilter = colorFilter
|
||||
}
|
||||
|
||||
@Suppress("DeprecatedCallableAddReplaceWith")
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity() = PixelFormat.TRANSLUCENT
|
||||
|
||||
override fun getIntrinsicHeight() = desiredHeight
|
||||
|
||||
override fun getIntrinsicWidth() = desiredWidth
|
||||
|
||||
private fun getTextSizeForWidth(width: Float, text: String): Float {
|
||||
val testTextSize = 48f
|
||||
paint.textSize = testTextSize
|
||||
paint.getTextBounds(text, 0, text.length, tempRect)
|
||||
return testTextSize * width / tempRect.width()
|
||||
}
|
||||
|
||||
private operator fun Rect.timesAssign(factor: Double) {
|
||||
val newWidth = (width() * factor).roundToInt()
|
||||
val newHeight = (height() * factor).roundToInt()
|
||||
inset(
|
||||
(width() - newWidth) / 2,
|
||||
(height() - newHeight) / 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,114 @@
|
||||
package org.koitharu.kotatsu.history.ui.util
|
||||
|
||||
import android.animation.Animator
|
||||
import android.animation.ValueAnimator
|
||||
import android.content.Context
|
||||
import android.graphics.Outline
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import android.view.ViewOutlineProvider
|
||||
import android.view.animation.AccelerateDecelerateInterpolator
|
||||
import androidx.annotation.AttrRes
|
||||
import androidx.annotation.StyleRes
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.history.domain.PROGRESS_NONE
|
||||
|
||||
class ReadingProgressView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
@AttrRes defStyleAttr: Int = 0,
|
||||
) : View(context, attrs, defStyleAttr), ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener {
|
||||
|
||||
private var percentAnimator: ValueAnimator? = null
|
||||
private val animationDuration = context.resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
|
||||
|
||||
@StyleRes
|
||||
private val drawableStyle: Int
|
||||
|
||||
var percent: Float
|
||||
get() = peekProgressDrawable()?.progress ?: PROGRESS_NONE
|
||||
set(value) {
|
||||
cancelAnimation()
|
||||
getProgressDrawable().progress = value
|
||||
}
|
||||
|
||||
init {
|
||||
val ta = context.obtainStyledAttributes(attrs, R.styleable.ReadingProgressView, defStyleAttr, 0)
|
||||
drawableStyle = ta.getResourceId(R.styleable.ReadingProgressView_progressStyle, R.style.ProgressDrawable)
|
||||
ta.recycle()
|
||||
outlineProvider = OutlineProvider()
|
||||
if (isInEditMode) {
|
||||
percent = 0.27f
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
super.onDetachedFromWindow()
|
||||
percentAnimator?.run {
|
||||
if (isRunning) end()
|
||||
}
|
||||
percentAnimator = null
|
||||
}
|
||||
|
||||
override fun onAnimationUpdate(animation: ValueAnimator) {
|
||||
val p = animation.animatedValue as Float
|
||||
getProgressDrawable().progress = p
|
||||
}
|
||||
|
||||
override fun onAnimationStart(animation: Animator?) = Unit
|
||||
|
||||
override fun onAnimationEnd(animation: Animator?) {
|
||||
if (percentAnimator === animation) {
|
||||
percentAnimator = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAnimationCancel(animation: Animator?) = Unit
|
||||
|
||||
override fun onAnimationRepeat(animation: Animator?) = Unit
|
||||
|
||||
fun setPercent(value: Float, animate: Boolean) {
|
||||
val currentDrawable = peekProgressDrawable()
|
||||
if (!animate || currentDrawable == null || value == PROGRESS_NONE) {
|
||||
percent = value
|
||||
return
|
||||
}
|
||||
percentAnimator?.cancel()
|
||||
percentAnimator = ValueAnimator.ofFloat(
|
||||
currentDrawable.progress.coerceAtLeast(0f),
|
||||
value
|
||||
).apply {
|
||||
duration = animationDuration
|
||||
interpolator = AccelerateDecelerateInterpolator()
|
||||
addUpdateListener(this@ReadingProgressView)
|
||||
addListener(this@ReadingProgressView)
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancelAnimation() {
|
||||
percentAnimator?.cancel()
|
||||
percentAnimator = null
|
||||
}
|
||||
|
||||
private fun peekProgressDrawable(): ReadingProgressDrawable? {
|
||||
return background as? ReadingProgressDrawable
|
||||
}
|
||||
|
||||
private fun getProgressDrawable(): ReadingProgressDrawable {
|
||||
var d = peekProgressDrawable()
|
||||
if (d != null) {
|
||||
return d
|
||||
}
|
||||
d = ReadingProgressDrawable(context, drawableStyle)
|
||||
background = d
|
||||
return d
|
||||
}
|
||||
|
||||
private class OutlineProvider : ViewOutlineProvider() {
|
||||
|
||||
override fun getOutline(view: View, outline: Outline) {
|
||||
outline.setOval(0, 0, view.width, view.height)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,8 @@
|
||||
package org.koitharu.kotatsu.list.domain
|
||||
|
||||
fun interface CountersProvider {
|
||||
interface ListExtraProvider {
|
||||
|
||||
suspend fun getCounter(mangaId: Long): Int
|
||||
|
||||
suspend fun getProgress(mangaId: Long): Float
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
package org.koitharu.kotatsu.scrobbling.data
|
||||
|
||||
import androidx.room.*
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
abstract class ScrobblingDao {
|
||||
|
||||
@Query("SELECT * FROM scrobblings WHERE scrobbler = :scrobbler AND manga_id = :mangaId")
|
||||
abstract suspend fun find(scrobbler: Int, mangaId: Long): ScrobblingEntity?
|
||||
|
||||
@Query("SELECT * FROM scrobblings WHERE scrobbler = :scrobbler AND manga_id = :mangaId")
|
||||
abstract fun observe(scrobbler: Int, mangaId: Long): Flow<ScrobblingEntity?>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
abstract suspend fun insert(entity: ScrobblingEntity)
|
||||
|
||||
@Update
|
||||
abstract suspend fun update(entity: ScrobblingEntity)
|
||||
|
||||
@Query("DELETE FROM scrobblings WHERE scrobbler = :scrobbler AND manga_id = :mangaId")
|
||||
abstract suspend fun delete(scrobbler: Int, mangaId: Long)
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package org.koitharu.kotatsu.scrobbling.data
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
|
||||
@Entity(
|
||||
tableName = "scrobblings",
|
||||
primaryKeys = ["scrobbler", "id", "manga_id"],
|
||||
)
|
||||
class ScrobblingEntity(
|
||||
@ColumnInfo(name = "scrobbler") val scrobbler: Int,
|
||||
@ColumnInfo(name = "id") val id: Int,
|
||||
@ColumnInfo(name = "manga_id") val mangaId: Long,
|
||||
@ColumnInfo(name = "target_id") val targetId: Long,
|
||||
@ColumnInfo(name = "status") val status: String?,
|
||||
@ColumnInfo(name = "chapter") val chapter: Int,
|
||||
@ColumnInfo(name = "comment") val comment: String?,
|
||||
@ColumnInfo(name = "rating") val rating: Float,
|
||||
) {
|
||||
|
||||
fun copy(
|
||||
status: String?,
|
||||
comment: String?,
|
||||
rating: Float,
|
||||
) = ScrobblingEntity(
|
||||
scrobbler = scrobbler,
|
||||
id = id,
|
||||
mangaId = mangaId,
|
||||
targetId = targetId,
|
||||
status = status,
|
||||
chapter = chapter,
|
||||
comment = comment,
|
||||
rating = rating,
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
package org.koitharu.kotatsu.scrobbling.domain
|
||||
|
||||
import androidx.collection.LongSparseArray
|
||||
import androidx.collection.getOrElse
|
||||
import androidx.core.text.parseAsHtml
|
||||
import java.util.*
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import org.koitharu.kotatsu.scrobbling.data.ScrobblingEntity
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.*
|
||||
import org.koitharu.kotatsu.utils.ext.findKey
|
||||
import org.koitharu.kotatsu.utils.ext.printStackTraceDebug
|
||||
|
||||
abstract class Scrobbler(
|
||||
protected val db: MangaDatabase,
|
||||
val scrobblerService: ScrobblerService,
|
||||
) {
|
||||
|
||||
private val infoCache = LongSparseArray<ScrobblerMangaInfo>()
|
||||
protected val statuses = EnumMap<ScrobblingStatus, String>(ScrobblingStatus::class.java)
|
||||
|
||||
abstract val isAvailable: Boolean
|
||||
|
||||
abstract suspend fun findManga(query: String, offset: Int): List<ScrobblerManga>
|
||||
|
||||
abstract suspend fun linkManga(mangaId: Long, targetId: Long)
|
||||
|
||||
abstract suspend fun scrobble(mangaId: Long, chapter: MangaChapter)
|
||||
|
||||
suspend fun getScrobblingInfoOrNull(mangaId: Long): ScrobblingInfo? {
|
||||
val entity = db.scrobblingDao.find(scrobblerService.id, mangaId) ?: return null
|
||||
return entity.toScrobblingInfo(mangaId)
|
||||
}
|
||||
|
||||
abstract suspend fun updateScrobblingInfo(mangaId: Long, rating: Float, status: ScrobblingStatus?, comment: String?)
|
||||
|
||||
fun observeScrobblingInfo(mangaId: Long): Flow<ScrobblingInfo?> {
|
||||
return db.scrobblingDao.observe(scrobblerService.id, mangaId)
|
||||
.map { it?.toScrobblingInfo(mangaId) }
|
||||
}
|
||||
|
||||
abstract suspend fun unregisterScrobbling(mangaId: Long)
|
||||
|
||||
protected abstract suspend fun getMangaInfo(id: Long): ScrobblerMangaInfo
|
||||
|
||||
private suspend fun ScrobblingEntity.toScrobblingInfo(mangaId: Long): ScrobblingInfo? {
|
||||
val mangaInfo = infoCache.getOrElse(targetId) {
|
||||
runCatching {
|
||||
getMangaInfo(targetId)
|
||||
}.onFailure {
|
||||
it.printStackTraceDebug()
|
||||
}.onSuccess {
|
||||
infoCache.put(targetId, it)
|
||||
}.getOrNull() ?: return null
|
||||
}
|
||||
return ScrobblingInfo(
|
||||
scrobbler = scrobblerService,
|
||||
mangaId = mangaId,
|
||||
targetId = targetId,
|
||||
status = statuses.findKey(status),
|
||||
chapter = chapter,
|
||||
comment = comment,
|
||||
rating = rating,
|
||||
title = mangaInfo.name,
|
||||
coverUrl = mangaInfo.cover,
|
||||
description = mangaInfo.descriptionHtml.parseAsHtml(),
|
||||
externalUrl = mangaInfo.url,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun Scrobbler.tryScrobble(mangaId: Long, chapter: MangaChapter): Boolean {
|
||||
return runCatching {
|
||||
scrobble(mangaId, chapter)
|
||||
}.onFailure {
|
||||
it.printStackTraceDebug()
|
||||
}.isSuccess
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
package org.koitharu.kotatsu.scrobbling.domain.model
|
||||
|
||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||
|
||||
class ScrobblerManga(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val altName: String?,
|
||||
val cover: String,
|
||||
val url: String,
|
||||
) : ListModel {
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (javaClass != other?.javaClass) return false
|
||||
|
||||
other as ScrobblerManga
|
||||
|
||||
if (id != other.id) return false
|
||||
if (name != other.name) return false
|
||||
if (altName != other.altName) return false
|
||||
if (cover != other.cover) return false
|
||||
if (url != other.url) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = id.hashCode()
|
||||
result = 31 * result + name.hashCode()
|
||||
result = 31 * result + altName.hashCode()
|
||||
result = 31 * result + cover.hashCode()
|
||||
result = 31 * result + url.hashCode()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "ScrobblerManga #$id \"$name\" $url"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
package org.koitharu.kotatsu.scrobbling.domain.model
|
||||
|
||||
class ScrobblerMangaInfo(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val cover: String,
|
||||
val url: String,
|
||||
val descriptionHtml: String,
|
||||
)
|
||||
@ -0,0 +1,14 @@
|
||||
package org.koitharu.kotatsu.scrobbling.domain.model
|
||||
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.annotation.StringRes
|
||||
import org.koitharu.kotatsu.R
|
||||
|
||||
enum class ScrobblerService(
|
||||
val id: Int,
|
||||
@StringRes val titleResId: Int,
|
||||
@DrawableRes val iconResId: Int,
|
||||
) {
|
||||
|
||||
SHIKIMORI(1, R.string.shikimori, R.drawable.ic_shikimori)
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package org.koitharu.kotatsu.scrobbling.domain.model
|
||||
|
||||
class ScrobblingInfo(
|
||||
val scrobbler: ScrobblerService,
|
||||
val mangaId: Long,
|
||||
val targetId: Long,
|
||||
val status: ScrobblingStatus?,
|
||||
val chapter: Int,
|
||||
val comment: String?,
|
||||
val rating: Float,
|
||||
val title: String,
|
||||
val coverUrl: String,
|
||||
val description: CharSequence?,
|
||||
val externalUrl: String,
|
||||
) {
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (javaClass != other?.javaClass) return false
|
||||
|
||||
other as ScrobblingInfo
|
||||
|
||||
if (scrobbler != other.scrobbler) return false
|
||||
if (mangaId != other.mangaId) return false
|
||||
if (targetId != other.targetId) return false
|
||||
if (status != other.status) return false
|
||||
if (chapter != other.chapter) return false
|
||||
if (comment != other.comment) return false
|
||||
if (rating != other.rating) return false
|
||||
if (title != other.title) return false
|
||||
if (coverUrl != other.coverUrl) return false
|
||||
if (description != other.description) return false
|
||||
if (externalUrl != other.externalUrl) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = scrobbler.hashCode()
|
||||
result = 31 * result + mangaId.hashCode()
|
||||
result = 31 * result + targetId.hashCode()
|
||||
result = 31 * result + (status?.hashCode() ?: 0)
|
||||
result = 31 * result + chapter
|
||||
result = 31 * result + (comment?.hashCode() ?: 0)
|
||||
result = 31 * result + rating.hashCode()
|
||||
result = 31 * result + title.hashCode()
|
||||
result = 31 * result + coverUrl.hashCode()
|
||||
result = 31 * result + (description?.hashCode() ?: 0)
|
||||
result = 31 * result + externalUrl.hashCode()
|
||||
return result
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package org.koitharu.kotatsu.scrobbling.domain.model
|
||||
|
||||
enum class ScrobblingStatus {
|
||||
|
||||
PLANNED,
|
||||
READING,
|
||||
RE_READING,
|
||||
COMPLETED,
|
||||
ON_HOLD,
|
||||
DROPPED,
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import org.koin.android.ext.koin.androidContext
|
||||
import org.koin.androidx.viewmodel.dsl.viewModel
|
||||
import org.koin.dsl.bind
|
||||
import org.koin.dsl.module
|
||||
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 org.koitharu.kotatsu.scrobbling.shikimori.ui.ShikimoriSettingsViewModel
|
||||
import org.koitharu.kotatsu.scrobbling.ui.selector.ScrobblingSelectorViewModel
|
||||
|
||||
val shikimoriModule
|
||||
get() = module {
|
||||
single { ShikimoriStorage(androidContext()) }
|
||||
factory {
|
||||
val okHttp = OkHttpClient.Builder().apply {
|
||||
authenticator(ShikimoriAuthenticator(get(), ::get))
|
||||
addInterceptor(ShikimoriInterceptor(get()))
|
||||
}.build()
|
||||
ShikimoriRepository(okHttp, get(), get())
|
||||
}
|
||||
factory { ShikimoriScrobbler(get(), get()) } bind Scrobbler::class
|
||||
viewModel { params ->
|
||||
ShikimoriSettingsViewModel(get(), params.getOrNull())
|
||||
}
|
||||
viewModel { params -> ScrobblingSelectorViewModel(params[0], get()) }
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.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
|
||||
|
||||
class ShikimoriAuthenticator(
|
||||
private val storage: ShikimoriStorage,
|
||||
private val repositoryProvider: () -> ShikimoriRepository,
|
||||
) : 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()
|
||||
runBlocking { repository.authorize(null) }
|
||||
return storage.accessToken
|
||||
}.onFailure {
|
||||
if (BuildConfig.DEBUG) {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.data
|
||||
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Response
|
||||
import okio.IOException
|
||||
import org.koitharu.kotatsu.core.network.CommonHeaders
|
||||
|
||||
private const val USER_AGENT_SHIKIMORI = "Kotatsu"
|
||||
|
||||
class ShikimoriInterceptor(private val storage: ShikimoriStorage) : Interceptor {
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request().newBuilder()
|
||||
request.header(CommonHeaders.USER_AGENT, USER_AGENT_SHIKIMORI)
|
||||
storage.accessToken?.let {
|
||||
request.header(CommonHeaders.AUTHORIZATION, "Bearer $it")
|
||||
}
|
||||
val response = chain.proceed(request.build())
|
||||
if (!response.isSuccessful && !response.isRedirect) {
|
||||
throw IOException("${response.code} ${response.message}")
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,199 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.data
|
||||
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.json.JSONObject
|
||||
import org.koitharu.kotatsu.BuildConfig
|
||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||
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.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.shikimori.data.model.ShikimoriUser
|
||||
import org.koitharu.kotatsu.utils.ext.toRequestBody
|
||||
|
||||
private const val REDIRECT_URI = "kotatsu://shikimori-auth"
|
||||
private const val BASE_URL = "https://shikimori.one/"
|
||||
private const val MANGA_PAGE_SIZE = 10
|
||||
|
||||
class ShikimoriRepository(
|
||||
private val okHttp: OkHttpClient,
|
||||
private val storage: ShikimoriStorage,
|
||||
private val db: MangaDatabase,
|
||||
) {
|
||||
|
||||
val oauthUrl: String
|
||||
get() = "${BASE_URL}oauth/authorize?client_id=${BuildConfig.SHIKIMORI_CLIENT_ID}&" +
|
||||
"redirect_uri=$REDIRECT_URI&response_type=code&scope="
|
||||
|
||||
val isAuthorized: Boolean
|
||||
get() = storage.accessToken != null
|
||||
|
||||
suspend fun authorize(code: String?) {
|
||||
val body = FormBody.Builder()
|
||||
body.add("grant_type", "authorization_code")
|
||||
body.add("client_id", BuildConfig.SHIKIMORI_CLIENT_ID)
|
||||
body.add("client_secret", BuildConfig.SHIKIMORI_CLIENT_SECRET)
|
||||
if (code != null) {
|
||||
body.add("redirect_uri", REDIRECT_URI)
|
||||
body.add("code", code)
|
||||
} else {
|
||||
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(): ShikimoriUser {
|
||||
val request = Request.Builder()
|
||||
.get()
|
||||
.url("${BASE_URL}api/users/whoami")
|
||||
val response = okHttp.newCall(request.build()).await().parseJson()
|
||||
return ShikimoriUser(response).also { storage.user = it }
|
||||
}
|
||||
|
||||
fun getCachedUser(): ShikimoriUser? {
|
||||
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"),
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.core.content.edit
|
||||
import org.json.JSONObject
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.model.ShikimoriUser
|
||||
|
||||
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"
|
||||
|
||||
class ShikimoriStorage(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,42 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.data.model
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
class ShikimoriUser(
|
||||
val id: Long,
|
||||
val nickname: String,
|
||||
val avatar: String,
|
||||
) {
|
||||
|
||||
constructor(json: JSONObject) : this(
|
||||
id = json.getLong("id"),
|
||||
nickname = json.getString("nickname"),
|
||||
avatar = json.getString("avatar"),
|
||||
)
|
||||
|
||||
fun toJson() = JSONObject().apply {
|
||||
put("id", id)
|
||||
put("nickname", nickname)
|
||||
put("avatar", avatar)
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (javaClass != other?.javaClass) return false
|
||||
|
||||
other as ShikimoriUser
|
||||
|
||||
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,68 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.domain
|
||||
|
||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import org.koitharu.kotatsu.scrobbling.domain.Scrobbler
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerMangaInfo
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerService
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblingStatus
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriRepository
|
||||
|
||||
private const val RATING_MAX = 10f
|
||||
|
||||
class ShikimoriScrobbler(
|
||||
private val repository: ShikimoriRepository,
|
||||
db: MangaDatabase,
|
||||
) : Scrobbler(db, ScrobblerService.SHIKIMORI) {
|
||||
|
||||
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,79 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.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 org.koin.android.ext.android.inject
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
import org.koin.core.parameter.parametersOf
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.base.ui.BasePreferenceFragment
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.model.ShikimoriUser
|
||||
import org.koitharu.kotatsu.utils.PreferenceIconTarget
|
||||
import org.koitharu.kotatsu.utils.ext.enqueueWith
|
||||
import org.koitharu.kotatsu.utils.ext.withArgs
|
||||
|
||||
class ShikimoriSettingsFragment : BasePreferenceFragment(R.string.shikimori) {
|
||||
|
||||
private val viewModel by viewModel<ShikimoriSettingsViewModel> {
|
||||
parametersOf(arguments?.getString(ARG_AUTH_CODE))
|
||||
}
|
||||
private val coil by inject<ImageLoader>(mode = LazyThreadSafetyMode.NONE)
|
||||
|
||||
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
|
||||
addPreferencesFromResource(R.xml.pref_shikimori)
|
||||
}
|
||||
|
||||
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: ShikimoriUser?) {
|
||||
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 = "shiki_user"
|
||||
private const val KEY_LOGOUT = "shiki_logout"
|
||||
|
||||
private const val ARG_AUTH_CODE = "auth_code"
|
||||
|
||||
fun newInstance(authCode: String?) = ShikimoriSettingsFragment().withArgs(1) {
|
||||
putString(ARG_AUTH_CODE, authCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,48 @@
|
||||
package org.koitharu.kotatsu.scrobbling.shikimori.ui
|
||||
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import org.koitharu.kotatsu.base.ui.BaseViewModel
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.ShikimoriRepository
|
||||
import org.koitharu.kotatsu.scrobbling.shikimori.data.model.ShikimoriUser
|
||||
|
||||
class ShikimoriSettingsViewModel(
|
||||
private val repository: ShikimoriRepository,
|
||||
authCode: String?,
|
||||
) : BaseViewModel() {
|
||||
|
||||
val authorizationUrl: String
|
||||
get() = repository.oauthUrl
|
||||
|
||||
val user = MutableLiveData<ShikimoriUser?>()
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,155 @@
|
||||
package org.koitharu.kotatsu.scrobbling.ui.selector
|
||||
|
||||
import android.app.Dialog
|
||||
import android.content.DialogInterface
|
||||
import android.os.Bundle
|
||||
import android.view.*
|
||||
import android.widget.Toast
|
||||
import androidx.appcompat.widget.SearchView
|
||||
import androidx.fragment.app.FragmentManager
|
||||
import org.koin.android.ext.android.get
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
import org.koin.core.parameter.parametersOf
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.base.domain.MangaIntent
|
||||
import org.koitharu.kotatsu.base.ui.BaseBottomSheet
|
||||
import org.koitharu.kotatsu.base.ui.list.OnListItemClickListener
|
||||
import org.koitharu.kotatsu.base.ui.list.PaginationScrollListener
|
||||
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
||||
import org.koitharu.kotatsu.databinding.SheetScrobblingSelectorBinding
|
||||
import org.koitharu.kotatsu.parsers.model.Manga
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
import org.koitharu.kotatsu.scrobbling.ui.selector.adapter.ShikiMangaSelectionDecoration
|
||||
import org.koitharu.kotatsu.scrobbling.ui.selector.adapter.ShikimoriSelectorAdapter
|
||||
import org.koitharu.kotatsu.utils.BottomSheetToolbarController
|
||||
import org.koitharu.kotatsu.utils.ext.getDisplayMessage
|
||||
import org.koitharu.kotatsu.utils.ext.withArgs
|
||||
|
||||
class ScrobblingSelectorBottomSheet :
|
||||
BaseBottomSheet<SheetScrobblingSelectorBinding>(),
|
||||
OnListItemClickListener<ScrobblerManga>,
|
||||
PaginationScrollListener.Callback,
|
||||
View.OnClickListener,
|
||||
MenuItem.OnActionExpandListener,
|
||||
SearchView.OnQueryTextListener,
|
||||
DialogInterface.OnKeyListener {
|
||||
|
||||
private val viewModel by viewModel<ScrobblingSelectorViewModel> {
|
||||
parametersOf(requireNotNull(requireArguments().getParcelable<ParcelableManga>(MangaIntent.KEY_MANGA)).manga)
|
||||
}
|
||||
|
||||
override fun onInflateView(inflater: LayoutInflater, container: ViewGroup?): SheetScrobblingSelectorBinding {
|
||||
return SheetScrobblingSelectorBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
|
||||
return super.onCreateDialog(savedInstanceState).also {
|
||||
it.setOnKeyListener(this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
binding.toolbar.setNavigationOnClickListener { dismiss() }
|
||||
addBottomSheetCallback(BottomSheetToolbarController(binding.toolbar))
|
||||
val listAdapter = ShikimoriSelectorAdapter(viewLifecycleOwner, get(), this)
|
||||
val decoration = ShikiMangaSelectionDecoration(view.context)
|
||||
with(binding.recyclerView) {
|
||||
adapter = listAdapter
|
||||
addItemDecoration(decoration)
|
||||
addOnScrollListener(PaginationScrollListener(4, this@ScrobblingSelectorBottomSheet))
|
||||
}
|
||||
binding.buttonDone.setOnClickListener(this)
|
||||
initOptionsMenu()
|
||||
|
||||
viewModel.content.observe(viewLifecycleOwner) { listAdapter.items = it }
|
||||
viewModel.selectedItemId.observe(viewLifecycleOwner) {
|
||||
decoration.checkedItemId = it
|
||||
binding.recyclerView.invalidateItemDecorations()
|
||||
}
|
||||
viewModel.onError.observe(viewLifecycleOwner, ::onError)
|
||||
viewModel.onClose.observe(viewLifecycleOwner) {
|
||||
dismiss()
|
||||
}
|
||||
viewModel.searchQuery.observe(viewLifecycleOwner) {
|
||||
binding.toolbar.subtitle = it
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClick(v: View) {
|
||||
when (v.id) {
|
||||
R.id.button_done -> viewModel.onDoneClick()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onItemClick(item: ScrobblerManga, view: View) {
|
||||
viewModel.selectedItemId.value = item.id
|
||||
}
|
||||
|
||||
override fun onScrolledToEnd() {
|
||||
viewModel.loadList(append = true)
|
||||
}
|
||||
|
||||
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
|
||||
setExpanded(isExpanded = true, isLocked = true)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
|
||||
val searchView = (item.actionView as? SearchView) ?: return false
|
||||
searchView.setQuery("", false)
|
||||
searchView.post { setExpanded(isExpanded = false, isLocked = false) }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onQueryTextSubmit(query: String?): Boolean {
|
||||
if (query == null || query.length < 3) {
|
||||
return false
|
||||
}
|
||||
viewModel.search(query)
|
||||
binding.toolbar.menu.findItem(R.id.action_search)?.collapseActionView()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onQueryTextChange(newText: String?): Boolean = false
|
||||
|
||||
override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
|
||||
if (keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
val menuItem = binding.toolbar.menu.findItem(R.id.action_search) ?: return false
|
||||
if (menuItem.isActionViewExpanded) {
|
||||
if (event?.action == KeyEvent.ACTION_UP) {
|
||||
menuItem.collapseActionView()
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun onError(e: Throwable) {
|
||||
Toast.makeText(requireContext(), e.getDisplayMessage(resources), Toast.LENGTH_LONG).show()
|
||||
if (viewModel.isEmpty) {
|
||||
dismissAllowingStateLoss()
|
||||
}
|
||||
}
|
||||
|
||||
private fun initOptionsMenu() {
|
||||
binding.toolbar.inflateMenu(R.menu.opt_shiki_selector)
|
||||
val searchMenuItem = binding.toolbar.menu.findItem(R.id.action_search)
|
||||
searchMenuItem.setOnActionExpandListener(this)
|
||||
val searchView = searchMenuItem.actionView as SearchView
|
||||
searchView.setOnQueryTextListener(this)
|
||||
searchView.setIconifiedByDefault(false)
|
||||
searchView.queryHint = searchMenuItem.title
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private const val TAG = "ScrobblingSelectorBottomSheet"
|
||||
|
||||
fun show(fm: FragmentManager, manga: Manga) =
|
||||
ScrobblingSelectorBottomSheet().withArgs(1) {
|
||||
putParcelable(MangaIntent.KEY_MANGA, ParcelableManga(manga, withChapters = false))
|
||||
}.show(fm, TAG)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,101 @@
|
||||
package org.koitharu.kotatsu.scrobbling.ui.selector
|
||||
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.recyclerview.widget.RecyclerView.NO_ID
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import org.koitharu.kotatsu.base.ui.BaseViewModel
|
||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||
import org.koitharu.kotatsu.list.ui.model.LoadingFooter
|
||||
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
||||
import org.koitharu.kotatsu.parsers.model.Manga
|
||||
import org.koitharu.kotatsu.scrobbling.domain.Scrobbler
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
import org.koitharu.kotatsu.utils.SingleLiveEvent
|
||||
import org.koitharu.kotatsu.utils.ext.asLiveDataDistinct
|
||||
|
||||
class ScrobblingSelectorViewModel(
|
||||
val manga: Manga,
|
||||
private val scrobbler: Scrobbler,
|
||||
) : BaseViewModel() {
|
||||
|
||||
private val shikiMangaList = MutableStateFlow<List<ScrobblerManga>?>(null)
|
||||
private val hasNextPage = MutableStateFlow(false)
|
||||
private var loadingJob: Job? = null
|
||||
private var doneJob: Job? = null
|
||||
|
||||
val content: LiveData<List<ListModel>> = combine(
|
||||
shikiMangaList.filterNotNull(),
|
||||
hasNextPage
|
||||
) { list, isHasNextPage ->
|
||||
when {
|
||||
list.isEmpty() -> listOf()
|
||||
isHasNextPage -> list + LoadingFooter
|
||||
else -> list
|
||||
}
|
||||
}.asLiveDataDistinct(viewModelScope.coroutineContext + Dispatchers.Default, listOf(LoadingState))
|
||||
|
||||
val selectedItemId = MutableLiveData(NO_ID)
|
||||
val searchQuery = MutableLiveData(manga.title)
|
||||
val onClose = SingleLiveEvent<Unit>()
|
||||
|
||||
val isEmpty: Boolean
|
||||
get() = shikiMangaList.value.isNullOrEmpty()
|
||||
|
||||
init {
|
||||
launchJob(Dispatchers.Default) {
|
||||
try {
|
||||
val info = scrobbler.getScrobblingInfoOrNull(manga.id)
|
||||
if (info != null) {
|
||||
selectedItemId.postValue(info.targetId)
|
||||
}
|
||||
} finally {
|
||||
loadList(append = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun search(query: String) {
|
||||
loadingJob?.cancel()
|
||||
searchQuery.value = query
|
||||
loadList(append = false)
|
||||
}
|
||||
|
||||
fun loadList(append: Boolean) {
|
||||
if (loadingJob?.isActive == true) {
|
||||
return
|
||||
}
|
||||
if (append && !hasNextPage.value) {
|
||||
return
|
||||
}
|
||||
loadingJob = launchLoadingJob(Dispatchers.Default) {
|
||||
val offset = if (append) shikiMangaList.value?.size ?: 0 else 0
|
||||
val list = scrobbler.findManga(checkNotNull(searchQuery.value), offset)
|
||||
if (!append) {
|
||||
shikiMangaList.value = list
|
||||
} else if (list.isNotEmpty()) {
|
||||
shikiMangaList.value = shikiMangaList.value?.plus(list) ?: list
|
||||
}
|
||||
hasNextPage.value = list.isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
fun onDoneClick() {
|
||||
if (doneJob?.isActive == true) {
|
||||
return
|
||||
}
|
||||
val targetId = selectedItemId.value ?: NO_ID
|
||||
if (targetId == NO_ID) {
|
||||
onClose.call(Unit)
|
||||
}
|
||||
doneJob = launchJob(Dispatchers.Default) {
|
||||
scrobbler.linkManga(manga.id, targetId)
|
||||
onClose.postCall(Unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package org.koitharu.kotatsu.scrobbling.ui.selector.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.view.View
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.recyclerview.widget.RecyclerView.NO_ID
|
||||
import org.koitharu.kotatsu.list.ui.MangaSelectionDecoration
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
import org.koitharu.kotatsu.utils.ext.getItem
|
||||
|
||||
class ShikiMangaSelectionDecoration(context: Context) : MangaSelectionDecoration(context) {
|
||||
|
||||
var checkedItemId: Long
|
||||
get() = selection.singleOrNull() ?: NO_ID
|
||||
set(value) {
|
||||
clearSelection()
|
||||
if (value != NO_ID) {
|
||||
selection.add(value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemId(parent: RecyclerView, child: View): Long {
|
||||
val holder = parent.getChildViewHolder(child) ?: return NO_ID
|
||||
val item = holder.getItem(ScrobblerManga::class.java) ?: return NO_ID
|
||||
return item.id
|
||||
}
|
||||
|
||||
override fun onDrawForeground(
|
||||
canvas: Canvas,
|
||||
parent: RecyclerView,
|
||||
child: View,
|
||||
bounds: RectF,
|
||||
state: RecyclerView.State,
|
||||
) {
|
||||
paint.color = strokeColor
|
||||
paint.style = Paint.Style.STROKE
|
||||
canvas.drawRoundRect(bounds, defaultRadius, defaultRadius, paint)
|
||||
checkIcon?.run {
|
||||
val offset = (bounds.height() - intrinsicHeight) / 2
|
||||
setBounds(
|
||||
(bounds.right - offset - intrinsicWidth).toInt(),
|
||||
(bounds.top + offset).toInt(),
|
||||
(bounds.right - offset).toInt(),
|
||||
(bounds.top + offset + intrinsicHeight).toInt(),
|
||||
)
|
||||
draw(canvas)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package org.koitharu.kotatsu.scrobbling.ui.selector.adapter
|
||||
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import coil.ImageLoader
|
||||
import coil.request.Disposable
|
||||
import coil.size.Scale
|
||||
import coil.util.CoilUtils
|
||||
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
||||
import org.koitharu.kotatsu.R
|
||||
import org.koitharu.kotatsu.base.ui.list.OnListItemClickListener
|
||||
import org.koitharu.kotatsu.databinding.ItemMangaListBinding
|
||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
import org.koitharu.kotatsu.utils.ext.enqueueWith
|
||||
import org.koitharu.kotatsu.utils.ext.newImageRequest
|
||||
import org.koitharu.kotatsu.utils.ext.textAndVisible
|
||||
|
||||
fun shikimoriMangaAD(
|
||||
lifecycleOwner: LifecycleOwner,
|
||||
coil: ImageLoader,
|
||||
clickListener: OnListItemClickListener<ScrobblerManga>,
|
||||
) = adapterDelegateViewBinding<ScrobblerManga, ListModel, ItemMangaListBinding>(
|
||||
{ inflater, parent -> ItemMangaListBinding.inflate(inflater, parent, false) }
|
||||
) {
|
||||
|
||||
var imageRequest: Disposable? = null
|
||||
|
||||
itemView.setOnClickListener {
|
||||
clickListener.onItemClick(item, it)
|
||||
}
|
||||
|
||||
bind {
|
||||
imageRequest?.dispose()
|
||||
binding.textViewTitle.text = item.name
|
||||
binding.textViewSubtitle.textAndVisible = item.altName
|
||||
imageRequest = binding.imageViewCover.newImageRequest(item.cover)
|
||||
.placeholder(R.drawable.ic_placeholder)
|
||||
.fallback(R.drawable.ic_placeholder)
|
||||
.error(R.drawable.ic_placeholder)
|
||||
.scale(Scale.FILL)
|
||||
.allowRgb565(true)
|
||||
.lifecycle(lifecycleOwner)
|
||||
.enqueueWith(coil)
|
||||
}
|
||||
|
||||
onViewRecycled {
|
||||
imageRequest?.dispose()
|
||||
imageRequest = null
|
||||
CoilUtils.dispose(binding.imageViewCover)
|
||||
binding.imageViewCover.setImageDrawable(null)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
package org.koitharu.kotatsu.scrobbling.ui.selector.adapter
|
||||
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.recyclerview.widget.DiffUtil
|
||||
import coil.ImageLoader
|
||||
import com.hannesdorfmann.adapterdelegates4.AsyncListDifferDelegationAdapter
|
||||
import kotlin.jvm.internal.Intrinsics
|
||||
import org.koitharu.kotatsu.base.ui.list.OnListItemClickListener
|
||||
import org.koitharu.kotatsu.list.ui.adapter.loadingFooterAD
|
||||
import org.koitharu.kotatsu.list.ui.adapter.loadingStateAD
|
||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||
import org.koitharu.kotatsu.scrobbling.domain.model.ScrobblerManga
|
||||
|
||||
class ShikimoriSelectorAdapter(
|
||||
lifecycleOwner: LifecycleOwner,
|
||||
coil: ImageLoader,
|
||||
clickListener: OnListItemClickListener<ScrobblerManga>,
|
||||
) : AsyncListDifferDelegationAdapter<ListModel>(DiffCallback()) {
|
||||
|
||||
init {
|
||||
delegatesManager.addDelegate(loadingStateAD())
|
||||
.addDelegate(shikimoriMangaAD(lifecycleOwner, coil, clickListener))
|
||||
.addDelegate(loadingFooterAD())
|
||||
}
|
||||
|
||||
private class DiffCallback : DiffUtil.ItemCallback<ListModel>() {
|
||||
|
||||
override fun areItemsTheSame(oldItem: ListModel, newItem: ListModel): Boolean {
|
||||
return when {
|
||||
oldItem === newItem -> true
|
||||
oldItem is ScrobblerManga && newItem is ScrobblerManga -> oldItem.id == newItem.id
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
override fun areContentsTheSame(oldItem: ListModel, newItem: ListModel): Boolean {
|
||||
return Intrinsics.areEqual(oldItem, newItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue