package eu.friedcutlet.yokan.services.extensions.js import eu.friedcutlet.yokan.services.extensions.RemoteManga import eu.friedcutlet.yokan.services.extensions.SourceRelatedGroup import eu.friedcutlet.yokan.services.extensions.SourceRelations import eu.friedcutlet.yokan.services.extensions.sourceImageUrl import kotlinx.serialization.json.* /** Bounded groups with stable source URLs; repeated labels merge without duplicate entries. */ internal fun sourceRelationsFromJson(element: JsonElement, baseUrl: String): SourceRelations { val root = element as? JsonArray ?: error("The source returned invalid related entries") require(root.size <= 50) { "The source returned too many relation groups" } val groups = linkedMapOf>() var count = 0L fun JsonObject.text(vararg keys: String) = keys.firstNotNullOfOrNull { key -> (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.takeIf(String::isNotEmpty) } root.forEach { value -> val group = value as? JsonObject ?: return@forEach val rows = (group["animes"] ?: group["items"]) as? JsonArray ?: return@forEach count += rows.size.toLong() require(count <= 1_000) { "The source returned too many related entries" } val name = group.text("name") ?: return@forEach val items = groups.getOrPut(name) { linkedMapOf() } rows.forEach row@{ element -> val row = element as? JsonObject ?: return@row val title = row.text("name", "title") ?: return@row val url = row.text("link", "url") ?: return@row if (url.any { it <= ' ' || it == '\\' || it == '\u007f' }) return@row if (RelationScheme.containsMatchIn(url) && !url.startsWith("https://", true) && !url.startsWith("http://", true)) return@row if ((RelationScheme.containsMatchIn(url) || url.startsWith("//")) && sourceImageUrl(url, baseUrl) == null) return@row val image = row.text("imageUrl", "thumbnailUrl", "thumbnail_url") if (url !in items) items[url] = RemoteManga(title, url, sourceImageUrl(image, baseUrl), row.text("description"), initialized = true) } } return SourceRelations(true, groups.mapNotNull { (name, items) -> items.values.takeIf { it.isNotEmpty() }?.let { SourceRelatedGroup(name, it.toList()) } }) } private val RelationScheme = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")