From bdd5c571aee5b7afa790e3448abfbe9bfd736ea3 Mon Sep 17 00:00:00 2001 From: Ziedelth Date: Tue, 16 Apr 2024 17:20:38 +0200 Subject: [PATCH] Fix Bsky facets --- .../fr/shikkanime/wrappers/BskyWrapper.kt | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/src/main/kotlin/fr/shikkanime/wrappers/BskyWrapper.kt b/src/main/kotlin/fr/shikkanime/wrappers/BskyWrapper.kt index eb757a42..fb1be431 100644 --- a/src/main/kotlin/fr/shikkanime/wrappers/BskyWrapper.kt +++ b/src/main/kotlin/fr/shikkanime/wrappers/BskyWrapper.kt @@ -68,8 +68,10 @@ object BskyWrapper { text: String, images: List = emptyList(), ): JsonObject { + val (finalText, facets) = getFacets(text) + val recordMap = mutableMapOf( - "text" to text, + "text" to finalText, TYPE to "app.bsky.feed.post", "createdAt" to ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC")) .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME).replace("+00:00", "Z"), @@ -82,16 +84,6 @@ object BskyWrapper { ) } - // Get all links in the text, and their start and end indexes - val facets = text.split(" ").mapNotNull { word -> - val link = word.trim() - if (link.startsWith("http")) { - val start = text.indexOf(link) - val end = start + link.length - Facet(link, start, end) - } else null - } - if (facets.isNotEmpty()) { recordMap["facets"] = facets.map { mapOf( @@ -128,4 +120,23 @@ object BskyWrapper { require(response.status.value == 200) { "Failed to create record (${response.bodyAsText()})" } return ObjectParser.fromJson(response.bodyAsText()) } + + private fun getFacets(text: String): Pair> { + var tmpText = text + + val facets = text.split(" ").mapNotNull { word -> + val link = word.trim() + + if (link.startsWith("http")) { + val beautifulLink = link.replace("https?://www\\.|\\?.*".toRegex(), "") + tmpText = tmpText.replace(link, beautifulLink) + + val start = tmpText.indexOf(beautifulLink) + val end = start + beautifulLink.length + Facet(link, start, end) + } else null + } + + return tmpText to facets + } } \ No newline at end of file