zip/rar extractors filter out non-image files

This commit is contained in:
Gauthier Roebroeck 2019-08-16 22:00:06 +08:00
parent 77b691e49d
commit 390baf15bb
4 changed files with 22 additions and 8 deletions

View file

@ -6,7 +6,6 @@ import java.nio.file.Path
import java.util.*
abstract class ArchiveExtractor {
protected val natSortComparator: Comparator<String> = CaseInsensitiveSimpleNaturalComparator.getInstance()
abstract fun getFilenames(path: Path): List<String>

View file

@ -36,4 +36,11 @@ class ContentDetector(
return mediaType.toString()
}
}
fun isImage(stream: InputStream): Boolean =
try {
detectMediaType(stream).startsWith("image/")
} catch (ex: Exception) {
false
}
}

View file

@ -7,13 +7,16 @@ import java.nio.file.Files
import java.nio.file.Path
@Service
class RarExtractor : ArchiveExtractor() {
class RarExtractor(
private val contentDetector: ContentDetector
) : ArchiveExtractor() {
override fun getFilenames(path: Path): List<String> {
val archive = Archive(Files.newInputStream(path))
return archive.fileHeaders
.filter { !it.isDirectory }
.filter { contentDetector.isImage(archive.getInputStream(it)) }
.map { it.fileNameString }
.sortedWith(natSortComparator)
}

View file

@ -6,13 +6,18 @@ import java.nio.file.Path
import java.util.zip.ZipFile
@Service
class ZipExtractor : ArchiveExtractor() {
class ZipExtractor(
private val contentDetector: ContentDetector
) : ArchiveExtractor() {
override fun getFilenames(path: Path) =
ZipFile(path.toFile()).entries().toList()
.filter { !it.isDirectory }
.map { it.name }
.sortedWith(natSortComparator)
override fun getFilenames(path: Path): List<String> {
val zip = ZipFile(path.toFile())
return zip.entries().toList()
.filter { !it.isDirectory }
.filter { contentDetector.isImage(zip.getInputStream(it)) }
.map { it.name }
.sortedWith(natSortComparator)
}
override fun getEntryStream(path: Path, entryName: String): InputStream =
ZipFile(path.toFile()).let {