pull/783/head
gedoor 4 years ago
parent 795623d1ff
commit 16d29aeb55
  1. 5
      app/src/main/java/io/legado/app/base/BaseDialogFragment.kt
  2. 19
      app/src/main/java/io/legado/app/data/entities/BookSource.kt
  3. 4
      app/src/main/java/io/legado/app/help/ImageLoader.kt
  4. 50
      app/src/main/java/io/legado/app/help/storage/ImportOldData.kt
  5. 10
      app/src/main/java/io/legado/app/lib/webdav/WebDav.kt
  6. 4
      app/src/main/java/io/legado/app/ui/about/AboutActivity.kt
  7. 6
      app/src/main/java/io/legado/app/ui/about/AboutFragment.kt
  8. 14
      app/src/main/java/io/legado/app/ui/book/read/TextActionMenu.kt
  9. 4
      app/src/main/java/io/legado/app/ui/book/read/page/ReadView.kt
  10. 4
      app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt
  11. 20
      app/src/main/java/io/legado/app/ui/filepicker/FilePicker.kt
  12. 4
      app/src/main/java/io/legado/app/ui/filepicker/entity/JavaBean.kt
  13. 20
      app/src/main/java/io/legado/app/ui/filepicker/utils/ConvertUtils.kt
  14. 6
      app/src/main/java/io/legado/app/ui/replace/ReplaceRuleActivity.kt
  15. 6
      app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt
  16. 8
      app/src/main/java/io/legado/app/ui/widget/font/FontAdapter.kt
  17. 7
      app/src/main/java/io/legado/app/ui/widget/text/BadgeView.kt
  18. 16
      app/src/main/java/io/legado/app/utils/StringUtils.kt
  19. 6
      app/src/main/java/io/legado/app/utils/SystemUtils.kt
  20. 8
      app/src/main/java/io/legado/app/utils/ViewExtensions.kt

