feat: 优化代码

pull/172/head
kunfei 5 years ago
parent 01ce97581f
commit 19e1d395f4
  1. 66
      app/src/main/java/io/legado/app/model/localBook/LocalBook.kt
  2. 6
      app/src/main/java/io/legado/app/ui/book/local/ImportBookViewModel.kt

@ -6,37 +6,43 @@ import io.legado.app.App
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
import io.legado.app.help.BookHelp import io.legado.app.help.BookHelp
import io.legado.app.utils.FileUtils import io.legado.app.utils.FileUtils
import io.legado.app.utils.isContentPath
import java.io.File
object LocalBook { object LocalBook {
fun importFile(doc: DocumentFile) { fun importFile(path: String) {
doc.name?.let { fileName -> val fileName = if (path.isContentPath()) {
val str = fileName.substringBeforeLast(".") val doc = DocumentFile.fromSingleUri(App.INSTANCE, Uri.parse(path))
val authorIndex = str.indexOf("作者") doc?.name ?: ""
var name: String } else {
var author: String File(path).name
if (authorIndex == -1) { }
name = str val str = fileName.substringBeforeLast(".")
author = "" val authorIndex = str.indexOf("作者")
} else { var name: String
name = str.substring(0, authorIndex) var author: String
author = str.substring(authorIndex) if (authorIndex == -1) {
author = BookHelp.formatAuthor(author) name = str
} author = ""
val smhStart = name.indexOf("") } else {
val smhEnd = name.indexOf("") name = str.substring(0, authorIndex)
if (smhStart != -1 && smhEnd != -1) { author = str.substring(authorIndex)
name = (name.substring(smhStart + 1, smhEnd)) author = BookHelp.formatAuthor(author)
} }
val book = Book( val smhStart = name.indexOf("")
bookUrl = doc.uri.toString(), val smhEnd = name.indexOf("")
name = name, if (smhStart != -1 && smhEnd != -1) {
author = author, name = (name.substring(smhStart + 1, smhEnd))
originName = fileName
)
App.db.bookDao().insert(book)
} }
val book = Book(
bookUrl = path,
name = name,
author = author,
originName = fileName
)
App.db.bookDao().insert(book)
} }
fun deleteBook(book: Book, deleteOriginal: Boolean) { fun deleteBook(book: Book, deleteOriginal: Boolean) {
@ -47,8 +53,12 @@ object LocalBook {
} }
if (deleteOriginal) { if (deleteOriginal) {
val uri = Uri.parse(book.bookUrl) if (book.bookUrl.isContentPath()) {
DocumentFile.fromSingleUri(App.INSTANCE, uri)?.delete() val uri = Uri.parse(book.bookUrl)
DocumentFile.fromSingleUri(App.INSTANCE, uri)?.delete()
} else {
FileUtils.deleteFile(book.bookUrl)
}
} }
} }
} }

@ -11,10 +11,8 @@ class ImportBookViewModel(application: Application) : BaseViewModel(application)
fun addToBookshelf(uriList: HashSet<String>, finally: () -> Unit) { fun addToBookshelf(uriList: HashSet<String>, finally: () -> Unit) {
execute { execute {
uriList.forEach { uriStr -> uriList.forEach {
DocumentFile.fromSingleUri(context, Uri.parse(uriStr))?.let { doc -> LocalBook.importFile(it)
LocalBook.importFile(doc)
}
} }
}.onFinally { }.onFinally {
finally.invoke() finally.invoke()

Loading…
Cancel
Save