mirror of
https://github.com/mihonapp/mihon.git
synced 2025-11-15 13:37:29 +01:00
Add option to export minimal library information to a CSV file (#1161)
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package eu.kanade.tachiyomi.data.export
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import tachiyomi.domain.manga.model.Manga
|
||||
|
||||
object LibraryExporter {
|
||||
|
||||
data class ExportOptions(
|
||||
val includeTitle: Boolean,
|
||||
val includeAuthor: Boolean,
|
||||
val includeArtist: Boolean,
|
||||
)
|
||||
|
||||
suspend fun exportToCsv(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
favorites: List<Manga>,
|
||||
options: ExportOptions,
|
||||
onExportComplete: () -> Unit,
|
||||
) {
|
||||
withContext(Dispatchers.IO) {
|
||||
context.contentResolver.openOutputStream(uri)?.use { outputStream ->
|
||||
val csvData = generateCsvData(favorites, options)
|
||||
outputStream.write(csvData.toByteArray())
|
||||
}
|
||||
onExportComplete()
|
||||
}
|
||||
}
|
||||
|
||||
private val escapeRequired = listOf("\r", "\n", "\"", ",")
|
||||
|
||||
private fun generateCsvData(favorites: List<Manga>, options: ExportOptions): String {
|
||||
val columnSize = listOf(
|
||||
options.includeTitle,
|
||||
options.includeAuthor,
|
||||
options.includeArtist,
|
||||
)
|
||||
.count { it }
|
||||
|
||||
val rows = buildList(favorites.size) {
|
||||
favorites.forEach { manga ->
|
||||
buildList(columnSize) {
|
||||
if (options.includeTitle) add(manga.title)
|
||||
if (options.includeAuthor) add(manga.author)
|
||||
if (options.includeArtist) add(manga.artist)
|
||||
}
|
||||
.let(::add)
|
||||
}
|
||||
}
|
||||
return rows.joinToString("\r\n") { columns ->
|
||||
columns.joinToString(",") columns@{ column ->
|
||||
if (column.isNullOrBlank()) return@columns ""
|
||||
if (escapeRequired.any { column.contains(it) }) {
|
||||
column.replace("\"", "\"\"").let { "\"$it\"" }
|
||||
} else {
|
||||
column
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user