Yokan / rebuild
Course 1 8624561

LocalMediaSelection.desktop.kt

composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.desktop.kt

implementation42 lines
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.services.scheduling.DesktopSession4import java.nio.file.Files5import javax.swing.JFileChooser6import kotlinx.coroutines.Dispatchers7import kotlinx.coroutines.currentCoroutineContext8import kotlinx.coroutines.ensureActive9import kotlinx.coroutines.swing.Swing10import kotlinx.coroutines.withContext1112actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {13    val selected = withContext(Dispatchers.Swing) {14        val chooser = JFileChooser().apply {15            fileSelectionMode = if (directory) JFileChooser.DIRECTORIES_ONLY else JFileChooser.FILES_ONLY16            isMultiSelectionEnabled = !directory17        }18        if (chooser.showOpenDialog(DesktopSession.frame) != JFileChooser.APPROVE_OPTION) null19        else if (directory) listOf(chooser.selectedFile.toPath()) else chooser.selectedFiles.map { it.toPath() }20    } ?: return null21    return withContext(Dispatchers.IO) {22        val inputs = mutableListOf<LocalMediaInput>()23        for (root in selected) {24            val paths = if (directory) Files.walk(root) else java.util.stream.Stream.of(root)25            paths.use { walk ->26                val iterator = walk.iterator()27                var visited = 028                while (iterator.hasNext()) {29                    currentCoroutineContext().ensureActive()30                    check(++visited <= 50_000) { "Selected folder is too large" }31                    val path = iterator.next()32                    if (!Files.isRegularFile(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) continue33                    val relative = if (directory) "${root.fileName}/${root.relativize(path).toString().replace('\\', '/')}" else path.fileName.toString()34                    if (relative.split('/').any { it.startsWith('.') } || relative.substringAfterLast('.', "").lowercase() !in localImportExtensions) continue35                    check(inputs.size < LOCAL_IMPORT_MAX_FILES) { "Too many selected files" }36                    inputs += JvmLocalMediaInput(relative, Files.size(path)) { Files.newInputStream(path) }37                }38            }39        }40        LocalMediaSelection(inputs)41    }42}43

Search chapters, reference and source filenames.