feat: 优化代码

pull/198/head
kunfei 5 years ago
parent 473a861efe
commit 611bdea5d2
  1. 162
      app/src/main/java/io/legado/app/help/BookHelp.kt
  2. 41
      app/src/main/java/io/legado/app/ui/config/OtherConfigFragment.kt
  3. 8
      app/src/main/java/io/legado/app/ui/widget/prefs/PreferenceCategory.kt
  4. 1
      app/src/main/res/values/pref_key_value.xml
  5. 5
      app/src/main/res/xml/pref_config_other.xml

@ -1,16 +1,15 @@
package io.legado.app.help package io.legado.app.help
import android.net.Uri
import androidx.documentfile.provider.DocumentFile
import com.github.houbb.opencc4j.core.impl.ZhConvertBootstrap import com.github.houbb.opencc4j.core.impl.ZhConvertBootstrap
import io.legado.app.App import io.legado.app.App
import io.legado.app.R
import io.legado.app.constant.EventBus import io.legado.app.constant.EventBus
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
import io.legado.app.data.entities.BookChapter import io.legado.app.data.entities.BookChapter
import io.legado.app.data.entities.ReplaceRule import io.legado.app.data.entities.ReplaceRule
import io.legado.app.model.localBook.AnalyzeTxtFile import io.legado.app.model.localBook.AnalyzeTxtFile
import io.legado.app.utils.* import io.legado.app.utils.FileUtils
import io.legado.app.utils.MD5Utils
import io.legado.app.utils.postEvent
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@ -21,12 +20,9 @@ import kotlin.math.min
object BookHelp { object BookHelp {
private const val cacheFolderName = "book_cache" private const val cacheFolderName = "book_cache"
val downloadPath: String private val downloadDir: File =
get() = App.INSTANCE.getPrefString(R.string.pk_download_path) App.INSTANCE.getExternalFilesDir(null)
?: App.INSTANCE.getExternalFilesDir(null)?.absolutePath ?: App.INSTANCE.cacheDir
?: App.INSTANCE.cacheDir.absolutePath
private val downloadUri get() = Uri.parse(downloadPath)
private fun bookFolderName(book: Book): String { private fun bookFolderName(book: Book): String {
return formatFolderName(book.name) + MD5Utils.md5Encode16(book.bookUrl) return formatFolderName(book.name) + MD5Utils.md5Encode16(book.bookUrl)
@ -41,137 +37,73 @@ object BookHelp {
} }
fun clearCache() { fun clearCache() {
if (downloadPath.isContentPath()) { FileUtils.deleteFile(
DocumentFile.fromTreeUri(App.INSTANCE, downloadUri) FileUtils.getPath(
?.findFile(cacheFolderName) downloadDir,
?.delete() subDirs = *arrayOf(cacheFolderName)
} else {
FileUtils.deleteFile(
FileUtils.getPath(
File(downloadPath),
subDirs = *arrayOf(cacheFolderName)
)
) )
} )
} }
@Synchronized @Synchronized
fun saveContent(book: Book, bookChapter: BookChapter, content: String) { fun saveContent(book: Book, bookChapter: BookChapter, content: String) {
if (content.isEmpty()) return if (content.isEmpty()) return
if (downloadPath.isContentPath()) { FileUtils.createFileIfNotExist(
DocumentFile.fromTreeUri(App.INSTANCE, downloadUri)?.let { root -> downloadDir,
DocumentUtils.createFileIfNotExist( formatChapterName(bookChapter),
root, subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
formatChapterName(bookChapter), ).writeText(content)
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
)?.uri?.writeText(App.INSTANCE, content)
}
} else {
FileUtils.createFileIfNotExist(
File(downloadPath),
formatChapterName(bookChapter),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
).writeText(content)
}
postEvent(EventBus.SAVE_CONTENT, bookChapter) postEvent(EventBus.SAVE_CONTENT, bookChapter)
} }
fun getChapterFiles(book: Book): List<String> { fun getChapterFiles(book: Book): List<String> {
val fileNameList = arrayListOf<String>() val fileNameList = arrayListOf<String>()
if (downloadPath.isContentPath()) { FileUtils.createFolderIfNotExist(
DocumentFile.fromTreeUri(App.INSTANCE, downloadUri)?.let { root -> downloadDir,
DocumentUtils.createFolderIfNotExist( subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
root, ).list()?.let {
subDirs = *arrayOf(cacheFolderName, bookFolderName(book)) fileNameList.addAll(it)
)?.let { bookDoc ->
DocumentUtils.listFiles(App.INSTANCE, bookDoc.uri).forEach {
fileNameList.add(it.name)
}
}
}
} else {
FileUtils.createFolderIfNotExist(
File(downloadPath),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
).list()?.let {
fileNameList.addAll(it)
}
} }
return fileNameList return fileNameList
} }
fun hasContent(book: Book, bookChapter: BookChapter): Boolean { fun hasContent(book: Book, bookChapter: BookChapter): Boolean {
when { return if (book.isLocalBook()) {
book.isLocalBook() -> { true
return true } else {
} FileUtils.exists(
downloadPath.isContentPath() -> { downloadDir,
DocumentFile.fromTreeUri(App.INSTANCE, downloadUri)?.let { root -> formatChapterName(bookChapter),
return DocumentUtils.exists( subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
root, )
formatChapterName(bookChapter),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
)
}
}
else -> {
return FileUtils.exists(
File(downloadPath),
formatChapterName(bookChapter),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
)
}
} }
return false
} }
fun getContent(book: Book, bookChapter: BookChapter): String? { fun getContent(book: Book, bookChapter: BookChapter): String? {
when { if (book.isLocalBook()) {
book.isLocalBook() -> { return AnalyzeTxtFile.getContent(book, bookChapter)
return AnalyzeTxtFile.getContent(book, bookChapter) } else {
} val file = FileUtils.getFile(
downloadPath.isContentPath() -> { downloadDir,
DocumentFile.fromTreeUri(App.INSTANCE, downloadUri)?.let { root -> formatChapterName(bookChapter),
return DocumentUtils.getDirDocument( subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
root, )
subDirs = *arrayOf(cacheFolderName, bookFolderName(book)) if (file.exists()) {
)?.findFile(formatChapterName(bookChapter)) return file.readText()
?.uri?.readText(App.INSTANCE)
}
}
else -> {
val file = FileUtils.getFile(
File(downloadPath),
formatChapterName(bookChapter),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
)
if (file.exists()) {
return file.readText()
}
} }
} }
return null return null
} }
fun delContent(book: Book, bookChapter: BookChapter) { fun delContent(book: Book, bookChapter: BookChapter) {
when { if (book.isLocalBook()) {
book.isLocalBook() -> return return
downloadPath.isContentPath() -> { } else {
DocumentFile.fromTreeUri(App.INSTANCE, downloadUri)?.let { root -> FileUtils.createFileIfNotExist(
DocumentUtils.getDirDocument( downloadDir,
root, formatChapterName(bookChapter),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book)) subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
)?.findFile(formatChapterName(bookChapter)) ).delete()
?.delete()
}
}
else -> {
FileUtils.createFileIfNotExist(
File(downloadPath),
formatChapterName(bookChapter),
subDirs = *arrayOf(cacheFolderName, bookFolderName(book))
).delete()
}
} }
} }

@ -1,8 +1,6 @@
package io.legado.app.ui.config package io.legado.app.ui.config
import android.app.Activity.RESULT_OK
import android.content.ComponentName import android.content.ComponentName
import android.content.Intent
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
@ -19,17 +17,13 @@ import io.legado.app.help.BookHelp
import io.legado.app.lib.theme.ATH import io.legado.app.lib.theme.ATH
import io.legado.app.receiver.SharedReceiverActivity import io.legado.app.receiver.SharedReceiverActivity
import io.legado.app.service.WebService import io.legado.app.service.WebService
import io.legado.app.ui.filechooser.FileChooserDialog
import io.legado.app.ui.filechooser.FilePicker
import io.legado.app.ui.widget.number.NumberPickerDialog import io.legado.app.ui.widget.number.NumberPickerDialog
import io.legado.app.utils.* import io.legado.app.utils.*
class OtherConfigFragment : PreferenceFragmentCompat(), class OtherConfigFragment : PreferenceFragmentCompat(),
FileChooserDialog.CallBack,
SharedPreferences.OnSharedPreferenceChangeListener { SharedPreferences.OnSharedPreferenceChangeListener {
private val requestCodeDownloadPath = 25324
private val packageManager = App.INSTANCE.packageManager private val packageManager = App.INSTANCE.packageManager
private val componentName = ComponentName( private val componentName = ComponentName(
App.INSTANCE, App.INSTANCE,
@ -40,7 +34,6 @@ class OtherConfigFragment : PreferenceFragmentCompat(),
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
putPrefBoolean(PreferKey.processText, isProcessTextEnabled()) putPrefBoolean(PreferKey.processText, isProcessTextEnabled())
addPreferencesFromResource(R.xml.pref_config_other) addPreferencesFromResource(R.xml.pref_config_other)
upPreferenceSummary(getString(R.string.pk_download_path), BookHelp.downloadPath)
upPreferenceSummary(PreferKey.threadCount, AppConfig.threadCount.toString()) upPreferenceSummary(PreferKey.threadCount, AppConfig.threadCount.toString())
upPreferenceSummary(PreferKey.webPort, webPort.toString()) upPreferenceSummary(PreferKey.webPort, webPort.toString())
} }
@ -74,7 +67,6 @@ class OtherConfigFragment : PreferenceFragmentCompat(),
.show { .show {
putPrefInt(PreferKey.webPort, it) putPrefInt(PreferKey.webPort, it)
} }
getString(R.string.pk_download_path) -> selectDownloadPath()
PreferKey.cleanCache -> { PreferKey.cleanCache -> {
BookHelp.clearCache() BookHelp.clearCache()
toast(R.string.clear_cache_success) toast(R.string.clear_cache_success)
@ -85,9 +77,6 @@ class OtherConfigFragment : PreferenceFragmentCompat(),
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
when (key) { when (key) {
getString(R.string.pk_download_path) -> {
upPreferenceSummary(key, BookHelp.downloadPath)
}
PreferKey.threadCount -> upPreferenceSummary( PreferKey.threadCount -> upPreferenceSummary(
key, AppConfig.threadCount.toString() key, AppConfig.threadCount.toString()
) )
@ -139,34 +128,4 @@ class OtherConfigFragment : PreferenceFragmentCompat(),
} }
} }
private fun selectDownloadPath() {
FilePicker.selectFolder(this, requestCodeDownloadPath) {
removePref(getString(R.string.pk_download_path))
}
}
private fun putDownloadPath(path: String) {
putPrefString(getString(R.string.pk_download_path), path)
}
override fun onFilePicked(requestCode: Int, currentPath: String) {
if (requestCode == requestCodeDownloadPath) {
putDownloadPath(currentPath)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
requestCodeDownloadPath -> if (resultCode == RESULT_OK) {
data?.data?.let { uri ->
requireContext().contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
putDownloadPath(uri.toString())
}
}
}
}
} }

@ -1,7 +1,6 @@
package io.legado.app.ui.widget.prefs package io.legado.app.ui.widget.prefs
import android.content.Context import android.content.Context
import android.graphics.Color
import android.util.AttributeSet import android.util.AttributeSet
import android.view.View import android.view.View
import android.widget.TextView import android.widget.TextView
@ -10,6 +9,7 @@ import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceViewHolder import androidx.preference.PreferenceViewHolder
import io.legado.app.R import io.legado.app.R
import io.legado.app.lib.theme.accentColor import io.legado.app.lib.theme.accentColor
import io.legado.app.utils.getCompatColor
class PreferenceCategory(context: Context, attrs: AttributeSet) : PreferenceCategory(context, attrs) { class PreferenceCategory(context: Context, attrs: AttributeSet) : PreferenceCategory(context, attrs) {
@ -25,7 +25,11 @@ class PreferenceCategory(context: Context, attrs: AttributeSet) : PreferenceCate
val view = it.findViewById(R.id.preference_title) val view = it.findViewById(R.id.preference_title)
if (view is TextView) { // && !view.isInEditMode if (view is TextView) { // && !view.isInEditMode
view.text = title view.text = title
view.setTextColor(context.accentColor) //设置title文本的颜色 if (view.isInEditMode) {
view.setTextColor(context.getCompatColor(R.color.colorAccent))
} else {
view.setTextColor(context.accentColor)
}
view.isVisible = title != null && title.isNotEmpty() view.isVisible = title != null && title.isNotEmpty()
val da = it.findViewById(R.id.preference_divider_above) val da = it.findViewById(R.id.preference_divider_above)

@ -10,7 +10,6 @@
<string name="pk_find_expand_group">expandGroupFind</string> <string name="pk_find_expand_group">expandGroupFind</string>
<string name="pk_default_read">defaultToRead</string> <string name="pk_default_read">defaultToRead</string>
<string name="pk_auto_download">autoDownload</string> <string name="pk_auto_download">autoDownload</string>
<string name="pk_download_path">downloadPath</string>
<string name="pk_check_update">checkUpdate</string> <string name="pk_check_update">checkUpdate</string>
<string name="source_rule_url">https://gitee.com/alanskycn/yuedu/blob/master/Rule/README.md</string> <string name="source_rule_url">https://gitee.com/alanskycn/yuedu/blob/master/Rule/README.md</string>

@ -50,11 +50,6 @@
android:title="@string/web_port_title" android:title="@string/web_port_title"
app:iconSpaceReserved="false" /> app:iconSpaceReserved="false" />
<io.legado.app.ui.widget.prefs.Preference
android:key="downloadPath"
android:title="@string/download_path"
app:iconSpaceReserved="false" />
<io.legado.app.ui.widget.prefs.Preference <io.legado.app.ui.widget.prefs.Preference
android:key="cleanCache" android:key="cleanCache"
android:title="@string/cleanCache" android:title="@string/cleanCache"

Loading…
Cancel
Save