@ -32,13 +32,10 @@ abstract class BaseDialogFragment : DialogFragment(), CoroutineScope {
abstract fun onFragmentCreated(view: View, savedInstanceState: Bundle?)
override fun show(manager: FragmentManager, tag: String?) {
try {
kotlin.runCatching {
//在每个add事务前增加一个remove事务,防止连续的add
manager.beginTransaction().remove(this).commit()
super.show(manager, tag)
} catch (e: Exception) {
//同一实例使用不同的tag会异常,这里捕获一下
e.printStackTrace()
}
}

@ -46,13 +46,14 @@ data class BookSource(
var ruleBookInfo: BookInfoRule? = null, // 书籍信息页规则
var ruleToc: TocRule? = null, // 目录页规则
var ruleContent: ContentRule? = null // 正文页规则
): Parcelable, JsExtensions {
) : Parcelable, JsExtensions {
override fun hashCode(): Int {
return bookSourceUrl.hashCode()
}
override fun equals(other: Any?) = if (other is BookSource) other.bookSourceUrl == bookSourceUrl else false
override fun equals(other: Any?) =
if (other is BookSource) other.bookSourceUrl == bookSourceUrl else false
@Throws(Exception::class)
fun getHeaderMap() = (HashMap<String, String>().apply {
@ -100,11 +101,11 @@ data class BookSource(
}
fun getExploreKinds() = arrayListOf<ExploreKind>().apply {
exploreUrl?.let {
var a = it
exploreUrl?.let { urlRule ->
var a = urlRule
if (a.isNotBlank()) {
try {
if (it.startsWith("<js>", false)) {
kotlin.runCatching {
if (urlRule.startsWith("<js>", false)) {
val aCache = ACache.get(App.INSTANCE, "explore")
a = aCache.getAsString(bookSourceUrl) ?: ""
if (a.isBlank()) {
@ -114,7 +115,7 @@ data class BookSource(
bindings["cookie"] = CookieStore
bindings["cache"] = CacheManager
a = AppConst.SCRIPT_ENGINE.eval(
it.substring(4, it.lastIndexOf("<")),
urlRule.substring(4, urlRule.lastIndexOf("<")),
bindings
).toString()
aCache.put(bookSourceUrl, a)
@ -126,8 +127,8 @@ data class BookSource(
if (d.size > 1)
add(ExploreKind(d[0], d[1]))
}
} catch (e: Exception) {
add(ExploreKind(e.localizedMessage ?: ""))
}.onFailure {
add(ExploreKind(it.localizedMessage ?: ""))
}
}
}

@ -22,9 +22,9 @@ object ImageLoader {
path.isNullOrEmpty() -> Glide.with(context).load(path)
path.isAbsUrl() -> Glide.with(context).load(AnalyzeUrl(path).getGlideUrl())
path.isContentScheme() -> Glide.with(context).load(Uri.parse(path))
else -> try {
else -> kotlin.runCatching {
Glide.with(context).load(File(path))
} catch (e: Exception) {
}.getOrElse {
Glide.with(context).load(path)
}
}

@ -15,61 +15,61 @@ object ImportOldData {
fun importUri(context: Context, uri: Uri) {
if (uri.isContentScheme()) {
DocumentFile.fromTreeUri(context, uri)?.listFiles()?.forEach {
when (it.name) {
DocumentFile.fromTreeUri(context, uri)?.listFiles()?.forEach { doc ->
when (doc.name) {
"myBookShelf.json" ->
try {
DocumentUtils.readText(context, it.uri)?.let { json ->
kotlin.runCatching {
DocumentUtils.readText(context, doc.uri)?.let { json ->
val importCount = importOldBookshelf(json)
context.toast("成功导入书籍${importCount}")
}
} catch (e: java.lang.Exception) {
context.toast("导入书籍失败\n${e.localizedMessage}")
}.onFailure {
context.toast("导入书籍失败\n${it.localizedMessage}")
}
"myBookSource.json" ->
try {
DocumentUtils.readText(context, it.uri)?.let { json ->
kotlin.runCatching {
DocumentUtils.readText(context, doc.uri)?.let { json ->
val importCount = importOldSource(json)
context.toast("成功导入书源${importCount}")
}
} catch (e: Exception) {
context.toast("导入源失败\n${e.localizedMessage}")
}.onFailure {
context.toast("导入源失败\n${it.localizedMessage}")
}
"myBookReplaceRule.json" ->
try {
DocumentUtils.readText(context, it.uri)?.let { json ->
kotlin.runCatching {
DocumentUtils.readText(context, doc.uri)?.let { json ->
val importCount = importOldReplaceRule(json)
context.toast("成功导入替换规则${importCount}")
}
} catch (e: Exception) {
context.toast("导入替换规则失败\n${e.localizedMessage}")
}.onFailure {
context.toast("导入替换规则失败\n${it.localizedMessage}")
}
}
}
} else {
uri.path?.let {
val file = File(it)
try {// 导入书架
uri.path?.let { path ->
val file = File(path)
kotlin.runCatching {// 导入书架
val shelfFile =
FileUtils.createFileIfNotExist(file, "myBookShelf.json")
val json = shelfFile.readText()
val importCount = importOldBookshelf(json)
context.toast("成功导入书籍${importCount}")
} catch (e: Exception) {
context.toast("导入书籍失败\n${e.localizedMessage}")
}.onFailure {
context.toast("导入书籍失败\n${it.localizedMessage}")
}
try {// Book source
kotlin.runCatching {// Book source
val sourceFile =
FileUtils.getFile(file, "myBookSource.json")
val json = sourceFile.readText()
val importCount = importOldSource(json)
context.toast("成功导入书源${importCount}")
} catch (e: Exception) {
context.toast("导入源失败\n${e.localizedMessage}")
}.onFailure {
context.toast("导入源失败\n${it.localizedMessage}")
}
try {// Replace rules
kotlin.runCatching {// Replace rules
val ruleFile = FileUtils.getFile(file, "myBookReplaceRule.json")
if (ruleFile.exists()) {
val json = ruleFile.readText()
@ -78,8 +78,8 @@ object ImportOldData {
} else {
context.toast("未找到替换规则")
}
} catch (e: Exception) {
context.toast("导入替换规则失败\n${e.localizedMessage}")
}.onFailure {
context.toast("导入替换规则失败\n${it.localizedMessage}")
}
}
}

@ -12,7 +12,6 @@ import rxhttp.wrapper.param.toInputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.net.MalformedURLException
import java.net.URL
import java.net.URLEncoder
@ -39,15 +38,12 @@ class WebDav(urlStr: String) {
private val url: URL = URL(urlStr)
private val httpUrl: String? by lazy {
val raw = url.toString().replace("davs://", "https://").replace("dav://", "http://")
try {
return@lazy URLEncoder.encode(raw, "UTF-8")
return@lazy kotlin.runCatching {
URLEncoder.encode(raw, "UTF-8")
.replace("\\+".toRegex(), "%20")
.replace("%3A".toRegex(), ":")
.replace("%2F".toRegex(), "/")
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
return@lazy null
}
}.getOrNull()
}
val host: String? get() = url.host
val path get() = url.toString()

@ -30,7 +30,7 @@ class AboutActivity : BaseActivity<ActivityAboutBinding>() {
.replace(R.id.fl_fragment, aboutFragment, fTag)
.commit()
binding.tvAppSummary.post {
try {
kotlin.runCatching {
val span = ForegroundColorSpan(accentColor)
val spannableString = SpannableString(binding.tvAppSummary.text)
val gzh = getString(R.string.legado_gzh)
@ -40,8 +40,6 @@ class AboutActivity : BaseActivity<ActivityAboutBinding>() {
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
binding.tvAppSummary.text = spannableString
} catch (e: Exception) {
e.printStackTrace()
}
}
}

@ -93,12 +93,10 @@ class AboutFragment : PreferenceFragmentCompat() {
Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key")
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return try {
return kotlin.runCatching {
startActivity(intent)
true
} catch (e: java.lang.Exception) {
false
}
}.getOrDefault(false)
}
}

@ -130,7 +130,7 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
readAloud(callBack.selectedText)
}
R.id.menu_browser -> {
try {
kotlin.runCatching {
val intent = if (callBack.selectedText.isAbsUrl()) {
Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(callBack.selectedText)
@ -141,9 +141,9 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
}
}
context.startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
context.toast(e.localizedMessage ?: "ERROR")
}.onFailure {
it.printStackTrace()
context.toast(it.localizedMessage ?: "ERROR")
}
}
else -> item.intent?.let {
@ -210,7 +210,7 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
*/
@RequiresApi(Build.VERSION_CODES.M)
private fun onInitializeMenu(menu: Menu) {
try {
kotlin.runCatching {
var menuItemOrder = 100
for (resolveInfo in getSupportedActivities()) {
menu.add(
@ -218,8 +218,8 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
menuItemOrder++, resolveInfo.loadLabel(context.packageManager)
).intent = createProcessTextIntentForResolveInfo(resolveInfo)
}
} catch (e: Exception) {
context.toast("获取文字操作菜单出错:${e.localizedMessage}")
}.onFailure {
context.toast("获取文字操作菜单出错:${it.localizedMessage}")
}
}

@ -338,10 +338,10 @@ class ReadView(context: Context, attrs: AttributeSet) :
}
end -= 1
}
try {
kotlin.runCatching {
curPage.selectStartMoveIndex(firstRelativePage, lineStart, start)
curPage.selectEndMoveIndex(firstRelativePage, lineEnd, end)
} catch (e: Exception) {
}.onFailure {
print(
"""
curPage.selectStartMoveIndex($firstRelativePage, $lineStart, $start)

@ -352,7 +352,7 @@ object ChapterProvider {
}
private fun getTypeface(fontPath: String): Typeface {
return try {
return kotlin.runCatching {
when {
fontPath.isContentScheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
val fd = App.INSTANCE.contentResolver
@ -370,7 +370,7 @@ object ChapterProvider {
else -> Typeface.SANS_SERIF
}
}
} catch (e: Exception) {
}.getOrElse {
ReadBookConfig.textFont = ""
ReadBookConfig.save()
Typeface.SANS_SERIF

@ -30,11 +30,10 @@ object FilePicker {
items(selectList) { _, index ->
when (index) {
0 -> {
try {
kotlin.runCatching {
val intent = createSelectDirIntent()
activity.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}.onFailure {
checkPermissions(activity) {
FilePickerDialog.show(
activity.supportFragmentManager,
@ -81,11 +80,10 @@ object FilePicker {
items(selectList) { _, index ->
when (index) {
0 -> {
try {
kotlin.runCatching {
val intent = createSelectDirIntent()
fragment.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}.onFailure {
checkPermissions(fragment) {
FilePickerDialog.show(
fragment.childFragmentManager,
@ -133,15 +131,14 @@ object FilePicker {
items(selectList) { _, index ->
when (index) {
0 -> {
try {
kotlin.runCatching {
val intent = createSelectFileIntent()
intent.putExtra(
Intent.EXTRA_MIME_TYPES,
typesOfExtensions(allowExtensions)
)
activity.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}.onFailure {
checkPermissions(activity) {
FilePickerDialog.show(
activity.supportFragmentManager,
@ -191,15 +188,14 @@ object FilePicker {
items(selectList) { _, index ->
when (index) {
0 -> {
try {
kotlin.runCatching {
val intent = createSelectFileIntent()
intent.putExtra(
Intent.EXTRA_MIME_TYPES,
typesOfExtensions(allowExtensions)
)
fragment.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}.onFailure {
checkPermissions(fragment) {
FilePickerDialog.show(
fragment.childFragmentManager,

@ -34,15 +34,13 @@ open class JavaBean : Serializable {
val fields = list.toTypedArray()
for (field in fields) {
val fieldName = field.name
try {
kotlin.runCatching {
val obj = field.get(this)
sb.append(fieldName)
sb.append("=")
sb.append(obj)
sb.append("\n")
} catch (ignored: IllegalAccessException) {
}
}
return sb.toString()
}

@ -6,7 +6,6 @@ import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.text.DecimalFormat
@ -24,11 +23,9 @@ object ConvertUtils {
const val KB: Long = 1024
fun toInt(obj: Any): Int {
return try {
return kotlin.runCatching {
Integer.parseInt(obj.toString())
} catch (e: NumberFormatException) {
-1
}
}.getOrDefault(-1)
}
fun toInt(bytes: ByteArray): Int {
@ -42,11 +39,9 @@ object ConvertUtils {
}
fun toFloat(obj: Any): Float {
return try {
return kotlin.runCatching {
java.lang.Float.parseFloat(obj.toString())
} catch (e: NumberFormatException) {
-1f
}
}.getOrDefault(-1f)
}
fun toString(objects: Array<Any>, tag: String): String {
@ -62,7 +57,7 @@ object ConvertUtils {
fun toBitmap(bytes: ByteArray, width: Int = -1, height: Int = -1): Bitmap? {
var bitmap: Bitmap? = null
if (bytes.isNotEmpty()) {
try {
kotlin.runCatching {
val options = BitmapFactory.Options()
// 设置让解码器以最佳方式解码
options.inPreferredConfig = null
@ -72,7 +67,6 @@ object ConvertUtils {
}
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
bitmap!!.density = 96// 96 dpi
} catch (e: Exception) {
}
}
return bitmap
@ -101,7 +95,7 @@ object ConvertUtils {
@JvmOverloads
fun toString(`is`: InputStream, charset: String = "utf-8"): String {
val sb = StringBuilder()
try {
kotlin.runCatching {
val reader = BufferedReader(InputStreamReader(`is`, charset))
while (true) {
val line = reader.readLine()
@ -113,9 +107,7 @@ object ConvertUtils {
}
reader.close()
`is`.close()
} catch (e: IOException) {
}
return sb.toString()
}

@ -246,13 +246,13 @@ class ReplaceRuleActivity : VMBaseActivity<ActivityReplaceRuleBinding, ReplaceRu
when (requestCode) {
importRequestCode -> if (resultCode == Activity.RESULT_OK) {
data?.data?.let { uri ->
try {
kotlin.runCatching {
uri.readText(this)?.let {
val dataKey = IntentDataHelp.putData(it)
startActivity<ImportReplaceRuleActivity>("dataKey" to dataKey)
}
} catch (e: Exception) {
toast("readTextError:${e.localizedMessage}")
}.onFailure {
toast("readTextError:${it.localizedMessage}")
}
}
}

@ -257,13 +257,13 @@ class RssSourceActivity : VMBaseActivity<ActivityRssSourceBinding, RssSourceView
when (requestCode) {
importRequestCode -> if (resultCode == Activity.RESULT_OK) {
data?.data?.let { uri ->
try {
kotlin.runCatching {
uri.readText(this)?.let {
val dataKey = IntentDataHelp.putData(it)
startActivity<ImportRssSourceActivity>("dataKey" to dataKey)
}
} catch (e: Exception) {
toast("readTextError:${e.localizedMessage}")
}.onFailure {
toast("readTextError:${it.localizedMessage}")
}
}
}

@ -29,7 +29,7 @@ class FontAdapter(context: Context, val callBack: CallBack) :
payloads: MutableList<Any>
) {
with(binding) {
try {
kotlin.runCatching {
val typeface: Typeface? = if (item.isContentPath) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.contentResolver
@ -44,9 +44,9 @@ class FontAdapter(context: Context, val callBack: CallBack) :
Typeface.createFromFile(item.uri.toString())
}
tvFont.typeface = typeface
} catch (e: Exception) {
e.printStackTrace()
context.toast("Read ${item.name} Error: ${e.localizedMessage}")
}.onFailure {
it.printStackTrace()
context.toast("Read ${item.name} Error: ${it.localizedMessage}")
}
tvFont.text = item.name
root.onClick { callBack.onClick(item) }

@ -43,12 +43,9 @@ class BadgeView @JvmOverloads constructor(
return null
}
val text = text.toString()
return try {
return kotlin.runCatching {
Integer.parseInt(text)
} catch (e: NumberFormatException) {
null
}
}.getOrNull()
}
var badgeGravity: Int

@ -3,7 +3,6 @@ package io.legado.app.utils
import android.annotation.SuppressLint
import android.text.TextUtils.isEmpty
import java.text.DecimalFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Matcher
@ -56,7 +55,7 @@ object StringUtils {
@SuppressLint("SimpleDateFormat")
val format = SimpleDateFormat(pattern)
val calendar = Calendar.getInstance()
try {
kotlin.runCatching {
val date = format.parse(source) ?: return ""
val curTime = calendar.timeInMillis
calendar.time = date
@ -95,8 +94,8 @@ object StringUtils {
convertFormat.format(date)
}
}
} catch (e: ParseException) {
e.printStackTrace()
}.onFailure {
it.printStackTrace()
}
return ""
@ -173,7 +172,7 @@ object StringUtils {
}
// "一千零二十五", "一千二" 形式
try {
return kotlin.runCatching {
for (i in cn.indices) {
val tmpNum = ChnMap[cn[i]]!!
when {
@ -204,11 +203,8 @@ object StringUtils {
}
}
result += tmp + billion
return result
} catch (e: Exception) {
return -1
}
result
}.getOrDefault(-1)
}
fun stringToInt(str: String?): Int {

@ -19,13 +19,13 @@ object SystemUtils {
fun getScreenOffTime(context: Context): Int {
var screenOffTime = 0
try {
kotlin.runCatching {
screenOffTime = Settings.System.getInt(
context.contentResolver,
Settings.System.SCREEN_OFF_TIMEOUT
)
} catch (e: Exception) {
e.printStackTrace()
}.onFailure {
it.printStackTrace()
}
return screenOffTime

@ -107,13 +107,11 @@ fun RadioGroup.checkByIndex(index: Int) {
@SuppressLint("RestrictedApi")
fun PopupMenu.show(x: Int, y: Int) {
try {
kotlin.runCatching {
val field: Field = this.javaClass.getDeclaredField("mPopup")
field.isAccessible = true
(field.get(this) as MenuPopupHelper).show(x, y)
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}.onFailure {
it.printStackTrace()
}
}
Loading…
Cancel
Save