Skip to content

Commit

Permalink
Merge branch 'gedoor:master' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
LM-Firefly authored Jul 30, 2024
2 parents 9658b1b + beb561a commit 8a9cc6b
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 62 deletions.
39 changes: 24 additions & 15 deletions app/src/main/java/io/legado/app/help/book/BookHelp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import io.legado.app.utils.NetworkUtils
import io.legado.app.utils.StringUtils
import io.legado.app.utils.SvgUtils
import io.legado.app.utils.UrlUtil
import io.legado.app.utils.createFileIfNotExist
import io.legado.app.utils.exists
import io.legado.app.utils.externalFiles
import io.legado.app.utils.getFile
Expand All @@ -29,10 +30,10 @@ import io.legado.app.utils.onEachParallel
import io.legado.app.utils.postEvent
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.apache.commons.text.similarity.JaccardSimilarity
import splitties.init.appCtx
Expand All @@ -55,7 +56,7 @@ object BookHelp {
private const val cacheFolderName = "book_cache"
private const val cacheImageFolderName = "images"
private const val cacheEpubFolderName = "epub"
private val downloadImages = ConcurrentHashMap.newKeySet<String>()
private val downloadImages = ConcurrentHashMap<String, Mutex>()

val cachePath = FileUtils.getPath(downloadDir, cacheFolderName)

Expand Down Expand Up @@ -173,15 +174,18 @@ object BookHelp {
src: String,
chapter: BookChapter? = null
) {
while (downloadImages.contains(src)) {
delay(100)
}
if (getImage(book, src).exists()) {
if (isImageExist(book, src)) {
return
}
downloadImages.add(src)
val analyzeUrl = AnalyzeUrl(src, source = bookSource)
val mutex = synchronized(this) {
downloadImages.getOrPut(src) { Mutex() }
}
mutex.lock()
try {
if (isImageExist(book, src)) {
return
}
val analyzeUrl = AnalyzeUrl(src, source = bookSource)
val bytes = analyzeUrl.getByteArrayAwait()
//某些图片被加密,需要进一步解密
ImageUtils.decode(
Expand All @@ -193,20 +197,15 @@ object BookHelp {
// throw NoStackTraceException("数据异常")
AppLog.put("${book.name} ${chapter?.title} 图片 $src 下载错误 数据异常")
}
FileUtils.createFileIfNotExist(
downloadDir,
cacheFolderName,
book.getFolderName(),
cacheImageFolderName,
"${MD5Utils.md5Encode16(src)}.${getImageSuffix(src)}"
).writeBytes(it)
writeImage(book, src, it)
}
} catch (e: Exception) {
coroutineContext.ensureActive()
val msg = "${book.name} ${chapter?.title} 图片 $src 下载失败\n${e.localizedMessage}"
AppLog.put(msg, e)
} finally {
downloadImages.remove(src)
mutex.unlock()
}
}

Expand All @@ -219,6 +218,16 @@ object BookHelp {
)
}

@Synchronized
fun writeImage(book: Book, src: String, bytes: ByteArray) {
getImage(book, src).createFileIfNotExist().writeBytes(bytes)
}

@Synchronized
fun isImageExist(book: Book, src: String): Boolean {
return getImage(book, src).exists()
}

fun getImageSuffix(src: String): String {
return UrlUtil.getSuffix(src, "jpg")
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/io/legado/app/model/ImageProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ object ImageProvider {
): File {
return withContext(IO) {
val vFile = BookHelp.getImage(book, src)
if (!vFile.exists()) {
if (!BookHelp.isImageExist(book, src)) {
val inputStream = when {
book.isEpub -> EpubFile.getImage(book, src)
book.isPdf -> PdfFile.getImage(book, src)
Expand Down
33 changes: 16 additions & 17 deletions app/src/main/java/io/legado/app/service/HttpReadAloudService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.Timeline
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.cache.CacheDataSink
Expand Down Expand Up @@ -75,7 +76,7 @@ class HttpReadAloudService : BaseReadAloudService(),
private val cache by lazy {
SimpleCache(
File(cacheDir, "httpTTS_cache"),
LeastRecentlyUsedCacheEvictor((50 * 1024 * 1024).toLong()),
LeastRecentlyUsedCacheEvictor(128 * 1024 * 1024),
StandaloneDatabaseProvider(appCtx)
)
}
Expand Down Expand Up @@ -182,15 +183,7 @@ class HttpReadAloudService : BaseReadAloudService(),
val file = getSpeakFileAsMd5(fileName)
val mediaItem = MediaItem.fromUri(Uri.fromFile(file))
launch(Main) {
if (exoPlayer.playbackState == Player.STATE_ENDED) {
exoPlayer.stop()
exoPlayer.clearMediaItems()
}
exoPlayer.addMediaItem(mediaItem)
if (!exoPlayer.isPlaying) {
exoPlayer.playWhenReady = !pause
exoPlayer.prepare()
}
}
}
preDownloadAudios(httpTts)
Expand Down Expand Up @@ -256,15 +249,7 @@ class HttpReadAloudService : BaseReadAloudService(),
downloaderChannel.send(downloader)
val mediaSource = createMediaSource(dataSourceFactory, fileName)
launch(Main) {
if (exoPlayer.playbackState == Player.STATE_ENDED) {
exoPlayer.stop()
exoPlayer.clearMediaItems()
}
exoPlayer.addMediaSource(mediaSource)
if (!exoPlayer.isPlaying) {
exoPlayer.playWhenReady = !pause
exoPlayer.prepare()
}
}
}
preDownloadAudiosStream(httpTts, downloaderChannel)
Expand Down Expand Up @@ -540,10 +525,24 @@ class HttpReadAloudService : BaseReadAloudService(),
// 结束
playErrorNo = 0
updateNextPos()
exoPlayer.stop()
exoPlayer.clearMediaItems()
}
}
}

override fun onTimelineChanged(timeline: Timeline, reason: Int) {
when (reason) {
Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED -> {
if (!timeline.isEmpty && exoPlayer.playbackState == Player.STATE_IDLE) {
exoPlayer.prepare()
}
}

else -> {}
}
}

override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED) return
if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO) {
Expand Down
18 changes: 18 additions & 0 deletions app/src/main/java/io/legado/app/utils/AsyncFileHandler.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.legado.app.utils

import io.legado.app.help.globalExecutor
import java.util.logging.FileHandler
import java.util.logging.LogRecord

class AsyncFileHandler(pattern: String) : FileHandler(pattern) {

override fun publish(record: LogRecord?) {
if (!isLoggable(record)) {
return
}
globalExecutor.execute {
super.publish(record)
}
}

}
25 changes: 0 additions & 25 deletions app/src/main/java/io/legado/app/utils/AsyncHandler.kt

This file was deleted.

2 changes: 1 addition & 1 deletion app/src/main/java/io/legado/app/utils/FileExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fun File.listFileDocs(filter: FileDocFilter? = null): ArrayList<FileDoc> {

fun File.createFileIfNotExist(): File {
if (!exists()) {
parentFile?.createFileIfNotExist()
parentFile?.createFolderIfNotExist()
createNewFile()
}
return this
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/java/io/legado/app/utils/LogUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import io.legado.app.help.config.AppConfig
import splitties.init.appCtx
import java.text.SimpleDateFormat
import java.util.Date
import java.util.logging.FileHandler
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
Expand Down Expand Up @@ -58,7 +57,7 @@ object LogUtils {
}
val date = getCurrentDateStr(TIME_PATTERN)
val logPath = FileUtils.getPath(root = logFolder, "appLog-$date.txt")
FileHandler(logPath).apply {
AsyncFileHandler(logPath).apply {
formatter = object : java.util.logging.Formatter() {
override fun format(record: LogRecord): String {
// 设置文件输出格式
Expand All @@ -70,7 +69,7 @@ object LogUtils {
} else {
Level.OFF
}
}.asynchronous()
}
}

fun upLevel() {
Expand Down

0 comments on commit 8a9cc6b

Please sign in to comment.