package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.domain.TitleCredit import io.ktor.http.URLBuilder import io.ktor.http.URLProtocol import io.ktor.http.URLParserException import io.ktor.http.takeFrom /** Source portraits may be web resources; local-file access belongs to the local scanner. */ internal fun normalizeSourceCast(credits: List, baseUrl: String): List = credits.take(500).mapNotNull { credit -> val name = credit.name.trim().takeIf(String::isNotEmpty) ?: return@mapNotNull null credit.copy( name = name, role = credit.role?.trim()?.takeIf(String::isNotEmpty), character = credit.character?.trim()?.takeIf(String::isNotEmpty), imageUrl = sourceImageUrl(credit.imageUrl, baseUrl), ) }.distinctBy { Triple(it.name, it.role, it.character) } internal fun sourceImageUrl(value: String?, baseUrl: String): String? { val reference = value?.trim()?.takeIf(String::isNotEmpty) ?: return null if (reference.any { it <= ' ' || it == '\\' || it == '\u007f' }) return null val scheme = SourcePortraitScheme.find(reference)?.value?.dropLast(1)?.lowercase() if (scheme != null && scheme != "http" && scheme != "https") return null if (scheme != null && !reference.startsWith("$scheme://", ignoreCase = true)) return null fun hasAuthority(url: String) = url.substringAfter("//").takeWhile { it != '/' && it != '?' && it != '#' }.isNotEmpty() if ((scheme != null || reference.startsWith("//")) && !hasAuthority(reference)) return null return try { val builder = if (scheme != null) URLBuilder() else { if (!baseUrl.startsWith("https://", ignoreCase = true) && !baseUrl.startsWith("http://", ignoreCase = true)) return null if (!hasAuthority(baseUrl) || baseUrl.any { it <= ' ' || it == '\\' || it == '\u007f' }) return null URLBuilder(baseUrl.substringBefore('#').substringBefore('?').trimEnd('/') + "/") } val url = builder.takeFrom(reference).build() // Ktor's parser accepts an unmatched IPv6 bracket; do not persist that address. val validHostBrackets = if (url.host.startsWith('[')) { url.host.endsWith(']') && ':' in url.host && url.host.count { it == '[' || it == ']' } == 2 } else '[' !in url.host && ']' !in url.host url.takeIf { (it.protocol == URLProtocol.HTTP || it.protocol == URLProtocol.HTTPS) && it.host.isNotBlank() && validHostBrackets && it.user == null && it.password == null }?.toString() } catch (_: URLParserException) { null } catch (_: IllegalArgumentException) { null } } private val SourcePortraitScheme = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")