Minor cleanup

(cherry picked from commit a93c0577acdf9fdc591087838ecb5a004d3acf81)

# Conflicts:
#	app/src/main/java/eu/kanade/tachiyomi/data/backup/AbstractBackupRestore.kt
#	app/src/main/java/eu/kanade/tachiyomi/util/lang/RxCoroutineBridge.kt
#	app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt
This commit is contained in:
arkon 2021-01-24 11:04:25 -05:00 committed by Jobobby04
parent 6fdff1b03b
commit 9320221a4e
6 changed files with 26 additions and 92 deletions

View File

@ -10,6 +10,7 @@ import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.util.chapter.NoChaptersException import eu.kanade.tachiyomi.util.chapter.NoChaptersException
import eu.kanade.tachiyomi.util.system.createFileInCacheDir
import exh.eh.EHentaiThrottleManager import exh.eh.EHentaiThrottleManager
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import uy.kohesive.injekt.injectLazy import uy.kohesive.injekt.injectLazy
@ -123,15 +124,15 @@ abstract class AbstractBackupRestore<T : AbstractBackupManager>(protected val co
internal fun writeErrorLog(): File { internal fun writeErrorLog(): File {
try { try {
if (errors.isNotEmpty()) { if (errors.isNotEmpty()) {
val destFile = File(context.externalCacheDir, "tachiyomi_restore.txt") val file = context.createFileInCacheDir("tachiyomi_restore.txt")
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()) val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
destFile.bufferedWriter().use { out -> file.bufferedWriter().use { out ->
errors.forEach { (date, message) -> errors.forEach { (date, message) ->
out.write("[${sdf.format(date)}] $message\n") out.write("[${sdf.format(date)}] $message\n")
} }
} }
return destFile return file
} }
} catch (e: Exception) { } catch (e: Exception) {
// Empty // Empty

View File

@ -37,6 +37,7 @@ import eu.kanade.tachiyomi.util.prepUpdateCover
import eu.kanade.tachiyomi.util.shouldDownloadNewChapters import eu.kanade.tachiyomi.util.shouldDownloadNewChapters
import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.acquireWakeLock import eu.kanade.tachiyomi.util.system.acquireWakeLock
import eu.kanade.tachiyomi.util.system.createFileInCacheDir
import eu.kanade.tachiyomi.util.system.isServiceRunning import eu.kanade.tachiyomi.util.system.isServiceRunning
import exh.md.utils.FollowStatus import exh.md.utils.FollowStatus
import exh.md.utils.MdUtil import exh.md.utils.MdUtil
@ -328,13 +329,9 @@ class LibraryUpdateService(
* @return an observable delivering the progress of each update. * @return an observable delivering the progress of each update.
*/ */
suspend fun updateChapterList(mangaToUpdate: List<LibraryManga>) { suspend fun updateChapterList(mangaToUpdate: List<LibraryManga>) {
// Initialize the variables holding the progress of the updates.
val progressCount = AtomicInteger(0) val progressCount = AtomicInteger(0)
// List containing new updates
val newUpdates = mutableListOf<Pair<LibraryManga, Array<Chapter>>>() val newUpdates = mutableListOf<Pair<LibraryManga, Array<Chapter>>>()
// List containing failed updates
val failedUpdates = mutableListOf<Pair<Manga, String?>>() val failedUpdates = mutableListOf<Pair<Manga, String?>>()
// Boolean to determine if DownloadManager has downloads
var hasDownloads = false var hasDownloads = false
mangaToUpdate mangaToUpdate
@ -433,7 +430,7 @@ class LibraryUpdateService(
} }
} }
scope.launchIO { ioScope.launchIO {
if (source is MangaDex && trackManager.mdList.isLogged) { if (source is MangaDex && trackManager.mdList.isLogged) {
val tracks = db.getTracks(manga).executeOnIO() val tracks = db.getTracks(manga).executeOnIO()
if (tracks.isEmpty() || tracks.none { it.sync_id == TrackManager.MDLIST }) { if (tracks.isEmpty() || tracks.none { it.sync_id == TrackManager.MDLIST }) {
@ -591,15 +588,14 @@ class LibraryUpdateService(
private fun writeErrorFile(errors: List<Pair<Manga, String?>>): File { private fun writeErrorFile(errors: List<Pair<Manga, String?>>): File {
try { try {
if (errors.isNotEmpty()) { if (errors.isNotEmpty()) {
val destFile = File(externalCacheDir, "tachiyomi_update_errors.txt") val file = createFileInCacheDir("tachiyomi_update_errors.txt")
file.bufferedWriter().use { out ->
destFile.bufferedWriter().use { out ->
errors.forEach { (manga, error) -> errors.forEach { (manga, error) ->
val source = sourceManager.getOrStub(manga.source) val source = sourceManager.getOrStub(manga.source)
out.write("${manga.title} ($source): $error\n") out.write("${manga.title} ($source): $error\n")
} }
} }
return destFile return file
} }
} catch (e: Exception) { } catch (e: Exception) {
// Empty // Empty

View File

@ -13,13 +13,12 @@ import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.model.toSManga import eu.kanade.tachiyomi.source.model.toSManga
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourcePresenter.Companion.toItems import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourcePresenter.Companion.toItems
import eu.kanade.tachiyomi.util.lang.asFlow import eu.kanade.tachiyomi.util.lang.awaitSingle
import eu.kanade.tachiyomi.util.lang.runAsObservable import eu.kanade.tachiyomi.util.lang.runAsObservable
import eu.kanade.tachiyomi.util.lang.withUIContext import eu.kanade.tachiyomi.util.lang.withUIContext
import exh.savedsearches.EXHSavedSearch import exh.savedsearches.EXHSavedSearch
import exh.savedsearches.JsonSavedSearch import exh.savedsearches.JsonSavedSearch
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.singleOrNull
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
@ -107,10 +106,8 @@ open class IndexPresenter(
if (source.supportsLatest) { if (source.supportsLatest) {
val results = try { val results = try {
source.fetchLatestUpdates(1) source.fetchLatestUpdates(1)
.asFlow() .awaitSingle()
.singleOrNull() .mangas
?.mangas
.orEmpty()
.take(10) .take(10)
.map { networkToLocalManga(it, source.id) } .map { networkToLocalManga(it, source.id) }
} catch (e: Exception) { } catch (e: Exception) {
@ -135,10 +132,8 @@ open class IndexPresenter(
val results = try { val results = try {
source.fetchPopularManga(1) source.fetchPopularManga(1)
.asFlow() .awaitSingle()
.singleOrNull() .mangas
?.mangas
.orEmpty()
.take(10) .take(10)
.map { networkToLocalManga(it, source.id) } .map { networkToLocalManga(it, source.id) }
} catch (e: Exception) { } catch (e: Exception) {

View File

@ -6,10 +6,10 @@ import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.NotificationReceiver import eu.kanade.tachiyomi.data.notification.NotificationReceiver
import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.createFileInCacheDir
import eu.kanade.tachiyomi.util.system.notificationBuilder import eu.kanade.tachiyomi.util.system.notificationBuilder
import eu.kanade.tachiyomi.util.system.notificationManager import eu.kanade.tachiyomi.util.system.notificationManager
import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.util.system.toast
import java.io.File
import java.io.IOException import java.io.IOException
class CrashLogUtil(private val context: Context) { class CrashLogUtil(private val context: Context) {
@ -20,11 +20,7 @@ class CrashLogUtil(private val context: Context) {
fun dumpLogs() { fun dumpLogs() {
try { try {
val file = File(context.externalCacheDir, "tachiyomi_crash_logs.txt") val file = context.createFileInCacheDir("tachiyomi_crash_logs.txt")
if (file.exists()) {
file.delete()
}
file.createNewFile()
Runtime.getRuntime().exec("logcat *:E -d -f ${file.absolutePath}") Runtime.getRuntime().exec("logcat *:E -d -f ${file.absolutePath}")
showNotification(file.getUriCompat(context)) showNotification(file.getUriCompat(context))

View File

@ -5,17 +5,10 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.suspendCancellableCoroutine
import rx.Emitter import rx.Emitter
import rx.Observable import rx.Observable
import rx.Observer
import rx.Scheduler
import rx.Single
import rx.SingleSubscriber
import rx.Subscriber import rx.Subscriber
import rx.Subscription import rx.Subscription
import kotlin.coroutines.resume import kotlin.coroutines.resume
@ -25,45 +18,6 @@ import kotlin.coroutines.resumeWithException
* Util functions for bridging RxJava and coroutines. Taken from TachiyomiEH/SY. * Util functions for bridging RxJava and coroutines. Taken from TachiyomiEH/SY.
*/ */
suspend fun <T> Single<T>.await(subscribeOn: Scheduler? = null): T {
return suspendCancellableCoroutine { continuation ->
val self = if (subscribeOn != null) subscribeOn(subscribeOn) else this
lateinit var sub: Subscription
sub = self.subscribe(
{
continuation.resume(it) {
sub.unsubscribe()
}
},
{
if (!continuation.isCancelled) {
continuation.resumeWithException(it)
}
}
)
continuation.invokeOnCancellation {
sub.unsubscribe()
}
}
}
suspend fun <T> Single<T>.await(): T = suspendCancellableCoroutine { cont ->
cont.unsubscribeOnCancellation(
subscribe(
object : SingleSubscriber<T>() {
override fun onSuccess(t: T) {
cont.resume(t)
}
override fun onError(error: Throwable) {
cont.resumeWithException(error)
}
}
)
)
}
suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne() suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne()
private suspend fun <T> Observable<T>.awaitOne(): T = suspendCancellableCoroutine { cont -> private suspend fun <T> Observable<T>.awaitOne(): T = suspendCancellableCoroutine { cont ->
@ -105,24 +59,6 @@ private suspend fun <T> Observable<T>.awaitOne(): T = suspendCancellableCoroutin
internal fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) = internal fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) =
invokeOnCancellation { sub.unsubscribe() } invokeOnCancellation { sub.unsubscribe() }
fun <T : Any?> Observable<T>.asFlow(): Flow<T> = callbackFlow {
val observer = object : Observer<T> {
override fun onNext(t: T) {
offer(t)
}
override fun onError(e: Throwable) {
close(e)
}
override fun onCompleted() {
close()
}
}
val subscription = subscribe(observer)
awaitClose { subscription.unsubscribe() }
}
fun <T> runAsObservable( fun <T> runAsObservable(
block: suspend () -> T, block: suspend () -> T,
backpressureMode: Emitter.BackpressureMode = Emitter.BackpressureMode.NONE backpressureMode: Emitter.BackpressureMode = Emitter.BackpressureMode.NONE

View File

@ -36,6 +36,7 @@ import eu.kanade.tachiyomi.util.lang.truncateCenter
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import java.io.File
import kotlin.math.roundToInt import kotlin.math.roundToInt
/** /**
@ -255,3 +256,12 @@ fun Context.openInBrowser(uri: Uri, @ColorInt toolbarColor: Int? = null) {
toast(e.message) toast(e.message)
} }
} }
fun Context.createFileInCacheDir(name: String): File {
val file = File(externalCacheDir, name)
if (file.exists()) {
file.delete()
}
file.createNewFile()
return file
}