Compare commits
68 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
adffa800e8
|
|||
|
3acca44b5e
|
|||
|
c7da4feb8f
|
|||
|
baee9bee0e
|
|||
|
ec41d36508
|
|||
| 8b63d227a7 | |||
|
|
c9b48c8207 | ||
|
|
6d7ce5205e | ||
|
|
5a02d534c9 | ||
|
|
6128e5b699 | ||
|
|
717a0ad4fb | ||
|
|
dee94ac0c4 | ||
|
9eec9a9957
|
|||
|
a4966b4661
|
|||
|
58e570601d
|
|||
|
7247cba855
|
|||
|
d6012f9ddd
|
|||
|
2eedd0b4a8
|
|||
|
5e6da9bb1c
|
|||
|
2f2a5b868d
|
|||
|
|
3f2e32dcc2 | ||
|
|
004109a6bc | ||
|
|
6159ee36c4 | ||
|
3b7d83dd6f
|
|||
|
877a018ced
|
|||
|
2e80b330e9
|
|||
|
42ca38e693
|
|||
|
|
d2fc3354af | ||
| 2a870e6167 | |||
|
|
393a9c2791 | ||
|
|
4c69839076 | ||
|
e37455e790
|
|||
|
|
36259ba901 | ||
|
|
5b041b9a49 | ||
|
1734e888d6
|
|||
|
9108646cea
|
|||
|
|
c6d1cf2f72 | ||
|
|
a317236cb0 | ||
|
|
3703c07a98 | ||
|
b7b32dd447
|
|||
|
c103386dc5
|
|||
|
a9d6ee4a95
|
|||
|
71f2c91e5a
|
|||
|
b878f358ff
|
|||
|
|
4c9989da78 | ||
|
|
8e8424022a | ||
|
86504b8bde
|
|||
|
f082fa084f
|
|||
| 040fe258e9 | |||
|
1076009572
|
|||
|
40dde71a1d
|
|||
|
|
9503aabf78 | ||
|
|
4ee16cfa2f | ||
|
f1c9eacaf0
|
|||
|
920e16be10
|
|||
|
4e0e5be726
|
|||
|
|
f18eca52af
|
||
|
451a155e08
|
|||
|
|
0612a7ad2c | ||
| 9c34f25eda | |||
| 42360c678f | |||
|
|
04a3d02aa9 | ||
|
808fd13ad0
|
|||
|
88c8dc4761
|
|||
|
a7eba67a97
|
|||
|
c27586231a
|
|||
|
db3db4637c
|
|||
|
bb2294f248
|
1
.gitignore
vendored
1
.gitignore
vendored
@@ -10,6 +10,7 @@
|
|||||||
/.idea/compiler.xml
|
/.idea/compiler.xml
|
||||||
/.idea/workspace.xml
|
/.idea/workspace.xml
|
||||||
/.idea/navEditor.xml
|
/.idea/navEditor.xml
|
||||||
|
/.idea/ktlint-plugin.xml
|
||||||
/.idea/assetWizardSettings.xml
|
/.idea/assetWizardSettings.xml
|
||||||
/.idea/kotlinScripting.xml
|
/.idea/kotlinScripting.xml
|
||||||
/.idea/kotlinc.xml
|
/.idea/kotlinc.xml
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ android {
|
|||||||
applicationId 'org.koitharu.kotatsu'
|
applicationId 'org.koitharu.kotatsu'
|
||||||
minSdk = 21
|
minSdk = 21
|
||||||
targetSdk = 34
|
targetSdk = 34
|
||||||
versionCode = 604
|
versionCode = 612
|
||||||
versionName = '6.5-b2'
|
versionName = '6.6.1'
|
||||||
generatedDensities = []
|
generatedDensities = []
|
||||||
testInstrumentationRunner 'org.koitharu.kotatsu.HiltTestRunner'
|
testInstrumentationRunner 'org.koitharu.kotatsu.HiltTestRunner'
|
||||||
ksp {
|
ksp {
|
||||||
@@ -82,17 +82,17 @@ afterEvaluate {
|
|||||||
}
|
}
|
||||||
dependencies {
|
dependencies {
|
||||||
//noinspection GradleDependency
|
//noinspection GradleDependency
|
||||||
implementation('com.github.KotatsuApp:kotatsu-parsers:97338f31c5') {
|
implementation('com.github.KotatsuApp:kotatsu-parsers:0e8579017b') {
|
||||||
exclude group: 'org.json', module: 'json'
|
exclude group: 'org.json', module: 'json'
|
||||||
}
|
}
|
||||||
|
|
||||||
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
|
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
|
||||||
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.9.21'
|
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.9.22'
|
||||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||||
|
|
||||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||||
implementation 'androidx.core:core-ktx:1.12.0'
|
implementation 'androidx.core:core-ktx:1.12.0'
|
||||||
implementation 'androidx.activity:activity-ktx:1.8.1'
|
implementation 'androidx.activity:activity-ktx:1.8.2'
|
||||||
implementation 'androidx.fragment:fragment-ktx:1.6.2'
|
implementation 'androidx.fragment:fragment-ktx:1.6.2'
|
||||||
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2'
|
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2'
|
||||||
implementation 'androidx.lifecycle:lifecycle-service:2.6.2'
|
implementation 'androidx.lifecycle:lifecycle-service:2.6.2'
|
||||||
@@ -103,7 +103,7 @@ dependencies {
|
|||||||
implementation 'androidx.viewpager2:viewpager2:1.1.0-beta02'
|
implementation 'androidx.viewpager2:viewpager2:1.1.0-beta02'
|
||||||
implementation 'androidx.preference:preference-ktx:1.2.1'
|
implementation 'androidx.preference:preference-ktx:1.2.1'
|
||||||
implementation 'androidx.biometric:biometric-ktx:1.2.0-alpha05'
|
implementation 'androidx.biometric:biometric-ktx:1.2.0-alpha05'
|
||||||
implementation 'com.google.android.material:material:1.10.0'
|
implementation 'com.google.android.material:material:1.11.0'
|
||||||
implementation 'androidx.lifecycle:lifecycle-common-java8:2.6.2'
|
implementation 'androidx.lifecycle:lifecycle-common-java8:2.6.2'
|
||||||
|
|
||||||
implementation 'androidx.work:work-runtime:2.9.0'
|
implementation 'androidx.work:work-runtime:2.9.0'
|
||||||
@@ -120,13 +120,13 @@ dependencies {
|
|||||||
|
|
||||||
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
||||||
implementation 'com.squareup.okhttp3:okhttp-dnsoverhttps:4.12.0'
|
implementation 'com.squareup.okhttp3:okhttp-dnsoverhttps:4.12.0'
|
||||||
implementation 'com.squareup.okio:okio:3.6.0'
|
implementation 'com.squareup.okio:okio:3.7.0'
|
||||||
|
|
||||||
implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl:4.3.2'
|
implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl:4.3.2'
|
||||||
implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-viewbinding:4.3.2'
|
implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-viewbinding:4.3.2'
|
||||||
|
|
||||||
implementation 'com.google.dagger:hilt-android:2.49'
|
implementation 'com.google.dagger:hilt-android:2.50'
|
||||||
kapt 'com.google.dagger:hilt-compiler:2.49'
|
kapt 'com.google.dagger:hilt-compiler:2.50'
|
||||||
implementation 'androidx.hilt:hilt-work:1.1.0'
|
implementation 'androidx.hilt:hilt-work:1.1.0'
|
||||||
kapt 'androidx.hilt:hilt-compiler:1.1.0'
|
kapt 'androidx.hilt:hilt-compiler:1.1.0'
|
||||||
|
|
||||||
@@ -155,6 +155,6 @@ dependencies {
|
|||||||
androidTestImplementation 'androidx.room:room-testing:2.6.1'
|
androidTestImplementation 'androidx.room:room-testing:2.6.1'
|
||||||
androidTestImplementation 'com.squareup.moshi:moshi-kotlin:1.15.0'
|
androidTestImplementation 'com.squareup.moshi:moshi-kotlin:1.15.0'
|
||||||
|
|
||||||
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.49'
|
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.50'
|
||||||
kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.49'
|
kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.50'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package org.koitharu.kotatsu.bookmarks.data
|
|||||||
|
|
||||||
import org.koitharu.kotatsu.bookmarks.domain.Bookmark
|
import org.koitharu.kotatsu.bookmarks.domain.Bookmark
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
|
|
||||||
fun BookmarkEntity.toBookmark(manga: Manga) = Bookmark(
|
fun BookmarkEntity.toBookmark(manga: Manga) = Bookmark(
|
||||||
manga = manga,
|
manga = manga,
|
||||||
@@ -11,7 +11,7 @@ fun BookmarkEntity.toBookmark(manga: Manga) = Bookmark(
|
|||||||
page = page,
|
page = page,
|
||||||
scroll = scroll,
|
scroll = scroll,
|
||||||
imageUrl = imageUrl,
|
imageUrl = imageUrl,
|
||||||
createdAt = Date(createdAt),
|
createdAt = Instant.ofEpochMilli(createdAt),
|
||||||
percent = percent,
|
percent = percent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ fun Bookmark.toEntity() = BookmarkEntity(
|
|||||||
page = page,
|
page = page,
|
||||||
scroll = scroll,
|
scroll = scroll,
|
||||||
imageUrl = imageUrl,
|
imageUrl = imageUrl,
|
||||||
createdAt = createdAt.time,
|
createdAt = createdAt.toEpochMilli(),
|
||||||
percent = percent,
|
percent = percent,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import org.koitharu.kotatsu.list.ui.model.ListModel
|
|||||||
import org.koitharu.kotatsu.local.data.hasImageExtension
|
import org.koitharu.kotatsu.local.data.hasImageExtension
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaPage
|
import org.koitharu.kotatsu.parsers.model.MangaPage
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
|
|
||||||
data class Bookmark(
|
data class Bookmark(
|
||||||
val manga: Manga,
|
val manga: Manga,
|
||||||
@@ -13,7 +13,7 @@ data class Bookmark(
|
|||||||
val page: Int,
|
val page: Int,
|
||||||
val scroll: Int,
|
val scroll: Int,
|
||||||
val imageUrl: String,
|
val imageUrl: String,
|
||||||
val createdAt: Date,
|
val createdAt: Instant,
|
||||||
val percent: Float,
|
val percent: Float,
|
||||||
) : ListModel {
|
) : ListModel {
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import org.koitharu.kotatsu.R
|
|||||||
import org.koitharu.kotatsu.core.exceptions.CloudFlareProtectedException
|
import org.koitharu.kotatsu.core.exceptions.CloudFlareProtectedException
|
||||||
import org.koitharu.kotatsu.core.util.ext.checkNotificationPermission
|
import org.koitharu.kotatsu.core.util.ext.checkNotificationPermission
|
||||||
import org.koitharu.kotatsu.parsers.model.ContentType
|
import org.koitharu.kotatsu.parsers.model.ContentType
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
|
|
||||||
class CaptchaNotifier(
|
class CaptchaNotifier(
|
||||||
private val context: Context,
|
private val context: Context,
|
||||||
@@ -58,16 +59,27 @@ class CaptchaNotifier(
|
|||||||
manager.notify(TAG, exception.source.hashCode(), notification)
|
manager.notify(TAG, exception.source.hashCode(), notification)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun dismiss(source: MangaSource) {
|
||||||
|
NotificationManagerCompat.from(context).cancel(TAG, source.hashCode())
|
||||||
|
}
|
||||||
|
|
||||||
override fun onError(request: ImageRequest, result: ErrorResult) {
|
override fun onError(request: ImageRequest, result: ErrorResult) {
|
||||||
super.onError(request, result)
|
super.onError(request, result)
|
||||||
val e = result.throwable
|
val e = result.throwable
|
||||||
if (e is CloudFlareProtectedException) {
|
if (e is CloudFlareProtectedException && request.parameters.value<Boolean>(PARAM_IGNORE_CAPTCHA) != true) {
|
||||||
notify(e)
|
notify(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
companion object {
|
||||||
|
|
||||||
|
fun ImageRequest.Builder.ignoreCaptchaErrors() = setParameter(
|
||||||
|
key = PARAM_IGNORE_CAPTCHA,
|
||||||
|
value = true,
|
||||||
|
memoryCacheKey = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
private const val PARAM_IGNORE_CAPTCHA = "ignore_captcha"
|
||||||
private const val CHANNEL_ID = "captcha"
|
private const val CHANNEL_ID = "captcha"
|
||||||
private const val TAG = CHANNEL_ID
|
private const val TAG = CHANNEL_ID
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,17 +3,20 @@ package org.koitharu.kotatsu.core.backup
|
|||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
|
|
||||||
class BackupEntry(
|
class BackupEntry(
|
||||||
val name: String,
|
val name: Name,
|
||||||
val data: JSONArray
|
val data: JSONArray
|
||||||
) {
|
) {
|
||||||
|
|
||||||
companion object Names {
|
enum class Name(
|
||||||
|
val key: String,
|
||||||
|
) {
|
||||||
|
|
||||||
const val INDEX = "index"
|
INDEX("index"),
|
||||||
const val HISTORY = "history"
|
HISTORY("history"),
|
||||||
const val CATEGORIES = "categories"
|
CATEGORIES("categories"),
|
||||||
const val FAVOURITES = "favourites"
|
FAVOURITES("favourites"),
|
||||||
const val SETTINGS = "settings"
|
SETTINGS("settings"),
|
||||||
const val BOOKMARKS = "bookmarks"
|
BOOKMARKS("bookmarks"),
|
||||||
|
SOURCES("sources"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import org.koitharu.kotatsu.BuildConfig
|
|||||||
import org.koitharu.kotatsu.core.db.MangaDatabase
|
import org.koitharu.kotatsu.core.db.MangaDatabase
|
||||||
import org.koitharu.kotatsu.core.prefs.AppSettings
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
import org.koitharu.kotatsu.parsers.util.json.JSONIterator
|
import org.koitharu.kotatsu.parsers.util.json.JSONIterator
|
||||||
|
import org.koitharu.kotatsu.parsers.util.json.getLongOrDefault
|
||||||
import org.koitharu.kotatsu.parsers.util.json.mapJSON
|
import org.koitharu.kotatsu.parsers.util.json.mapJSON
|
||||||
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
||||||
|
import java.util.Date
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
private const val PAGE_SIZE = 10
|
private const val PAGE_SIZE = 10
|
||||||
@@ -20,7 +22,7 @@ class BackupRepository @Inject constructor(
|
|||||||
|
|
||||||
suspend fun dumpHistory(): BackupEntry {
|
suspend fun dumpHistory(): BackupEntry {
|
||||||
var offset = 0
|
var offset = 0
|
||||||
val entry = BackupEntry(BackupEntry.HISTORY, JSONArray())
|
val entry = BackupEntry(BackupEntry.Name.HISTORY, JSONArray())
|
||||||
while (true) {
|
while (true) {
|
||||||
val history = db.getHistoryDao().findAll(offset, PAGE_SIZE)
|
val history = db.getHistoryDao().findAll(offset, PAGE_SIZE)
|
||||||
if (history.isEmpty()) {
|
if (history.isEmpty()) {
|
||||||
@@ -41,7 +43,7 @@ class BackupRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun dumpCategories(): BackupEntry {
|
suspend fun dumpCategories(): BackupEntry {
|
||||||
val entry = BackupEntry(BackupEntry.CATEGORIES, JSONArray())
|
val entry = BackupEntry(BackupEntry.Name.CATEGORIES, JSONArray())
|
||||||
val categories = db.getFavouriteCategoriesDao().findAll()
|
val categories = db.getFavouriteCategoriesDao().findAll()
|
||||||
for (item in categories) {
|
for (item in categories) {
|
||||||
entry.data.put(JsonSerializer(item).toJson())
|
entry.data.put(JsonSerializer(item).toJson())
|
||||||
@@ -51,9 +53,9 @@ class BackupRepository @Inject constructor(
|
|||||||
|
|
||||||
suspend fun dumpFavourites(): BackupEntry {
|
suspend fun dumpFavourites(): BackupEntry {
|
||||||
var offset = 0
|
var offset = 0
|
||||||
val entry = BackupEntry(BackupEntry.FAVOURITES, JSONArray())
|
val entry = BackupEntry(BackupEntry.Name.FAVOURITES, JSONArray())
|
||||||
while (true) {
|
while (true) {
|
||||||
val favourites = db.getFavouritesDao().findAll(offset, PAGE_SIZE)
|
val favourites = db.getFavouritesDao().findAllRaw(offset, PAGE_SIZE)
|
||||||
if (favourites.isEmpty()) {
|
if (favourites.isEmpty()) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -72,7 +74,7 @@ class BackupRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun dumpBookmarks(): BackupEntry {
|
suspend fun dumpBookmarks(): BackupEntry {
|
||||||
val entry = BackupEntry(BackupEntry.BOOKMARKS, JSONArray())
|
val entry = BackupEntry(BackupEntry.Name.BOOKMARKS, JSONArray())
|
||||||
val all = db.getBookmarksDao().findAll()
|
val all = db.getBookmarksDao().findAll()
|
||||||
for ((m, b) in all) {
|
for ((m, b) in all) {
|
||||||
val json = JSONObject()
|
val json = JSONObject()
|
||||||
@@ -90,7 +92,7 @@ class BackupRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun dumpSettings(): BackupEntry {
|
fun dumpSettings(): BackupEntry {
|
||||||
val entry = BackupEntry(BackupEntry.SETTINGS, JSONArray())
|
val entry = BackupEntry(BackupEntry.Name.SETTINGS, JSONArray())
|
||||||
val settingsDump = settings.getAllValues().toMutableMap()
|
val settingsDump = settings.getAllValues().toMutableMap()
|
||||||
settingsDump.remove(AppSettings.KEY_APP_PASSWORD)
|
settingsDump.remove(AppSettings.KEY_APP_PASSWORD)
|
||||||
settingsDump.remove(AppSettings.KEY_PROXY_PASSWORD)
|
settingsDump.remove(AppSettings.KEY_PROXY_PASSWORD)
|
||||||
@@ -101,8 +103,18 @@ class BackupRepository @Inject constructor(
|
|||||||
return entry
|
return entry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun dumpSources(): BackupEntry {
|
||||||
|
val entry = BackupEntry(BackupEntry.Name.SOURCES, JSONArray())
|
||||||
|
val all = db.getSourcesDao().findAll()
|
||||||
|
for (source in all) {
|
||||||
|
val json = JsonSerializer(source).toJson()
|
||||||
|
entry.data.put(json)
|
||||||
|
}
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
|
||||||
fun createIndex(): BackupEntry {
|
fun createIndex(): BackupEntry {
|
||||||
val entry = BackupEntry(BackupEntry.INDEX, JSONArray())
|
val entry = BackupEntry(BackupEntry.Name.INDEX, JSONArray())
|
||||||
val json = JSONObject()
|
val json = JSONObject()
|
||||||
json.put("app_id", BuildConfig.APPLICATION_ID)
|
json.put("app_id", BuildConfig.APPLICATION_ID)
|
||||||
json.put("app_version", BuildConfig.VERSION_CODE)
|
json.put("app_version", BuildConfig.VERSION_CODE)
|
||||||
@@ -111,6 +123,11 @@ class BackupRepository @Inject constructor(
|
|||||||
return entry
|
return entry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun getBackupDate(entry: BackupEntry?): Date? {
|
||||||
|
val timestamp = entry?.data?.optJSONObject(0)?.getLongOrDefault("created_at", 0) ?: 0
|
||||||
|
return if (timestamp == 0L) null else Date(timestamp)
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun restoreHistory(entry: BackupEntry): CompositeResult {
|
suspend fun restoreHistory(entry: BackupEntry): CompositeResult {
|
||||||
val result = CompositeResult()
|
val result = CompositeResult()
|
||||||
for (item in entry.data.JSONIterator()) {
|
for (item in entry.data.JSONIterator()) {
|
||||||
@@ -184,6 +201,17 @@ class BackupRepository @Inject constructor(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun restoreSources(entry: BackupEntry): CompositeResult {
|
||||||
|
val result = CompositeResult()
|
||||||
|
for (item in entry.data.JSONIterator()) {
|
||||||
|
val source = JsonDeserializer(item).toMangaSourceEntity()
|
||||||
|
result += runCatchingCancellable {
|
||||||
|
db.getSourcesDao().upsert(source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
fun restoreSettings(entry: BackupEntry): CompositeResult {
|
fun restoreSettings(entry: BackupEntry): CompositeResult {
|
||||||
val result = CompositeResult()
|
val result = CompositeResult()
|
||||||
for (item in entry.data.JSONIterator()) {
|
for (item in entry.data.JSONIterator()) {
|
||||||
|
|||||||
@@ -1,25 +1,44 @@
|
|||||||
package org.koitharu.kotatsu.core.backup
|
package org.koitharu.kotatsu.core.backup
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CoroutineStart
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.runInterruptible
|
import kotlinx.coroutines.runInterruptible
|
||||||
import okio.Closeable
|
import okio.Closeable
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.processLifecycleScope
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.util.EnumSet
|
||||||
import java.util.zip.ZipFile
|
import java.util.zip.ZipFile
|
||||||
|
|
||||||
class BackupZipInput(val file: File) : Closeable {
|
class BackupZipInput(val file: File) : Closeable {
|
||||||
|
|
||||||
private val zipFile = ZipFile(file)
|
private val zipFile = ZipFile(file)
|
||||||
|
|
||||||
suspend fun getEntry(name: String): BackupEntry? = runInterruptible(Dispatchers.IO) {
|
suspend fun getEntry(name: BackupEntry.Name): BackupEntry? = runInterruptible(Dispatchers.IO) {
|
||||||
val entry = zipFile.getEntry(name) ?: return@runInterruptible null
|
val entry = zipFile.getEntry(name.key) ?: return@runInterruptible null
|
||||||
val json = zipFile.getInputStream(entry).use {
|
val json = zipFile.getInputStream(entry).use {
|
||||||
JSONArray(it.bufferedReader().readText())
|
JSONArray(it.bufferedReader().readText())
|
||||||
}
|
}
|
||||||
BackupEntry(name, json)
|
BackupEntry(name, json)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun entries(): Set<BackupEntry.Name> = runInterruptible(Dispatchers.IO) {
|
||||||
|
zipFile.entries().toList().mapNotNullTo(EnumSet.noneOf(BackupEntry.Name::class.java)) { ze ->
|
||||||
|
BackupEntry.Name.entries.find { it.key == ze.name }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun close() {
|
override fun close() {
|
||||||
zipFile.close()
|
zipFile.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun cleanupAsync() {
|
||||||
|
processLifecycleScope.launch(Dispatchers.IO, CoroutineStart.ATOMIC) {
|
||||||
|
runCatching {
|
||||||
|
close()
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,10 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.runInterruptible
|
import kotlinx.coroutines.runInterruptible
|
||||||
import okio.Closeable
|
import okio.Closeable
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.util.ext.format
|
|
||||||
import org.koitharu.kotatsu.core.zip.ZipOutput
|
import org.koitharu.kotatsu.core.zip.ZipOutput
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Date
|
import java.time.LocalDate
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.zip.Deflater
|
import java.util.zip.Deflater
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ class BackupZipOutput(val file: File) : Closeable {
|
|||||||
private val output = ZipOutput(file, Deflater.BEST_COMPRESSION)
|
private val output = ZipOutput(file, Deflater.BEST_COMPRESSION)
|
||||||
|
|
||||||
suspend fun put(entry: BackupEntry) = runInterruptible(Dispatchers.IO) {
|
suspend fun put(entry: BackupEntry) = runInterruptible(Dispatchers.IO) {
|
||||||
output.put(entry.name, entry.data.toString(2))
|
output.put(entry.name.key, entry.data.toString(2))
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun finish() = runInterruptible(Dispatchers.IO) {
|
suspend fun finish() = runInterruptible(Dispatchers.IO) {
|
||||||
@@ -39,7 +39,7 @@ suspend fun BackupZipOutput(context: Context): BackupZipOutput = runInterruptibl
|
|||||||
val filename = buildString {
|
val filename = buildString {
|
||||||
append(context.getString(R.string.app_name).replace(' ', '_').lowercase(Locale.ROOT))
|
append(context.getString(R.string.app_name).replace(' ', '_').lowercase(Locale.ROOT))
|
||||||
append('_')
|
append('_')
|
||||||
append(Date().format("ddMMyyyy"))
|
append(LocalDate.now().format(DateTimeFormatter.ofPattern("ddMMyyyy")))
|
||||||
append(".bk.zip")
|
append(".bk.zip")
|
||||||
}
|
}
|
||||||
BackupZipOutput(File(dir, filename))
|
BackupZipOutput(File(dir, filename))
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package org.koitharu.kotatsu.core.backup
|
|||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import org.koitharu.kotatsu.bookmarks.data.BookmarkEntity
|
import org.koitharu.kotatsu.bookmarks.data.BookmarkEntity
|
||||||
import org.koitharu.kotatsu.core.db.entity.MangaEntity
|
import org.koitharu.kotatsu.core.db.entity.MangaEntity
|
||||||
|
import org.koitharu.kotatsu.core.db.entity.MangaSourceEntity
|
||||||
import org.koitharu.kotatsu.core.db.entity.TagEntity
|
import org.koitharu.kotatsu.core.db.entity.TagEntity
|
||||||
import org.koitharu.kotatsu.favourites.data.FavouriteCategoryEntity
|
import org.koitharu.kotatsu.favourites.data.FavouriteCategoryEntity
|
||||||
import org.koitharu.kotatsu.favourites.data.FavouriteEntity
|
import org.koitharu.kotatsu.favourites.data.FavouriteEntity
|
||||||
@@ -78,6 +79,12 @@ class JsonDeserializer(private val json: JSONObject) {
|
|||||||
percent = json.getDouble("percent").toFloat(),
|
percent = json.getDouble("percent").toFloat(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
fun toMangaSourceEntity() = MangaSourceEntity(
|
||||||
|
source = json.getString("source"),
|
||||||
|
isEnabled = json.getBoolean("enabled"),
|
||||||
|
sortKey = json.getInt("sort_key"),
|
||||||
|
)
|
||||||
|
|
||||||
fun toMap(): Map<String, Any?> {
|
fun toMap(): Map<String, Any?> {
|
||||||
val map = mutableMapOf<String, Any?>()
|
val map = mutableMapOf<String, Any?>()
|
||||||
val keys = json.keys()
|
val keys = json.keys()
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package org.koitharu.kotatsu.core.backup
|
|||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import org.koitharu.kotatsu.bookmarks.data.BookmarkEntity
|
import org.koitharu.kotatsu.bookmarks.data.BookmarkEntity
|
||||||
import org.koitharu.kotatsu.core.db.entity.MangaEntity
|
import org.koitharu.kotatsu.core.db.entity.MangaEntity
|
||||||
|
import org.koitharu.kotatsu.core.db.entity.MangaSourceEntity
|
||||||
import org.koitharu.kotatsu.core.db.entity.TagEntity
|
import org.koitharu.kotatsu.core.db.entity.TagEntity
|
||||||
import org.koitharu.kotatsu.favourites.data.FavouriteCategoryEntity
|
import org.koitharu.kotatsu.favourites.data.FavouriteCategoryEntity
|
||||||
import org.koitharu.kotatsu.favourites.data.FavouriteEntity
|
import org.koitharu.kotatsu.favourites.data.FavouriteEntity
|
||||||
@@ -82,6 +83,14 @@ class JsonSerializer private constructor(private val json: JSONObject) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
constructor(e: MangaSourceEntity) : this(
|
||||||
|
JSONObject().apply {
|
||||||
|
put("source", e.source)
|
||||||
|
put("enabled", e.isEnabled)
|
||||||
|
put("sort_key", e.sortKey)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
constructor(m: Map<String, *>) : this(
|
constructor(m: Map<String, *>) : this(
|
||||||
JSONObject(m),
|
JSONObject(m),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -31,6 +31,16 @@ abstract class TagsDao {
|
|||||||
)
|
)
|
||||||
abstract suspend fun findPopularTags(source: String, limit: Int): List<TagEntity>
|
abstract suspend fun findPopularTags(source: String, limit: Int): List<TagEntity>
|
||||||
|
|
||||||
|
@Query(
|
||||||
|
"""SELECT tags.* FROM tags
|
||||||
|
LEFT JOIN manga_tags ON tags.tag_id = manga_tags.tag_id
|
||||||
|
WHERE tags.source = :source
|
||||||
|
GROUP BY tags.title
|
||||||
|
ORDER BY COUNT(manga_id) ASC
|
||||||
|
LIMIT :limit""",
|
||||||
|
)
|
||||||
|
abstract suspend fun findRareTags(source: String, limit: Int): List<TagEntity>
|
||||||
|
|
||||||
@Query(
|
@Query(
|
||||||
"""SELECT tags.* FROM tags
|
"""SELECT tags.* FROM tags
|
||||||
LEFT JOIN manga_tags ON tags.tag_id = manga_tags.tag_id
|
LEFT JOIN manga_tags ON tags.tag_id = manga_tags.tag_id
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
package org.koitharu.kotatsu.core.exceptions
|
package org.koitharu.kotatsu.core.exceptions
|
||||||
|
|
||||||
import okio.IOException
|
import okio.IOException
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
|
import java.time.temporal.ChronoUnit
|
||||||
|
|
||||||
class TooManyRequestExceptions(
|
class TooManyRequestExceptions(
|
||||||
val url: String,
|
val url: String,
|
||||||
val retryAt: Date?,
|
val retryAt: Instant?,
|
||||||
) : IOException() {
|
) : IOException() {
|
||||||
|
|
||||||
val retryAfter: Long
|
val retryAfter: Long
|
||||||
get() = if (retryAt == null) 0 else (retryAt.time - System.currentTimeMillis()).coerceAtLeast(0)
|
get() = retryAt?.until(Instant.now(), ChronoUnit.MILLIS) ?: 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,8 +20,9 @@ import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
|||||||
import org.koitharu.kotatsu.core.util.ext.printStackTraceDebug
|
import org.koitharu.kotatsu.core.util.ext.printStackTraceDebug
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
import java.text.SimpleDateFormat
|
import java.time.LocalDateTime
|
||||||
import java.util.Date
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue
|
import java.util.concurrent.ConcurrentLinkedQueue
|
||||||
|
|
||||||
@@ -41,11 +42,7 @@ class FileLogger(
|
|||||||
}
|
}
|
||||||
val isEnabled: Boolean
|
val isEnabled: Boolean
|
||||||
get() = settings.isLoggingEnabled
|
get() = settings.isLoggingEnabled
|
||||||
private val dateFormat = SimpleDateFormat.getDateTimeInstance(
|
private val dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.ROOT)
|
||||||
SimpleDateFormat.SHORT,
|
|
||||||
SimpleDateFormat.SHORT,
|
|
||||||
Locale.ROOT,
|
|
||||||
)
|
|
||||||
private val buffer = ConcurrentLinkedQueue<String>()
|
private val buffer = ConcurrentLinkedQueue<String>()
|
||||||
private val mutex = Mutex()
|
private val mutex = Mutex()
|
||||||
private var flushJob: Job? = null
|
private var flushJob: Job? = null
|
||||||
@@ -55,7 +52,7 @@ class FileLogger(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
val text = buildString {
|
val text = buildString {
|
||||||
append(dateFormat.format(Date()))
|
append(dateTimeFormatter.format(LocalDateTime.now()))
|
||||||
append(": ")
|
append(": ")
|
||||||
if (e != null) {
|
if (e != null) {
|
||||||
append("E!")
|
append("E!")
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import kotlinx.parcelize.Parcelize
|
|||||||
import org.koitharu.kotatsu.list.domain.ListSortOrder
|
import org.koitharu.kotatsu.list.domain.ListSortOrder
|
||||||
import org.koitharu.kotatsu.list.ui.ListModelDiffCallback
|
import org.koitharu.kotatsu.list.ui.ListModelDiffCallback
|
||||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
|
|
||||||
@Parcelize
|
@Parcelize
|
||||||
data class FavouriteCategory(
|
data class FavouriteCategory(
|
||||||
@@ -13,7 +13,7 @@ data class FavouriteCategory(
|
|||||||
val title: String,
|
val title: String,
|
||||||
val sortKey: Int,
|
val sortKey: Int,
|
||||||
val order: ListSortOrder,
|
val order: ListSortOrder,
|
||||||
val createdAt: Date,
|
val createdAt: Instant,
|
||||||
val isTrackingEnabled: Boolean,
|
val isTrackingEnabled: Boolean,
|
||||||
val isVisibleInLibrary: Boolean,
|
val isVisibleInLibrary: Boolean,
|
||||||
) : Parcelable, ListModel {
|
) : Parcelable, ListModel {
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ import androidx.core.os.LocaleListCompat
|
|||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.util.ext.iterator
|
import org.koitharu.kotatsu.core.util.ext.iterator
|
||||||
import org.koitharu.kotatsu.details.ui.model.ChapterListItem
|
import org.koitharu.kotatsu.details.ui.model.ChapterListItem
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaState
|
import org.koitharu.kotatsu.parsers.model.MangaState
|
||||||
import org.koitharu.kotatsu.parsers.util.mapToSet
|
import org.koitharu.kotatsu.parsers.util.mapToSet
|
||||||
|
import com.google.android.material.R as materialR
|
||||||
|
|
||||||
@JvmName("mangaIds")
|
@JvmName("mangaIds")
|
||||||
fun Collection<Manga>.ids() = mapToSet { it.id }
|
fun Collection<Manga>.ids() = mapToSet { it.id }
|
||||||
@@ -42,15 +44,25 @@ val MangaState.titleResId: Int
|
|||||||
MangaState.FINISHED -> R.string.state_finished
|
MangaState.FINISHED -> R.string.state_finished
|
||||||
MangaState.ABANDONED -> R.string.state_abandoned
|
MangaState.ABANDONED -> R.string.state_abandoned
|
||||||
MangaState.PAUSED -> R.string.state_paused
|
MangaState.PAUSED -> R.string.state_paused
|
||||||
|
MangaState.UPCOMING -> R.string.state_upcoming
|
||||||
}
|
}
|
||||||
|
|
||||||
@get:DrawableRes
|
@get:DrawableRes
|
||||||
val MangaState.iconResId: Int
|
val MangaState.iconResId: Int
|
||||||
get() = when (this) {
|
get() = when (this) {
|
||||||
MangaState.ONGOING -> R.drawable.ic_state_ongoing
|
MangaState.ONGOING -> R.drawable.ic_play
|
||||||
MangaState.FINISHED -> R.drawable.ic_state_finished
|
MangaState.FINISHED -> R.drawable.ic_state_finished
|
||||||
MangaState.ABANDONED -> R.drawable.ic_state_abandoned
|
MangaState.ABANDONED -> R.drawable.ic_state_abandoned
|
||||||
MangaState.PAUSED -> R.drawable.ic_action_pause
|
MangaState.PAUSED -> R.drawable.ic_action_pause
|
||||||
|
MangaState.UPCOMING -> materialR.drawable.ic_clock_black_24dp
|
||||||
|
}
|
||||||
|
|
||||||
|
@get:StringRes
|
||||||
|
val ContentRating.titleResId: Int
|
||||||
|
get() = when (this) {
|
||||||
|
ContentRating.SAFE -> R.string.rating_safe
|
||||||
|
ContentRating.SUGGESTIVE -> R.string.rating_suggestive
|
||||||
|
ContentRating.ADULT -> R.string.rating_adult
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Manga.findChapter(id: Long): MangaChapter? {
|
fun Manga.findChapter(id: Long): MangaChapter? {
|
||||||
|
|||||||
@@ -2,14 +2,14 @@ package org.koitharu.kotatsu.core.model
|
|||||||
|
|
||||||
import android.os.Parcelable
|
import android.os.Parcelable
|
||||||
import kotlinx.parcelize.Parcelize
|
import kotlinx.parcelize.Parcelize
|
||||||
import java.util.*
|
import java.time.Instant
|
||||||
|
|
||||||
@Parcelize
|
@Parcelize
|
||||||
data class MangaHistory(
|
data class MangaHistory(
|
||||||
val createdAt: Date,
|
val createdAt: Instant,
|
||||||
val updatedAt: Date,
|
val updatedAt: Instant,
|
||||||
val chapterId: Long,
|
val chapterId: Long,
|
||||||
val page: Int,
|
val page: Int,
|
||||||
val scroll: Int,
|
val scroll: Int,
|
||||||
val percent: Float,
|
val percent: Float,
|
||||||
) : Parcelable
|
) : Parcelable
|
||||||
|
|||||||
@@ -1,17 +1,23 @@
|
|||||||
package org.koitharu.kotatsu.core.model
|
package org.koitharu.kotatsu.core.model
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.text.SpannableStringBuilder
|
||||||
|
import android.text.style.ForegroundColorSpan
|
||||||
|
import android.text.style.RelativeSizeSpan
|
||||||
|
import android.text.style.SuperscriptSpan
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
|
import androidx.core.text.buildSpannedString
|
||||||
|
import androidx.core.text.inSpans
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.getDisplayName
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.getThemeColor
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.toLocale
|
||||||
import org.koitharu.kotatsu.parsers.model.ContentType
|
import org.koitharu.kotatsu.parsers.model.ContentType
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
import org.koitharu.kotatsu.parsers.util.toTitleCase
|
import org.koitharu.kotatsu.parsers.util.toTitleCase
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import com.google.android.material.R as materialR
|
||||||
fun MangaSource.getLocaleTitle(): String? {
|
|
||||||
val lc = Locale(locale ?: return null)
|
|
||||||
return lc.getDisplayLanguage(lc).toTitleCase(lc)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun MangaSource(name: String): MangaSource {
|
fun MangaSource(name: String): MangaSource {
|
||||||
MangaSource.entries.forEach {
|
MangaSource.entries.forEach {
|
||||||
@@ -33,6 +39,24 @@ val ContentType.titleResId
|
|||||||
|
|
||||||
fun MangaSource.getSummary(context: Context): String {
|
fun MangaSource.getSummary(context: Context): String {
|
||||||
val type = context.getString(contentType.titleResId)
|
val type = context.getString(contentType.titleResId)
|
||||||
val locale = getLocaleTitle() ?: context.getString(R.string.various_languages)
|
val locale = locale?.toLocale().getDisplayName(context)
|
||||||
return context.getString(R.string.source_summary_pattern, type, locale)
|
return context.getString(R.string.source_summary_pattern, type, locale)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun MangaSource.getTitle(context: Context): CharSequence = if (isNsfw()) {
|
||||||
|
buildSpannedString {
|
||||||
|
append(title)
|
||||||
|
append(' ')
|
||||||
|
appendNsfwLabel(context)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
title
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun SpannableStringBuilder.appendNsfwLabel(context: Context) = inSpans(
|
||||||
|
ForegroundColorSpan(context.getThemeColor(materialR.attr.colorError, Color.RED)),
|
||||||
|
RelativeSizeSpan(0.74f),
|
||||||
|
SuperscriptSpan(),
|
||||||
|
) {
|
||||||
|
append(context.getString(R.string.nsfw))
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,15 +4,11 @@ import okhttp3.Interceptor
|
|||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
import okhttp3.internal.closeQuietly
|
import okhttp3.internal.closeQuietly
|
||||||
import org.koitharu.kotatsu.core.exceptions.TooManyRequestExceptions
|
import org.koitharu.kotatsu.core.exceptions.TooManyRequestExceptions
|
||||||
import java.text.SimpleDateFormat
|
import java.time.Instant
|
||||||
import java.util.Date
|
import java.time.ZonedDateTime
|
||||||
import java.util.Locale
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
|
|
||||||
class RateLimitInterceptor : Interceptor {
|
class RateLimitInterceptor : Interceptor {
|
||||||
|
|
||||||
private val dateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ZZZ", Locale.ENGLISH)
|
|
||||||
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val response = chain.proceed(chain.request())
|
val response = chain.proceed(chain.request())
|
||||||
if (response.code == 429) {
|
if (response.code == 429) {
|
||||||
@@ -27,10 +23,8 @@ class RateLimitInterceptor : Interceptor {
|
|||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun String.parseRetryDate(): Date? {
|
private fun String.parseRetryDate(): Instant? {
|
||||||
toIntOrNull()?.let {
|
return toLongOrNull()?.let { Instant.now().plusSeconds(it) }
|
||||||
return Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(it.toLong()))
|
?: ZonedDateTime.parse(this, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()
|
||||||
}
|
|
||||||
return dateFormat.parse(this)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import org.koitharu.kotatsu.core.cache.ContentCache
|
|||||||
import org.koitharu.kotatsu.core.network.MirrorSwitchInterceptor
|
import org.koitharu.kotatsu.core.network.MirrorSwitchInterceptor
|
||||||
import org.koitharu.kotatsu.local.data.LocalMangaRepository
|
import org.koitharu.kotatsu.local.data.LocalMangaRepository
|
||||||
import org.koitharu.kotatsu.parsers.MangaLoaderContext
|
import org.koitharu.kotatsu.parsers.MangaLoaderContext
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaListFilter
|
import org.koitharu.kotatsu.parsers.model.MangaListFilter
|
||||||
@@ -28,10 +29,16 @@ interface MangaRepository {
|
|||||||
|
|
||||||
val states: Set<MangaState>
|
val states: Set<MangaState>
|
||||||
|
|
||||||
|
val contentRatings: Set<ContentRating>
|
||||||
|
|
||||||
var defaultSortOrder: SortOrder
|
var defaultSortOrder: SortOrder
|
||||||
|
|
||||||
val isMultipleTagsSupported: Boolean
|
val isMultipleTagsSupported: Boolean
|
||||||
|
|
||||||
|
val isTagsExclusionSupported: Boolean
|
||||||
|
|
||||||
|
val isSearchSupported: Boolean
|
||||||
|
|
||||||
suspend fun getList(offset: Int, filter: MangaListFilter?): List<Manga>
|
suspend fun getList(offset: Int, filter: MangaListFilter?): List<Manga>
|
||||||
|
|
||||||
suspend fun getDetails(manga: Manga): Manga
|
suspend fun getDetails(manga: Manga): Manga
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import org.koitharu.kotatsu.parsers.MangaParser
|
|||||||
import org.koitharu.kotatsu.parsers.MangaParserAuthProvider
|
import org.koitharu.kotatsu.parsers.MangaParserAuthProvider
|
||||||
import org.koitharu.kotatsu.parsers.config.ConfigKey
|
import org.koitharu.kotatsu.parsers.config.ConfigKey
|
||||||
import org.koitharu.kotatsu.parsers.exception.ParseException
|
import org.koitharu.kotatsu.parsers.exception.ParseException
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.Favicons
|
import org.koitharu.kotatsu.parsers.model.Favicons
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
@@ -49,6 +50,9 @@ class RemoteMangaRepository(
|
|||||||
override val states: Set<MangaState>
|
override val states: Set<MangaState>
|
||||||
get() = parser.availableStates
|
get() = parser.availableStates
|
||||||
|
|
||||||
|
override val contentRatings: Set<ContentRating>
|
||||||
|
get() = parser.availableContentRating
|
||||||
|
|
||||||
override var defaultSortOrder: SortOrder
|
override var defaultSortOrder: SortOrder
|
||||||
get() = getConfig().defaultSortOrder ?: sortOrders.first()
|
get() = getConfig().defaultSortOrder ?: sortOrders.first()
|
||||||
set(value) {
|
set(value) {
|
||||||
@@ -58,6 +62,12 @@ class RemoteMangaRepository(
|
|||||||
override val isMultipleTagsSupported: Boolean
|
override val isMultipleTagsSupported: Boolean
|
||||||
get() = parser.isMultipleTagsSupported
|
get() = parser.isMultipleTagsSupported
|
||||||
|
|
||||||
|
override val isSearchSupported: Boolean
|
||||||
|
get() = parser.isSearchSupported
|
||||||
|
|
||||||
|
override val isTagsExclusionSupported: Boolean
|
||||||
|
get() = parser.isTagsExclusionSupported
|
||||||
|
|
||||||
var domain: String
|
var domain: String
|
||||||
get() = parser.domain
|
get() = parser.domain
|
||||||
set(value) {
|
set(value) {
|
||||||
|
|||||||
@@ -204,6 +204,9 @@ class AppSettings @Inject constructor(@ApplicationContext context: Context) {
|
|||||||
val isUnstableUpdatesAllowed: Boolean
|
val isUnstableUpdatesAllowed: Boolean
|
||||||
get() = prefs.getBoolean(KEY_UPDATES_UNSTABLE, false)
|
get() = prefs.getBoolean(KEY_UPDATES_UNSTABLE, false)
|
||||||
|
|
||||||
|
val defaultDetailsTab: Int
|
||||||
|
get() = prefs.getString(KEY_DETAILS_TAB, null)?.toIntOrNull()?.coerceIn(0, 1) ?: 0
|
||||||
|
|
||||||
val isContentPrefetchEnabled: Boolean
|
val isContentPrefetchEnabled: Boolean
|
||||||
get() {
|
get() {
|
||||||
if (isBackgroundNetworkRestricted()) {
|
if (isBackgroundNetworkRestricted()) {
|
||||||
@@ -295,13 +298,13 @@ class AppSettings @Inject constructor(@ApplicationContext context: Context) {
|
|||||||
get() = prefs.getBoolean(KEY_READER_SCREEN_ON, true)
|
get() = prefs.getBoolean(KEY_READER_SCREEN_ON, true)
|
||||||
|
|
||||||
var readerColorFilter: ReaderColorFilter?
|
var readerColorFilter: ReaderColorFilter?
|
||||||
get() {
|
get() = runCatching {
|
||||||
val brightness = prefs.getFloat(KEY_CF_BRIGHTNESS, ReaderColorFilter.EMPTY.brightness)
|
val brightness = prefs.getFloat(KEY_CF_BRIGHTNESS, ReaderColorFilter.EMPTY.brightness)
|
||||||
val contrast = prefs.getFloat(KEY_CF_CONTRAST, ReaderColorFilter.EMPTY.contrast)
|
val contrast = prefs.getFloat(KEY_CF_CONTRAST, ReaderColorFilter.EMPTY.contrast)
|
||||||
val inverted = prefs.getBoolean(KEY_CF_INVERTED, ReaderColorFilter.EMPTY.isInverted)
|
val inverted = prefs.getBoolean(KEY_CF_INVERTED, ReaderColorFilter.EMPTY.isInverted)
|
||||||
val grayscale = prefs.getBoolean(KEY_CF_GRAYSCALE, ReaderColorFilter.EMPTY.isGrayscale)
|
val grayscale = prefs.getBoolean(KEY_CF_GRAYSCALE, ReaderColorFilter.EMPTY.isGrayscale)
|
||||||
return ReaderColorFilter(brightness, contrast, inverted, grayscale).takeUnless { it.isEmpty }
|
ReaderColorFilter(brightness, contrast, inverted, grayscale).takeUnless { it.isEmpty }
|
||||||
}
|
}.getOrNull()
|
||||||
set(value) {
|
set(value) {
|
||||||
prefs.edit {
|
prefs.edit {
|
||||||
val cf = value ?: ReaderColorFilter.EMPTY
|
val cf = value ?: ReaderColorFilter.EMPTY
|
||||||
@@ -559,6 +562,7 @@ class AppSettings @Inject constructor(@ApplicationContext context: Context) {
|
|||||||
const val KEY_CF_INVERTED = "cf_inverted"
|
const val KEY_CF_INVERTED = "cf_inverted"
|
||||||
const val KEY_CF_GRAYSCALE = "cf_grayscale"
|
const val KEY_CF_GRAYSCALE = "cf_grayscale"
|
||||||
const val KEY_IGNORE_DOZE = "ignore_dose"
|
const val KEY_IGNORE_DOZE = "ignore_dose"
|
||||||
|
const val KEY_DETAILS_TAB = "details_tab"
|
||||||
|
|
||||||
// About
|
// About
|
||||||
const val KEY_APP_UPDATE = "app_update"
|
const val KEY_APP_UPDATE = "app_update"
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package org.koitharu.kotatsu.core.ui
|
package org.koitharu.kotatsu.core.ui
|
||||||
|
|
||||||
|
import android.content.ActivityNotFoundException
|
||||||
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import androidx.annotation.CallSuper
|
import androidx.annotation.CallSuper
|
||||||
@@ -8,7 +10,9 @@ import androidx.core.graphics.Insets
|
|||||||
import androidx.core.view.updatePadding
|
import androidx.core.view.updatePadding
|
||||||
import androidx.preference.PreferenceFragmentCompat
|
import androidx.preference.PreferenceFragmentCompat
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import com.google.android.material.snackbar.Snackbar
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.prefs.AppSettings
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
import org.koitharu.kotatsu.core.ui.util.RecyclerViewOwner
|
import org.koitharu.kotatsu.core.ui.util.RecyclerViewOwner
|
||||||
import org.koitharu.kotatsu.core.ui.util.WindowInsetsDelegate
|
import org.koitharu.kotatsu.core.ui.util.WindowInsetsDelegate
|
||||||
@@ -62,4 +66,12 @@ abstract class BasePreferenceFragment(@StringRes private val titleId: Int) :
|
|||||||
protected fun setTitle(title: CharSequence?) {
|
protected fun setTitle(title: CharSequence?) {
|
||||||
(activity as? SettingsActivity)?.setSectionTitle(title)
|
(activity as? SettingsActivity)?.setSectionTitle(title)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected fun startActivitySafe(intent: Intent) {
|
||||||
|
try {
|
||||||
|
startActivity(intent)
|
||||||
|
} catch (_: ActivityNotFoundException) {
|
||||||
|
Snackbar.make(listView, R.string.operation_not_supported, Snackbar.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,4 +38,12 @@ abstract class BoundsScrollListener(
|
|||||||
firstVisibleItemPosition: Int,
|
firstVisibleItemPosition: Int,
|
||||||
visibleItemCount: Int
|
visibleItemCount: Int
|
||||||
) = Unit
|
) = Unit
|
||||||
|
|
||||||
|
fun invalidate(recyclerView: RecyclerView) {
|
||||||
|
onScrolled(recyclerView, 0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun postInvalidate(recyclerView: RecyclerView) = recyclerView.post {
|
||||||
|
invalidate(recyclerView)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ package org.koitharu.kotatsu.core.ui.model
|
|||||||
|
|
||||||
import android.content.res.Resources
|
import android.content.res.Resources
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.util.ext.daysDiff
|
import java.time.LocalDate
|
||||||
import org.koitharu.kotatsu.core.util.ext.format
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Date
|
|
||||||
|
|
||||||
sealed class DateTimeAgo {
|
sealed class DateTimeAgo {
|
||||||
|
|
||||||
@@ -74,32 +73,22 @@ sealed class DateTimeAgo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Absolute(private val date: Date) : DateTimeAgo() {
|
data class Absolute(private val date: LocalDate) : DateTimeAgo() {
|
||||||
|
|
||||||
private val day = date.daysDiff(0)
|
|
||||||
|
|
||||||
override fun format(resources: Resources): String {
|
override fun format(resources: Resources): String {
|
||||||
return if (date.time == 0L) {
|
return if (date == EPOCH_DATE) {
|
||||||
resources.getString(R.string.unknown)
|
resources.getString(R.string.unknown)
|
||||||
} else {
|
} else {
|
||||||
date.format("d MMMM")
|
date.format(formatter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun equals(other: Any?): Boolean {
|
override fun toString() = "abs_${date.toEpochDay()}"
|
||||||
if (this === other) return true
|
|
||||||
if (javaClass != other?.javaClass) return false
|
|
||||||
|
|
||||||
other as Absolute
|
companion object {
|
||||||
|
// TODO: Use Java 9's LocalDate.EPOCH.
|
||||||
return day == other.day
|
private val EPOCH_DATE = LocalDate.of(1970, 1, 1)
|
||||||
|
private val formatter = DateTimeFormatter.ofPattern("d MMMM")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun hashCode(): Int {
|
|
||||||
return day
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun toString() = "abs_$day"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
object LongAgo : DateTimeAgo() {
|
object LongAgo : DateTimeAgo() {
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ val SortOrder.titleRes: Int
|
|||||||
SortOrder.RATING -> R.string.by_rating
|
SortOrder.RATING -> R.string.by_rating
|
||||||
SortOrder.NEWEST -> R.string.newest
|
SortOrder.NEWEST -> R.string.newest
|
||||||
SortOrder.ALPHABETICAL -> R.string.by_name
|
SortOrder.ALPHABETICAL -> R.string.by_name
|
||||||
|
SortOrder.ALPHABETICAL_DESC -> R.string.by_name_reverse
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ class WindowInsetsDelegate : OnApplyWindowInsetsListener, View.OnLayoutChangeLis
|
|||||||
lastInsets = null
|
lastInsets = null
|
||||||
}
|
}
|
||||||
|
|
||||||
interface WindowInsetsListener {
|
fun interface WindowInsetsListener {
|
||||||
|
|
||||||
fun onWindowInsetsChanged(insets: Insets)
|
fun onWindowInsetsChanged(insets: Insets)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -108,7 +108,6 @@ class ChipsView @JvmOverloads constructor(
|
|||||||
chip.setChipDrawable(drawable)
|
chip.setChipDrawable(drawable)
|
||||||
chip.isCheckedIconVisible = true
|
chip.isCheckedIconVisible = true
|
||||||
chip.isChipIconVisible = false
|
chip.isChipIconVisible = false
|
||||||
chip.setCheckedIconResource(R.drawable.ic_check)
|
|
||||||
chip.isCloseIconVisible = onChipCloseClickListener != null
|
chip.isCloseIconVisible = onChipCloseClickListener != null
|
||||||
chip.setOnCloseIconClickListener(chipOnCloseListener)
|
chip.setOnCloseIconClickListener(chipOnCloseListener)
|
||||||
chip.setEnsureMinTouchTargetSize(false)
|
chip.setEnsureMinTouchTargetSize(false)
|
||||||
|
|||||||
@@ -9,10 +9,8 @@ import androidx.fragment.app.FragmentManager
|
|||||||
import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks
|
import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks
|
||||||
import org.acra.ACRA
|
import org.acra.ACRA
|
||||||
import org.koitharu.kotatsu.core.ui.DefaultActivityLifecycleCallbacks
|
import org.koitharu.kotatsu.core.ui.DefaultActivityLifecycleCallbacks
|
||||||
import java.text.DateFormat
|
import java.time.LocalTime
|
||||||
import java.text.SimpleDateFormat
|
import java.time.temporal.ChronoUnit
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
|
||||||
import java.util.WeakHashMap
|
import java.util.WeakHashMap
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -20,7 +18,6 @@ import javax.inject.Singleton
|
|||||||
@Singleton
|
@Singleton
|
||||||
class AcraScreenLogger @Inject constructor() : FragmentLifecycleCallbacks(), DefaultActivityLifecycleCallbacks {
|
class AcraScreenLogger @Inject constructor() : FragmentLifecycleCallbacks(), DefaultActivityLifecycleCallbacks {
|
||||||
|
|
||||||
private val timeFormat = SimpleDateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.ROOT)
|
|
||||||
private val keys = WeakHashMap<Any, String>()
|
private val keys = WeakHashMap<Any, String>()
|
||||||
|
|
||||||
override fun onFragmentAttached(fm: FragmentManager, f: Fragment, context: Context) {
|
override fun onFragmentAttached(fm: FragmentManager, f: Fragment, context: Context) {
|
||||||
@@ -47,11 +44,10 @@ class AcraScreenLogger @Inject constructor() : FragmentLifecycleCallbacks(), Def
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun Any.key() = keys.getOrPut(this) {
|
private fun Any.key() = keys.getOrPut(this) {
|
||||||
"${time()}: ${javaClass.simpleName}"
|
val time = LocalTime.now().truncatedTo(ChronoUnit.SECONDS)
|
||||||
|
"$time: ${javaClass.simpleName}"
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun time() = timeFormat.format(Date())
|
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
private fun Bundle?.contentToString() = this?.keySet()?.joinToString { k ->
|
private fun Bundle?.contentToString() = this?.keySet()?.joinToString { k ->
|
||||||
val v = get(k)
|
val v = get(k)
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import android.content.SyncResult
|
|||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.content.pm.ResolveInfo
|
import android.content.pm.ResolveInfo
|
||||||
import android.database.SQLException
|
import android.database.SQLException
|
||||||
|
import android.graphics.Bitmap
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
@@ -29,6 +30,7 @@ import android.view.Window
|
|||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.activity.result.ActivityResultLauncher
|
import androidx.activity.result.ActivityResultLauncher
|
||||||
import androidx.annotation.IntegerRes
|
import androidx.annotation.IntegerRes
|
||||||
|
import androidx.annotation.WorkerThread
|
||||||
import androidx.core.app.ActivityOptionsCompat
|
import androidx.core.app.ActivityOptionsCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
@@ -37,6 +39,7 @@ import androidx.lifecycle.Lifecycle
|
|||||||
import androidx.lifecycle.coroutineScope
|
import androidx.lifecycle.coroutineScope
|
||||||
import androidx.work.CoroutineWorker
|
import androidx.work.CoroutineWorker
|
||||||
import com.google.android.material.elevation.ElevationOverlayProvider
|
import com.google.android.material.elevation.ElevationOverlayProvider
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
import kotlinx.coroutines.channels.trySendBlocking
|
import kotlinx.coroutines.channels.trySendBlocking
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
@@ -45,7 +48,9 @@ import kotlinx.coroutines.flow.callbackFlow
|
|||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.coroutines.flow.flow
|
import kotlinx.coroutines.flow.flow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runInterruptible
|
||||||
import okio.IOException
|
import okio.IOException
|
||||||
|
import okio.use
|
||||||
import org.json.JSONException
|
import org.json.JSONException
|
||||||
import org.jsoup.internal.StringUtil.StringJoiner
|
import org.jsoup.internal.StringUtil.StringJoiner
|
||||||
import org.koitharu.kotatsu.BuildConfig
|
import org.koitharu.kotatsu.BuildConfig
|
||||||
@@ -53,6 +58,7 @@ import org.koitharu.kotatsu.R
|
|||||||
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
||||||
import org.xmlpull.v1.XmlPullParser
|
import org.xmlpull.v1.XmlPullParser
|
||||||
import org.xmlpull.v1.XmlPullParserException
|
import org.xmlpull.v1.XmlPullParserException
|
||||||
|
import java.io.File
|
||||||
import kotlin.math.roundToLong
|
import kotlin.math.roundToLong
|
||||||
|
|
||||||
val Context.activityManager: ActivityManager?
|
val Context.activityManager: ActivityManager?
|
||||||
@@ -130,7 +136,7 @@ fun Window.setNavigationBarTransparentCompat(context: Context, elevation: Float,
|
|||||||
} else {
|
} else {
|
||||||
// Set navbar scrim 70% of navigationBarColor
|
// Set navbar scrim 70% of navigationBarColor
|
||||||
ElevationOverlayProvider(context).compositeOverlayIfNeeded(
|
ElevationOverlayProvider(context).compositeOverlayIfNeeded(
|
||||||
context.getThemeColor(android.R.attr.navigationBarColor, alphaFactor),
|
context.getThemeColor(R.attr.m3ColorBottomMenuBackground, alphaFactor),
|
||||||
elevation,
|
elevation,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -230,3 +236,18 @@ fun Context.checkNotificationPermission(): Boolean = if (Build.VERSION.SDK_INT >
|
|||||||
} else {
|
} else {
|
||||||
NotificationManagerCompat.from(this).areNotificationsEnabled()
|
NotificationManagerCompat.from(this).areNotificationsEnabled()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@WorkerThread
|
||||||
|
suspend fun Bitmap.compressToPNG(output: File) = runInterruptible(Dispatchers.IO) {
|
||||||
|
output.outputStream().use { os ->
|
||||||
|
if (!compress(Bitmap.CompressFormat.PNG, 100, os)) {
|
||||||
|
throw IOException("Failed to encode bitmap into PNG format")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Context.ensureRamAtLeast(requiredSize: Long) {
|
||||||
|
if (ramAvailable < requiredSize) {
|
||||||
|
throw IllegalStateException("Not enough free memory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,30 +1,32 @@
|
|||||||
package org.koitharu.kotatsu.core.util.ext
|
package org.koitharu.kotatsu.core.util.ext
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
import org.koitharu.kotatsu.core.ui.model.DateTimeAgo
|
||||||
import android.text.format.DateUtils
|
import java.time.Instant
|
||||||
import java.text.SimpleDateFormat
|
import java.time.LocalDate
|
||||||
import java.util.*
|
import java.time.LocalDateTime
|
||||||
import java.util.concurrent.TimeUnit
|
import java.time.ZoneId
|
||||||
|
import java.time.temporal.ChronoUnit
|
||||||
|
|
||||||
@SuppressLint("SimpleDateFormat")
|
fun calculateTimeAgo(instant: Instant, showMonths: Boolean = false): DateTimeAgo {
|
||||||
fun Date.format(pattern: String): String = SimpleDateFormat(pattern).format(this)
|
// TODO: Use Java 9's LocalDate.ofInstant().
|
||||||
|
val localDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate()
|
||||||
|
val now = LocalDate.now()
|
||||||
|
val diffDays = localDate.until(now, ChronoUnit.DAYS)
|
||||||
|
|
||||||
fun Date.formatRelative(minResolution: Long): CharSequence = DateUtils.getRelativeTimeSpanString(
|
return when {
|
||||||
time, System.currentTimeMillis(), minResolution,
|
diffDays == 0L -> {
|
||||||
)
|
if (instant.until(Instant.now(), ChronoUnit.MINUTES) < 3) DateTimeAgo.JustNow
|
||||||
|
else DateTimeAgo.Today
|
||||||
fun Date.daysDiff(other: Long): Int {
|
}
|
||||||
val thisDay = time / TimeUnit.DAYS.toMillis(1L)
|
diffDays == 1L -> DateTimeAgo.Yesterday
|
||||||
val otherDay = other / TimeUnit.DAYS.toMillis(1L)
|
diffDays < 6 -> DateTimeAgo.DaysAgo(diffDays.toInt())
|
||||||
return (thisDay - otherDay).toInt()
|
else -> {
|
||||||
}
|
val diffMonths = localDate.until(now, ChronoUnit.MONTHS)
|
||||||
|
if (showMonths && diffMonths <= 6) {
|
||||||
fun Date.startOfDay(): Long {
|
DateTimeAgo.MonthsAgo(diffMonths.toInt())
|
||||||
val calendar = Calendar.getInstance()
|
} else {
|
||||||
calendar.time = this
|
DateTimeAgo.Absolute(localDate)
|
||||||
calendar[Calendar.HOUR_OF_DAY] = 0
|
}
|
||||||
calendar[Calendar.MINUTE] = 0
|
}
|
||||||
calendar[Calendar.SECOND] = 0
|
}
|
||||||
calendar[Calendar.MILLISECOND] = 0
|
|
||||||
return calendar.timeInMillis
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,12 +20,13 @@ inline fun <T> LocaleListCompat.mapToSet(block: (Locale) -> T): Set<T> {
|
|||||||
|
|
||||||
fun LocaleListCompat.getOrThrow(index: Int) = get(index) ?: throw NoSuchElementException()
|
fun LocaleListCompat.getOrThrow(index: Int) = get(index) ?: throw NoSuchElementException()
|
||||||
|
|
||||||
fun String?.getLocaleDisplayName(context: Context): String {
|
fun String.toLocale() = Locale(this)
|
||||||
|
|
||||||
|
fun Locale?.getDisplayName(context: Context): String {
|
||||||
if (this == null) {
|
if (this == null) {
|
||||||
return context.getString(R.string.various_languages)
|
return context.getString(R.string.various_languages)
|
||||||
}
|
}
|
||||||
val lc = Locale(this)
|
return getDisplayLanguage(this).toTitleCase(this)
|
||||||
return lc.getDisplayLanguage(lc).toTitleCase(lc)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private class LocaleListCompatIterator(private val list: LocaleListCompat) : ListIterator<Locale> {
|
private class LocaleListCompatIterator(private val list: LocaleListCompat) : ListIterator<Locale> {
|
||||||
|
|||||||
@@ -3,18 +3,18 @@ package org.koitharu.kotatsu.core.util.ext
|
|||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.res.Resources
|
import android.content.res.Resources
|
||||||
import android.util.TypedValue
|
|
||||||
import androidx.annotation.Px
|
import androidx.annotation.Px
|
||||||
|
import androidx.core.util.TypedValueCompat
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
@Px
|
@Px
|
||||||
fun Resources.resolveDp(dp: Int) = (dp * displayMetrics.density).roundToInt()
|
fun Resources.resolveDp(dp: Int) = resolveDp(dp.toFloat()).roundToInt()
|
||||||
|
|
||||||
@Px
|
@Px
|
||||||
fun Resources.resolveDp(dp: Float) = dp * displayMetrics.density
|
fun Resources.resolveDp(dp: Float) = TypedValueCompat.dpToPx(dp, displayMetrics)
|
||||||
|
|
||||||
@Px
|
@Px
|
||||||
fun Resources.resolveSp(sp: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, displayMetrics)
|
fun Resources.resolveSp(sp: Float) = TypedValueCompat.spToPx(sp, displayMetrics)
|
||||||
|
|
||||||
@SuppressLint("DiscouragedApi")
|
@SuppressLint("DiscouragedApi")
|
||||||
fun Context.getSystemBoolean(resName: String, fallback: Boolean): Boolean {
|
fun Context.getSystemBoolean(resName: String, fallback: Boolean): Boolean {
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import android.view.View.MeasureSpec
|
|||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.view.inputmethod.InputMethodManager
|
import android.view.inputmethod.InputMethodManager
|
||||||
import android.widget.Checkable
|
import android.widget.Checkable
|
||||||
|
import androidx.appcompat.widget.ActionMenuView
|
||||||
|
import androidx.appcompat.widget.Toolbar
|
||||||
import androidx.core.view.children
|
import androidx.core.view.children
|
||||||
import androidx.core.view.descendants
|
import androidx.core.view.descendants
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
@@ -153,3 +155,9 @@ fun View.setOnContextClickListenerCompat(listener: View.OnLongClickListener) {
|
|||||||
setOnContextClickListener(listener::onLongClick)
|
setOnContextClickListener(listener::onLongClick)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val Toolbar.menuView: ActionMenuView?
|
||||||
|
get() {
|
||||||
|
menu // to call ensureMenu()
|
||||||
|
return children.firstNotNullOfOrNull { it as? ActionMenuView }
|
||||||
|
}
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ class MangaPrefetchService : CoroutineIntentService() {
|
|||||||
val intent = Intent(context, MangaPrefetchService::class.java)
|
val intent = Intent(context, MangaPrefetchService::class.java)
|
||||||
intent.action = ACTION_PREFETCH_DETAILS
|
intent.action = ACTION_PREFETCH_DETAILS
|
||||||
intent.putExtra(EXTRA_MANGA, ParcelableManga(manga))
|
intent.putExtra(EXTRA_MANGA, ParcelableManga(manga))
|
||||||
context.startService(intent)
|
tryStart(context, intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun prefetchPages(context: Context, chapter: MangaChapter) {
|
fun prefetchPages(context: Context, chapter: MangaChapter) {
|
||||||
@@ -99,19 +99,14 @@ class MangaPrefetchService : CoroutineIntentService() {
|
|||||||
val intent = Intent(context, MangaPrefetchService::class.java)
|
val intent = Intent(context, MangaPrefetchService::class.java)
|
||||||
intent.action = ACTION_PREFETCH_PAGES
|
intent.action = ACTION_PREFETCH_PAGES
|
||||||
intent.putExtra(EXTRA_CHAPTER, ParcelableChapter(chapter))
|
intent.putExtra(EXTRA_CHAPTER, ParcelableChapter(chapter))
|
||||||
try {
|
tryStart(context, intent)
|
||||||
context.startService(intent)
|
|
||||||
} catch (e: IllegalStateException) {
|
|
||||||
// probably app is in background
|
|
||||||
e.printStackTraceDebug()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun prefetchLast(context: Context) {
|
fun prefetchLast(context: Context) {
|
||||||
if (!isPrefetchAvailable(context, null)) return
|
if (!isPrefetchAvailable(context, null)) return
|
||||||
val intent = Intent(context, MangaPrefetchService::class.java)
|
val intent = Intent(context, MangaPrefetchService::class.java)
|
||||||
intent.action = ACTION_PREFETCH_LAST
|
intent.action = ACTION_PREFETCH_LAST
|
||||||
context.startService(intent)
|
tryStart(context, intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isPrefetchAvailable(context: Context, source: MangaSource?): Boolean {
|
private fun isPrefetchAvailable(context: Context, source: MangaSource?): Boolean {
|
||||||
@@ -127,5 +122,14 @@ class MangaPrefetchService : CoroutineIntentService() {
|
|||||||
)
|
)
|
||||||
return entryPoint.contentCache.isCachingEnabled && entryPoint.settings.isContentPrefetchEnabled
|
return entryPoint.contentCache.isCachingEnabled && entryPoint.settings.isContentPrefetchEnabled
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun tryStart(context: Context, intent: Intent) {
|
||||||
|
try {
|
||||||
|
context.startService(intent)
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
// probably app is in background
|
||||||
|
e.printStackTraceDebug()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import android.view.View
|
|||||||
import android.view.View.OnLayoutChangeListener
|
import android.view.View.OnLayoutChangeListener
|
||||||
import androidx.activity.OnBackPressedCallback
|
import androidx.activity.OnBackPressedCallback
|
||||||
import androidx.appcompat.view.ActionMode
|
import androidx.appcompat.view.ActionMode
|
||||||
|
import androidx.viewpager2.widget.ViewPager2
|
||||||
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
||||||
import org.koitharu.kotatsu.core.ui.util.ActionModeListener
|
import org.koitharu.kotatsu.core.ui.util.ActionModeListener
|
||||||
import org.koitharu.kotatsu.core.util.ext.doOnExpansionsChanged
|
import org.koitharu.kotatsu.core.util.ext.doOnExpansionsChanged
|
||||||
|
|
||||||
class ChaptersBottomSheetMediator(
|
class ChaptersBottomSheetMediator(
|
||||||
private val behavior: BottomSheetBehavior<*>,
|
private val behavior: BottomSheetBehavior<*>,
|
||||||
|
private val pager: ViewPager2,
|
||||||
) : OnBackPressedCallback(false),
|
) : OnBackPressedCallback(false),
|
||||||
ActionModeListener,
|
ActionModeListener,
|
||||||
OnLayoutChangeListener, View.OnGenericMotionListener {
|
OnLayoutChangeListener, View.OnGenericMotionListener {
|
||||||
@@ -74,6 +76,7 @@ class ChaptersBottomSheetMediator(
|
|||||||
fun lock() {
|
fun lock() {
|
||||||
lockCounter++
|
lockCounter++
|
||||||
behavior.isDraggable = lockCounter <= 0
|
behavior.isDraggable = lockCounter <= 0
|
||||||
|
pager.isUserInputEnabled = lockCounter <= 0
|
||||||
}
|
}
|
||||||
|
|
||||||
fun unlock() {
|
fun unlock() {
|
||||||
@@ -82,5 +85,6 @@ class ChaptersBottomSheetMediator(
|
|||||||
lockCounter = 0
|
lockCounter = 0
|
||||||
}
|
}
|
||||||
behavior.isDraggable = lockCounter <= 0
|
behavior.isDraggable = lockCounter <= 0
|
||||||
|
pager.isUserInputEnabled = lockCounter <= 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,13 +22,14 @@ import androidx.appcompat.widget.PopupMenu
|
|||||||
import androidx.core.graphics.Insets
|
import androidx.core.graphics.Insets
|
||||||
import androidx.core.text.buildSpannedString
|
import androidx.core.text.buildSpannedString
|
||||||
import androidx.core.text.inSpans
|
import androidx.core.text.inSpans
|
||||||
|
import androidx.core.view.MenuHost
|
||||||
import androidx.core.view.isGone
|
import androidx.core.view.isGone
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
import androidx.core.view.updateLayoutParams
|
import androidx.core.view.updateLayoutParams
|
||||||
import androidx.core.view.updatePadding
|
import androidx.core.view.updatePadding
|
||||||
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
||||||
import com.google.android.material.snackbar.BaseTransientBottomBar
|
|
||||||
import com.google.android.material.snackbar.Snackbar
|
import com.google.android.material.snackbar.Snackbar
|
||||||
|
import com.google.android.material.tabs.TabLayoutMediator
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.flow.FlowCollector
|
import kotlinx.coroutines.flow.FlowCollector
|
||||||
import kotlinx.coroutines.flow.filterNotNull
|
import kotlinx.coroutines.flow.filterNotNull
|
||||||
@@ -37,15 +38,19 @@ import org.koitharu.kotatsu.core.exceptions.resolve.SnackbarErrorObserver
|
|||||||
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
||||||
import org.koitharu.kotatsu.core.os.AppShortcutManager
|
import org.koitharu.kotatsu.core.os.AppShortcutManager
|
||||||
import org.koitharu.kotatsu.core.parser.MangaIntent
|
import org.koitharu.kotatsu.core.parser.MangaIntent
|
||||||
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
import org.koitharu.kotatsu.core.ui.BaseActivity
|
import org.koitharu.kotatsu.core.ui.BaseActivity
|
||||||
import org.koitharu.kotatsu.core.ui.util.MenuInvalidator
|
import org.koitharu.kotatsu.core.ui.util.MenuInvalidator
|
||||||
|
import org.koitharu.kotatsu.core.ui.util.ReversibleActionObserver
|
||||||
import org.koitharu.kotatsu.core.util.ext.doOnExpansionsChanged
|
import org.koitharu.kotatsu.core.util.ext.doOnExpansionsChanged
|
||||||
import org.koitharu.kotatsu.core.util.ext.getAnimationDuration
|
import org.koitharu.kotatsu.core.util.ext.getAnimationDuration
|
||||||
import org.koitharu.kotatsu.core.util.ext.getThemeColor
|
import org.koitharu.kotatsu.core.util.ext.getThemeColor
|
||||||
import org.koitharu.kotatsu.core.util.ext.isAnimationsEnabled
|
import org.koitharu.kotatsu.core.util.ext.isAnimationsEnabled
|
||||||
import org.koitharu.kotatsu.core.util.ext.measureHeight
|
import org.koitharu.kotatsu.core.util.ext.measureHeight
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.menuView
|
||||||
import org.koitharu.kotatsu.core.util.ext.observe
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.recyclerView
|
||||||
import org.koitharu.kotatsu.core.util.ext.setNavigationBarTransparentCompat
|
import org.koitharu.kotatsu.core.util.ext.setNavigationBarTransparentCompat
|
||||||
import org.koitharu.kotatsu.core.util.ext.setNavigationIconSafe
|
import org.koitharu.kotatsu.core.util.ext.setNavigationIconSafe
|
||||||
import org.koitharu.kotatsu.core.util.ext.setOnContextClickListenerCompat
|
import org.koitharu.kotatsu.core.util.ext.setOnContextClickListenerCompat
|
||||||
@@ -54,6 +59,7 @@ import org.koitharu.kotatsu.databinding.ActivityDetailsBinding
|
|||||||
import org.koitharu.kotatsu.details.service.MangaPrefetchService
|
import org.koitharu.kotatsu.details.service.MangaPrefetchService
|
||||||
import org.koitharu.kotatsu.details.ui.model.ChapterListItem
|
import org.koitharu.kotatsu.details.ui.model.ChapterListItem
|
||||||
import org.koitharu.kotatsu.details.ui.model.HistoryInfo
|
import org.koitharu.kotatsu.details.ui.model.HistoryInfo
|
||||||
|
import org.koitharu.kotatsu.details.ui.pager.DetailsPagerAdapter
|
||||||
import org.koitharu.kotatsu.download.ui.worker.DownloadStartedObserver
|
import org.koitharu.kotatsu.download.ui.worker.DownloadStartedObserver
|
||||||
import org.koitharu.kotatsu.main.ui.owners.NoModalBottomSheetOwner
|
import org.koitharu.kotatsu.main.ui.owners.NoModalBottomSheetOwner
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
@@ -74,10 +80,18 @@ class DetailsActivity :
|
|||||||
@Inject
|
@Inject
|
||||||
lateinit var appShortcutManager: AppShortcutManager
|
lateinit var appShortcutManager: AppShortcutManager
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var settings: AppSettings
|
||||||
|
|
||||||
private var buttonTip: WeakReference<ButtonTip>? = null
|
private var buttonTip: WeakReference<ButtonTip>? = null
|
||||||
|
|
||||||
private val viewModel: DetailsViewModel by viewModels()
|
private val viewModel: DetailsViewModel by viewModels()
|
||||||
private lateinit var chaptersMenuProvider: ChaptersMenuProvider
|
|
||||||
|
val secondaryMenuHost: MenuHost
|
||||||
|
get() = viewBinding.toolbarChapters ?: this
|
||||||
|
|
||||||
|
var bottomSheetMediator: ChaptersBottomSheetMediator? = null
|
||||||
|
private set
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
@@ -93,24 +107,22 @@ class DetailsActivity :
|
|||||||
|
|
||||||
if (viewBinding.layoutBottom != null) {
|
if (viewBinding.layoutBottom != null) {
|
||||||
val behavior = BottomSheetBehavior.from(checkNotNull(viewBinding.layoutBottom))
|
val behavior = BottomSheetBehavior.from(checkNotNull(viewBinding.layoutBottom))
|
||||||
val bsMediator = ChaptersBottomSheetMediator(behavior)
|
val bsMediator = ChaptersBottomSheetMediator(behavior, viewBinding.pager)
|
||||||
actionModeDelegate.addListener(bsMediator)
|
actionModeDelegate.addListener(bsMediator)
|
||||||
checkNotNull(viewBinding.layoutBsHeader).addOnLayoutChangeListener(bsMediator)
|
checkNotNull(viewBinding.layoutBsHeader).addOnLayoutChangeListener(bsMediator)
|
||||||
onBackPressedDispatcher.addCallback(bsMediator)
|
onBackPressedDispatcher.addCallback(bsMediator)
|
||||||
chaptersMenuProvider = ChaptersMenuProvider(viewModel, bsMediator)
|
bottomSheetMediator = bsMediator
|
||||||
behavior.doOnExpansionsChanged(::onChaptersSheetStateChanged)
|
behavior.doOnExpansionsChanged(::onChaptersSheetStateChanged)
|
||||||
viewBinding.toolbarChapters?.setNavigationOnClickListener {
|
viewBinding.toolbarChapters?.setNavigationOnClickListener {
|
||||||
behavior.state = BottomSheetBehavior.STATE_COLLAPSED
|
behavior.state = BottomSheetBehavior.STATE_COLLAPSED
|
||||||
}
|
}
|
||||||
viewBinding.toolbarChapters?.setOnGenericMotionListener(bsMediator)
|
viewBinding.toolbarChapters?.setOnGenericMotionListener(bsMediator)
|
||||||
} else {
|
|
||||||
chaptersMenuProvider = ChaptersMenuProvider(viewModel, null)
|
|
||||||
addMenuProvider(chaptersMenuProvider)
|
|
||||||
}
|
}
|
||||||
onBackPressedDispatcher.addCallback(chaptersMenuProvider)
|
initPager()
|
||||||
|
|
||||||
viewModel.manga.filterNotNull().observe(this, ::onMangaUpdated)
|
viewModel.manga.filterNotNull().observe(this, ::onMangaUpdated)
|
||||||
viewModel.onMangaRemoved.observeEvent(this, ::onMangaRemoved)
|
viewModel.onMangaRemoved.observeEvent(this, ::onMangaRemoved)
|
||||||
|
viewModel.newChaptersCount.observe(this, ::onNewChaptersChanged)
|
||||||
viewModel.onError.observeEvent(
|
viewModel.onError.observeEvent(
|
||||||
this,
|
this,
|
||||||
SnackbarErrorObserver(
|
SnackbarErrorObserver(
|
||||||
@@ -124,19 +136,16 @@ class DetailsActivity :
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
viewModel.onShowToast.observeEvent(this) {
|
viewModel.onActionDone.observeEvent(this, ReversibleActionObserver(viewBinding.containerDetails))
|
||||||
makeSnackbar(getString(it), Snackbar.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
viewModel.onShowTip.observeEvent(this) { showTip() }
|
viewModel.onShowTip.observeEvent(this) { showTip() }
|
||||||
viewModel.historyInfo.observe(this, ::onHistoryChanged)
|
viewModel.historyInfo.observe(this, ::onHistoryChanged)
|
||||||
viewModel.selectedBranch.observe(this) {
|
viewModel.selectedBranch.observe(this) {
|
||||||
viewBinding.toolbarChapters?.subtitle = it
|
viewBinding.toolbarChapters?.subtitle = it
|
||||||
viewBinding.textViewSubtitle?.textAndVisible = it
|
viewBinding.textViewSubtitle?.textAndVisible = it
|
||||||
}
|
}
|
||||||
viewModel.isChaptersReversed.observe(
|
val chaptersMenuInvalidator = MenuInvalidator(viewBinding.toolbarChapters ?: this)
|
||||||
this,
|
viewModel.isChaptersReversed.observe(this, chaptersMenuInvalidator)
|
||||||
MenuInvalidator(viewBinding.toolbarChapters ?: this),
|
viewModel.isChaptersEmpty.observe(this, chaptersMenuInvalidator)
|
||||||
)
|
|
||||||
val menuInvalidator = MenuInvalidator(this)
|
val menuInvalidator = MenuInvalidator(this)
|
||||||
viewModel.favouriteCategories.observe(this, menuInvalidator)
|
viewModel.favouriteCategories.observe(this, menuInvalidator)
|
||||||
viewModel.remoteManga.observe(this, menuInvalidator)
|
viewModel.remoteManga.observe(this, menuInvalidator)
|
||||||
@@ -153,7 +162,7 @@ class DetailsActivity :
|
|||||||
DetailsMenuProvider(
|
DetailsMenuProvider(
|
||||||
activity = this,
|
activity = this,
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
snackbarHost = viewBinding.containerChapters,
|
snackbarHost = viewBinding.pager,
|
||||||
appShortcutManager = appShortcutManager,
|
appShortcutManager = appShortcutManager,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -217,12 +226,11 @@ class DetailsActivity :
|
|||||||
TransitionManager.beginDelayedTransition(toolbar, transition)
|
TransitionManager.beginDelayedTransition(toolbar, transition)
|
||||||
}
|
}
|
||||||
if (isExpanded) {
|
if (isExpanded) {
|
||||||
toolbar.addMenuProvider(chaptersMenuProvider)
|
|
||||||
toolbar.setNavigationIconSafe(materialR.drawable.abc_ic_clear_material)
|
toolbar.setNavigationIconSafe(materialR.drawable.abc_ic_clear_material)
|
||||||
} else {
|
} else {
|
||||||
toolbar.removeMenuProvider(chaptersMenuProvider)
|
|
||||||
toolbar.navigationIcon = null
|
toolbar.navigationIcon = null
|
||||||
}
|
}
|
||||||
|
toolbar.menuView?.isVisible = isExpanded
|
||||||
viewBinding.buttonRead.isGone = isExpanded
|
viewBinding.buttonRead.isGone = isExpanded
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,6 +301,18 @@ class DetailsActivity :
|
|||||||
viewBinding.textViewTitle?.text = text
|
viewBinding.textViewTitle?.text = text
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun onNewChaptersChanged(count: Int) {
|
||||||
|
val tab = viewBinding.tabs.getTabAt(0) ?: return
|
||||||
|
if (count == 0) {
|
||||||
|
tab.removeBadge()
|
||||||
|
} else {
|
||||||
|
val badge = tab.orCreateBadge
|
||||||
|
badge.horizontalOffsetWithText = -resources.getDimensionPixelOffset(R.dimen.margin_small)
|
||||||
|
badge.number = count
|
||||||
|
badge.isVisible = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun showBranchPopupMenu(v: View) {
|
private fun showBranchPopupMenu(v: View) {
|
||||||
val menu = PopupMenu(v.context, v)
|
val menu = PopupMenu(v.context, v)
|
||||||
val branches = viewModel.branches.value
|
val branches = viewModel.branches.value
|
||||||
@@ -326,9 +346,8 @@ class DetailsActivity :
|
|||||||
val manga = viewModel.manga.value ?: return
|
val manga = viewModel.manga.value ?: return
|
||||||
val chapterId = viewModel.historyInfo.value.history?.chapterId
|
val chapterId = viewModel.historyInfo.value.history?.chapterId
|
||||||
if (chapterId != null && manga.chapters?.none { x -> x.id == chapterId } == true) {
|
if (chapterId != null && manga.chapters?.none { x -> x.id == chapterId } == true) {
|
||||||
val snackbar =
|
Snackbar.make(viewBinding.containerDetails, R.string.chapter_is_missing, Snackbar.LENGTH_SHORT)
|
||||||
makeSnackbar(getString(R.string.chapter_is_missing), Snackbar.LENGTH_SHORT)
|
.show()
|
||||||
snackbar.show()
|
|
||||||
} else {
|
} else {
|
||||||
startActivity(
|
startActivity(
|
||||||
IntentBuilder(this)
|
IntentBuilder(this)
|
||||||
@@ -343,6 +362,14 @@ class DetailsActivity :
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun initPager() {
|
||||||
|
viewBinding.pager.recyclerView?.isNestedScrollingEnabled = false
|
||||||
|
val adapter = DetailsPagerAdapter(this)
|
||||||
|
viewBinding.pager.adapter = adapter
|
||||||
|
TabLayoutMediator(viewBinding.tabs, viewBinding.pager, adapter).attach()
|
||||||
|
viewBinding.pager.setCurrentItem(settings.defaultDetailsTab, false)
|
||||||
|
}
|
||||||
|
|
||||||
private fun showBottomSheet(isVisible: Boolean) {
|
private fun showBottomSheet(isVisible: Boolean) {
|
||||||
val view = viewBinding.layoutBottom ?: return
|
val view = viewBinding.layoutBottom ?: return
|
||||||
if (view.isVisible == isVisible) return
|
if (view.isVisible == isVisible) return
|
||||||
@@ -353,17 +380,6 @@ class DetailsActivity :
|
|||||||
view.isVisible = isVisible
|
view.isVisible = isVisible
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun makeSnackbar(
|
|
||||||
text: CharSequence,
|
|
||||||
@BaseTransientBottomBar.Duration duration: Int,
|
|
||||||
): Snackbar {
|
|
||||||
val sb = Snackbar.make(viewBinding.containerDetails, text, duration)
|
|
||||||
if (viewBinding.layoutBottom?.isVisible == true) {
|
|
||||||
sb.anchorView = viewBinding.toolbarChapters
|
|
||||||
}
|
|
||||||
return sb
|
|
||||||
}
|
|
||||||
|
|
||||||
private class PrefetchObserver(
|
private class PrefetchObserver(
|
||||||
private val context: Context,
|
private val context: Context,
|
||||||
) : FlowCollector<List<ChapterListItem>?> {
|
) : FlowCollector<List<ChapterListItem>?> {
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ import android.widget.Toast
|
|||||||
import androidx.appcompat.widget.PopupMenu
|
import androidx.appcompat.widget.PopupMenu
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.core.graphics.Insets
|
import androidx.core.graphics.Insets
|
||||||
import androidx.core.text.buildSpannedString
|
|
||||||
import androidx.core.text.color
|
|
||||||
import androidx.core.text.method.LinkMovementMethodCompat
|
import androidx.core.text.method.LinkMovementMethodCompat
|
||||||
import androidx.core.view.isGone
|
import androidx.core.view.isGone
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
@@ -23,13 +21,14 @@ import coil.request.SuccessResult
|
|||||||
import coil.util.CoilUtils
|
import coil.util.CoilUtils
|
||||||
import com.google.android.material.chip.Chip
|
import com.google.android.material.chip.Chip
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.flow.combine
|
|
||||||
import kotlinx.coroutines.flow.filterNotNull
|
import kotlinx.coroutines.flow.filterNotNull
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.bookmarks.domain.Bookmark
|
import org.koitharu.kotatsu.bookmarks.domain.Bookmark
|
||||||
import org.koitharu.kotatsu.bookmarks.ui.adapter.BookmarksAdapter
|
import org.koitharu.kotatsu.bookmarks.ui.adapter.BookmarksAdapter
|
||||||
import org.koitharu.kotatsu.bookmarks.ui.sheet.BookmarksSheet
|
import org.koitharu.kotatsu.bookmarks.ui.sheet.BookmarksSheet
|
||||||
import org.koitharu.kotatsu.core.model.countChaptersByBranch
|
import org.koitharu.kotatsu.core.model.countChaptersByBranch
|
||||||
|
import org.koitharu.kotatsu.core.model.iconResId
|
||||||
|
import org.koitharu.kotatsu.core.model.titleResId
|
||||||
import org.koitharu.kotatsu.core.ui.BaseFragment
|
import org.koitharu.kotatsu.core.ui.BaseFragment
|
||||||
import org.koitharu.kotatsu.core.ui.BaseListAdapter
|
import org.koitharu.kotatsu.core.ui.BaseListAdapter
|
||||||
import org.koitharu.kotatsu.core.ui.image.CoverSizeResolver
|
import org.koitharu.kotatsu.core.ui.image.CoverSizeResolver
|
||||||
@@ -40,7 +39,6 @@ import org.koitharu.kotatsu.core.util.FileSize
|
|||||||
import org.koitharu.kotatsu.core.util.ext.crossfade
|
import org.koitharu.kotatsu.core.util.ext.crossfade
|
||||||
import org.koitharu.kotatsu.core.util.ext.drawableTop
|
import org.koitharu.kotatsu.core.util.ext.drawableTop
|
||||||
import org.koitharu.kotatsu.core.util.ext.enqueueWith
|
import org.koitharu.kotatsu.core.util.ext.enqueueWith
|
||||||
import org.koitharu.kotatsu.core.util.ext.getThemeColor
|
|
||||||
import org.koitharu.kotatsu.core.util.ext.ifNullOrEmpty
|
import org.koitharu.kotatsu.core.util.ext.ifNullOrEmpty
|
||||||
import org.koitharu.kotatsu.core.util.ext.isTextTruncated
|
import org.koitharu.kotatsu.core.util.ext.isTextTruncated
|
||||||
import org.koitharu.kotatsu.core.util.ext.observe
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
@@ -66,7 +64,6 @@ import org.koitharu.kotatsu.list.ui.size.StaticItemSizeResolver
|
|||||||
import org.koitharu.kotatsu.main.ui.owners.NoModalBottomSheetOwner
|
import org.koitharu.kotatsu.main.ui.owners.NoModalBottomSheetOwner
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaState
|
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
import org.koitharu.kotatsu.reader.ui.ReaderActivity
|
import org.koitharu.kotatsu.reader.ui.ReaderActivity
|
||||||
import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblingInfo
|
import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblingInfo
|
||||||
@@ -74,7 +71,6 @@ import org.koitharu.kotatsu.scrobbling.common.ui.selector.ScrobblingSelectorShee
|
|||||||
import org.koitharu.kotatsu.search.ui.MangaListActivity
|
import org.koitharu.kotatsu.search.ui.MangaListActivity
|
||||||
import org.koitharu.kotatsu.search.ui.SearchActivity
|
import org.koitharu.kotatsu.search.ui.SearchActivity
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import com.google.android.material.R as materialR
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class DetailsFragment :
|
class DetailsFragment :
|
||||||
@@ -121,7 +117,7 @@ class DetailsFragment :
|
|||||||
viewModel.description.observe(viewLifecycleOwner, ::onDescriptionChanged)
|
viewModel.description.observe(viewLifecycleOwner, ::onDescriptionChanged)
|
||||||
viewModel.localSize.observe(viewLifecycleOwner, ::onLocalSizeChanged)
|
viewModel.localSize.observe(viewLifecycleOwner, ::onLocalSizeChanged)
|
||||||
viewModel.relatedManga.observe(viewLifecycleOwner, ::onRelatedMangaChanged)
|
viewModel.relatedManga.observe(viewLifecycleOwner, ::onRelatedMangaChanged)
|
||||||
combine(viewModel.chapters, viewModel.newChaptersCount, ::Pair).observe(viewLifecycleOwner, ::onChaptersChanged)
|
viewModel.chapters.observe(viewLifecycleOwner, ::onChaptersChanged)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onItemClick(item: Bookmark, view: View) {
|
override fun onItemClick(item: Bookmark, view: View) {
|
||||||
@@ -181,28 +177,13 @@ class DetailsFragment :
|
|||||||
ratingBar.isVisible = false
|
ratingBar.isVisible = false
|
||||||
}
|
}
|
||||||
|
|
||||||
when (manga.state) {
|
infoLayout.textViewState.apply {
|
||||||
MangaState.FINISHED -> infoLayout.textViewState.apply {
|
manga.state?.let { state ->
|
||||||
textAndVisible = resources.getString(R.string.state_finished)
|
textAndVisible = resources.getString(state.titleResId)
|
||||||
drawableTop = ContextCompat.getDrawable(context, R.drawable.ic_state_finished)
|
drawableTop = ContextCompat.getDrawable(context, state.iconResId)
|
||||||
|
} ?: run {
|
||||||
|
isVisible = false
|
||||||
}
|
}
|
||||||
|
|
||||||
MangaState.ONGOING -> infoLayout.textViewState.apply {
|
|
||||||
textAndVisible = resources.getString(R.string.state_ongoing)
|
|
||||||
drawableTop = ContextCompat.getDrawable(context, R.drawable.ic_state_ongoing)
|
|
||||||
}
|
|
||||||
|
|
||||||
MangaState.ABANDONED -> infoLayout.textViewState.apply {
|
|
||||||
textAndVisible = resources.getString(R.string.state_abandoned)
|
|
||||||
drawableTop = ContextCompat.getDrawable(context, R.drawable.ic_state_abandoned)
|
|
||||||
}
|
|
||||||
|
|
||||||
MangaState.PAUSED -> infoLayout.textViewState.apply {
|
|
||||||
textAndVisible = resources.getString(R.string.state_paused)
|
|
||||||
drawableTop = ContextCompat.getDrawable(context, R.drawable.ic_action_pause)
|
|
||||||
}
|
|
||||||
|
|
||||||
null -> infoLayout.textViewState.isVisible = false
|
|
||||||
}
|
}
|
||||||
if (manga.source == MangaSource.LOCAL) {
|
if (manga.source == MangaSource.LOCAL) {
|
||||||
infoLayout.textViewSource.isVisible = false
|
infoLayout.textViewSource.isVisible = false
|
||||||
@@ -218,8 +199,7 @@ class DetailsFragment :
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onChaptersChanged(data: Pair<List<ChapterListItem>?, Int>) {
|
private fun onChaptersChanged(chapters: List<ChapterListItem>?) {
|
||||||
val (chapters, newChapters) = data
|
|
||||||
val infoLayout = requireViewBinding().infoLayout
|
val infoLayout = requireViewBinding().infoLayout
|
||||||
if (chapters.isNullOrEmpty()) {
|
if (chapters.isNullOrEmpty()) {
|
||||||
infoLayout.textViewChapters.isVisible = false
|
infoLayout.textViewChapters.isVisible = false
|
||||||
@@ -227,19 +207,7 @@ class DetailsFragment :
|
|||||||
val count = chapters.countChaptersByBranch()
|
val count = chapters.countChaptersByBranch()
|
||||||
infoLayout.textViewChapters.isVisible = true
|
infoLayout.textViewChapters.isVisible = true
|
||||||
val chaptersText = resources.getQuantityString(R.plurals.chapters, count, count)
|
val chaptersText = resources.getQuantityString(R.plurals.chapters, count, count)
|
||||||
infoLayout.textViewChapters.text = if (newChapters == 0) {
|
infoLayout.textViewChapters.text = chaptersText
|
||||||
chaptersText
|
|
||||||
} else {
|
|
||||||
buildSpannedString {
|
|
||||||
append(chaptersText)
|
|
||||||
append(' ')
|
|
||||||
color(infoLayout.textViewChapters.context.getThemeColor(materialR.attr.colorError)) {
|
|
||||||
append("(+")
|
|
||||||
append(newChapters.toString())
|
|
||||||
append(')')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.mapLatest
|
|||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.plus
|
import kotlinx.coroutines.plus
|
||||||
|
import okio.FileNotFoundException
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.bookmarks.domain.Bookmark
|
import org.koitharu.kotatsu.bookmarks.domain.Bookmark
|
||||||
import org.koitharu.kotatsu.bookmarks.domain.BookmarksRepository
|
import org.koitharu.kotatsu.bookmarks.domain.BookmarksRepository
|
||||||
@@ -30,6 +31,7 @@ import org.koitharu.kotatsu.core.prefs.AppSettings
|
|||||||
import org.koitharu.kotatsu.core.prefs.ListMode
|
import org.koitharu.kotatsu.core.prefs.ListMode
|
||||||
import org.koitharu.kotatsu.core.prefs.observeAsStateFlow
|
import org.koitharu.kotatsu.core.prefs.observeAsStateFlow
|
||||||
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
||||||
|
import org.koitharu.kotatsu.core.ui.util.ReversibleAction
|
||||||
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
||||||
import org.koitharu.kotatsu.core.util.ext.call
|
import org.koitharu.kotatsu.core.util.ext.call
|
||||||
import org.koitharu.kotatsu.core.util.ext.computeSize
|
import org.koitharu.kotatsu.core.util.ext.computeSize
|
||||||
@@ -53,6 +55,7 @@ import org.koitharu.kotatsu.local.data.LocalStorageChanges
|
|||||||
import org.koitharu.kotatsu.local.domain.DeleteLocalMangaUseCase
|
import org.koitharu.kotatsu.local.domain.DeleteLocalMangaUseCase
|
||||||
import org.koitharu.kotatsu.local.domain.model.LocalManga
|
import org.koitharu.kotatsu.local.domain.model.LocalManga
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
|
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
||||||
import org.koitharu.kotatsu.scrobbling.common.domain.Scrobbler
|
import org.koitharu.kotatsu.scrobbling.common.domain.Scrobbler
|
||||||
import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblingInfo
|
import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblingInfo
|
||||||
import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblingStatus
|
import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblingStatus
|
||||||
@@ -79,7 +82,7 @@ class DetailsViewModel @Inject constructor(
|
|||||||
private val mangaId = intent.mangaId
|
private val mangaId = intent.mangaId
|
||||||
private var loadingJob: Job
|
private var loadingJob: Job
|
||||||
|
|
||||||
val onShowToast = MutableEventFlow<Int>()
|
val onActionDone = MutableEventFlow<ReversibleAction>()
|
||||||
val onShowTip = MutableEventFlow<Unit>()
|
val onShowTip = MutableEventFlow<Unit>()
|
||||||
val onSelectChapter = MutableEventFlow<Long>()
|
val onSelectChapter = MutableEventFlow<Long>()
|
||||||
val onDownloadStarted = MutableEventFlow<Unit>()
|
val onDownloadStarted = MutableEventFlow<Unit>()
|
||||||
@@ -134,8 +137,14 @@ class DetailsViewModel @Inject constructor(
|
|||||||
.map { it?.local }
|
.map { it?.local }
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
.map { local ->
|
.map { local ->
|
||||||
local?.file?.computeSize() ?: 0L
|
if (local != null) {
|
||||||
}.stateIn(viewModelScope + Dispatchers.Default, SharingStarted.WhileSubscribed(), 0)
|
runCatchingCancellable {
|
||||||
|
local.file.computeSize()
|
||||||
|
}.getOrDefault(0L)
|
||||||
|
} else {
|
||||||
|
0L
|
||||||
|
}
|
||||||
|
}.stateIn(viewModelScope + Dispatchers.Default, SharingStarted.WhileSubscribed(5000), 0L)
|
||||||
|
|
||||||
@Deprecated("")
|
@Deprecated("")
|
||||||
val description = details
|
val description = details
|
||||||
@@ -227,7 +236,7 @@ class DetailsViewModel @Inject constructor(
|
|||||||
fun deleteLocal() {
|
fun deleteLocal() {
|
||||||
val m = details.value?.local?.manga
|
val m = details.value?.local?.manga
|
||||||
if (m == null) {
|
if (m == null) {
|
||||||
onShowToast.call(R.string.file_not_found)
|
errorEvent.call(FileNotFoundException())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
launchLoadingJob(Dispatchers.Default) {
|
launchLoadingJob(Dispatchers.Default) {
|
||||||
@@ -239,7 +248,7 @@ class DetailsViewModel @Inject constructor(
|
|||||||
fun removeBookmark(bookmark: Bookmark) {
|
fun removeBookmark(bookmark: Bookmark) {
|
||||||
launchJob(Dispatchers.Default) {
|
launchJob(Dispatchers.Default) {
|
||||||
bookmarksRepository.removeBookmark(bookmark)
|
bookmarksRepository.removeBookmark(bookmark)
|
||||||
onShowToast.call(R.string.bookmark_removed)
|
onActionDone.call(ReversibleAction(R.string.bookmark_removed, null))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package org.koitharu.kotatsu.details.ui.pager
|
||||||
|
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import androidx.fragment.app.FragmentActivity
|
||||||
|
import androidx.viewpager2.adapter.FragmentStateAdapter
|
||||||
|
import com.google.android.material.tabs.TabLayout
|
||||||
|
import com.google.android.material.tabs.TabLayoutMediator
|
||||||
|
import org.koitharu.kotatsu.R
|
||||||
|
import org.koitharu.kotatsu.details.ui.pager.chapters.ChaptersFragment
|
||||||
|
import org.koitharu.kotatsu.details.ui.pager.pages.PagesFragment
|
||||||
|
|
||||||
|
class DetailsPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity),
|
||||||
|
TabLayoutMediator.TabConfigurationStrategy {
|
||||||
|
|
||||||
|
override fun getItemCount(): Int = 2
|
||||||
|
|
||||||
|
override fun createFragment(position: Int): Fragment = when (position) {
|
||||||
|
0 -> ChaptersFragment()
|
||||||
|
1 -> PagesFragment()
|
||||||
|
else -> throw IllegalArgumentException("Invalid position $position")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
|
||||||
|
tab.setText(
|
||||||
|
when (position) {
|
||||||
|
0 -> R.string.chapters
|
||||||
|
1 -> R.string.pages
|
||||||
|
else -> 0
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package org.koitharu.kotatsu.details.ui
|
package org.koitharu.kotatsu.details.ui.pager.chapters
|
||||||
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.Menu
|
import android.view.Menu
|
||||||
@@ -11,6 +10,7 @@ import androidx.appcompat.view.ActionMode
|
|||||||
import androidx.core.graphics.Insets
|
import androidx.core.graphics.Insets
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
import androidx.fragment.app.activityViewModels
|
import androidx.fragment.app.activityViewModels
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
import com.google.android.material.snackbar.Snackbar
|
import com.google.android.material.snackbar.Snackbar
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.ui.BaseFragment
|
import org.koitharu.kotatsu.core.ui.BaseFragment
|
||||||
@@ -20,6 +20,9 @@ import org.koitharu.kotatsu.core.util.RecyclerViewScrollCallback
|
|||||||
import org.koitharu.kotatsu.core.util.ext.observe
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
||||||
import org.koitharu.kotatsu.databinding.FragmentChaptersBinding
|
import org.koitharu.kotatsu.databinding.FragmentChaptersBinding
|
||||||
|
import org.koitharu.kotatsu.details.ui.ChaptersMenuProvider
|
||||||
|
import org.koitharu.kotatsu.details.ui.DetailsActivity
|
||||||
|
import org.koitharu.kotatsu.details.ui.DetailsViewModel
|
||||||
import org.koitharu.kotatsu.details.ui.adapter.ChaptersAdapter
|
import org.koitharu.kotatsu.details.ui.adapter.ChaptersAdapter
|
||||||
import org.koitharu.kotatsu.details.ui.adapter.ChaptersSelectionDecoration
|
import org.koitharu.kotatsu.details.ui.adapter.ChaptersSelectionDecoration
|
||||||
import org.koitharu.kotatsu.details.ui.model.ChapterListItem
|
import org.koitharu.kotatsu.details.ui.model.ChapterListItem
|
||||||
@@ -57,9 +60,6 @@ class ChaptersFragment :
|
|||||||
checkNotNull(selectionController).attachToRecyclerView(this)
|
checkNotNull(selectionController).attachToRecyclerView(this)
|
||||||
setHasFixedSize(true)
|
setHasFixedSize(true)
|
||||||
adapter = chaptersAdapter
|
adapter = chaptersAdapter
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
|
||||||
scrollIndicators = if (resources.getBoolean(R.bool.is_tablet)) 0 else View.SCROLL_INDICATOR_TOP
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
viewModel.isLoading.observe(viewLifecycleOwner, this::onLoadingStateChanged)
|
viewModel.isLoading.observe(viewLifecycleOwner, this::onLoadingStateChanged)
|
||||||
viewModel.chapters.observe(viewLifecycleOwner, this::onChaptersChanged)
|
viewModel.chapters.observe(viewLifecycleOwner, this::onChaptersChanged)
|
||||||
@@ -69,6 +69,12 @@ class ChaptersFragment :
|
|||||||
viewModel.onSelectChapter.observeEvent(viewLifecycleOwner) {
|
viewModel.onSelectChapter.observeEvent(viewLifecycleOwner) {
|
||||||
selectionController?.onItemLongClick(it)
|
selectionController?.onItemLongClick(it)
|
||||||
}
|
}
|
||||||
|
val detailsActivity = activity as? DetailsActivity
|
||||||
|
if (detailsActivity != null) {
|
||||||
|
val menuProvider = ChaptersMenuProvider(viewModel, detailsActivity.bottomSheetMediator)
|
||||||
|
activity?.onBackPressedDispatcher?.addCallback(menuProvider)
|
||||||
|
detailsActivity.secondaryMenuHost.addMenuProvider(menuProvider, viewLifecycleOwner, Lifecycle.State.RESUMED)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroyView() {
|
override fun onDestroyView() {
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package org.koitharu.kotatsu.details.ui.pager.pages
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.graphics.Insets
|
||||||
|
import androidx.core.view.isInvisible
|
||||||
|
import androidx.core.view.isVisible
|
||||||
|
import androidx.fragment.app.activityViewModels
|
||||||
|
import androidx.fragment.app.viewModels
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import coil.ImageLoader
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import org.koitharu.kotatsu.R
|
||||||
|
import org.koitharu.kotatsu.core.exceptions.resolve.SnackbarErrorObserver
|
||||||
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
|
import org.koitharu.kotatsu.core.ui.BaseFragment
|
||||||
|
import org.koitharu.kotatsu.core.ui.list.BoundsScrollListener
|
||||||
|
import org.koitharu.kotatsu.core.ui.list.OnListItemClickListener
|
||||||
|
import org.koitharu.kotatsu.core.util.RecyclerViewScrollCallback
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.showOrHide
|
||||||
|
import org.koitharu.kotatsu.databinding.FragmentPagesBinding
|
||||||
|
import org.koitharu.kotatsu.details.ui.DetailsViewModel
|
||||||
|
import org.koitharu.kotatsu.list.ui.MangaListSpanResolver
|
||||||
|
import org.koitharu.kotatsu.list.ui.adapter.ListItemType
|
||||||
|
import org.koitharu.kotatsu.list.ui.adapter.TypedListSpacingDecoration
|
||||||
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
|
import org.koitharu.kotatsu.reader.ui.ReaderActivity.IntentBuilder
|
||||||
|
import org.koitharu.kotatsu.reader.ui.ReaderState
|
||||||
|
import org.koitharu.kotatsu.reader.ui.thumbnails.PageThumbnail
|
||||||
|
import org.koitharu.kotatsu.reader.ui.thumbnails.adapter.PageThumbnailAdapter
|
||||||
|
import javax.inject.Inject
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class PagesFragment :
|
||||||
|
BaseFragment<FragmentPagesBinding>(),
|
||||||
|
OnListItemClickListener<PageThumbnail> {
|
||||||
|
|
||||||
|
private val detailsViewModel by activityViewModels<DetailsViewModel>()
|
||||||
|
private val viewModel by viewModels<PagesViewModel>()
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var coil: ImageLoader
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var settings: AppSettings
|
||||||
|
|
||||||
|
private var thumbnailsAdapter: PageThumbnailAdapter? = null
|
||||||
|
private var spanResolver: MangaListSpanResolver? = null
|
||||||
|
private var scrollListener: ScrollListener? = null
|
||||||
|
|
||||||
|
private val spanSizeLookup = SpanSizeLookup()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
combine(
|
||||||
|
detailsViewModel.details,
|
||||||
|
detailsViewModel.history,
|
||||||
|
detailsViewModel.selectedBranch,
|
||||||
|
) { details, history, branch ->
|
||||||
|
if (details != null && (details.isLoaded || details.chapters.isNotEmpty())) {
|
||||||
|
PagesViewModel.State(details, history, branch)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}.observe(this, viewModel::updateState)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentPagesBinding {
|
||||||
|
return FragmentPagesBinding.inflate(inflater, container, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onViewBindingCreated(binding: FragmentPagesBinding, savedInstanceState: Bundle?) {
|
||||||
|
super.onViewBindingCreated(binding, savedInstanceState)
|
||||||
|
spanResolver = MangaListSpanResolver(binding.root.resources)
|
||||||
|
thumbnailsAdapter = PageThumbnailAdapter(
|
||||||
|
coil = coil,
|
||||||
|
lifecycleOwner = viewLifecycleOwner,
|
||||||
|
clickListener = this@PagesFragment,
|
||||||
|
)
|
||||||
|
with(binding.recyclerView) {
|
||||||
|
addItemDecoration(TypedListSpacingDecoration(context, false))
|
||||||
|
adapter = thumbnailsAdapter
|
||||||
|
setHasFixedSize(true)
|
||||||
|
addOnLayoutChangeListener(spanResolver)
|
||||||
|
spanResolver?.setGridSize(settings.gridSize / 100f, this)
|
||||||
|
addOnScrollListener(ScrollListener().also { scrollListener = it })
|
||||||
|
(layoutManager as GridLayoutManager).let {
|
||||||
|
it.spanSizeLookup = spanSizeLookup
|
||||||
|
it.spanCount = checkNotNull(spanResolver).spanCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
detailsViewModel.isChaptersEmpty.observe(viewLifecycleOwner, ::onNoChaptersChanged)
|
||||||
|
viewModel.thumbnails.observe(viewLifecycleOwner, ::onThumbnailsChanged)
|
||||||
|
viewModel.onError.observeEvent(viewLifecycleOwner, SnackbarErrorObserver(binding.recyclerView, this))
|
||||||
|
viewModel.isLoading.observe(viewLifecycleOwner) { binding.progressBar.showOrHide(it) }
|
||||||
|
viewModel.isLoadingUp.observe(viewLifecycleOwner) { binding.progressBarTop.showOrHide(it) }
|
||||||
|
viewModel.isLoadingDown.observe(viewLifecycleOwner) { binding.progressBarBottom.showOrHide(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroyView() {
|
||||||
|
spanResolver = null
|
||||||
|
scrollListener = null
|
||||||
|
thumbnailsAdapter = null
|
||||||
|
spanSizeLookup.invalidateCache()
|
||||||
|
super.onDestroyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onWindowInsetsChanged(insets: Insets) = Unit
|
||||||
|
|
||||||
|
override fun onItemClick(item: PageThumbnail, view: View) {
|
||||||
|
val manga = detailsViewModel.manga.value ?: return
|
||||||
|
val state = ReaderState(item.page.chapterId, item.page.index, 0)
|
||||||
|
val intent = IntentBuilder(view.context).manga(manga).state(state).build()
|
||||||
|
startActivity(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun onThumbnailsChanged(list: List<ListModel>) {
|
||||||
|
val adapter = thumbnailsAdapter ?: return
|
||||||
|
if (adapter.itemCount == 0) {
|
||||||
|
var position = list.indexOfFirst { it is PageThumbnail && it.isCurrent }
|
||||||
|
if (position > 0) {
|
||||||
|
val spanCount = spanResolver?.spanCount ?: 0
|
||||||
|
val offset = if (position > spanCount + 1) {
|
||||||
|
(resources.getDimensionPixelSize(R.dimen.manga_list_details_item_height) * 0.6).roundToInt()
|
||||||
|
} else {
|
||||||
|
position = 0
|
||||||
|
0
|
||||||
|
}
|
||||||
|
val scrollCallback = RecyclerViewScrollCallback(requireViewBinding().recyclerView, position, offset)
|
||||||
|
adapter.emit(list)
|
||||||
|
scrollCallback.run()
|
||||||
|
} else {
|
||||||
|
adapter.emit(list)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
adapter.emit(list)
|
||||||
|
}
|
||||||
|
spanSizeLookup.invalidateCache()
|
||||||
|
viewBinding?.recyclerView?.let {
|
||||||
|
scrollListener?.postInvalidate(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onNoChaptersChanged(isNoChapters: Boolean) {
|
||||||
|
with(viewBinding ?: return) {
|
||||||
|
textViewHolder.isVisible = isNoChapters
|
||||||
|
recyclerView.isInvisible = isNoChapters
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class ScrollListener : BoundsScrollListener(3, 3) {
|
||||||
|
|
||||||
|
override fun onScrolledToStart(recyclerView: RecyclerView) {
|
||||||
|
viewModel.loadPrevChapter()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onScrolledToEnd(recyclerView: RecyclerView) {
|
||||||
|
viewModel.loadNextChapter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class SpanSizeLookup : GridLayoutManager.SpanSizeLookup() {
|
||||||
|
|
||||||
|
init {
|
||||||
|
isSpanIndexCacheEnabled = true
|
||||||
|
isSpanGroupIndexCacheEnabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getSpanSize(position: Int): Int {
|
||||||
|
val total = (viewBinding?.recyclerView?.layoutManager as? GridLayoutManager)?.spanCount ?: return 1
|
||||||
|
return when (thumbnailsAdapter?.getItemViewType(position)) {
|
||||||
|
ListItemType.PAGE_THUMB.ordinal -> 1
|
||||||
|
else -> total
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun invalidateCache() {
|
||||||
|
invalidateSpanGroupIndexCache()
|
||||||
|
invalidateSpanIndexCache()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package org.koitharu.kotatsu.details.ui.pager.pages
|
||||||
|
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
|
import org.koitharu.kotatsu.core.model.MangaHistory
|
||||||
|
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.firstNotNull
|
||||||
|
import org.koitharu.kotatsu.details.data.MangaDetails
|
||||||
|
import org.koitharu.kotatsu.list.ui.model.ListHeader
|
||||||
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
|
import org.koitharu.kotatsu.reader.domain.ChaptersLoader
|
||||||
|
import org.koitharu.kotatsu.reader.ui.thumbnails.PageThumbnail
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class PagesViewModel @Inject constructor(
|
||||||
|
private val chaptersLoader: ChaptersLoader,
|
||||||
|
) : BaseViewModel() {
|
||||||
|
|
||||||
|
private var loadingJob: Job? = null
|
||||||
|
private var loadingPrevJob: Job? = null
|
||||||
|
private var loadingNextJob: Job? = null
|
||||||
|
|
||||||
|
private val state = MutableStateFlow<State?>(null)
|
||||||
|
val thumbnails = MutableStateFlow<List<ListModel>>(emptyList())
|
||||||
|
val isLoadingUp = MutableStateFlow(false)
|
||||||
|
val isLoadingDown = MutableStateFlow(false)
|
||||||
|
|
||||||
|
init {
|
||||||
|
loadingJob = launchLoadingJob(Dispatchers.Default) {
|
||||||
|
val firstState = state.firstNotNull()
|
||||||
|
doInit(firstState)
|
||||||
|
launchJob(Dispatchers.Default) {
|
||||||
|
state.collectLatest {
|
||||||
|
if (it != null) {
|
||||||
|
doInit(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateState(newState: State?) {
|
||||||
|
if (newState != null) {
|
||||||
|
state.value = newState
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadPrevChapter() {
|
||||||
|
if (loadingJob?.isActive == true || loadingPrevJob?.isActive == true) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loadingPrevJob = loadPrevNextChapter(isNext = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadNextChapter() {
|
||||||
|
if (loadingJob?.isActive == true || loadingNextJob?.isActive == true) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loadingNextJob = loadPrevNextChapter(isNext = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun doInit(state: State) {
|
||||||
|
chaptersLoader.init(state.details)
|
||||||
|
val initialChapterId = state.history?.chapterId ?: state.details.allChapters.firstOrNull()?.id ?: return
|
||||||
|
if (!chaptersLoader.hasPages(initialChapterId)) {
|
||||||
|
chaptersLoader.loadSingleChapter(initialChapterId)
|
||||||
|
}
|
||||||
|
updateList(state.history)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadPrevNextChapter(isNext: Boolean): Job = launchJob(Dispatchers.Default) {
|
||||||
|
val indicator = if (isNext) isLoadingDown else isLoadingUp
|
||||||
|
indicator.value = true
|
||||||
|
try {
|
||||||
|
val currentState = state.firstNotNull()
|
||||||
|
val currentId = (if (isNext) chaptersLoader.last() else chaptersLoader.first()).chapterId
|
||||||
|
chaptersLoader.loadPrevNextChapter(currentState.details, currentId, isNext)
|
||||||
|
updateList(currentState.history)
|
||||||
|
} finally {
|
||||||
|
indicator.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateList(history: MangaHistory?) {
|
||||||
|
val snapshot = chaptersLoader.snapshot()
|
||||||
|
val pages = buildList(snapshot.size + chaptersLoader.size + 2) {
|
||||||
|
var previousChapterId = 0L
|
||||||
|
for (page in snapshot) {
|
||||||
|
if (page.chapterId != previousChapterId) {
|
||||||
|
chaptersLoader.peekChapter(page.chapterId)?.let {
|
||||||
|
add(ListHeader(it.name))
|
||||||
|
}
|
||||||
|
previousChapterId = page.chapterId
|
||||||
|
}
|
||||||
|
this += PageThumbnail(
|
||||||
|
isCurrent = history?.let {
|
||||||
|
page.chapterId == it.chapterId && page.index == it.page
|
||||||
|
} ?: false,
|
||||||
|
page = page,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
thumbnails.value = pages
|
||||||
|
}
|
||||||
|
|
||||||
|
data class State(
|
||||||
|
val details: MangaDetails,
|
||||||
|
val history: MangaHistory?,
|
||||||
|
val branch: String?
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import androidx.work.Data
|
|||||||
import org.koitharu.kotatsu.history.data.PROGRESS_NONE
|
import org.koitharu.kotatsu.history.data.PROGRESS_NONE
|
||||||
import org.koitharu.kotatsu.local.domain.model.LocalManga
|
import org.koitharu.kotatsu.local.domain.model.LocalManga
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
|
|
||||||
data class DownloadState(
|
data class DownloadState(
|
||||||
val manga: Manga,
|
val manga: Manga,
|
||||||
@@ -72,7 +72,7 @@ data class DownloadState(
|
|||||||
|
|
||||||
fun getEta(data: Data): Long = data.getLong(DATA_ETA, -1L)
|
fun getEta(data: Data): Long = data.getLong(DATA_ETA, -1L)
|
||||||
|
|
||||||
fun getTimestamp(data: Data): Date = Date(data.getLong(DATA_TIMESTAMP, 0L))
|
fun getTimestamp(data: Data): Instant = Instant.ofEpochMilli(data.getLong(DATA_TIMESTAMP, 0L))
|
||||||
|
|
||||||
fun getDownloadedChapters(data: Data): Int = data.getInt(DATA_CHAPTERS, 0)
|
fun getDownloadedChapters(data: Data): Int = data.getInt(DATA_CHAPTERS, 0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import org.koitharu.kotatsu.download.ui.list.chapters.DownloadChapter
|
|||||||
import org.koitharu.kotatsu.list.ui.ListModelDiffCallback
|
import org.koitharu.kotatsu.list.ui.ListModelDiffCallback
|
||||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
data class DownloadItemModel(
|
data class DownloadItemModel(
|
||||||
@@ -21,7 +21,7 @@ data class DownloadItemModel(
|
|||||||
val max: Int,
|
val max: Int,
|
||||||
val progress: Int,
|
val progress: Int,
|
||||||
val eta: Long,
|
val eta: Long,
|
||||||
val timestamp: Date,
|
val timestamp: Instant,
|
||||||
val chaptersDownloaded: Int,
|
val chaptersDownloaded: Int,
|
||||||
val isExpanded: Boolean,
|
val isExpanded: Boolean,
|
||||||
val chapters: StateFlow<List<DownloadChapter>?>,
|
val chapters: StateFlow<List<DownloadChapter>?>,
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ import org.koitharu.kotatsu.core.ui.BaseViewModel
|
|||||||
import org.koitharu.kotatsu.core.ui.model.DateTimeAgo
|
import org.koitharu.kotatsu.core.ui.model.DateTimeAgo
|
||||||
import org.koitharu.kotatsu.core.ui.util.ReversibleAction
|
import org.koitharu.kotatsu.core.ui.util.ReversibleAction
|
||||||
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.calculateTimeAgo
|
||||||
import org.koitharu.kotatsu.core.util.ext.call
|
import org.koitharu.kotatsu.core.util.ext.call
|
||||||
import org.koitharu.kotatsu.core.util.ext.daysDiff
|
|
||||||
import org.koitharu.kotatsu.core.util.ext.isEmpty
|
import org.koitharu.kotatsu.core.util.ext.isEmpty
|
||||||
import org.koitharu.kotatsu.download.domain.DownloadState
|
import org.koitharu.kotatsu.download.domain.DownloadState
|
||||||
import org.koitharu.kotatsu.download.ui.list.chapters.DownloadChapter
|
import org.koitharu.kotatsu.download.ui.list.chapters.DownloadChapter
|
||||||
@@ -44,10 +44,8 @@ import org.koitharu.kotatsu.local.domain.model.LocalManga
|
|||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.util.mapToSet
|
import org.koitharu.kotatsu.parsers.util.mapToSet
|
||||||
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
||||||
import java.util.Date
|
|
||||||
import java.util.LinkedList
|
import java.util.LinkedList
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
@@ -225,7 +223,7 @@ class DownloadsViewModel @Inject constructor(
|
|||||||
WorkInfo.State.ENQUEUED -> queued += item
|
WorkInfo.State.ENQUEUED -> queued += item
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
val date = timeAgo(item.timestamp)
|
val date = calculateTimeAgo(item.timestamp)
|
||||||
if (prevDate != date) {
|
if (prevDate != date) {
|
||||||
destination += ListHeader(date)
|
destination += ListHeader(date)
|
||||||
}
|
}
|
||||||
@@ -275,19 +273,6 @@ class DownloadsViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun timeAgo(date: Date): DateTimeAgo {
|
|
||||||
val diff = (System.currentTimeMillis() - date.time).coerceAtLeast(0L)
|
|
||||||
val diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff).toInt()
|
|
||||||
val diffDays = -date.daysDiff(System.currentTimeMillis())
|
|
||||||
return when {
|
|
||||||
diffMinutes < 3 -> DateTimeAgo.JustNow
|
|
||||||
diffDays < 1 -> DateTimeAgo.Today
|
|
||||||
diffDays == 1 -> DateTimeAgo.Yesterday
|
|
||||||
diffDays < 6 -> DateTimeAgo.DaysAgo(diffDays)
|
|
||||||
else -> DateTimeAgo.Absolute(date)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun emptyStateList() = listOf(
|
private fun emptyStateList() = listOf(
|
||||||
EmptyState(
|
EmptyState(
|
||||||
icon = R.drawable.ic_empty_common,
|
icon = R.drawable.ic_empty_common,
|
||||||
|
|||||||
@@ -76,12 +76,9 @@ class ExploreRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
val list = repository.getList(
|
val list = repository.getList(
|
||||||
offset = 0,
|
offset = 0,
|
||||||
filter = MangaListFilter.Advanced(
|
filter = MangaListFilter.Advanced.Builder(order)
|
||||||
sortOrder = order,
|
.tags(setOfNotNull(tag))
|
||||||
tags = setOfNotNull(tag),
|
.build(),
|
||||||
locale = null,
|
|
||||||
states = emptySet(),
|
|
||||||
),
|
|
||||||
).asArrayList()
|
).asArrayList()
|
||||||
if (settings.isSuggestionsExcludeNsfw) {
|
if (settings.isSuggestionsExcludeNsfw) {
|
||||||
list.removeAll { it.isNsfw }
|
list.removeAll { it.isNsfw }
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ class ExploreFragment :
|
|||||||
override fun onRetryClick(error: Throwable) = Unit
|
override fun onRetryClick(error: Throwable) = Unit
|
||||||
|
|
||||||
override fun onEmptyActionClick() {
|
override fun onEmptyActionClick() {
|
||||||
startActivity(SettingsActivity.newManageSourcesIntent(context ?: return))
|
startActivity(Intent(context ?: return, SourcesCatalogActivity::class.java))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onOpenManga(manga: Manga) {
|
private fun onOpenManga(manga: Manga) {
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import org.koitharu.kotatsu.core.ui.util.ReversibleAction
|
|||||||
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
||||||
import org.koitharu.kotatsu.core.util.ext.call
|
import org.koitharu.kotatsu.core.util.ext.call
|
||||||
import org.koitharu.kotatsu.explore.data.MangaSourcesRepository
|
import org.koitharu.kotatsu.explore.data.MangaSourcesRepository
|
||||||
import org.koitharu.kotatsu.explore.data.SourcesSortOrder
|
|
||||||
import org.koitharu.kotatsu.explore.domain.ExploreRepository
|
import org.koitharu.kotatsu.explore.domain.ExploreRepository
|
||||||
import org.koitharu.kotatsu.explore.ui.model.ExploreButtons
|
import org.koitharu.kotatsu.explore.ui.model.ExploreButtons
|
||||||
import org.koitharu.kotatsu.explore.ui.model.MangaSourceItem
|
import org.koitharu.kotatsu.explore.ui.model.MangaSourceItem
|
||||||
@@ -30,7 +29,6 @@ import org.koitharu.kotatsu.list.ui.model.EmptyHint
|
|||||||
import org.koitharu.kotatsu.list.ui.model.ListHeader
|
import org.koitharu.kotatsu.list.ui.model.ListHeader
|
||||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
||||||
import org.koitharu.kotatsu.list.ui.model.TipModel
|
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
||||||
@@ -56,8 +54,6 @@ class ExploreViewModel @Inject constructor(
|
|||||||
valueProducer = { isSuggestionsEnabled },
|
valueProducer = { isSuggestionsEnabled },
|
||||||
)
|
)
|
||||||
|
|
||||||
val sortOrder = MutableStateFlow(SourcesSortOrder.MANUAL) // TODO
|
|
||||||
|
|
||||||
val onOpenManga = MutableEventFlow<Manga>()
|
val onOpenManga = MutableEventFlow<Manga>()
|
||||||
val onActionDone = MutableEventFlow<ReversibleAction>()
|
val onActionDone = MutableEventFlow<ReversibleAction>()
|
||||||
val onShowSuggestionsTip = MutableEventFlow<Unit>()
|
val onShowSuggestionsTip = MutableEventFlow<Unit>()
|
||||||
@@ -129,31 +125,25 @@ class ExploreViewModel @Inject constructor(
|
|||||||
randomLoading: Boolean,
|
randomLoading: Boolean,
|
||||||
newSources: Set<MangaSource>,
|
newSources: Set<MangaSource>,
|
||||||
): List<ListModel> {
|
): List<ListModel> {
|
||||||
val result = ArrayList<ListModel>(sources.size + 4)
|
val result = ArrayList<ListModel>(sources.size + 3)
|
||||||
result += ExploreButtons(randomLoading)
|
result += ExploreButtons(randomLoading)
|
||||||
if (recommendation != null) {
|
if (recommendation != null) {
|
||||||
result += ListHeader(R.string.suggestions)
|
result += ListHeader(R.string.suggestions)
|
||||||
result += RecommendationsItem(recommendation)
|
result += RecommendationsItem(recommendation)
|
||||||
}
|
}
|
||||||
if (sources.isNotEmpty()) {
|
if (sources.isNotEmpty()) {
|
||||||
result += ListHeader(R.string.remote_sources, R.string.catalog)
|
result += ListHeader(
|
||||||
if (newSources.isNotEmpty()) {
|
textRes = R.string.remote_sources,
|
||||||
result += TipModel(
|
buttonTextRes = R.string.catalog,
|
||||||
key = TIP_NEW_SOURCES,
|
badge = if (newSources.isNotEmpty()) "" else null,
|
||||||
title = R.string.new_sources_text,
|
)
|
||||||
text = R.string.new_sources_text,
|
|
||||||
icon = R.drawable.ic_explore_normal,
|
|
||||||
primaryButtonText = R.string.manage,
|
|
||||||
secondaryButtonText = R.string.discard,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
sources.mapTo(result) { MangaSourceItem(it, isGrid) }
|
sources.mapTo(result) { MangaSourceItem(it, isGrid) }
|
||||||
} else {
|
} else {
|
||||||
result += EmptyHint(
|
result += EmptyHint(
|
||||||
icon = R.drawable.ic_empty_common,
|
icon = R.drawable.ic_empty_common,
|
||||||
textPrimary = R.string.no_manga_sources,
|
textPrimary = R.string.no_manga_sources,
|
||||||
textSecondary = R.string.no_manga_sources_text,
|
textSecondary = R.string.no_manga_sources_text,
|
||||||
actionStringRes = R.string.manage,
|
actionStringRes = R.string.catalog,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import coil.ImageLoader
|
|||||||
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.model.getSummary
|
import org.koitharu.kotatsu.core.model.getSummary
|
||||||
|
import org.koitharu.kotatsu.core.model.getTitle
|
||||||
import org.koitharu.kotatsu.core.parser.favicon.faviconUri
|
import org.koitharu.kotatsu.core.parser.favicon.faviconUri
|
||||||
import org.koitharu.kotatsu.core.ui.image.FaviconDrawable
|
import org.koitharu.kotatsu.core.ui.image.FaviconDrawable
|
||||||
import org.koitharu.kotatsu.core.ui.image.TrimTransformation
|
import org.koitharu.kotatsu.core.ui.image.TrimTransformation
|
||||||
@@ -112,7 +113,7 @@ fun exploreSourceListItemAD(
|
|||||||
binding.root.setOnContextClickListenerCompat(eventListener)
|
binding.root.setOnContextClickListenerCompat(eventListener)
|
||||||
|
|
||||||
bind {
|
bind {
|
||||||
binding.textViewTitle.text = item.source.title
|
binding.textViewTitle.text = item.source.getTitle(context)
|
||||||
binding.textViewSubtitle.text = item.source.getSummary(context)
|
binding.textViewSubtitle.text = item.source.getSummary(context)
|
||||||
val fallbackIcon = FaviconDrawable(context, R.style.FaviconDrawable_Small, item.source.name)
|
val fallbackIcon = FaviconDrawable(context, R.style.FaviconDrawable_Small, item.source.name)
|
||||||
binding.imageViewIcon.newImageRequest(lifecycleOwner, item.source.faviconUri())?.run {
|
binding.imageViewIcon.newImageRequest(lifecycleOwner, item.source.faviconUri())?.run {
|
||||||
@@ -147,7 +148,7 @@ fun exploreSourceGridItemAD(
|
|||||||
binding.root.setOnContextClickListenerCompat(eventListener)
|
binding.root.setOnContextClickListenerCompat(eventListener)
|
||||||
|
|
||||||
bind {
|
bind {
|
||||||
binding.textViewTitle.text = item.source.title
|
binding.textViewTitle.text = item.source.getTitle(context)
|
||||||
val fallbackIcon = FaviconDrawable(context, R.style.FaviconDrawable_Large, item.source.name)
|
val fallbackIcon = FaviconDrawable(context, R.style.FaviconDrawable_Large, item.source.name)
|
||||||
binding.imageViewIcon.newImageRequest(lifecycleOwner, item.source.faviconUri())?.run {
|
binding.imageViewIcon.newImageRequest(lifecycleOwner, item.source.faviconUri())?.run {
|
||||||
fallback(fallbackIcon)
|
fallback(fallbackIcon)
|
||||||
|
|||||||
@@ -4,14 +4,14 @@ import org.koitharu.kotatsu.core.db.entity.toManga
|
|||||||
import org.koitharu.kotatsu.core.db.entity.toMangaTags
|
import org.koitharu.kotatsu.core.db.entity.toMangaTags
|
||||||
import org.koitharu.kotatsu.core.model.FavouriteCategory
|
import org.koitharu.kotatsu.core.model.FavouriteCategory
|
||||||
import org.koitharu.kotatsu.list.domain.ListSortOrder
|
import org.koitharu.kotatsu.list.domain.ListSortOrder
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
|
|
||||||
fun FavouriteCategoryEntity.toFavouriteCategory(id: Long = categoryId.toLong()) = FavouriteCategory(
|
fun FavouriteCategoryEntity.toFavouriteCategory(id: Long = categoryId.toLong()) = FavouriteCategory(
|
||||||
id = id,
|
id = id,
|
||||||
title = title,
|
title = title,
|
||||||
sortKey = sortKey,
|
sortKey = sortKey,
|
||||||
order = ListSortOrder(order, ListSortOrder.NEWEST),
|
order = ListSortOrder(order, ListSortOrder.NEWEST),
|
||||||
createdAt = Date(createdAt),
|
createdAt = Instant.ofEpochMilli(createdAt),
|
||||||
isTrackingEnabled = track,
|
isTrackingEnabled = track,
|
||||||
isVisibleInLibrary = isVisibleInLibrary,
|
isVisibleInLibrary = isVisibleInLibrary,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ abstract class FavouritesDao {
|
|||||||
)
|
)
|
||||||
abstract suspend fun findAll(offset: Int, limit: Int): List<FavouriteManga>
|
abstract suspend fun findAll(offset: Int, limit: Int): List<FavouriteManga>
|
||||||
|
|
||||||
|
@Transaction
|
||||||
|
@Query("SELECT * FROM favourites WHERE deleted_at = 0 ORDER BY created_at DESC LIMIT :limit OFFSET :offset")
|
||||||
|
abstract suspend fun findAllRaw(offset: Int, limit: Int): List<FavouriteManga>
|
||||||
|
|
||||||
@Transaction
|
@Transaction
|
||||||
@Query(
|
@Query(
|
||||||
"SELECT * FROM favourites WHERE category_id = :categoryId AND deleted_at = 0 " +
|
"SELECT * FROM favourites WHERE category_id = :categoryId AND deleted_at = 0 " +
|
||||||
|
|||||||
@@ -65,10 +65,7 @@ fun categoryAD(
|
|||||||
binding.imageViewEdit.setOnClickListener(eventListener)
|
binding.imageViewEdit.setOnClickListener(eventListener)
|
||||||
binding.imageViewHandle.setOnTouchListener(eventListener)
|
binding.imageViewHandle.setOnTouchListener(eventListener)
|
||||||
|
|
||||||
bind { payloads ->
|
bind {
|
||||||
if (payloads.isNotEmpty()) {
|
|
||||||
return@bind
|
|
||||||
}
|
|
||||||
binding.textViewTitle.text = item.category.title
|
binding.textViewTitle.text = item.category.title
|
||||||
binding.textViewSubtitle.text = if (item.mangaCount == 0) {
|
binding.textViewSubtitle.text = if (item.mangaCount == 0) {
|
||||||
getString(R.string.empty)
|
getString(R.string.empty)
|
||||||
|
|||||||
@@ -15,13 +15,13 @@ fun categoriesHeaderAD() = adapterDelegateViewBinding<CategoriesHeaderItem, List
|
|||||||
|
|
||||||
val onClickListener = View.OnClickListener { v ->
|
val onClickListener = View.OnClickListener { v ->
|
||||||
val intent = when (v.id) {
|
val intent = when (v.id) {
|
||||||
R.id.button_create -> FavouritesCategoryEditActivity.newIntent(v.context)
|
R.id.chip_create -> FavouritesCategoryEditActivity.newIntent(v.context)
|
||||||
R.id.button_manage -> FavouriteCategoriesActivity.newIntent(v.context)
|
R.id.chip_manage -> FavouriteCategoriesActivity.newIntent(v.context)
|
||||||
else -> return@OnClickListener
|
else -> return@OnClickListener
|
||||||
}
|
}
|
||||||
v.context.startActivity(intent)
|
v.context.startActivity(intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
binding.buttonCreate.setOnClickListener(onClickListener)
|
binding.chipCreate.setOnClickListener(onClickListener)
|
||||||
binding.buttonManage.setOnClickListener(onClickListener)
|
binding.chipManage.setOnClickListener(onClickListener)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import org.koitharu.kotatsu.list.ui.model.ListModel
|
|||||||
import org.koitharu.kotatsu.list.ui.model.LoadingFooter
|
import org.koitharu.kotatsu.list.ui.model.LoadingFooter
|
||||||
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
||||||
import org.koitharu.kotatsu.list.ui.model.toErrorFooter
|
import org.koitharu.kotatsu.list.ui.model.toErrorFooter
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaListFilter
|
import org.koitharu.kotatsu.parsers.model.MangaListFilter
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaState
|
import org.koitharu.kotatsu.parsers.model.MangaState
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
@@ -67,11 +68,28 @@ class FilterCoordinator @Inject constructor(
|
|||||||
private val coroutineScope = lifecycle.lifecycleScope
|
private val coroutineScope = lifecycle.lifecycleScope
|
||||||
private val repository = mangaRepositoryFactory.create(savedStateHandle.require(RemoteListFragment.ARG_SOURCE))
|
private val repository = mangaRepositoryFactory.create(savedStateHandle.require(RemoteListFragment.ARG_SOURCE))
|
||||||
private val currentState = MutableStateFlow(
|
private val currentState = MutableStateFlow(
|
||||||
MangaListFilter.Advanced(repository.defaultSortOrder, emptySet(), null, emptySet()),
|
MangaListFilter.Advanced(
|
||||||
|
sortOrder = repository.defaultSortOrder,
|
||||||
|
tags = emptySet(),
|
||||||
|
tagsExclude = emptySet(),
|
||||||
|
locale = null,
|
||||||
|
states = emptySet(),
|
||||||
|
contentRating = emptySet(),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
private val localTags = SuspendLazy {
|
private val localTags = SuspendLazy {
|
||||||
dataRepository.findTags(repository.source)
|
dataRepository.findTags(repository.source)
|
||||||
}
|
}
|
||||||
|
private val tagsFlow = flow {
|
||||||
|
val localTags = localTags.get()
|
||||||
|
emit(PendingData(localTags, isLoading = true, error = null))
|
||||||
|
tryLoadTags()
|
||||||
|
.onSuccess { remoteTags ->
|
||||||
|
emit(PendingData(mergeTags(remoteTags, localTags), isLoading = false, error = null))
|
||||||
|
}.onFailure {
|
||||||
|
emit(PendingData(localTags, isLoading = false, error = it))
|
||||||
|
}
|
||||||
|
}.stateIn(coroutineScope, SharingStarted.WhileSubscribed(5000), PendingData(emptySet(), true, null))
|
||||||
private var availableTagsDeferred = loadTagsAsync()
|
private var availableTagsDeferred = loadTagsAsync()
|
||||||
private var availableLocalesDeferred = loadLocalesAsync()
|
private var availableLocalesDeferred = loadLocalesAsync()
|
||||||
private var allTagsLoadJob: Job? = null
|
private var allTagsLoadJob: Job? = null
|
||||||
@@ -96,6 +114,22 @@ class FilterCoordinator @Inject constructor(
|
|||||||
)
|
)
|
||||||
}.stateIn(coroutineScope + Dispatchers.Default, SharingStarted.Lazily, loadingProperty())
|
}.stateIn(coroutineScope + Dispatchers.Default, SharingStarted.Lazily, loadingProperty())
|
||||||
|
|
||||||
|
override val filterTagsExcluded: StateFlow<FilterProperty<MangaTag>> = if (repository.isTagsExclusionSupported) {
|
||||||
|
combine(
|
||||||
|
currentState.distinctUntilChangedBy { it.tagsExclude },
|
||||||
|
getBottomTagsAsFlow(4),
|
||||||
|
) { state, tags ->
|
||||||
|
FilterProperty(
|
||||||
|
availableItems = tags.items.asArrayList(),
|
||||||
|
selectedItems = state.tagsExclude,
|
||||||
|
isLoading = tags.isLoading,
|
||||||
|
error = tags.error,
|
||||||
|
)
|
||||||
|
}.stateIn(coroutineScope + Dispatchers.Default, SharingStarted.Lazily, loadingProperty())
|
||||||
|
} else {
|
||||||
|
MutableStateFlow(emptyProperty())
|
||||||
|
}
|
||||||
|
|
||||||
override val filterSortOrder: StateFlow<FilterProperty<SortOrder>> = combine(
|
override val filterSortOrder: StateFlow<FilterProperty<SortOrder>> = combine(
|
||||||
currentState.distinctUntilChangedBy { it.sortOrder },
|
currentState.distinctUntilChangedBy { it.sortOrder },
|
||||||
flowOf(repository.sortOrders),
|
flowOf(repository.sortOrders),
|
||||||
@@ -120,6 +154,18 @@ class FilterCoordinator @Inject constructor(
|
|||||||
)
|
)
|
||||||
}.stateIn(coroutineScope + Dispatchers.Default, SharingStarted.Lazily, loadingProperty())
|
}.stateIn(coroutineScope + Dispatchers.Default, SharingStarted.Lazily, loadingProperty())
|
||||||
|
|
||||||
|
override val filterContentRating: StateFlow<FilterProperty<ContentRating>> = combine(
|
||||||
|
currentState.distinctUntilChangedBy { it.contentRating },
|
||||||
|
flowOf(repository.contentRatings),
|
||||||
|
) { rating, ratings ->
|
||||||
|
FilterProperty(
|
||||||
|
availableItems = ratings.sortedBy { it.ordinal },
|
||||||
|
selectedItems = rating.contentRating,
|
||||||
|
isLoading = false,
|
||||||
|
error = null,
|
||||||
|
)
|
||||||
|
}.stateIn(coroutineScope + Dispatchers.Default, SharingStarted.Lazily, loadingProperty())
|
||||||
|
|
||||||
override val filterLocale: StateFlow<FilterProperty<Locale?>> = combine(
|
override val filterLocale: StateFlow<FilterProperty<Locale?>> = combine(
|
||||||
currentState.distinctUntilChangedBy { it.locale },
|
currentState.distinctUntilChangedBy { it.locale },
|
||||||
getLocalesAsFlow(),
|
getLocalesAsFlow(),
|
||||||
@@ -187,7 +233,32 @@ class FilterCoordinator @Inject constructor(
|
|||||||
emptySet()
|
emptySet()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
oldValue.copy(tags = newTags)
|
oldValue.copy(
|
||||||
|
tags = newTags,
|
||||||
|
tagsExclude = oldValue.tagsExclude - newTags,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun setTagExcluded(value: MangaTag, addOrRemove: Boolean) {
|
||||||
|
currentState.update { oldValue ->
|
||||||
|
val newTags = if (repository.isMultipleTagsSupported) {
|
||||||
|
if (addOrRemove) {
|
||||||
|
oldValue.tagsExclude + value
|
||||||
|
} else {
|
||||||
|
oldValue.tagsExclude - value
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (addOrRemove) {
|
||||||
|
setOf(value)
|
||||||
|
} else {
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
oldValue.copy(
|
||||||
|
tagsExclude = newTags,
|
||||||
|
tags = oldValue.tags - newTags
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,6 +273,17 @@ class FilterCoordinator @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun setContentRating(value: ContentRating, addOrRemove: Boolean) {
|
||||||
|
currentState.update { oldValue ->
|
||||||
|
val newRating = if (addOrRemove) {
|
||||||
|
oldValue.contentRating + value
|
||||||
|
} else {
|
||||||
|
oldValue.contentRating - value
|
||||||
|
}
|
||||||
|
oldValue.copy(contentRating = newRating)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onListHeaderClick(item: ListHeader, view: View) {
|
override fun onListHeaderClick(item: ListHeader, view: View) {
|
||||||
currentState.update { oldValue ->
|
currentState.update { oldValue ->
|
||||||
oldValue.copy(
|
oldValue.copy(
|
||||||
@@ -224,13 +306,16 @@ class FilterCoordinator @Inject constructor(
|
|||||||
|
|
||||||
fun setTags(tags: Set<MangaTag>) {
|
fun setTags(tags: Set<MangaTag>) {
|
||||||
currentState.update { oldValue ->
|
currentState.update { oldValue ->
|
||||||
oldValue.copy(tags = tags)
|
oldValue.copy(
|
||||||
|
tags = tags,
|
||||||
|
tagsExclude = oldValue.tagsExclude - tags
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun reset() {
|
fun reset() {
|
||||||
currentState.update { oldValue ->
|
currentState.update { oldValue ->
|
||||||
oldValue.copy(oldValue.sortOrder, emptySet(), null, emptySet())
|
MangaListFilter.Advanced.Builder(oldValue.sortOrder).build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,17 +333,6 @@ class FilterCoordinator @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getTagsAsFlow() = flow {
|
|
||||||
val localTags = localTags.get()
|
|
||||||
emit(PendingData(localTags, isLoading = true, error = null))
|
|
||||||
tryLoadTags()
|
|
||||||
.onSuccess { remoteTags ->
|
|
||||||
emit(PendingData(mergeTags(remoteTags, localTags), isLoading = false, error = null))
|
|
||||||
}.onFailure {
|
|
||||||
emit(PendingData(localTags, isLoading = false, error = it))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun getLocalesAsFlow(): Flow<PendingData<Locale>> = flow {
|
private fun getLocalesAsFlow(): Flow<PendingData<Locale>> = flow {
|
||||||
emit(PendingData(emptySet(), isLoading = true, error = null))
|
emit(PendingData(emptySet(), isLoading = true, error = null))
|
||||||
tryLoadLocales()
|
tryLoadLocales()
|
||||||
@@ -277,7 +351,18 @@ class FilterCoordinator @Inject constructor(
|
|||||||
searchRepository.getTagsSuggestion(it).take(limit)
|
searchRepository.getTagsSuggestion(it).take(limit)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
getTagsAsFlow(),
|
tagsFlow,
|
||||||
|
) { suggested, all ->
|
||||||
|
val res = suggested.toMutableList()
|
||||||
|
if (res.size < limit) {
|
||||||
|
res.addAll(all.items.shuffled().take(limit - res.size))
|
||||||
|
}
|
||||||
|
PendingData(res, all.isLoading, all.error.takeIf { res.size < limit })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getBottomTagsAsFlow(limit: Int): Flow<PendingData<MangaTag>> = combine(
|
||||||
|
flow { emit(searchRepository.getRareTags(repository.source, limit)) },
|
||||||
|
tagsFlow,
|
||||||
) { suggested, all ->
|
) { suggested, all ->
|
||||||
val res = suggested.toMutableList()
|
val res = suggested.toMutableList()
|
||||||
if (res.size < limit) {
|
if (res.size < limit) {
|
||||||
@@ -411,6 +496,8 @@ class FilterCoordinator @Inject constructor(
|
|||||||
|
|
||||||
private fun <T> loadingProperty() = FilterProperty<T>(emptyList(), emptySet(), true, null)
|
private fun <T> loadingProperty() = FilterProperty<T>(emptyList(), emptySet(), true, null)
|
||||||
|
|
||||||
|
private fun <T> emptyProperty() = FilterProperty<T>(emptyList(), emptySet(), false, null)
|
||||||
|
|
||||||
private class TagTitleComparator(lc: String?) : Comparator<MangaTag> {
|
private class TagTitleComparator(lc: String?) : Comparator<MangaTag> {
|
||||||
|
|
||||||
private val collator = lc?.let { Collator.getInstance(Locale(it)) }
|
private val collator = lc?.let { Collator.getInstance(Locale(it)) }
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class FilterHeaderFragment : BaseFragment<FragmentFilterHeaderBinding>(), ChipsV
|
|||||||
override fun onChipClick(chip: Chip, data: Any?) {
|
override fun onChipClick(chip: Chip, data: Any?) {
|
||||||
val tag = data as? MangaTag
|
val tag = data as? MangaTag
|
||||||
if (tag == null) {
|
if (tag == null) {
|
||||||
TagsCatalogSheet.show(parentFragmentManager)
|
TagsCatalogSheet.show(parentFragmentManager, isExcludeTag = false)
|
||||||
} else {
|
} else {
|
||||||
filter.setTag(tag, chip.isChecked)
|
filter.setTag(tag, chip.isChecked)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import kotlinx.coroutines.flow.StateFlow
|
|||||||
import org.koitharu.kotatsu.filter.ui.model.FilterHeaderModel
|
import org.koitharu.kotatsu.filter.ui.model.FilterHeaderModel
|
||||||
import org.koitharu.kotatsu.filter.ui.model.FilterProperty
|
import org.koitharu.kotatsu.filter.ui.model.FilterProperty
|
||||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaState
|
import org.koitharu.kotatsu.parsers.model.MangaState
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
import org.koitharu.kotatsu.parsers.model.SortOrder
|
import org.koitharu.kotatsu.parsers.model.SortOrder
|
||||||
@@ -15,10 +16,14 @@ interface MangaFilter : OnFilterChangedListener {
|
|||||||
|
|
||||||
val filterTags: StateFlow<FilterProperty<MangaTag>>
|
val filterTags: StateFlow<FilterProperty<MangaTag>>
|
||||||
|
|
||||||
|
val filterTagsExcluded: StateFlow<FilterProperty<MangaTag>>
|
||||||
|
|
||||||
val filterSortOrder: StateFlow<FilterProperty<SortOrder>>
|
val filterSortOrder: StateFlow<FilterProperty<SortOrder>>
|
||||||
|
|
||||||
val filterState: StateFlow<FilterProperty<MangaState>>
|
val filterState: StateFlow<FilterProperty<MangaState>>
|
||||||
|
|
||||||
|
val filterContentRating: StateFlow<FilterProperty<ContentRating>>
|
||||||
|
|
||||||
val filterLocale: StateFlow<FilterProperty<Locale?>>
|
val filterLocale: StateFlow<FilterProperty<Locale?>>
|
||||||
|
|
||||||
val header: StateFlow<FilterHeaderModel>
|
val header: StateFlow<FilterHeaderModel>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package org.koitharu.kotatsu.filter.ui
|
package org.koitharu.kotatsu.filter.ui
|
||||||
|
|
||||||
import org.koitharu.kotatsu.list.ui.adapter.ListHeaderClickListener
|
import org.koitharu.kotatsu.list.ui.adapter.ListHeaderClickListener
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaState
|
import org.koitharu.kotatsu.parsers.model.MangaState
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
import org.koitharu.kotatsu.parsers.model.SortOrder
|
import org.koitharu.kotatsu.parsers.model.SortOrder
|
||||||
@@ -14,5 +15,9 @@ interface OnFilterChangedListener : ListHeaderClickListener {
|
|||||||
|
|
||||||
fun setTag(value: MangaTag, addOrRemove: Boolean)
|
fun setTag(value: MangaTag, addOrRemove: Boolean)
|
||||||
|
|
||||||
|
fun setTagExcluded(value: MangaTag, addOrRemove: Boolean)
|
||||||
|
|
||||||
fun setState(value: MangaState, addOrRemove: Boolean)
|
fun setState(value: MangaState, addOrRemove: Boolean)
|
||||||
|
|
||||||
|
fun setContentRating(value: ContentRating, addOrRemove: Boolean)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import android.view.ViewGroup
|
|||||||
import android.widget.AdapterView
|
import android.widget.AdapterView
|
||||||
import android.widget.ArrayAdapter
|
import android.widget.ArrayAdapter
|
||||||
import androidx.core.view.isGone
|
import androidx.core.view.isGone
|
||||||
|
import androidx.core.view.updatePadding
|
||||||
import androidx.fragment.app.FragmentManager
|
import androidx.fragment.app.FragmentManager
|
||||||
import com.google.android.material.chip.Chip
|
import com.google.android.material.chip.Chip
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
@@ -17,12 +18,14 @@ import org.koitharu.kotatsu.core.ui.sheet.BaseAdaptiveSheet
|
|||||||
import org.koitharu.kotatsu.core.ui.widgets.ChipsView
|
import org.koitharu.kotatsu.core.ui.widgets.ChipsView
|
||||||
import org.koitharu.kotatsu.core.util.ext.getDisplayMessage
|
import org.koitharu.kotatsu.core.util.ext.getDisplayMessage
|
||||||
import org.koitharu.kotatsu.core.util.ext.observe
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.parentView
|
||||||
import org.koitharu.kotatsu.core.util.ext.showDistinct
|
import org.koitharu.kotatsu.core.util.ext.showDistinct
|
||||||
import org.koitharu.kotatsu.core.util.ext.textAndVisible
|
import org.koitharu.kotatsu.core.util.ext.textAndVisible
|
||||||
import org.koitharu.kotatsu.databinding.SheetFilterBinding
|
import org.koitharu.kotatsu.databinding.SheetFilterBinding
|
||||||
import org.koitharu.kotatsu.filter.ui.FilterOwner
|
import org.koitharu.kotatsu.filter.ui.FilterOwner
|
||||||
import org.koitharu.kotatsu.filter.ui.model.FilterProperty
|
import org.koitharu.kotatsu.filter.ui.model.FilterProperty
|
||||||
import org.koitharu.kotatsu.filter.ui.tags.TagsCatalogSheet
|
import org.koitharu.kotatsu.filter.ui.tags.TagsCatalogSheet
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaState
|
import org.koitharu.kotatsu.parsers.model.MangaState
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
import org.koitharu.kotatsu.parsers.model.SortOrder
|
import org.koitharu.kotatsu.parsers.model.SortOrder
|
||||||
@@ -30,8 +33,9 @@ import org.koitharu.kotatsu.parsers.util.toTitleCase
|
|||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import com.google.android.material.R as materialR
|
import com.google.android.material.R as materialR
|
||||||
|
|
||||||
class FilterSheetFragment :
|
class FilterSheetFragment : BaseAdaptiveSheet<SheetFilterBinding>(),
|
||||||
BaseAdaptiveSheet<SheetFilterBinding>(), AdapterView.OnItemSelectedListener, ChipsView.OnChipClickListener {
|
AdapterView.OnItemSelectedListener,
|
||||||
|
ChipsView.OnChipClickListener {
|
||||||
|
|
||||||
override fun onCreateViewBinding(inflater: LayoutInflater, container: ViewGroup?): SheetFilterBinding {
|
override fun onCreateViewBinding(inflater: LayoutInflater, container: ViewGroup?): SheetFilterBinding {
|
||||||
return SheetFilterBinding.inflate(inflater, container, false)
|
return SheetFilterBinding.inflate(inflater, container, false)
|
||||||
@@ -39,19 +43,26 @@ class FilterSheetFragment :
|
|||||||
|
|
||||||
override fun onViewBindingCreated(binding: SheetFilterBinding, savedInstanceState: Bundle?) {
|
override fun onViewBindingCreated(binding: SheetFilterBinding, savedInstanceState: Bundle?) {
|
||||||
super.onViewBindingCreated(binding, savedInstanceState)
|
super.onViewBindingCreated(binding, savedInstanceState)
|
||||||
if (dialog == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
if (dialog == null) {
|
||||||
binding.scrollView.scrollIndicators = 0
|
binding.layoutBody.updatePadding(top = binding.layoutBody.paddingBottom)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
binding.scrollView.scrollIndicators = 0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
val filter = requireFilter()
|
val filter = requireFilter()
|
||||||
filter.filterSortOrder.observe(viewLifecycleOwner, this::onSortOrderChanged)
|
filter.filterSortOrder.observe(viewLifecycleOwner, this::onSortOrderChanged)
|
||||||
filter.filterLocale.observe(viewLifecycleOwner, this::onLocaleChanged)
|
filter.filterLocale.observe(viewLifecycleOwner, this::onLocaleChanged)
|
||||||
filter.filterTags.observe(viewLifecycleOwner, this::onTagsChanged)
|
filter.filterTags.observe(viewLifecycleOwner, this::onTagsChanged)
|
||||||
|
filter.filterTagsExcluded.observe(viewLifecycleOwner, this::onTagsExcludedChanged)
|
||||||
filter.filterState.observe(viewLifecycleOwner, this::onStateChanged)
|
filter.filterState.observe(viewLifecycleOwner, this::onStateChanged)
|
||||||
|
filter.filterContentRating.observe(viewLifecycleOwner, this::onContentRatingChanged)
|
||||||
|
|
||||||
binding.spinnerLocale.onItemSelectedListener = this
|
binding.spinnerLocale.onItemSelectedListener = this
|
||||||
binding.spinnerOrder.onItemSelectedListener = this
|
binding.spinnerOrder.onItemSelectedListener = this
|
||||||
binding.chipsState.onChipClickListener = this
|
binding.chipsState.onChipClickListener = this
|
||||||
|
binding.chipsContentRating.onChipClickListener = this
|
||||||
binding.chipsGenres.onChipClickListener = this
|
binding.chipsGenres.onChipClickListener = this
|
||||||
|
binding.chipsGenresExclude.onChipClickListener = this
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
|
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
|
||||||
@@ -68,8 +79,14 @@ class FilterSheetFragment :
|
|||||||
val filter = requireFilter()
|
val filter = requireFilter()
|
||||||
when (data) {
|
when (data) {
|
||||||
is MangaState -> filter.setState(data, chip.isChecked)
|
is MangaState -> filter.setState(data, chip.isChecked)
|
||||||
is MangaTag -> filter.setTag(data, chip.isChecked)
|
is MangaTag -> if (chip.parentView?.id == R.id.chips_genresExclude) {
|
||||||
null -> TagsCatalogSheet.show(childFragmentManager)
|
filter.setTagExcluded(data, chip.isChecked)
|
||||||
|
} else {
|
||||||
|
filter.setTag(data, chip.isChecked)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ContentRating -> filter.setContentRating(data, chip.isChecked)
|
||||||
|
null -> TagsCatalogSheet.show(childFragmentManager, chip.parentView?.id == R.id.chips_genresExclude)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,6 +179,51 @@ class FilterSheetFragment :
|
|||||||
b.chipsGenres.setChips(chips)
|
b.chipsGenres.setChips(chips)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun onTagsExcludedChanged(value: FilterProperty<MangaTag>) {
|
||||||
|
val b = viewBinding ?: return
|
||||||
|
b.textViewGenresExcludeTitle.isGone = value.isEmpty()
|
||||||
|
b.chipsGenresExclude.isGone = value.isEmpty()
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val chips = ArrayList<ChipsView.ChipModel>(value.selectedItems.size + value.availableItems.size + 1)
|
||||||
|
value.selectedItems.mapTo(chips) { tag ->
|
||||||
|
ChipsView.ChipModel(
|
||||||
|
tint = 0,
|
||||||
|
title = tag.title,
|
||||||
|
icon = 0,
|
||||||
|
isCheckable = true,
|
||||||
|
isChecked = true,
|
||||||
|
data = tag,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
value.availableItems.mapNotNullTo(chips) { tag ->
|
||||||
|
if (tag !in value.selectedItems) {
|
||||||
|
ChipsView.ChipModel(
|
||||||
|
tint = 0,
|
||||||
|
title = tag.title,
|
||||||
|
icon = 0,
|
||||||
|
isCheckable = true,
|
||||||
|
isChecked = false,
|
||||||
|
data = tag,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chips.add(
|
||||||
|
ChipsView.ChipModel(
|
||||||
|
tint = 0,
|
||||||
|
title = getString(R.string.more),
|
||||||
|
icon = materialR.drawable.abc_ic_menu_overflow_material,
|
||||||
|
isCheckable = false,
|
||||||
|
isChecked = false,
|
||||||
|
data = null,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
b.chipsGenresExclude.setChips(chips)
|
||||||
|
}
|
||||||
|
|
||||||
private fun onStateChanged(value: FilterProperty<MangaState>) {
|
private fun onStateChanged(value: FilterProperty<MangaState>) {
|
||||||
val b = viewBinding ?: return
|
val b = viewBinding ?: return
|
||||||
b.textViewStateTitle.isGone = value.isEmpty()
|
b.textViewStateTitle.isGone = value.isEmpty()
|
||||||
@@ -182,6 +244,26 @@ class FilterSheetFragment :
|
|||||||
b.chipsState.setChips(chips)
|
b.chipsState.setChips(chips)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun onContentRatingChanged(value: FilterProperty<ContentRating>) {
|
||||||
|
val b = viewBinding ?: return
|
||||||
|
b.textViewContentRatingTitle.isGone = value.isEmpty()
|
||||||
|
b.chipsContentRating.isGone = value.isEmpty()
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val chips = value.availableItems.map { contentRating ->
|
||||||
|
ChipsView.ChipModel(
|
||||||
|
tint = 0,
|
||||||
|
title = getString(contentRating.titleResId),
|
||||||
|
icon = 0,
|
||||||
|
isCheckable = true,
|
||||||
|
isChecked = contentRating in value.selectedItems,
|
||||||
|
data = contentRating,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
b.chipsContentRating.setChips(chips)
|
||||||
|
}
|
||||||
|
|
||||||
private fun requireFilter() = (requireActivity() as FilterOwner).filter
|
private fun requireFilter() = (requireActivity() as FilterOwner).filter
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import org.koitharu.kotatsu.core.ui.sheet.AdaptiveSheetCallback
|
|||||||
import org.koitharu.kotatsu.core.ui.sheet.BaseAdaptiveSheet
|
import org.koitharu.kotatsu.core.ui.sheet.BaseAdaptiveSheet
|
||||||
import org.koitharu.kotatsu.core.util.ext.observe
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
import org.koitharu.kotatsu.core.util.ext.showDistinct
|
import org.koitharu.kotatsu.core.util.ext.showDistinct
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.withArgs
|
||||||
import org.koitharu.kotatsu.databinding.SheetTagsBinding
|
import org.koitharu.kotatsu.databinding.SheetTagsBinding
|
||||||
import org.koitharu.kotatsu.filter.ui.FilterOwner
|
import org.koitharu.kotatsu.filter.ui.FilterOwner
|
||||||
import org.koitharu.kotatsu.filter.ui.model.TagCatalogItem
|
import org.koitharu.kotatsu.filter.ui.model.TagCatalogItem
|
||||||
@@ -30,7 +31,10 @@ class TagsCatalogSheet : BaseAdaptiveSheet<SheetTagsBinding>(), OnListItemClickL
|
|||||||
private val viewModel by viewModels<TagsCatalogViewModel>(
|
private val viewModel by viewModels<TagsCatalogViewModel>(
|
||||||
extrasProducer = {
|
extrasProducer = {
|
||||||
defaultViewModelCreationExtras.withCreationCallback<TagsCatalogViewModel.Factory> { factory ->
|
defaultViewModelCreationExtras.withCreationCallback<TagsCatalogViewModel.Factory> { factory ->
|
||||||
factory.create((requireActivity() as FilterOwner).filter)
|
factory.create(
|
||||||
|
filter = (requireActivity() as FilterOwner).filter,
|
||||||
|
isExcludeTag = requireArguments().getBoolean(ARG_EXCLUDE),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -54,8 +58,7 @@ class TagsCatalogSheet : BaseAdaptiveSheet<SheetTagsBinding>(), OnListItemClickL
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onItemClick(item: TagCatalogItem, view: View) {
|
override fun onItemClick(item: TagCatalogItem, view: View) {
|
||||||
val filter = (requireActivity() as FilterOwner).filter
|
viewModel.handleTagClick(item.tag, item.isChecked)
|
||||||
filter.setTag(item.tag, !item.isChecked)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onFocusChange(v: View?, hasFocus: Boolean) {
|
override fun onFocusChange(v: View?, hasFocus: Boolean) {
|
||||||
@@ -90,7 +93,10 @@ class TagsCatalogSheet : BaseAdaptiveSheet<SheetTagsBinding>(), OnListItemClickL
|
|||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
private const val TAG = "TagsCatalogSheet"
|
private const val TAG = "TagsCatalogSheet"
|
||||||
|
private const val ARG_EXCLUDE = "exclude"
|
||||||
|
|
||||||
fun show(fm: FragmentManager) = TagsCatalogSheet().showDistinct(fm, TAG)
|
fun show(fm: FragmentManager, isExcludeTag: Boolean) = TagsCatalogSheet().withArgs(1) {
|
||||||
|
putBoolean(ARG_EXCLUDE, isExcludeTag)
|
||||||
|
}.showDistinct(fm, TAG)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,29 +8,32 @@ import dagger.hilt.android.lifecycle.HiltViewModel
|
|||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.plus
|
import kotlinx.coroutines.plus
|
||||||
import org.koitharu.kotatsu.core.parser.MangaDataRepository
|
|
||||||
import org.koitharu.kotatsu.core.parser.MangaRepository
|
|
||||||
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
||||||
import org.koitharu.kotatsu.filter.ui.MangaFilter
|
import org.koitharu.kotatsu.filter.ui.MangaFilter
|
||||||
|
import org.koitharu.kotatsu.filter.ui.model.FilterProperty
|
||||||
import org.koitharu.kotatsu.filter.ui.model.TagCatalogItem
|
import org.koitharu.kotatsu.filter.ui.model.TagCatalogItem
|
||||||
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
import org.koitharu.kotatsu.list.ui.model.LoadingState
|
||||||
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
|
|
||||||
@HiltViewModel(assistedFactory = TagsCatalogViewModel.Factory::class)
|
@HiltViewModel(assistedFactory = TagsCatalogViewModel.Factory::class)
|
||||||
class TagsCatalogViewModel @AssistedInject constructor(
|
class TagsCatalogViewModel @AssistedInject constructor(
|
||||||
@Assisted filter: MangaFilter,
|
@Assisted private val filter: MangaFilter,
|
||||||
mangaRepositoryFactory: MangaRepository.Factory,
|
@Assisted private val isExcluded: Boolean,
|
||||||
dataRepository: MangaDataRepository,
|
|
||||||
) : BaseViewModel() {
|
) : BaseViewModel() {
|
||||||
|
|
||||||
val searchQuery = MutableStateFlow("")
|
val searchQuery = MutableStateFlow("")
|
||||||
|
|
||||||
|
private val filterProperty: StateFlow<FilterProperty<MangaTag>>
|
||||||
|
get() = if (isExcluded) filter.filterTagsExcluded else filter.filterTags
|
||||||
|
|
||||||
private val tags = combine(
|
private val tags = combine(
|
||||||
filter.allTags,
|
filter.allTags,
|
||||||
filter.filterTags.map { it.selectedItems },
|
filterProperty.map { it.selectedItems },
|
||||||
) { all, selected ->
|
) { all, selected ->
|
||||||
all.map { x ->
|
all.map { x ->
|
||||||
if (x is TagCatalogItem) {
|
if (x is TagCatalogItem) {
|
||||||
@@ -52,9 +55,17 @@ class TagsCatalogViewModel @AssistedInject constructor(
|
|||||||
}
|
}
|
||||||
}.stateIn(viewModelScope + Dispatchers.Default, SharingStarted.Lazily, listOf(LoadingState))
|
}.stateIn(viewModelScope + Dispatchers.Default, SharingStarted.Lazily, listOf(LoadingState))
|
||||||
|
|
||||||
|
fun handleTagClick(tag: MangaTag, isChecked: Boolean) {
|
||||||
|
if (isExcluded) {
|
||||||
|
filter.setTagExcluded(tag, !isChecked)
|
||||||
|
} else {
|
||||||
|
filter.setTag(tag, !isChecked)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@AssistedFactory
|
@AssistedFactory
|
||||||
interface Factory {
|
interface Factory {
|
||||||
fun create(filter: MangaFilter): TagsCatalogViewModel
|
fun create(filter: MangaFilter, isExcludeTag: Boolean): TagsCatalogViewModel
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
package org.koitharu.kotatsu.history.data
|
package org.koitharu.kotatsu.history.data
|
||||||
|
|
||||||
import org.koitharu.kotatsu.core.model.MangaHistory
|
import org.koitharu.kotatsu.core.model.MangaHistory
|
||||||
import java.util.*
|
import java.time.Instant
|
||||||
|
|
||||||
fun HistoryEntity.toMangaHistory() = MangaHistory(
|
fun HistoryEntity.toMangaHistory() = MangaHistory(
|
||||||
createdAt = Date(createdAt),
|
createdAt = Instant.ofEpochMilli(createdAt),
|
||||||
updatedAt = Date(updatedAt),
|
updatedAt = Instant.ofEpochMilli(updatedAt),
|
||||||
chapterId = chapterId,
|
chapterId = chapterId,
|
||||||
page = page,
|
page = page,
|
||||||
scroll = scroll.toInt(),
|
scroll = scroll.toInt(),
|
||||||
percent = percent,
|
percent = percent,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ import androidx.core.view.MenuProvider
|
|||||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.ui.dialog.RememberSelectionDialogListener
|
import org.koitharu.kotatsu.core.ui.dialog.RememberSelectionDialogListener
|
||||||
import org.koitharu.kotatsu.core.util.ext.startOfDay
|
import java.time.Instant
|
||||||
import java.util.Date
|
import java.time.LocalDate
|
||||||
import java.util.concurrent.TimeUnit
|
import java.time.ZoneId
|
||||||
|
import java.time.temporal.ChronoUnit
|
||||||
import com.google.android.material.R as materialR
|
import com.google.android.material.R as materialR
|
||||||
|
|
||||||
class HistoryListMenuProvider(
|
class HistoryListMenuProvider(
|
||||||
@@ -50,9 +51,9 @@ class HistoryListMenuProvider(
|
|||||||
.setNegativeButton(android.R.string.cancel, null)
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
.setPositiveButton(R.string.clear) { _, _ ->
|
.setPositiveButton(R.string.clear) { _, _ ->
|
||||||
val minDate = when (selectionListener.selection) {
|
val minDate = when (selectionListener.selection) {
|
||||||
0 -> System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2)
|
0 -> Instant.now().minus(2, ChronoUnit.HOURS)
|
||||||
1 -> Date().startOfDay()
|
1 -> LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()
|
||||||
2 -> 0L
|
2 -> Instant.EPOCH
|
||||||
else -> return@setPositiveButton
|
else -> return@setPositiveButton
|
||||||
}
|
}
|
||||||
viewModel.clearHistory(minDate)
|
viewModel.clearHistory(minDate)
|
||||||
|
|||||||
@@ -19,10 +19,9 @@ import org.koitharu.kotatsu.core.prefs.AppSettings
|
|||||||
import org.koitharu.kotatsu.core.prefs.ListMode
|
import org.koitharu.kotatsu.core.prefs.ListMode
|
||||||
import org.koitharu.kotatsu.core.prefs.observeAsFlow
|
import org.koitharu.kotatsu.core.prefs.observeAsFlow
|
||||||
import org.koitharu.kotatsu.core.prefs.observeAsStateFlow
|
import org.koitharu.kotatsu.core.prefs.observeAsStateFlow
|
||||||
import org.koitharu.kotatsu.core.ui.model.DateTimeAgo
|
|
||||||
import org.koitharu.kotatsu.core.ui.util.ReversibleAction
|
import org.koitharu.kotatsu.core.ui.util.ReversibleAction
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.calculateTimeAgo
|
||||||
import org.koitharu.kotatsu.core.util.ext.call
|
import org.koitharu.kotatsu.core.util.ext.call
|
||||||
import org.koitharu.kotatsu.core.util.ext.daysDiff
|
|
||||||
import org.koitharu.kotatsu.core.util.ext.onFirst
|
import org.koitharu.kotatsu.core.util.ext.onFirst
|
||||||
import org.koitharu.kotatsu.download.ui.worker.DownloadWorker
|
import org.koitharu.kotatsu.download.ui.worker.DownloadWorker
|
||||||
import org.koitharu.kotatsu.history.data.HistoryRepository
|
import org.koitharu.kotatsu.history.data.HistoryRepository
|
||||||
@@ -40,8 +39,7 @@ import org.koitharu.kotatsu.list.ui.model.toGridModel
|
|||||||
import org.koitharu.kotatsu.list.ui.model.toListDetailedModel
|
import org.koitharu.kotatsu.list.ui.model.toListDetailedModel
|
||||||
import org.koitharu.kotatsu.list.ui.model.toListModel
|
import org.koitharu.kotatsu.list.ui.model.toListModel
|
||||||
import org.koitharu.kotatsu.local.data.LocalMangaRepository
|
import org.koitharu.kotatsu.local.data.LocalMangaRepository
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
@@ -100,13 +98,13 @@ class HistoryListViewModel @Inject constructor(
|
|||||||
|
|
||||||
override fun onRetry() = Unit
|
override fun onRetry() = Unit
|
||||||
|
|
||||||
fun clearHistory(minDate: Long) {
|
fun clearHistory(minDate: Instant) {
|
||||||
launchJob(Dispatchers.Default) {
|
launchJob(Dispatchers.Default) {
|
||||||
val stringRes = if (minDate <= 0) {
|
val stringRes = if (minDate <= Instant.EPOCH) {
|
||||||
repository.clear()
|
repository.clear()
|
||||||
R.string.history_cleared
|
R.string.history_cleared
|
||||||
} else {
|
} else {
|
||||||
repository.deleteAfter(minDate)
|
repository.deleteAfter(minDate.toEpochMilli())
|
||||||
R.string.removed_from_history
|
R.string.removed_from_history
|
||||||
}
|
}
|
||||||
onActionDone.call(ReversibleAction(stringRes, null))
|
onActionDone.call(ReversibleAction(stringRes, null))
|
||||||
@@ -165,8 +163,8 @@ class HistoryListViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun MangaHistory.header(order: ListSortOrder): ListHeader? = when (order) {
|
private fun MangaHistory.header(order: ListSortOrder): ListHeader? = when (order) {
|
||||||
ListSortOrder.UPDATED -> ListHeader(timeAgo(updatedAt))
|
ListSortOrder.UPDATED -> ListHeader(calculateTimeAgo(updatedAt))
|
||||||
ListSortOrder.NEWEST -> ListHeader(timeAgo(createdAt))
|
ListSortOrder.NEWEST -> ListHeader(calculateTimeAgo(createdAt))
|
||||||
ListSortOrder.PROGRESS -> ListHeader(
|
ListSortOrder.PROGRESS -> ListHeader(
|
||||||
when (percent) {
|
when (percent) {
|
||||||
1f -> R.string.status_completed
|
1f -> R.string.status_completed
|
||||||
@@ -181,18 +179,4 @@ class HistoryListViewModel @Inject constructor(
|
|||||||
ListSortOrder.NEW_CHAPTERS,
|
ListSortOrder.NEW_CHAPTERS,
|
||||||
ListSortOrder.RATING -> null
|
ListSortOrder.RATING -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun timeAgo(date: Date): DateTimeAgo {
|
|
||||||
val diff = (System.currentTimeMillis() - date.time).coerceAtLeast(0L)
|
|
||||||
val diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff).toInt()
|
|
||||||
val diffDays = -date.daysDiff(System.currentTimeMillis())
|
|
||||||
return when {
|
|
||||||
diffMinutes < 3 -> DateTimeAgo.JustNow
|
|
||||||
diffDays < 1 -> DateTimeAgo.Today
|
|
||||||
diffDays == 1 -> DateTimeAgo.Yesterday
|
|
||||||
diffDays < 6 -> DateTimeAgo.DaysAgo(diffDays)
|
|
||||||
diffDays < 200 -> DateTimeAgo.MonthsAgo(diffDays / 30)
|
|
||||||
else -> DateTimeAgo.LongAgo
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -171,6 +171,9 @@ abstract class MangaListFragment :
|
|||||||
private suspend fun onListChanged(list: List<ListModel>) {
|
private suspend fun onListChanged(list: List<ListModel>) {
|
||||||
listAdapter?.emit(list)
|
listAdapter?.emit(list)
|
||||||
spanSizeLookup.invalidateCache()
|
spanSizeLookup.invalidateCache()
|
||||||
|
viewBinding?.recyclerView?.let {
|
||||||
|
paginationListener?.postInvalidate(it)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resolveException(e: Throwable) {
|
private fun resolveException(e: Throwable) {
|
||||||
|
|||||||
@@ -14,22 +14,37 @@ import com.google.android.material.R as materialR
|
|||||||
|
|
||||||
@CheckResult
|
@CheckResult
|
||||||
fun View.bindBadge(badge: BadgeDrawable?, counter: Int): BadgeDrawable? {
|
fun View.bindBadge(badge: BadgeDrawable?, counter: Int): BadgeDrawable? {
|
||||||
return if (counter > 0) {
|
return bindBadgeImpl(badge, null, counter)
|
||||||
val badgeDrawable = badge ?: initBadge(this)
|
}
|
||||||
badgeDrawable.number = counter
|
|
||||||
badgeDrawable.isVisible = true
|
@CheckResult
|
||||||
badgeDrawable.align(this)
|
fun View.bindBadge(badge: BadgeDrawable?, text: String?): BadgeDrawable? {
|
||||||
badgeDrawable
|
return bindBadgeImpl(badge, text, 0)
|
||||||
} else {
|
|
||||||
badge?.isVisible = false
|
|
||||||
badge
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun View.clearBadge(badge: BadgeDrawable?) {
|
fun View.clearBadge(badge: BadgeDrawable?) {
|
||||||
BadgeUtils.detachBadgeDrawable(badge, this)
|
BadgeUtils.detachBadgeDrawable(badge, this)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun View.bindBadgeImpl(
|
||||||
|
badge: BadgeDrawable?,
|
||||||
|
text: String?,
|
||||||
|
counter: Int,
|
||||||
|
): BadgeDrawable? = if (text != null || counter > 0) {
|
||||||
|
val badgeDrawable = badge ?: initBadge(this)
|
||||||
|
if (counter > 0) {
|
||||||
|
badgeDrawable.number = counter
|
||||||
|
} else {
|
||||||
|
badgeDrawable.text = text?.takeUnless { it.isEmpty() }
|
||||||
|
}
|
||||||
|
badgeDrawable.isVisible = true
|
||||||
|
badgeDrawable.align(this)
|
||||||
|
badgeDrawable
|
||||||
|
} else {
|
||||||
|
badge?.isVisible = false
|
||||||
|
badge
|
||||||
|
}
|
||||||
|
|
||||||
private fun initBadge(anchor: View): BadgeDrawable {
|
private fun initBadge(anchor: View): BadgeDrawable {
|
||||||
val badge = BadgeDrawable.create(anchor.context)
|
val badge = BadgeDrawable.create(anchor.context)
|
||||||
val resources = anchor.resources
|
val resources = anchor.resources
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package org.koitharu.kotatsu.list.ui.adapter
|
|||||||
|
|
||||||
import androidx.core.view.isInvisible
|
import androidx.core.view.isInvisible
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
|
import com.google.android.material.badge.BadgeDrawable
|
||||||
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
||||||
import org.koitharu.kotatsu.databinding.ItemHeaderButtonBinding
|
import org.koitharu.kotatsu.databinding.ItemHeaderButtonBinding
|
||||||
import org.koitharu.kotatsu.list.ui.model.ListHeader
|
import org.koitharu.kotatsu.list.ui.model.ListHeader
|
||||||
@@ -12,6 +13,8 @@ fun listHeaderAD(
|
|||||||
) = adapterDelegateViewBinding<ListHeader, ListModel, ItemHeaderButtonBinding>(
|
) = adapterDelegateViewBinding<ListHeader, ListModel, ItemHeaderButtonBinding>(
|
||||||
{ inflater, parent -> ItemHeaderButtonBinding.inflate(inflater, parent, false) },
|
{ inflater, parent -> ItemHeaderButtonBinding.inflate(inflater, parent, false) },
|
||||||
) {
|
) {
|
||||||
|
var badge: BadgeDrawable? = null
|
||||||
|
|
||||||
if (listener != null) {
|
if (listener != null) {
|
||||||
binding.buttonMore.setOnClickListener {
|
binding.buttonMore.setOnClickListener {
|
||||||
listener.onListHeaderClick(item, it)
|
listener.onListHeaderClick(item, it)
|
||||||
@@ -23,9 +26,11 @@ fun listHeaderAD(
|
|||||||
if (item.buttonTextRes == 0) {
|
if (item.buttonTextRes == 0) {
|
||||||
binding.buttonMore.isInvisible = true
|
binding.buttonMore.isInvisible = true
|
||||||
binding.buttonMore.text = null
|
binding.buttonMore.text = null
|
||||||
|
binding.buttonMore.clearBadge(badge)
|
||||||
} else {
|
} else {
|
||||||
binding.buttonMore.setText(item.buttonTextRes)
|
binding.buttonMore.setText(item.buttonTextRes)
|
||||||
binding.buttonMore.isVisible = true
|
binding.buttonMore.isVisible = true
|
||||||
|
badge = itemView.bindBadge(badge, item.badge)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,38 +6,41 @@ import org.koitharu.kotatsu.core.ui.model.DateTimeAgo
|
|||||||
|
|
||||||
@Suppress("DataClassPrivateConstructor")
|
@Suppress("DataClassPrivateConstructor")
|
||||||
data class ListHeader private constructor(
|
data class ListHeader private constructor(
|
||||||
private val text: CharSequence?,
|
private val textRaw: Any,
|
||||||
@StringRes private val textRes: Int,
|
|
||||||
private val dateTimeAgo: DateTimeAgo?,
|
|
||||||
@StringRes val buttonTextRes: Int,
|
@StringRes val buttonTextRes: Int,
|
||||||
val payload: Any?,
|
val payload: Any?,
|
||||||
|
val badge: String?,
|
||||||
) : ListModel {
|
) : ListModel {
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
text: CharSequence,
|
text: CharSequence,
|
||||||
@StringRes buttonTextRes: Int = 0,
|
@StringRes buttonTextRes: Int = 0,
|
||||||
payload: Any? = null,
|
payload: Any? = null,
|
||||||
) : this(text, 0, null, buttonTextRes, payload)
|
badge: String? = null,
|
||||||
|
) : this(textRaw = text, buttonTextRes, payload, badge)
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@StringRes textRes: Int,
|
@StringRes textRes: Int,
|
||||||
@StringRes buttonTextRes: Int = 0,
|
@StringRes buttonTextRes: Int = 0,
|
||||||
payload: Any? = null,
|
payload: Any? = null,
|
||||||
) : this(null, textRes, null, buttonTextRes, payload)
|
badge: String? = null,
|
||||||
|
) : this(textRaw = textRes, buttonTextRes, payload, badge)
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
dateTimeAgo: DateTimeAgo,
|
dateTimeAgo: DateTimeAgo,
|
||||||
@StringRes buttonTextRes: Int = 0,
|
@StringRes buttonTextRes: Int = 0,
|
||||||
payload: Any? = null,
|
payload: Any? = null,
|
||||||
) : this(null, 0, dateTimeAgo, buttonTextRes, payload)
|
badge: String? = null,
|
||||||
|
) : this(textRaw = dateTimeAgo, buttonTextRes, payload, badge)
|
||||||
|
|
||||||
fun getText(context: Context): CharSequence? = when {
|
fun getText(context: Context): CharSequence? = when (textRaw) {
|
||||||
text != null -> text
|
is CharSequence -> textRaw
|
||||||
textRes != 0 -> context.getString(textRes)
|
is Int -> if (textRaw != 0) context.getString(textRaw) else null
|
||||||
else -> dateTimeAgo?.format(context.resources)
|
is DateTimeAgo -> textRaw.format(context.resources)
|
||||||
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun areItemsTheSame(other: ListModel): Boolean {
|
override fun areItemsTheSame(other: ListModel): Boolean {
|
||||||
return other is ListHeader && text == other.text && dateTimeAgo == other.dateTimeAgo && textRes == other.textRes
|
return other is ListHeader && textRaw == other.textRaw
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import org.koitharu.kotatsu.filter.ui.FilterOwner
|
|||||||
import org.koitharu.kotatsu.image.ui.ImageActivity
|
import org.koitharu.kotatsu.image.ui.ImageActivity
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
|
import org.koitharu.kotatsu.reader.ui.ReaderActivity
|
||||||
import org.koitharu.kotatsu.search.ui.MangaListActivity
|
import org.koitharu.kotatsu.search.ui.MangaListActivity
|
||||||
import org.koitharu.kotatsu.search.ui.SearchActivity
|
import org.koitharu.kotatsu.search.ui.SearchActivity
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -56,8 +57,10 @@ class PreviewFragment : BaseFragment<FragmentPreviewBinding>(), View.OnClickList
|
|||||||
binding.textViewAuthor.setOnClickListener(this)
|
binding.textViewAuthor.setOnClickListener(this)
|
||||||
binding.imageViewCover.setOnClickListener(this)
|
binding.imageViewCover.setOnClickListener(this)
|
||||||
binding.buttonOpen.setOnClickListener(this)
|
binding.buttonOpen.setOnClickListener(this)
|
||||||
|
binding.buttonRead.setOnClickListener(this)
|
||||||
|
|
||||||
viewModel.manga.observe(viewLifecycleOwner, ::onMangaUpdated)
|
viewModel.manga.observe(viewLifecycleOwner, ::onMangaUpdated)
|
||||||
|
viewModel.footer.observe(viewLifecycleOwner, ::onFooterUpdated)
|
||||||
viewModel.tagsChips.observe(viewLifecycleOwner, ::onTagsChipsChanged)
|
viewModel.tagsChips.observe(viewLifecycleOwner, ::onTagsChipsChanged)
|
||||||
viewModel.description.observe(viewLifecycleOwner, ::onDescriptionChanged)
|
viewModel.description.observe(viewLifecycleOwner, ::onDescriptionChanged)
|
||||||
}
|
}
|
||||||
@@ -70,6 +73,14 @@ class PreviewFragment : BaseFragment<FragmentPreviewBinding>(), View.OnClickList
|
|||||||
DetailsActivity.newIntent(v.context, manga),
|
DetailsActivity.newIntent(v.context, manga),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
R.id.button_read -> {
|
||||||
|
startActivity(
|
||||||
|
ReaderActivity.IntentBuilder(v.context)
|
||||||
|
.manga(manga)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
R.id.textView_author -> startActivity(
|
R.id.textView_author -> startActivity(
|
||||||
SearchActivity.newIntent(
|
SearchActivity.newIntent(
|
||||||
context = v.context,
|
context = v.context,
|
||||||
@@ -118,6 +129,43 @@ class PreviewFragment : BaseFragment<FragmentPreviewBinding>(), View.OnClickList
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun onFooterUpdated(footer: PreviewViewModel.FooterInfo?) {
|
||||||
|
with(requireViewBinding()) {
|
||||||
|
toolbarBottom.isVisible = footer != null
|
||||||
|
if (footer == null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toolbarBottom.title = when {
|
||||||
|
footer.isInProgress() -> {
|
||||||
|
getString(R.string.chapter_d_of_d, footer.currentChapter, footer.totalChapters)
|
||||||
|
}
|
||||||
|
|
||||||
|
footer.totalChapters > 0 -> {
|
||||||
|
resources.getQuantityString(R.plurals.chapters, footer.totalChapters, footer.totalChapters)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
getString(R.string.no_chapters)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buttonRead.isEnabled = footer.totalChapters > 0
|
||||||
|
buttonRead.setIconResource(
|
||||||
|
when {
|
||||||
|
footer.isIncognito -> R.drawable.ic_incognito
|
||||||
|
footer.isInProgress() -> R.drawable.ic_play
|
||||||
|
else -> R.drawable.ic_read
|
||||||
|
},
|
||||||
|
)
|
||||||
|
buttonRead.setText(
|
||||||
|
if (footer.isInProgress()) {
|
||||||
|
R.string._continue
|
||||||
|
} else {
|
||||||
|
R.string.read
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun onDescriptionChanged(description: CharSequence?) {
|
private fun onDescriptionChanged(description: CharSequence?) {
|
||||||
val tv = viewBinding?.textViewDescription ?: return
|
val tv = viewBinding?.textViewDescription ?: return
|
||||||
when {
|
when {
|
||||||
|
|||||||
@@ -13,11 +13,14 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.coroutines.flow.distinctUntilChangedBy
|
import kotlinx.coroutines.flow.distinctUntilChangedBy
|
||||||
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.transformLatest
|
import kotlinx.coroutines.flow.transformLatest
|
||||||
import kotlinx.coroutines.plus
|
import kotlinx.coroutines.plus
|
||||||
|
import org.koitharu.kotatsu.core.model.getPreferredBranch
|
||||||
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
||||||
import org.koitharu.kotatsu.core.parser.MangaIntent
|
import org.koitharu.kotatsu.core.parser.MangaIntent
|
||||||
import org.koitharu.kotatsu.core.parser.MangaRepository
|
import org.koitharu.kotatsu.core.parser.MangaRepository
|
||||||
@@ -25,6 +28,7 @@ import org.koitharu.kotatsu.core.ui.BaseViewModel
|
|||||||
import org.koitharu.kotatsu.core.ui.widgets.ChipsView
|
import org.koitharu.kotatsu.core.ui.widgets.ChipsView
|
||||||
import org.koitharu.kotatsu.core.util.ext.require
|
import org.koitharu.kotatsu.core.util.ext.require
|
||||||
import org.koitharu.kotatsu.core.util.ext.sanitize
|
import org.koitharu.kotatsu.core.util.ext.sanitize
|
||||||
|
import org.koitharu.kotatsu.history.data.HistoryRepository
|
||||||
import org.koitharu.kotatsu.list.domain.ListExtraProvider
|
import org.koitharu.kotatsu.list.domain.ListExtraProvider
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -33,6 +37,7 @@ class PreviewViewModel @Inject constructor(
|
|||||||
savedStateHandle: SavedStateHandle,
|
savedStateHandle: SavedStateHandle,
|
||||||
private val extraProvider: ListExtraProvider,
|
private val extraProvider: ListExtraProvider,
|
||||||
private val repositoryFactory: MangaRepository.Factory,
|
private val repositoryFactory: MangaRepository.Factory,
|
||||||
|
private val historyRepository: HistoryRepository,
|
||||||
private val imageGetter: Html.ImageGetter,
|
private val imageGetter: Html.ImageGetter,
|
||||||
) : BaseViewModel() {
|
) : BaseViewModel() {
|
||||||
|
|
||||||
@@ -40,6 +45,26 @@ class PreviewViewModel @Inject constructor(
|
|||||||
savedStateHandle.require<ParcelableManga>(MangaIntent.KEY_MANGA).manga,
|
savedStateHandle.require<ParcelableManga>(MangaIntent.KEY_MANGA).manga,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val footer = combine(
|
||||||
|
manga,
|
||||||
|
historyRepository.observeOne(manga.value.id),
|
||||||
|
manga.flatMapLatest { historyRepository.observeShouldSkip(it) }.distinctUntilChanged(),
|
||||||
|
) { m, history, incognito ->
|
||||||
|
if (m.chapters == null) {
|
||||||
|
return@combine null
|
||||||
|
}
|
||||||
|
val b = m.getPreferredBranch(history)
|
||||||
|
val chapters = m.getChapters(b).orEmpty()
|
||||||
|
FooterInfo(
|
||||||
|
branch = b,
|
||||||
|
currentChapter = history?.chapterId?.let {
|
||||||
|
chapters.indexOfFirst { x -> x.id == it }
|
||||||
|
} ?: -1,
|
||||||
|
totalChapters = chapters.size,
|
||||||
|
isIncognito = incognito,
|
||||||
|
)
|
||||||
|
}.stateIn(viewModelScope + Dispatchers.Default, SharingStarted.Lazily, null)
|
||||||
|
|
||||||
val description = manga
|
val description = manga
|
||||||
.distinctUntilChangedBy { it.description.orEmpty() }
|
.distinctUntilChangedBy { it.description.orEmpty() }
|
||||||
.transformLatest {
|
.transformLatest {
|
||||||
@@ -82,4 +107,14 @@ class PreviewViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
return spannable.trim()
|
return spannable.trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
data class FooterInfo(
|
||||||
|
val branch: String?,
|
||||||
|
val currentChapter: Int,
|
||||||
|
val totalChapters: Int,
|
||||||
|
val isIncognito: Boolean,
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun isInProgress() = currentChapter >= 0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import org.koitharu.kotatsu.local.data.input.LocalMangaInput
|
|||||||
import org.koitharu.kotatsu.local.data.output.LocalMangaOutput
|
import org.koitharu.kotatsu.local.data.output.LocalMangaOutput
|
||||||
import org.koitharu.kotatsu.local.data.output.LocalMangaUtil
|
import org.koitharu.kotatsu.local.data.output.LocalMangaUtil
|
||||||
import org.koitharu.kotatsu.local.domain.model.LocalManga
|
import org.koitharu.kotatsu.local.domain.model.LocalManga
|
||||||
|
import org.koitharu.kotatsu.parsers.model.ContentRating
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaListFilter
|
import org.koitharu.kotatsu.parsers.model.MangaListFilter
|
||||||
@@ -52,8 +53,11 @@ class LocalMangaRepository @Inject constructor(
|
|||||||
private val locks = CompositeMutex2<Long>()
|
private val locks = CompositeMutex2<Long>()
|
||||||
|
|
||||||
override val isMultipleTagsSupported: Boolean = true
|
override val isMultipleTagsSupported: Boolean = true
|
||||||
|
override val isTagsExclusionSupported: Boolean = true
|
||||||
|
override val isSearchSupported: Boolean = true
|
||||||
override val sortOrders: Set<SortOrder> = EnumSet.of(SortOrder.ALPHABETICAL, SortOrder.RATING, SortOrder.NEWEST)
|
override val sortOrders: Set<SortOrder> = EnumSet.of(SortOrder.ALPHABETICAL, SortOrder.RATING, SortOrder.NEWEST)
|
||||||
override val states = emptySet<MangaState>()
|
override val states = emptySet<MangaState>()
|
||||||
|
override val contentRatings = emptySet<ContentRating>()
|
||||||
|
|
||||||
override var defaultSortOrder: SortOrder
|
override var defaultSortOrder: SortOrder
|
||||||
get() = settings.localListOrder
|
get() = settings.localListOrder
|
||||||
@@ -75,6 +79,9 @@ class LocalMangaRepository @Inject constructor(
|
|||||||
if (filter.tags.isNotEmpty()) {
|
if (filter.tags.isNotEmpty()) {
|
||||||
list.retainAll { x -> x.containsTags(filter.tags) }
|
list.retainAll { x -> x.containsTags(filter.tags) }
|
||||||
}
|
}
|
||||||
|
if (filter.tagsExclude.isNotEmpty()) {
|
||||||
|
list.removeAll { x -> x.containsAnyTag(filter.tags) }
|
||||||
|
}
|
||||||
when (filter.sortOrder) {
|
when (filter.sortOrder) {
|
||||||
SortOrder.ALPHABETICAL -> list.sortWith(compareBy(AlphanumComparator()) { x -> x.manga.title })
|
SortOrder.ALPHABETICAL -> list.sortWith(compareBy(AlphanumComparator()) { x -> x.manga.title })
|
||||||
SortOrder.RATING -> list.sortByDescending { it.manga.rating }
|
SortOrder.RATING -> list.sortByDescending { it.manga.rating }
|
||||||
@@ -133,7 +140,7 @@ class LocalMangaRepository @Inject constructor(
|
|||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun findSavedManga(remoteManga: Manga): LocalManga? {
|
suspend fun findSavedManga(remoteManga: Manga): LocalManga? = runCatchingCancellable {
|
||||||
// fast path
|
// fast path
|
||||||
LocalMangaInput.find(storageManager.getReadableDirs(), remoteManga)?.let {
|
LocalMangaInput.find(storageManager.getReadableDirs(), remoteManga)?.let {
|
||||||
return it.getManga()
|
return it.getManga()
|
||||||
@@ -155,7 +162,9 @@ class LocalMangaRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.firstOrNull()?.getManga()
|
}.firstOrNull()?.getManga()
|
||||||
}
|
}.onFailure {
|
||||||
|
it.printStackTraceDebug()
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
override suspend fun getPageUrl(page: MangaPage) = page.url
|
override suspend fun getPageUrl(page: MangaPage) = page.url
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package org.koitharu.kotatsu.local.data
|
package org.koitharu.kotatsu.local.data
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
import android.os.StatFs
|
import android.os.StatFs
|
||||||
import com.tomclaw.cache.DiskLruCache
|
import com.tomclaw.cache.DiskLruCache
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
@@ -10,15 +11,17 @@ import kotlinx.coroutines.withContext
|
|||||||
import okio.Source
|
import okio.Source
|
||||||
import okio.buffer
|
import okio.buffer
|
||||||
import okio.sink
|
import okio.sink
|
||||||
|
import okio.use
|
||||||
import org.koitharu.kotatsu.core.util.FileSize
|
import org.koitharu.kotatsu.core.util.FileSize
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.compressToPNG
|
||||||
import org.koitharu.kotatsu.core.util.ext.longHashCode
|
import org.koitharu.kotatsu.core.util.ext.longHashCode
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.printStackTraceDebug
|
||||||
import org.koitharu.kotatsu.core.util.ext.subdir
|
import org.koitharu.kotatsu.core.util.ext.subdir
|
||||||
import org.koitharu.kotatsu.core.util.ext.takeIfReadable
|
import org.koitharu.kotatsu.core.util.ext.takeIfReadable
|
||||||
import org.koitharu.kotatsu.core.util.ext.takeIfWriteable
|
import org.koitharu.kotatsu.core.util.ext.takeIfWriteable
|
||||||
import org.koitharu.kotatsu.core.util.ext.writeAllCancellable
|
import org.koitharu.kotatsu.core.util.ext.writeAllCancellable
|
||||||
import org.koitharu.kotatsu.parsers.util.SuspendLazy
|
import org.koitharu.kotatsu.parsers.util.SuspendLazy
|
||||||
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
import org.koitharu.kotatsu.parsers.util.runCatchingCancellable
|
||||||
import org.koitharu.kotatsu.core.util.ext.printStackTraceDebug
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -66,6 +69,16 @@ class PagesCache @Inject constructor(@ApplicationContext context: Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun put(url: String, bitmap: Bitmap): File = withContext(Dispatchers.IO) {
|
||||||
|
val file = File(cacheDir.get().parentFile, url.longHashCode().toString())
|
||||||
|
try {
|
||||||
|
bitmap.compressToPNG(file)
|
||||||
|
lruCache.get().put(url, file)
|
||||||
|
} finally {
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun getAvailableSize(): Long = runCatchingCancellable {
|
private suspend fun getAvailableSize(): Long = runCatchingCancellable {
|
||||||
val statFs = StatFs(cacheDir.get().absolutePath)
|
val statFs = StatFs(cacheDir.get().absolutePath)
|
||||||
statFs.availableBytes
|
statFs.availableBytes
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import org.koitharu.kotatsu.parsers.model.MangaPage
|
|||||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
import org.koitharu.kotatsu.parsers.util.toCamelCase
|
import org.koitharu.kotatsu.parsers.util.toCamelCase
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.util.TreeMap
|
||||||
import java.util.zip.ZipFile
|
import java.util.zip.ZipFile
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -49,8 +50,15 @@ class LocalMangaDirInput(root: File) : LocalMangaInput(root) {
|
|||||||
url = mangaUri,
|
url = mangaUri,
|
||||||
coverUrl = cover,
|
coverUrl = cover,
|
||||||
largeCoverUrl = cover,
|
largeCoverUrl = cover,
|
||||||
chapters = info.chapters?.mapIndexed { i, c ->
|
chapters = info.chapters?.mapIndexedNotNull { i, c ->
|
||||||
c.copy(url = chapterFiles[i].toUri().toString(), source = MangaSource.LOCAL)
|
val fileName = index.getChapterFileName(c.id)
|
||||||
|
val file = if (fileName != null) {
|
||||||
|
chapterFiles[fileName]
|
||||||
|
} else {
|
||||||
|
// old downloads
|
||||||
|
chapterFiles.values.elementAtOrNull(i)
|
||||||
|
} ?: return@mapIndexedNotNull null
|
||||||
|
c.copy(url = file.toUri().toString(), source = MangaSource.LOCAL)
|
||||||
},
|
},
|
||||||
) ?: Manga(
|
) ?: Manga(
|
||||||
id = root.absolutePath.longHashCode(),
|
id = root.absolutePath.longHashCode(),
|
||||||
@@ -59,7 +67,7 @@ class LocalMangaDirInput(root: File) : LocalMangaInput(root) {
|
|||||||
publicUrl = mangaUri,
|
publicUrl = mangaUri,
|
||||||
source = MangaSource.LOCAL,
|
source = MangaSource.LOCAL,
|
||||||
coverUrl = findFirstImageEntry().orEmpty(),
|
coverUrl = findFirstImageEntry().orEmpty(),
|
||||||
chapters = chapterFiles.mapIndexed { i, f ->
|
chapters = chapterFiles.values.mapIndexed { i, f ->
|
||||||
MangaChapter(
|
MangaChapter(
|
||||||
id = "$i${f.name}".longHashCode(),
|
id = "$i${f.name}".longHashCode(),
|
||||||
name = f.nameWithoutExtension.toHumanReadable(),
|
name = f.nameWithoutExtension.toHumanReadable(),
|
||||||
@@ -120,9 +128,9 @@ class LocalMangaDirInput(root: File) : LocalMangaInput(root) {
|
|||||||
|
|
||||||
private fun String.toHumanReadable() = replace("_", " ").toCamelCase()
|
private fun String.toHumanReadable() = replace("_", " ").toCamelCase()
|
||||||
|
|
||||||
private fun getChaptersFiles(): List<File> = root.walkCompat()
|
private fun getChaptersFiles() = root.walkCompat()
|
||||||
.filter { it.hasCbzExtension() }
|
.filter { it.hasCbzExtension() }
|
||||||
.toListSorted(compareBy(AlphanumComparator()) { it.name })
|
.associateByTo(TreeMap(AlphanumComparator())) { it.name }
|
||||||
|
|
||||||
private fun findFirstImageEntry(): String? {
|
private fun findFirstImageEntry(): String? {
|
||||||
return root.walkCompat().firstOrNull { hasImageExtension(it) }?.toUri()?.toString()
|
return root.walkCompat().firstOrNull { hasImageExtension(it) }?.toUri()?.toString()
|
||||||
|
|||||||
@@ -30,6 +30,12 @@ data class LocalManga(
|
|||||||
return manga.tags.containsAll(tags)
|
return manga.tags.containsAll(tags)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun containsAnyTag(tags: Set<MangaTag>): Boolean {
|
||||||
|
return tags.any { tag ->
|
||||||
|
manga.tags.contains(tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun toString(): String {
|
override fun toString(): String {
|
||||||
return "LocalManga(${file.path}: ${manga.title})"
|
return "LocalManga(${file.path}: ${manga.title})"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ import androidx.appcompat.view.ActionMode
|
|||||||
import androidx.core.app.ActivityCompat
|
import androidx.core.app.ActivityCompat
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.core.graphics.Insets
|
import androidx.core.graphics.Insets
|
||||||
import androidx.core.view.ViewCompat
|
|
||||||
import androidx.core.view.WindowInsetsCompat
|
|
||||||
import androidx.core.view.inputmethod.EditorInfoCompat
|
import androidx.core.view.inputmethod.EditorInfoCompat
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
import androidx.core.view.updateLayoutParams
|
import androidx.core.view.updateLayoutParams
|
||||||
@@ -47,7 +45,6 @@ import org.koitharu.kotatsu.core.util.ext.hideKeyboard
|
|||||||
import org.koitharu.kotatsu.core.util.ext.observe
|
import org.koitharu.kotatsu.core.util.ext.observe
|
||||||
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
import org.koitharu.kotatsu.core.util.ext.observeEvent
|
||||||
import org.koitharu.kotatsu.core.util.ext.scaleUpActivityOptionsOf
|
import org.koitharu.kotatsu.core.util.ext.scaleUpActivityOptionsOf
|
||||||
import org.koitharu.kotatsu.core.util.ext.setNavigationBarTransparentCompat
|
|
||||||
import org.koitharu.kotatsu.databinding.ActivityMainBinding
|
import org.koitharu.kotatsu.databinding.ActivityMainBinding
|
||||||
import org.koitharu.kotatsu.details.service.MangaPrefetchService
|
import org.koitharu.kotatsu.details.service.MangaPrefetchService
|
||||||
import org.koitharu.kotatsu.details.ui.DetailsActivity
|
import org.koitharu.kotatsu.details.ui.DetailsActivity
|
||||||
@@ -98,17 +95,6 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), AppBarOwner, BottomNav
|
|||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
setContentView(ActivityMainBinding.inflate(layoutInflater))
|
setContentView(ActivityMainBinding.inflate(layoutInflater))
|
||||||
|
|
||||||
if (bottomNav != null) {
|
|
||||||
ViewCompat.setOnApplyWindowInsetsListener(viewBinding.root) { _, insets ->
|
|
||||||
if (insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom > 0) {
|
|
||||||
val elevation = bottomNav?.elevation ?: 0f
|
|
||||||
window.setNavigationBarTransparentCompat(this@MainActivity, elevation)
|
|
||||||
}
|
|
||||||
insets
|
|
||||||
}
|
|
||||||
ViewCompat.requestApplyInsets(viewBinding.root)
|
|
||||||
}
|
|
||||||
|
|
||||||
with(viewBinding.searchView) {
|
with(viewBinding.searchView) {
|
||||||
onFocusChangeListener = this@MainActivity
|
onFocusChangeListener = this@MainActivity
|
||||||
searchSuggestionListener = this@MainActivity
|
searchSuggestionListener = this@MainActivity
|
||||||
@@ -139,7 +125,7 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), AppBarOwner, BottomNav
|
|||||||
viewModel.onError.observeEvent(this, SnackbarErrorObserver(viewBinding.container, null))
|
viewModel.onError.observeEvent(this, SnackbarErrorObserver(viewBinding.container, null))
|
||||||
viewModel.isLoading.observe(this, this::onLoadingStateChanged)
|
viewModel.isLoading.observe(this, this::onLoadingStateChanged)
|
||||||
viewModel.isResumeEnabled.observe(this, this::onResumeEnabledChanged)
|
viewModel.isResumeEnabled.observe(this, this::onResumeEnabledChanged)
|
||||||
viewModel.counters.observe(this, ::onCountersChanged)
|
viewModel.feedCounter.observe(this, ::onFeedCounterChanged)
|
||||||
viewModel.appUpdate.observe(this, MenuInvalidator(this))
|
viewModel.appUpdate.observe(this, MenuInvalidator(this))
|
||||||
viewModel.onFirstStart.observeEvent(this) {
|
viewModel.onFirstStart.observeEvent(this) {
|
||||||
WelcomeSheet.show(supportFragmentManager)
|
WelcomeSheet.show(supportFragmentManager)
|
||||||
@@ -292,10 +278,8 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), AppBarOwner, BottomNav
|
|||||||
startActivity(IntentBuilder(this).manga(manga).build(), options)
|
startActivity(IntentBuilder(this).manga(manga).build(), options)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onCountersChanged(counters: Map<NavItem, Int>) {
|
private fun onFeedCounterChanged(counter: Int) {
|
||||||
counters.forEach { (navItem, counter) ->
|
navigationDelegate.setCounter(NavItem.FEED, counter)
|
||||||
navigationDelegate.setCounter(navItem, counter)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onIncognitoModeChanged(isIncognito: Boolean) {
|
private fun onIncognitoModeChanged(isIncognito: Boolean) {
|
||||||
|
|||||||
@@ -4,15 +4,11 @@ import androidx.lifecycle.viewModelScope
|
|||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.combine
|
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.plus
|
import kotlinx.coroutines.plus
|
||||||
import org.koitharu.kotatsu.core.exceptions.EmptyHistoryException
|
import org.koitharu.kotatsu.core.exceptions.EmptyHistoryException
|
||||||
import org.koitharu.kotatsu.core.github.AppUpdateRepository
|
import org.koitharu.kotatsu.core.github.AppUpdateRepository
|
||||||
import org.koitharu.kotatsu.core.prefs.AppSettings
|
import org.koitharu.kotatsu.core.prefs.AppSettings
|
||||||
import org.koitharu.kotatsu.core.prefs.NavItem
|
|
||||||
import org.koitharu.kotatsu.core.prefs.observeAsStateFlow
|
import org.koitharu.kotatsu.core.prefs.observeAsStateFlow
|
||||||
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
||||||
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
import org.koitharu.kotatsu.core.util.ext.MutableEventFlow
|
||||||
@@ -22,7 +18,6 @@ import org.koitharu.kotatsu.history.data.HistoryRepository
|
|||||||
import org.koitharu.kotatsu.main.domain.ReadingResumeEnabledUseCase
|
import org.koitharu.kotatsu.main.domain.ReadingResumeEnabledUseCase
|
||||||
import org.koitharu.kotatsu.parsers.model.Manga
|
import org.koitharu.kotatsu.parsers.model.Manga
|
||||||
import org.koitharu.kotatsu.tracker.domain.TrackingRepository
|
import org.koitharu.kotatsu.tracker.domain.TrackingRepository
|
||||||
import java.util.EnumMap
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
@@ -52,19 +47,8 @@ class MainViewModel @Inject constructor(
|
|||||||
|
|
||||||
val appUpdate = appUpdateRepository.observeAvailableUpdate()
|
val appUpdate = appUpdateRepository.observeAvailableUpdate()
|
||||||
|
|
||||||
val counters = combine(
|
val feedCounter = trackingRepository.observeUpdatedMangaCount()
|
||||||
trackingRepository.observeUpdatedMangaCount(),
|
.stateIn(viewModelScope + Dispatchers.Default, SharingStarted.Lazily, 0)
|
||||||
observeNewSourcesCount(),
|
|
||||||
) { tracks, newSources ->
|
|
||||||
val em = EnumMap<NavItem, Int>(NavItem::class.java)
|
|
||||||
em[NavItem.EXPLORE] = newSources
|
|
||||||
em[NavItem.FEED] = tracks
|
|
||||||
em
|
|
||||||
}.stateIn(
|
|
||||||
scope = viewModelScope + Dispatchers.Default,
|
|
||||||
started = SharingStarted.WhileSubscribed(5000),
|
|
||||||
initialValue = emptyMap<NavItem, Int>(),
|
|
||||||
)
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
launchJob {
|
launchJob {
|
||||||
@@ -87,8 +71,4 @@ class MainViewModel @Inject constructor(
|
|||||||
fun setIncognitoMode(isEnabled: Boolean) {
|
fun setIncognitoMode(isEnabled: Boolean) {
|
||||||
settings.isIncognitoModeEnabled = isEnabled
|
settings.isIncognitoModeEnabled = isEnabled
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun observeNewSourcesCount() = sourcesRepository.observeNewSources()
|
|
||||||
.map { if (sourcesRepository.isSetupRequired()) 0 else it.size }
|
|
||||||
.distinctUntilChanged()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,5 +123,11 @@ class WelcomeSheet : BaseAdaptiveSheet<SheetWelcomeBinding>(), ChipsView.OnChipC
|
|||||||
private const val TAG = "WelcomeSheet"
|
private const val TAG = "WelcomeSheet"
|
||||||
|
|
||||||
fun show(fm: FragmentManager) = WelcomeSheet().showDistinct(fm, TAG)
|
fun show(fm: FragmentManager) = WelcomeSheet().showDistinct(fm, TAG)
|
||||||
|
|
||||||
|
fun dismiss(fm: FragmentManager): Boolean {
|
||||||
|
val sheet = fm.findFragmentByTag(TAG) as? WelcomeSheet ?: return false
|
||||||
|
sheet.dismissAllowingStateLoss()
|
||||||
|
return true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package org.koitharu.kotatsu.reader.domain
|
package org.koitharu.kotatsu.reader.domain
|
||||||
|
|
||||||
import androidx.collection.LongSparseArray
|
import androidx.collection.LongSparseArray
|
||||||
|
import androidx.collection.contains
|
||||||
import org.koitharu.kotatsu.reader.ui.pager.ReaderPage
|
import org.koitharu.kotatsu.reader.ui.pager.ReaderPage
|
||||||
|
|
||||||
class ChapterPages private constructor(private val pages: ArrayDeque<ReaderPage>) : List<ReaderPage> by pages {
|
class ChapterPages private constructor(private val pages: ArrayDeque<ReaderPage>) : List<ReaderPage> by pages {
|
||||||
@@ -57,6 +58,8 @@ class ChapterPages private constructor(private val pages: ArrayDeque<ReaderPage>
|
|||||||
return pages.subList(range.first, range.last + 1)
|
return pages.subList(range.first, range.last + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
operator fun contains(chapterId: Long) = indices.contains(chapterId)
|
||||||
|
|
||||||
private fun shiftIndices(delta: Int) {
|
private fun shiftIndices(delta: Int) {
|
||||||
for (i in 0 until indices.size()) {
|
for (i in 0 until indices.size()) {
|
||||||
val range = indices.valueAt(i)
|
val range = indices.valueAt(i)
|
||||||
|
|||||||
@@ -67,6 +67,10 @@ class ChaptersLoader @Inject constructor(
|
|||||||
|
|
||||||
fun peekChapter(chapterId: Long): MangaChapter? = chapters[chapterId]
|
fun peekChapter(chapterId: Long): MangaChapter? = chapters[chapterId]
|
||||||
|
|
||||||
|
fun hasPages(chapterId: Long): Boolean {
|
||||||
|
return chapterId in chapterPages
|
||||||
|
}
|
||||||
|
|
||||||
fun getPages(chapterId: Long): List<ReaderPage> {
|
fun getPages(chapterId: Long): List<ReaderPage> {
|
||||||
return chapterPages.subList(chapterId)
|
return chapterPages.subList(chapterId)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
package org.koitharu.kotatsu.reader.domain
|
package org.koitharu.kotatsu.reader.domain
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import androidx.annotation.AnyThread
|
import androidx.annotation.AnyThread
|
||||||
import androidx.collection.LongSparseArray
|
import androidx.collection.LongSparseArray
|
||||||
import androidx.collection.set
|
import androidx.collection.set
|
||||||
|
import androidx.core.net.toFile
|
||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
import dagger.hilt.android.ActivityRetainedLifecycle
|
import dagger.hilt.android.ActivityRetainedLifecycle
|
||||||
import dagger.hilt.android.lifecycle.RetainedLifecycle
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import dagger.hilt.android.scopes.ActivityRetainedScoped
|
import dagger.hilt.android.scopes.ActivityRetainedScoped
|
||||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
@@ -26,6 +25,7 @@ import kotlinx.coroutines.sync.withLock
|
|||||||
import kotlinx.coroutines.sync.withPermit
|
import kotlinx.coroutines.sync.withPermit
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
|
import okio.use
|
||||||
import org.koitharu.kotatsu.core.network.CommonHeaders
|
import org.koitharu.kotatsu.core.network.CommonHeaders
|
||||||
import org.koitharu.kotatsu.core.network.ImageProxyInterceptor
|
import org.koitharu.kotatsu.core.network.ImageProxyInterceptor
|
||||||
import org.koitharu.kotatsu.core.network.MangaHttpClient
|
import org.koitharu.kotatsu.core.network.MangaHttpClient
|
||||||
@@ -35,6 +35,8 @@ import org.koitharu.kotatsu.core.prefs.AppSettings
|
|||||||
import org.koitharu.kotatsu.core.util.FileSize
|
import org.koitharu.kotatsu.core.util.FileSize
|
||||||
import org.koitharu.kotatsu.core.util.RetainedLifecycleCoroutineScope
|
import org.koitharu.kotatsu.core.util.RetainedLifecycleCoroutineScope
|
||||||
import org.koitharu.kotatsu.core.util.ext.URI_SCHEME_ZIP
|
import org.koitharu.kotatsu.core.util.ext.URI_SCHEME_ZIP
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.compressToPNG
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.ensureRamAtLeast
|
||||||
import org.koitharu.kotatsu.core.util.ext.ensureSuccess
|
import org.koitharu.kotatsu.core.util.ext.ensureSuccess
|
||||||
import org.koitharu.kotatsu.core.util.ext.exists
|
import org.koitharu.kotatsu.core.util.ext.exists
|
||||||
import org.koitharu.kotatsu.core.util.ext.getCompletionResultOrNull
|
import org.koitharu.kotatsu.core.util.ext.getCompletionResultOrNull
|
||||||
@@ -49,10 +51,11 @@ import org.koitharu.kotatsu.local.data.isZipUri
|
|||||||
import org.koitharu.kotatsu.parsers.model.MangaPage
|
import org.koitharu.kotatsu.parsers.model.MangaPage
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||||
import org.koitharu.kotatsu.reader.ui.pager.ReaderPage
|
import org.koitharu.kotatsu.reader.ui.pager.ReaderPage
|
||||||
import java.io.File
|
|
||||||
import java.util.LinkedList
|
import java.util.LinkedList
|
||||||
import java.util.concurrent.atomic.AtomicInteger
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
import java.util.zip.ZipFile
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import kotlin.concurrent.Volatile
|
||||||
import kotlin.coroutines.AbstractCoroutineContextElement
|
import kotlin.coroutines.AbstractCoroutineContextElement
|
||||||
import kotlin.coroutines.CoroutineContext
|
import kotlin.coroutines.CoroutineContext
|
||||||
|
|
||||||
@@ -65,11 +68,7 @@ class PageLoader @Inject constructor(
|
|||||||
private val settings: AppSettings,
|
private val settings: AppSettings,
|
||||||
private val mangaRepositoryFactory: MangaRepository.Factory,
|
private val mangaRepositoryFactory: MangaRepository.Factory,
|
||||||
private val imageProxyInterceptor: ImageProxyInterceptor,
|
private val imageProxyInterceptor: ImageProxyInterceptor,
|
||||||
) : RetainedLifecycle.OnClearedListener {
|
) {
|
||||||
|
|
||||||
init {
|
|
||||||
lifecycle.addOnClearedListener(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
val loaderScope = RetainedLifecycleCoroutineScope(lifecycle) + InternalErrorHandler() + Dispatchers.Default
|
val loaderScope = RetainedLifecycleCoroutineScope(lifecycle) + InternalErrorHandler() + Dispatchers.Default
|
||||||
|
|
||||||
@@ -77,17 +76,13 @@ class PageLoader @Inject constructor(
|
|||||||
private val semaphore = Semaphore(3)
|
private val semaphore = Semaphore(3)
|
||||||
private val convertLock = Mutex()
|
private val convertLock = Mutex()
|
||||||
private val prefetchLock = Mutex()
|
private val prefetchLock = Mutex()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
private var repository: MangaRepository? = null
|
private var repository: MangaRepository? = null
|
||||||
private val prefetchQueue = LinkedList<MangaPage>()
|
private val prefetchQueue = LinkedList<MangaPage>()
|
||||||
private val counter = AtomicInteger(0)
|
private val counter = AtomicInteger(0)
|
||||||
private var prefetchQueueLimit = PREFETCH_LIMIT_DEFAULT // TODO adaptive
|
private var prefetchQueueLimit = PREFETCH_LIMIT_DEFAULT // TODO adaptive
|
||||||
|
|
||||||
override fun onCleared() {
|
|
||||||
synchronized(tasks) {
|
|
||||||
tasks.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isPrefetchApplicable(): Boolean {
|
fun isPrefetchApplicable(): Boolean {
|
||||||
return repository is RemoteMangaRepository
|
return repository is RemoteMangaRepository
|
||||||
&& settings.isPagesPreloadEnabled
|
&& settings.isPagesPreloadEnabled
|
||||||
@@ -131,21 +126,30 @@ class PageLoader @Inject constructor(
|
|||||||
return loadPageAsync(page, force).await()
|
return loadPageAsync(page, force).await()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun convertInPlace(file: File) {
|
suspend fun convertBimap(uri: Uri): Uri = convertLock.withLock {
|
||||||
convertLock.withLock {
|
if (uri.isZipUri()) {
|
||||||
if (context.ramAvailable < file.length() * 2) {
|
val bitmap = runInterruptible(Dispatchers.IO) {
|
||||||
return@withLock
|
ZipFile(uri.schemeSpecificPart).use { zip ->
|
||||||
}
|
val entry = zip.getEntry(uri.fragment)
|
||||||
runInterruptible(Dispatchers.Default) {
|
context.ensureRamAtLeast(entry.size * 2)
|
||||||
val image = BitmapFactory.decodeFile(file.absolutePath)
|
zip.getInputStream(zip.getEntry(uri.fragment)).use {
|
||||||
try {
|
BitmapFactory.decodeStream(it)
|
||||||
file.outputStream().use { out ->
|
|
||||||
image.compress(Bitmap.CompressFormat.PNG, 100, out)
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
image.recycle()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
cache.put(uri.toString(), bitmap).toUri()
|
||||||
|
} else {
|
||||||
|
val file = uri.toFile()
|
||||||
|
context.ensureRamAtLeast(file.length() * 2)
|
||||||
|
val image = runInterruptible(Dispatchers.IO) {
|
||||||
|
BitmapFactory.decodeFile(file.absolutePath)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
image.compressToPNG(file)
|
||||||
|
} finally {
|
||||||
|
image.recycle()
|
||||||
|
}
|
||||||
|
uri
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,7 +241,7 @@ class PageLoader @Inject constructor(
|
|||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
private const val PROGRESS_UNDEFINED = -1f
|
private const val PROGRESS_UNDEFINED = -1f
|
||||||
private const val PREFETCH_LIMIT_DEFAULT = 10
|
private const val PREFETCH_LIMIT_DEFAULT = 6
|
||||||
private const val PREFETCH_MIN_RAM_MB = 80L
|
private const val PREFETCH_MIN_RAM_MB = 80L
|
||||||
|
|
||||||
fun createPageRequest(page: MangaPage, pageUrl: String) = Request.Builder()
|
fun createPageRequest(page: MangaPage, pageUrl: String) = Request.Builder()
|
||||||
|
|||||||
@@ -24,8 +24,9 @@ import org.koitharu.kotatsu.core.util.ext.printStackTraceDebug
|
|||||||
import org.koitharu.kotatsu.core.util.ext.resolveDp
|
import org.koitharu.kotatsu.core.util.ext.resolveDp
|
||||||
import org.koitharu.kotatsu.parsers.util.format
|
import org.koitharu.kotatsu.parsers.util.format
|
||||||
import org.koitharu.kotatsu.reader.ui.pager.ReaderUiState
|
import org.koitharu.kotatsu.reader.ui.pager.ReaderUiState
|
||||||
import java.text.SimpleDateFormat
|
import java.time.LocalTime
|
||||||
import java.util.Date
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
import com.google.android.material.R as materialR
|
import com.google.android.material.R as materialR
|
||||||
|
|
||||||
class ReaderInfoBarView @JvmOverloads constructor(
|
class ReaderInfoBarView @JvmOverloads constructor(
|
||||||
@@ -36,7 +37,7 @@ class ReaderInfoBarView @JvmOverloads constructor(
|
|||||||
|
|
||||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
private val textBounds = Rect()
|
private val textBounds = Rect()
|
||||||
private val timeFormat = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT)
|
private val timeFormat = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
|
||||||
private val timeReceiver = TimeReceiver()
|
private val timeReceiver = TimeReceiver()
|
||||||
private var insetLeft: Int = 0
|
private var insetLeft: Int = 0
|
||||||
private var insetRight: Int = 0
|
private var insetRight: Int = 0
|
||||||
@@ -52,7 +53,7 @@ class ReaderInfoBarView @JvmOverloads constructor(
|
|||||||
200,
|
200,
|
||||||
)
|
)
|
||||||
|
|
||||||
private var timeText = timeFormat.format(Date())
|
private var timeText = timeFormat.format(LocalTime.now())
|
||||||
private var text: String = ""
|
private var text: String = ""
|
||||||
|
|
||||||
private val innerHeight
|
private val innerHeight
|
||||||
@@ -181,7 +182,7 @@ class ReaderInfoBarView @JvmOverloads constructor(
|
|||||||
private inner class TimeReceiver : BroadcastReceiver() {
|
private inner class TimeReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
override fun onReceive(context: Context?, intent: Intent?) {
|
override fun onReceive(context: Context?, intent: Intent?) {
|
||||||
timeText = timeFormat.format(Date())
|
timeText = timeFormat.format(LocalTime.now())
|
||||||
invalidate()
|
invalidate()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ import org.koitharu.kotatsu.reader.domain.DetectReaderModeUseCase
|
|||||||
import org.koitharu.kotatsu.reader.domain.PageLoader
|
import org.koitharu.kotatsu.reader.domain.PageLoader
|
||||||
import org.koitharu.kotatsu.reader.ui.config.ReaderSettings
|
import org.koitharu.kotatsu.reader.ui.config.ReaderSettings
|
||||||
import org.koitharu.kotatsu.reader.ui.pager.ReaderUiState
|
import org.koitharu.kotatsu.reader.ui.pager.ReaderUiState
|
||||||
import java.util.Date
|
import java.time.Instant
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
private const val BOUNDS_PAGE_OFFSET = 2
|
private const val BOUNDS_PAGE_OFFSET = 2
|
||||||
@@ -302,7 +302,7 @@ class ReaderViewModel @Inject constructor(
|
|||||||
page = state.page,
|
page = state.page,
|
||||||
scroll = state.scroll,
|
scroll = state.scroll,
|
||||||
imageUrl = page.preview.ifNullOrEmpty { page.url },
|
imageUrl = page.preview.ifNullOrEmpty { page.url },
|
||||||
createdAt = Date(),
|
createdAt = Instant.now(),
|
||||||
percent = computePercent(state.chapterId, state.page),
|
percent = computePercent(state.chapterId, state.page),
|
||||||
)
|
)
|
||||||
bookmarksRepository.addBookmark(bookmark)
|
bookmarksRepository.addBookmark(bookmark)
|
||||||
|
|||||||
@@ -119,9 +119,9 @@ class ColorFilterConfigActivity :
|
|||||||
.setMessage(R.string.color_correction_apply_text)
|
.setMessage(R.string.color_correction_apply_text)
|
||||||
.setNegativeButton(android.R.string.cancel, null)
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
.setPositiveButton(R.string.this_manga) { _, _ ->
|
.setPositiveButton(R.string.this_manga) { _, _ ->
|
||||||
viewModel.saveGlobally()
|
|
||||||
}.setNeutralButton(R.string.globally) { _, _ ->
|
|
||||||
viewModel.save()
|
viewModel.save()
|
||||||
|
}.setNeutralButton(R.string.globally) { _, _ ->
|
||||||
|
viewModel.saveGlobally()
|
||||||
}.show()
|
}.show()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package org.koitharu.kotatsu.reader.ui.pager
|
package org.koitharu.kotatsu.reader.ui.pager
|
||||||
|
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import androidx.core.net.toFile
|
|
||||||
import androidx.core.net.toUri
|
|
||||||
import androidx.lifecycle.Observer
|
import androidx.lifecycle.Observer
|
||||||
import com.davemorrissey.labs.subscaleview.DefaultOnImageEventListener
|
import com.davemorrissey.labs.subscaleview.DefaultOnImageEventListener
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -139,10 +137,9 @@ class PageHolderDelegate(
|
|||||||
prevJob?.join()
|
prevJob?.join()
|
||||||
state = State.CONVERTING
|
state = State.CONVERTING
|
||||||
try {
|
try {
|
||||||
val file = uri.toFile()
|
val newUri = loader.convertBimap(uri)
|
||||||
loader.convertInPlace(file)
|
|
||||||
state = State.CONVERTED
|
state = State.CONVERTED
|
||||||
callback.onImageReady(file.toUri())
|
callback.onImageReady(newUri)
|
||||||
} catch (ce: CancellationException) {
|
} catch (ce: CancellationException) {
|
||||||
throw ce
|
throw ce
|
||||||
} catch (e2: Throwable) {
|
} catch (e2: Throwable) {
|
||||||
|
|||||||
@@ -12,9 +12,11 @@ class WebtoonFrameLayout @JvmOverloads constructor(
|
|||||||
@AttrRes defStyleAttr: Int = 0,
|
@AttrRes defStyleAttr: Int = 0,
|
||||||
) : FrameLayout(context, attrs, defStyleAttr) {
|
) : FrameLayout(context, attrs, defStyleAttr) {
|
||||||
|
|
||||||
val target: WebtoonImageView by lazy(LazyThreadSafetyMode.NONE) {
|
private var _target: WebtoonImageView? = null
|
||||||
findViewById(R.id.ssiv)
|
val target: WebtoonImageView
|
||||||
}
|
get() = _target ?: findViewById<WebtoonImageView?>(R.id.ssiv).also {
|
||||||
|
_target = it
|
||||||
|
}
|
||||||
|
|
||||||
fun dispatchVerticalScroll(dy: Int): Int {
|
fun dispatchVerticalScroll(dy: Int): Int {
|
||||||
if (dy == 0) {
|
if (dy == 0) {
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
package org.koitharu.kotatsu.reader.ui.pager.webtoon
|
package org.koitharu.kotatsu.reader.ui.pager.webtoon
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Paint
|
||||||
import android.graphics.PointF
|
import android.graphics.PointF
|
||||||
import android.util.AttributeSet
|
import android.util.AttributeSet
|
||||||
import androidx.core.view.ancestors
|
import androidx.core.view.ancestors
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
|
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
|
||||||
import org.koitharu.kotatsu.parsers.util.toIntUp
|
import org.koitharu.kotatsu.BuildConfig
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.resolveDp
|
||||||
private const val SCROLL_UNKNOWN = -1
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
class WebtoonImageView @JvmOverloads constructor(
|
class WebtoonImageView @JvmOverloads constructor(
|
||||||
context: Context,
|
context: Context,
|
||||||
@@ -18,7 +20,14 @@ class WebtoonImageView @JvmOverloads constructor(
|
|||||||
private val ct = PointF()
|
private val ct = PointF()
|
||||||
|
|
||||||
private var scrollPos = 0
|
private var scrollPos = 0
|
||||||
private var scrollRange = SCROLL_UNKNOWN
|
private var debugPaint: Paint? = null
|
||||||
|
|
||||||
|
override fun onDraw(canvas: Canvas) {
|
||||||
|
super.onDraw(canvas)
|
||||||
|
if (BuildConfig.DEBUG) {
|
||||||
|
drawDebug(canvas)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun scrollBy(delta: Int) {
|
fun scrollBy(delta: Int) {
|
||||||
val maxScroll = getScrollRange()
|
val maxScroll = getScrollRange()
|
||||||
@@ -41,14 +50,14 @@ class WebtoonImageView @JvmOverloads constructor(
|
|||||||
fun getScroll() = scrollPos
|
fun getScroll() = scrollPos
|
||||||
|
|
||||||
fun getScrollRange(): Int {
|
fun getScrollRange(): Int {
|
||||||
if (scrollRange == SCROLL_UNKNOWN) {
|
if (!isReady) {
|
||||||
computeScrollRange()
|
return 0
|
||||||
}
|
}
|
||||||
return scrollRange.coerceAtLeast(0)
|
val totalHeight = (sHeight * width / sWidth.toFloat()).roundToInt()
|
||||||
|
return (totalHeight - height).coerceAtLeast(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun recycle() {
|
override fun recycle() {
|
||||||
scrollRange = SCROLL_UNKNOWN
|
|
||||||
scrollPos = 0
|
scrollPos = 0
|
||||||
super.recycle()
|
super.recycle()
|
||||||
}
|
}
|
||||||
@@ -91,8 +100,6 @@ class WebtoonImageView @JvmOverloads constructor(
|
|||||||
override fun onDownsamplingChanged() {
|
override fun onDownsamplingChanged() {
|
||||||
super.onDownsamplingChanged()
|
super.onDownsamplingChanged()
|
||||||
adjustScale()
|
adjustScale()
|
||||||
computeScrollRange()
|
|
||||||
ancestors.firstNotNullOfOrNull { it as? WebtoonRecyclerView }?.updateChildrenScroll()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onReady() {
|
override fun onReady() {
|
||||||
@@ -102,13 +109,10 @@ class WebtoonImageView @JvmOverloads constructor(
|
|||||||
|
|
||||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||||
super.onSizeChanged(w, h, oldw, oldh)
|
super.onSizeChanged(w, h, oldw, oldh)
|
||||||
if (oldh == h || oldw == 0 || oldh == 0 || scrollRange == SCROLL_UNKNOWN) return
|
if (oldh != h && oldw != 0 && oldh != 0 && isReady) {
|
||||||
|
ancestors.firstNotNullOfOrNull { it as? WebtoonRecyclerView }?.updateChildrenScroll()
|
||||||
computeScrollRange()
|
} else {
|
||||||
val container = ancestors.firstNotNullOfOrNull { it as? WebtoonFrameLayout } ?: return
|
return
|
||||||
val parentHeight = parentHeight()
|
|
||||||
if (scrollPos != 0 && container.bottom < parentHeight) {
|
|
||||||
scrollTo(scrollRange)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,14 +124,6 @@ class WebtoonImageView @JvmOverloads constructor(
|
|||||||
setScaleAndCenter(minScale, ct)
|
setScaleAndCenter(minScale, ct)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun computeScrollRange() {
|
|
||||||
if (!isReady) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val totalHeight = (sHeight * minScale).toIntUp()
|
|
||||||
scrollRange = (totalHeight - height).coerceAtLeast(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun adjustScale() {
|
private fun adjustScale() {
|
||||||
minScale = width / sWidth.toFloat()
|
minScale = width / sWidth.toFloat()
|
||||||
maxScale = minScale
|
maxScale = minScale
|
||||||
@@ -137,4 +133,18 @@ class WebtoonImageView @JvmOverloads constructor(
|
|||||||
private fun parentHeight(): Int {
|
private fun parentHeight(): Int {
|
||||||
return ancestors.firstNotNullOfOrNull { it as? RecyclerView }?.height ?: 0
|
return ancestors.firstNotNullOfOrNull { it as? RecyclerView }?.height ?: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun drawDebug(canvas: Canvas) {
|
||||||
|
val paint = debugPaint ?: Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = android.graphics.Color.RED
|
||||||
|
strokeWidth = context.resources.resolveDp(2f)
|
||||||
|
textAlign = android.graphics.Paint.Align.LEFT
|
||||||
|
textSize = context.resources.resolveDp(14f)
|
||||||
|
debugPaint = this
|
||||||
|
}
|
||||||
|
paint.style = Paint.Style.STROKE
|
||||||
|
canvas.drawRect(1f, 1f, width.toFloat() - 1f, height.toFloat() - 1f, paint)
|
||||||
|
paint.style = Paint.Style.FILL
|
||||||
|
canvas.drawText("${getScroll()} / ${getScrollRange()}", 100f, 100f, paint)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,10 @@ package org.koitharu.kotatsu.reader.ui.pager.webtoon
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.AttributeSet
|
import android.util.AttributeSet
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.core.view.ViewCompat.TYPE_TOUCH
|
import androidx.core.view.ViewCompat.TYPE_TOUCH
|
||||||
import androidx.core.view.forEach
|
import androidx.core.view.forEach
|
||||||
|
import androidx.core.view.iterator
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
import org.koitharu.kotatsu.BuildConfig
|
|
||||||
import org.koitharu.kotatsu.core.util.ext.findCenterViewPosition
|
import org.koitharu.kotatsu.core.util.ext.findCenterViewPosition
|
||||||
import java.util.LinkedList
|
import java.util.LinkedList
|
||||||
import java.util.WeakHashMap
|
import java.util.WeakHashMap
|
||||||
@@ -18,6 +17,7 @@ class WebtoonRecyclerView @JvmOverloads constructor(
|
|||||||
|
|
||||||
private var onPageScrollListeners: MutableList<OnPageScrollListener>? = null
|
private var onPageScrollListeners: MutableList<OnPageScrollListener>? = null
|
||||||
private val detachedViews = WeakHashMap<View, Unit>()
|
private val detachedViews = WeakHashMap<View, Unit>()
|
||||||
|
private var isFixingScroll: Boolean = false
|
||||||
|
|
||||||
override fun onChildDetachedFromWindow(child: View) {
|
override fun onChildDetachedFromWindow(child: View) {
|
||||||
super.onChildDetachedFromWindow(child)
|
super.onChildDetachedFromWindow(child)
|
||||||
@@ -56,6 +56,13 @@ class WebtoonRecyclerView @JvmOverloads constructor(
|
|||||||
return consumedY != 0 || dy == 0
|
return consumedY != 0 || dy == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onScrollStateChanged(state: Int) {
|
||||||
|
super.onScrollStateChanged(state)
|
||||||
|
if (state == SCROLL_STATE_IDLE) {
|
||||||
|
updateChildrenScroll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun consumeVerticalScroll(dy: Int): Int {
|
private fun consumeVerticalScroll(dy: Int): Int {
|
||||||
if (childCount == 0) {
|
if (childCount == 0) {
|
||||||
return 0
|
return 0
|
||||||
@@ -106,16 +113,12 @@ class WebtoonRecyclerView @JvmOverloads constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun notifyScrollChanged(dy: Int) {
|
private fun notifyScrollChanged(dy: Int) {
|
||||||
updateChildrenScroll()
|
|
||||||
val listeners = onPageScrollListeners
|
val listeners = onPageScrollListeners
|
||||||
if (listeners.isNullOrEmpty()) {
|
if (listeners.isNullOrEmpty()) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val centerPosition = findCenterViewPosition()
|
val centerPosition = findCenterViewPosition()
|
||||||
listeners.forEach { it.dispatchScroll(this, dy, centerPosition) }
|
listeners.forEach { it.dispatchScroll(this, dy, centerPosition) }
|
||||||
if (BuildConfig.DEBUG) {
|
|
||||||
validateLayout()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun relayoutChildren() {
|
fun relayoutChildren() {
|
||||||
@@ -128,29 +131,35 @@ class WebtoonRecyclerView @JvmOverloads constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun updateChildrenScroll() {
|
fun updateChildrenScroll() {
|
||||||
forEach { child ->
|
if (isFixingScroll) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isFixingScroll = true
|
||||||
|
for (child in this) {
|
||||||
val ssiv = (child as WebtoonFrameLayout).target
|
val ssiv = (child as WebtoonFrameLayout).target
|
||||||
when {
|
if (adjustScroll(child, ssiv)) {
|
||||||
child.top < 0 -> ssiv.scrollTo(ssiv.getScrollRange())
|
break
|
||||||
child.top > 0 -> ssiv.scrollTo(0)
|
|
||||||
else -> ssiv.scrollBy(0)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
isFixingScroll = false
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validateLayout() {
|
private fun adjustScroll(child: View, ssiv: WebtoonImageView): Boolean = when {
|
||||||
forEach { child ->
|
child.bottom < height && ssiv.getScroll() < ssiv.getScrollRange() -> {
|
||||||
val ssiv = (child as WebtoonFrameLayout).target
|
val distance = minOf(height - child.bottom, ssiv.getScrollRange() - ssiv.getScroll())
|
||||||
val scroll = ssiv.getScroll()
|
scrollBy(0, -distance)
|
||||||
val assertion = when {
|
ssiv.scrollBy(distance)
|
||||||
child.top < 0 -> scroll == ssiv.getScrollRange()
|
true
|
||||||
child.top > 0 -> scroll == 0
|
|
||||||
else -> true
|
|
||||||
}
|
|
||||||
if (!assertion) {
|
|
||||||
Toast.makeText(context, "Scroll = $scroll for view with top: ${child.top}", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
child.top > 0 && ssiv.getScroll() > 0 -> {
|
||||||
|
val distance = minOf(child.top, ssiv.getScroll())
|
||||||
|
scrollBy(0, distance)
|
||||||
|
ssiv.scrollBy(-distance)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> false
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class OnPageScrollListener {
|
abstract class OnPageScrollListener {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package org.koitharu.kotatsu.reader.ui.thumbnails
|
package org.koitharu.kotatsu.reader.ui.thumbnails
|
||||||
|
|
||||||
import org.koitharu.kotatsu.core.parser.MangaRepository
|
|
||||||
import org.koitharu.kotatsu.list.ui.model.ListModel
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
import org.koitharu.kotatsu.reader.ui.pager.ReaderPage
|
import org.koitharu.kotatsu.reader.ui.pager.ReaderPage
|
||||||
|
|
||||||
data class PageThumbnail(
|
data class PageThumbnail(
|
||||||
val isCurrent: Boolean,
|
val isCurrent: Boolean,
|
||||||
val repository: MangaRepository,
|
|
||||||
val page: ReaderPage,
|
val page: ReaderPage,
|
||||||
) : ListModel {
|
) : ListModel {
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import kotlinx.coroutines.flow.stateIn
|
|||||||
import org.koitharu.kotatsu.core.model.findById
|
import org.koitharu.kotatsu.core.model.findById
|
||||||
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
import org.koitharu.kotatsu.core.model.parcelable.ParcelableManga
|
||||||
import org.koitharu.kotatsu.core.parser.MangaIntent
|
import org.koitharu.kotatsu.core.parser.MangaIntent
|
||||||
import org.koitharu.kotatsu.core.parser.MangaRepository
|
|
||||||
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
import org.koitharu.kotatsu.core.ui.BaseViewModel
|
||||||
import org.koitharu.kotatsu.core.util.ext.firstNotNull
|
import org.koitharu.kotatsu.core.util.ext.firstNotNull
|
||||||
import org.koitharu.kotatsu.core.util.ext.require
|
import org.koitharu.kotatsu.core.util.ext.require
|
||||||
@@ -26,7 +25,6 @@ import javax.inject.Inject
|
|||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class PagesThumbnailsViewModel @Inject constructor(
|
class PagesThumbnailsViewModel @Inject constructor(
|
||||||
savedStateHandle: SavedStateHandle,
|
savedStateHandle: SavedStateHandle,
|
||||||
mangaRepositoryFactory: MangaRepository.Factory,
|
|
||||||
private val chaptersLoader: ChaptersLoader,
|
private val chaptersLoader: ChaptersLoader,
|
||||||
detailsLoadUseCase: DetailsLoadUseCase,
|
detailsLoadUseCase: DetailsLoadUseCase,
|
||||||
) : BaseViewModel() {
|
) : BaseViewModel() {
|
||||||
@@ -36,14 +34,13 @@ class PagesThumbnailsViewModel @Inject constructor(
|
|||||||
private val initialChapterId: Long = savedStateHandle[PagesThumbnailsSheet.ARG_CHAPTER_ID] ?: 0L
|
private val initialChapterId: Long = savedStateHandle[PagesThumbnailsSheet.ARG_CHAPTER_ID] ?: 0L
|
||||||
val manga = savedStateHandle.require<ParcelableManga>(PagesThumbnailsSheet.ARG_MANGA).manga
|
val manga = savedStateHandle.require<ParcelableManga>(PagesThumbnailsSheet.ARG_MANGA).manga
|
||||||
|
|
||||||
private val repository = mangaRepositoryFactory.create(manga.source)
|
|
||||||
private val mangaDetails = detailsLoadUseCase(MangaIntent.of(manga)).map {
|
private val mangaDetails = detailsLoadUseCase(MangaIntent.of(manga)).map {
|
||||||
val b = manga.chapters?.findById(initialChapterId)?.branch
|
val b = manga.chapters?.findById(initialChapterId)?.branch
|
||||||
branch.value = b
|
branch.value = b
|
||||||
it.filterChapters(b)
|
it.filterChapters(b)
|
||||||
}.withErrorHandling()
|
}.withErrorHandling()
|
||||||
.stateIn(viewModelScope, SharingStarted.Lazily, null)
|
.stateIn(viewModelScope, SharingStarted.Lazily, null)
|
||||||
private var loadingJob: Job? = null
|
private var loadingJob: Job
|
||||||
private var loadingPrevJob: Job? = null
|
private var loadingPrevJob: Job? = null
|
||||||
private var loadingNextJob: Job? = null
|
private var loadingNextJob: Job? = null
|
||||||
|
|
||||||
@@ -59,14 +56,14 @@ class PagesThumbnailsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun loadPrevChapter() {
|
fun loadPrevChapter() {
|
||||||
if (loadingJob?.isActive == true || loadingPrevJob?.isActive == true) {
|
if (loadingJob.isActive || loadingPrevJob?.isActive == true) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
loadingPrevJob = loadPrevNextChapter(isNext = false)
|
loadingPrevJob = loadPrevNextChapter(isNext = false)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun loadNextChapter() {
|
fun loadNextChapter() {
|
||||||
if (loadingJob?.isActive == true || loadingNextJob?.isActive == true) {
|
if (loadingJob.isActive || loadingNextJob?.isActive == true) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
loadingNextJob = loadPrevNextChapter(isNext = true)
|
loadingNextJob = loadPrevNextChapter(isNext = true)
|
||||||
@@ -91,7 +88,6 @@ class PagesThumbnailsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
this += PageThumbnail(
|
this += PageThumbnail(
|
||||||
isCurrent = page.chapterId == initialChapterId && page.index == currentPageIndex,
|
isCurrent = page.chapterId == initialChapterId && page.index == currentPageIndex,
|
||||||
repository = repository,
|
|
||||||
page = page,
|
page = page,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import androidx.core.view.MenuProvider
|
|||||||
import androidx.core.view.inputmethod.EditorInfoCompat
|
import androidx.core.view.inputmethod.EditorInfoCompat
|
||||||
import androidx.fragment.app.viewModels
|
import androidx.fragment.app.viewModels
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChangedBy
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.ui.list.ListSelectionController
|
import org.koitharu.kotatsu.core.ui.list.ListSelectionController
|
||||||
import org.koitharu.kotatsu.core.ui.util.MenuInvalidator
|
import org.koitharu.kotatsu.core.ui.util.MenuInvalidator
|
||||||
@@ -44,6 +46,11 @@ class RemoteListFragment : MangaListFragment(), FilterOwner {
|
|||||||
viewModel.onOpenManga.observeEvent(viewLifecycleOwner) {
|
viewModel.onOpenManga.observeEvent(viewLifecycleOwner) {
|
||||||
startActivity(DetailsActivity.newIntent(binding.root.context, it))
|
startActivity(DetailsActivity.newIntent(binding.root.context, it))
|
||||||
}
|
}
|
||||||
|
viewModel.header.distinctUntilChangedBy { it.isFilterApplied }
|
||||||
|
.drop(1)
|
||||||
|
.observe(viewLifecycleOwner) {
|
||||||
|
activity?.invalidateMenu()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onScrolledToEnd() {
|
override fun onScrolledToEnd() {
|
||||||
@@ -94,12 +101,18 @@ class RemoteListFragment : MangaListFragment(), FilterOwner {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
R.id.action_filter_reset -> {
|
||||||
|
viewModel.resetFilter()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
else -> false
|
else -> false
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onPrepareMenu(menu: Menu) {
|
override fun onPrepareMenu(menu: Menu) {
|
||||||
super.onPrepareMenu(menu)
|
super.onPrepareMenu(menu)
|
||||||
menu.findItem(R.id.action_random)?.isEnabled = !viewModel.isRandomLoading.value
|
menu.findItem(R.id.action_random)?.isEnabled = !viewModel.isRandomLoading.value
|
||||||
|
menu.findItem(R.id.action_filter_reset)?.isVisible = viewModel.header.value.isFilterApplied
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onQueryTextSubmit(query: String?): Boolean {
|
override fun onQueryTextSubmit(query: String?): Boolean {
|
||||||
|
|||||||
@@ -28,8 +28,9 @@ import org.koitharu.kotatsu.scrobbling.common.domain.model.ScrobblerUser
|
|||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
private const val DOMAIN = "shikimori.one"
|
||||||
private const val REDIRECT_URI = "kotatsu://shikimori-auth"
|
private const val REDIRECT_URI = "kotatsu://shikimori-auth"
|
||||||
private const val BASE_URL = "https://shikimori.me/"
|
private const val BASE_URL = "https://$DOMAIN/"
|
||||||
private const val MANGA_PAGE_SIZE = 10
|
private const val MANGA_PAGE_SIZE = 10
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@@ -199,15 +200,15 @@ class ShikimoriRepository @Inject constructor(
|
|||||||
id = json.getLong("id"),
|
id = json.getLong("id"),
|
||||||
name = json.getString("name"),
|
name = json.getString("name"),
|
||||||
altName = json.getStringOrNull("russian"),
|
altName = json.getStringOrNull("russian"),
|
||||||
cover = json.getJSONObject("image").getString("preview").toAbsoluteUrl("shikimori.me"),
|
cover = json.getJSONObject("image").getString("preview").toAbsoluteUrl(DOMAIN),
|
||||||
url = json.getString("url").toAbsoluteUrl("shikimori.me"),
|
url = json.getString("url").toAbsoluteUrl(DOMAIN),
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun ScrobblerMangaInfo(json: JSONObject) = ScrobblerMangaInfo(
|
private fun ScrobblerMangaInfo(json: JSONObject) = ScrobblerMangaInfo(
|
||||||
id = json.getLong("id"),
|
id = json.getLong("id"),
|
||||||
name = json.getString("name"),
|
name = json.getString("name"),
|
||||||
cover = json.getJSONObject("image").getString("preview").toAbsoluteUrl("shikimori.me"),
|
cover = json.getJSONObject("image").getString("preview").toAbsoluteUrl(DOMAIN),
|
||||||
url = json.getString("url").toAbsoluteUrl("shikimori.me"),
|
url = json.getString("url").toAbsoluteUrl(DOMAIN),
|
||||||
descriptionHtml = json.getString("description_html"),
|
descriptionHtml = json.getString("description_html"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -111,6 +111,10 @@ class MangaSearchRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun getRareTags(source: MangaSource, limit: Int): List<MangaTag> {
|
||||||
|
return db.getTagsDao().findRareTags(source.name, limit).toMangaTagsList()
|
||||||
|
}
|
||||||
|
|
||||||
fun getSourcesSuggestion(query: String, limit: Int): List<MangaSource> {
|
fun getSourcesSuggestion(query: String, limit: Int): List<MangaSource> {
|
||||||
if (query.length < 3) {
|
if (query.length < 3) {
|
||||||
return emptyList()
|
return emptyList()
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
package org.koitharu.kotatsu.search.ui.suggestion.adapter
|
package org.koitharu.kotatsu.search.ui.suggestion.adapter
|
||||||
|
|
||||||
import androidx.core.text.buildSpannedString
|
|
||||||
import androidx.lifecycle.LifecycleOwner
|
import androidx.lifecycle.LifecycleOwner
|
||||||
import coil.ImageLoader
|
import coil.ImageLoader
|
||||||
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
||||||
import org.koitharu.kotatsu.R
|
import org.koitharu.kotatsu.R
|
||||||
import org.koitharu.kotatsu.core.model.getSummary
|
import org.koitharu.kotatsu.core.model.getSummary
|
||||||
|
import org.koitharu.kotatsu.core.model.getTitle
|
||||||
import org.koitharu.kotatsu.core.parser.favicon.faviconUri
|
import org.koitharu.kotatsu.core.parser.favicon.faviconUri
|
||||||
import org.koitharu.kotatsu.core.ui.image.FaviconDrawable
|
import org.koitharu.kotatsu.core.ui.image.FaviconDrawable
|
||||||
import org.koitharu.kotatsu.core.util.ext.enqueueWith
|
import org.koitharu.kotatsu.core.util.ext.enqueueWith
|
||||||
@@ -14,7 +14,6 @@ import org.koitharu.kotatsu.core.util.ext.source
|
|||||||
import org.koitharu.kotatsu.databinding.ItemSearchSuggestionSourceBinding
|
import org.koitharu.kotatsu.databinding.ItemSearchSuggestionSourceBinding
|
||||||
import org.koitharu.kotatsu.search.ui.suggestion.SearchSuggestionListener
|
import org.koitharu.kotatsu.search.ui.suggestion.SearchSuggestionListener
|
||||||
import org.koitharu.kotatsu.search.ui.suggestion.model.SearchSuggestionItem
|
import org.koitharu.kotatsu.search.ui.suggestion.model.SearchSuggestionItem
|
||||||
import org.koitharu.kotatsu.settings.sources.adapter.appendNsfwLabel
|
|
||||||
|
|
||||||
fun searchSuggestionSourceAD(
|
fun searchSuggestionSourceAD(
|
||||||
coil: ImageLoader,
|
coil: ImageLoader,
|
||||||
@@ -32,15 +31,7 @@ fun searchSuggestionSourceAD(
|
|||||||
}
|
}
|
||||||
|
|
||||||
bind {
|
bind {
|
||||||
binding.textViewTitle.text = if (item.isNsfw) {
|
binding.textViewTitle.text = item.source.getTitle(context)
|
||||||
buildSpannedString {
|
|
||||||
append(item.source.title)
|
|
||||||
append(' ')
|
|
||||||
appendNsfwLabel(context)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
item.source.title
|
|
||||||
}
|
|
||||||
binding.textViewSubtitle.text = item.source.getSummary(context)
|
binding.textViewSubtitle.text = item.source.getSummary(context)
|
||||||
binding.switchLocal.isChecked = item.isEnabled
|
binding.switchLocal.isChecked = item.isEnabled
|
||||||
val fallbackIcon = FaviconDrawable(context, R.style.FaviconDrawable_Small, item.source.name)
|
val fallbackIcon = FaviconDrawable(context, R.style.FaviconDrawable_Small, item.source.name)
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
package org.koitharu.kotatsu.search.ui.suggestion.adapter
|
package org.koitharu.kotatsu.search.ui.suggestion.adapter
|
||||||
|
|
||||||
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegate
|
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
||||||
import org.koitharu.kotatsu.R
|
|
||||||
import org.koitharu.kotatsu.core.ui.widgets.ChipsView
|
import org.koitharu.kotatsu.core.ui.widgets.ChipsView
|
||||||
|
import org.koitharu.kotatsu.databinding.ItemSearchSuggestionTagsBinding
|
||||||
import org.koitharu.kotatsu.parsers.model.MangaTag
|
import org.koitharu.kotatsu.parsers.model.MangaTag
|
||||||
import org.koitharu.kotatsu.search.ui.suggestion.SearchSuggestionListener
|
import org.koitharu.kotatsu.search.ui.suggestion.SearchSuggestionListener
|
||||||
import org.koitharu.kotatsu.search.ui.suggestion.model.SearchSuggestionItem
|
import org.koitharu.kotatsu.search.ui.suggestion.model.SearchSuggestionItem
|
||||||
|
|
||||||
fun searchSuggestionTagsAD(
|
fun searchSuggestionTagsAD(
|
||||||
listener: SearchSuggestionListener,
|
listener: SearchSuggestionListener,
|
||||||
) = adapterDelegate<SearchSuggestionItem.Tags, SearchSuggestionItem>(R.layout.item_search_suggestion_tags) {
|
) = adapterDelegateViewBinding<SearchSuggestionItem.Tags, SearchSuggestionItem, ItemSearchSuggestionTagsBinding>(
|
||||||
|
{ layoutInflater, parent -> ItemSearchSuggestionTagsBinding.inflate(layoutInflater, parent, false) },
|
||||||
|
) {
|
||||||
|
|
||||||
val chipGroup = itemView as ChipsView
|
binding.chipsGenres.onChipClickListener = ChipsView.OnChipClickListener { _, data ->
|
||||||
|
|
||||||
chipGroup.onChipClickListener = ChipsView.OnChipClickListener { _, data ->
|
|
||||||
listener.onTagClick(data as? MangaTag ?: return@OnChipClickListener)
|
listener.onTagClick(data as? MangaTag ?: return@OnChipClickListener)
|
||||||
}
|
}
|
||||||
|
|
||||||
bind {
|
bind {
|
||||||
chipGroup.setChips(item.tags)
|
binding.chipsGenres.setChips(item.tags)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -110,11 +110,7 @@ class ServicesSettingsFragment : BasePreferenceFragment(R.string.services),
|
|||||||
if (account == null) {
|
if (account == null) {
|
||||||
am.addAccount(accountType, accountType, null, null, requireActivity(), null, null)
|
am.addAccount(accountType, accountType, null, null, requireActivity(), null, null)
|
||||||
} else {
|
} else {
|
||||||
try {
|
startActivitySafe(SyncSettingsIntent(account))
|
||||||
startActivity(SyncSettingsIntent(account))
|
|
||||||
} catch (_: ActivityNotFoundException) {
|
|
||||||
Snackbar.make(listView, R.string.operation_not_supported, Snackbar.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ class AboutSettingsFragment : BasePreferenceFragment(R.string.about) {
|
|||||||
private fun openLink(url: String, title: CharSequence?) {
|
private fun openLink(url: String, title: CharSequence?) {
|
||||||
val intent = Intent(Intent.ACTION_VIEW)
|
val intent = Intent(Intent.ACTION_VIEW)
|
||||||
intent.data = url.toUri()
|
intent.data = url.toUri()
|
||||||
startActivity(
|
startActivitySafe(
|
||||||
if (title != null) {
|
if (title != null) {
|
||||||
Intent.createChooser(intent, title)
|
Intent.createChooser(intent, title)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -54,7 +54,11 @@ class AppBackupAgent : BackupAgent() {
|
|||||||
mtime: Long
|
mtime: Long
|
||||||
) {
|
) {
|
||||||
if (destination?.name?.endsWith(".bk.zip") == true) {
|
if (destination?.name?.endsWith(".bk.zip") == true) {
|
||||||
restoreBackupFile(data.fileDescriptor, size, BackupRepository(MangaDatabase(applicationContext), AppSettings(applicationContext)))
|
restoreBackupFile(
|
||||||
|
data.fileDescriptor,
|
||||||
|
size,
|
||||||
|
BackupRepository(MangaDatabase(applicationContext), AppSettings(applicationContext)),
|
||||||
|
)
|
||||||
destination.delete()
|
destination.delete()
|
||||||
} else {
|
} else {
|
||||||
super.onRestoreFile(data, size, destination, type, mode, mtime)
|
super.onRestoreFile(data, size, destination, type, mode, mtime)
|
||||||
@@ -69,6 +73,7 @@ class AppBackupAgent : BackupAgent() {
|
|||||||
backup.put(repository.dumpCategories())
|
backup.put(repository.dumpCategories())
|
||||||
backup.put(repository.dumpFavourites())
|
backup.put(repository.dumpFavourites())
|
||||||
backup.put(repository.dumpBookmarks())
|
backup.put(repository.dumpBookmarks())
|
||||||
|
backup.put(repository.dumpSources())
|
||||||
backup.put(repository.dumpSettings())
|
backup.put(repository.dumpSettings())
|
||||||
backup.finish()
|
backup.finish()
|
||||||
backup.file
|
backup.file
|
||||||
@@ -86,11 +91,12 @@ class AppBackupAgent : BackupAgent() {
|
|||||||
val backup = BackupZipInput(tempFile)
|
val backup = BackupZipInput(tempFile)
|
||||||
try {
|
try {
|
||||||
runBlocking {
|
runBlocking {
|
||||||
backup.getEntry(BackupEntry.HISTORY)?.let { repository.restoreHistory(it) }
|
backup.getEntry(BackupEntry.Name.HISTORY)?.let { repository.restoreHistory(it) }
|
||||||
backup.getEntry(BackupEntry.CATEGORIES)?.let { repository.restoreCategories(it) }
|
backup.getEntry(BackupEntry.Name.CATEGORIES)?.let { repository.restoreCategories(it) }
|
||||||
backup.getEntry(BackupEntry.FAVOURITES)?.let { repository.restoreFavourites(it) }
|
backup.getEntry(BackupEntry.Name.FAVOURITES)?.let { repository.restoreFavourites(it) }
|
||||||
backup.getEntry(BackupEntry.BOOKMARKS)?.let { repository.restoreBookmarks(it) }
|
backup.getEntry(BackupEntry.Name.BOOKMARKS)?.let { repository.restoreBookmarks(it) }
|
||||||
backup.getEntry(BackupEntry.SETTINGS)?.let { repository.restoreSettings(it) }
|
backup.getEntry(BackupEntry.Name.SOURCES)?.let { repository.restoreSources(it) }
|
||||||
|
backup.getEntry(BackupEntry.Name.SETTINGS)?.let { repository.restoreSettings(it) }
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
backup.close()
|
backup.close()
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package org.koitharu.kotatsu.settings.backup
|
||||||
|
|
||||||
|
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
|
||||||
|
import org.koitharu.kotatsu.core.ui.BaseListAdapter
|
||||||
|
import org.koitharu.kotatsu.core.ui.list.OnListItemClickListener
|
||||||
|
import org.koitharu.kotatsu.core.util.ext.setChecked
|
||||||
|
import org.koitharu.kotatsu.databinding.ItemCheckableMultipleBinding
|
||||||
|
import org.koitharu.kotatsu.list.ui.ListModelDiffCallback.Companion.PAYLOAD_CHECKED_CHANGED
|
||||||
|
import org.koitharu.kotatsu.list.ui.adapter.ListItemType
|
||||||
|
|
||||||
|
class BackupEntriesAdapter(
|
||||||
|
clickListener: OnListItemClickListener<BackupEntryModel>,
|
||||||
|
) : BaseListAdapter<BackupEntryModel>() {
|
||||||
|
|
||||||
|
init {
|
||||||
|
addDelegate(ListItemType.NAV_ITEM, backupEntryAD(clickListener))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun backupEntryAD(
|
||||||
|
clickListener: OnListItemClickListener<BackupEntryModel>,
|
||||||
|
) = adapterDelegateViewBinding<BackupEntryModel, BackupEntryModel, ItemCheckableMultipleBinding>(
|
||||||
|
{ layoutInflater, parent -> ItemCheckableMultipleBinding.inflate(layoutInflater, parent, false) },
|
||||||
|
) {
|
||||||
|
|
||||||
|
binding.root.setOnClickListener { v ->
|
||||||
|
clickListener.onItemClick(item, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
bind { payloads ->
|
||||||
|
with(binding.root) {
|
||||||
|
setText(item.titleResId)
|
||||||
|
setChecked(item.isChecked, PAYLOAD_CHECKED_CHANGED in payloads)
|
||||||
|
isEnabled = item.isEnabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package org.koitharu.kotatsu.settings.backup
|
||||||
|
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import org.koitharu.kotatsu.R
|
||||||
|
import org.koitharu.kotatsu.core.backup.BackupEntry
|
||||||
|
import org.koitharu.kotatsu.list.ui.ListModelDiffCallback
|
||||||
|
import org.koitharu.kotatsu.list.ui.model.ListModel
|
||||||
|
|
||||||
|
data class BackupEntryModel(
|
||||||
|
val name: BackupEntry.Name,
|
||||||
|
val isChecked: Boolean,
|
||||||
|
val isEnabled: Boolean,
|
||||||
|
) : ListModel {
|
||||||
|
|
||||||
|
@get:StringRes
|
||||||
|
val titleResId: Int
|
||||||
|
get() = when (name) {
|
||||||
|
BackupEntry.Name.INDEX -> 0 // should not appear here
|
||||||
|
BackupEntry.Name.HISTORY -> R.string.history
|
||||||
|
BackupEntry.Name.CATEGORIES -> R.string.favourites_categories
|
||||||
|
BackupEntry.Name.FAVOURITES -> R.string.favourites
|
||||||
|
BackupEntry.Name.SETTINGS -> R.string.settings
|
||||||
|
BackupEntry.Name.BOOKMARKS -> R.string.bookmarks
|
||||||
|
BackupEntry.Name.SOURCES -> R.string.remote_sources
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun areItemsTheSame(other: ListModel): Boolean {
|
||||||
|
return other is BackupEntryModel && other.name == name
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getChangePayload(previousState: ListModel): Any? {
|
||||||
|
if (previousState !is BackupEntryModel) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return if (previousState.isEnabled != isEnabled) {
|
||||||
|
ListModelDiffCallback.PAYLOAD_ANYTHING_CHANGED
|
||||||
|
} else if (previousState.isChecked != isChecked) {
|
||||||
|
ListModelDiffCallback.PAYLOAD_CHECKED_CHANGED
|
||||||
|
} else {
|
||||||
|
super.getChangePayload(previousState)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,21 +24,25 @@ class BackupViewModel @Inject constructor(
|
|||||||
init {
|
init {
|
||||||
launchLoadingJob {
|
launchLoadingJob {
|
||||||
val file = BackupZipOutput(context).use { backup ->
|
val file = BackupZipOutput(context).use { backup ->
|
||||||
|
val step = 1f / 6f
|
||||||
backup.put(repository.createIndex())
|
backup.put(repository.createIndex())
|
||||||
|
|
||||||
progress.value = 0f
|
progress.value = 0f
|
||||||
backup.put(repository.dumpHistory())
|
backup.put(repository.dumpHistory())
|
||||||
|
|
||||||
progress.value = 0.2f
|
progress.value += step
|
||||||
backup.put(repository.dumpCategories())
|
backup.put(repository.dumpCategories())
|
||||||
|
|
||||||
progress.value = 0.4f
|
progress.value += step
|
||||||
backup.put(repository.dumpFavourites())
|
backup.put(repository.dumpFavourites())
|
||||||
|
|
||||||
progress.value = 0.6f
|
progress.value += step
|
||||||
backup.put(repository.dumpBookmarks())
|
backup.put(repository.dumpBookmarks())
|
||||||
|
|
||||||
progress.value = 0.8f
|
progress.value += step
|
||||||
|
backup.put(repository.dumpSources())
|
||||||
|
|
||||||
|
progress.value += step
|
||||||
backup.put(repository.dumpSettings())
|
backup.put(repository.dumpSettings())
|
||||||
|
|
||||||
backup.finish()
|
backup.finish()
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user