package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.files.downloadItemTypeFolder fun downloadStorageRoot(configuredRoot: String?, files: LocalFileService): String = (configuredRoot?.takeIf { it.isNotBlank() } ?: files.downloadRoot).trimEnd('/', '\\') fun downloadStorageRootCandidates(configuredRoot: String?, files: LocalFileService): List { val root = downloadStorageRoot(configuredRoot, files) return listOf(root, "$root/downloads").distinct() } /** Chapter folder a download writes to: `////`. */ internal fun downloadChapterLocation( storageRoot: String, itemType: DbItemType, sourceLabel: String, mangaName: String, scanlator: String, chapterName: String, ): String { val source = sanitizeDownloadName(sourceLabel.ifBlank { "Source" }) val manga = sanitizeDownloadName(mangaName.ifBlank { "Unknown" }) val scanlatorPrefix = if (scanlator.isNotBlank()) "${sanitizeDownloadName(scanlator)}_" else "" val chapter = sanitizeDownloadName(chapterName.ifBlank { "Chapter" }) return "$storageRoot/${downloadItemTypeFolder(itemType)}/$source/$manga/$scanlatorPrefix$chapter" } /** The source folder label of a chapter download: "Name (LANG)", else the title's own source name. */ internal fun downloadSourceLabel(sourceName: String?, sourceLang: String?, titleSource: String): String = sourceName?.let { "$it (${sourceLang.orEmpty().uppercase()})" } ?: titleSource internal fun sanitizeDownloadName(value: String): String = value.trim().replace(UnsafeFileNameChars, "_").take(120) .let { if (it.isBlank() || it == "." || it == "..") "_" else it } private val UnsafeFileNameChars = Regex("[\\\\/:*?\"<>|\\u0000]")