Keep Android message link parsing linear and validate authority
This commit is contained in:
1 parent
0e04d4f6aa
commit
52f2e244f7
3 files changed
+104
-10
No files matched your search
@@ -80,6 +80,9 @@ android {
|
||||
// Зависимость только между задачами: Android fixtures из JVM-модуля не входят в classpath приложения/APK.
|
||||
tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {
|
||||
dependsOn(":router-tests:test")
|
||||
val messageLinkCases = rootProject.file("../chatgui/tests/message_links_cases.tsv")
|
||||
inputs.file(messageLinkCases)
|
||||
systemProperty("utun.messageLinkCases", messageLinkCases.absolutePath)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -1,33 +1,51 @@
|
||||
package com.utun.chat.data
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URL
|
||||
|
||||
/** Границы UTF-16 и полный адрес; разбор не меняет текст и не открывает ссылки. */
|
||||
/** Диапазон [start, end) в UTF-16 исходного сообщения и полный адрес без внешней пунктуации. */
|
||||
data class MessageLink(val start: Int, val end: Int, val url: String)
|
||||
|
||||
/** Чистый разбор для подсветки: HTTP/HTTPS без учёта регистра и utun://; сеть и JNI не вызываются. */
|
||||
object MessageLinks {
|
||||
private val pattern = Regex("utun://[A-Za-z0-9+/]+={0,2}|(?i:https?://)[^\\s\\p{Z}\\p{Cc}<>\"'`«»“”‘’]+")
|
||||
private val invalidEscape = Regex("%(?![0-9A-Fa-f]{2})")
|
||||
|
||||
/** Некорректные URL в пользовательском тексте остаются обычным текстом. */
|
||||
/** Проверяет полный HTTP/HTTPS URL; порт пустой либо десятичный 0..65535. Некорректный текст — обычный ввод, без логов. */
|
||||
fun isWebUrl(url: String): Boolean {
|
||||
if (!pattern.matches(url) || invalidEscape.containsMatchIn(url)) return false
|
||||
return try {
|
||||
val parsed = URL(url)
|
||||
(parsed.protocol == "http" || parsed.protocol == "https") && parsed.host.isNotEmpty() && parsed.port in -1..65535
|
||||
} catch (_: java.net.MalformedURLException) { false }
|
||||
if ((parsed.protocol != "http" && parsed.protocol != "https") || parsed.host.isEmpty() || parsed.port !in -1..65535) return false
|
||||
// URL допускает -1/+80 и недопустимые символы host; URI проверяет только authority, не ограничивая Unicode/[] в пути.
|
||||
val authority = URI("//${parsed.authority}").rawAuthority?.substringAfterLast('@') ?: return false
|
||||
val port = if (authority.startsWith("[")) authority.substringAfter(']').substringAfter(':', "")
|
||||
else authority.substringAfter(':', "")
|
||||
port.all { it in '0'..'9' }
|
||||
} catch (_: java.net.MalformedURLException) { false } catch (_: java.net.URISyntaxException) { false }
|
||||
}
|
||||
|
||||
/** Возвращает непересекающиеся диапазоны по порядку; отделение хвоста занимает O(n), адрес копируется один раз. */
|
||||
fun parse(text: String): List<MessageLink> = pattern.findAll(text).mapNotNull { match ->
|
||||
var url = match.value
|
||||
if (!url.startsWith("utun://")) {
|
||||
while (url.isNotEmpty()) {
|
||||
val last = url.last()
|
||||
val closing = ")]}".indexOf(last)
|
||||
val unmatched = closing >= 0 && url.count { it == last } > url.count { it == "([{"[closing] }
|
||||
if (last !in ".,;:!?" && !unmatched) break
|
||||
url = url.dropLast(1)
|
||||
val balance = IntArray(3)
|
||||
for (char in url) {
|
||||
val opening = "([{".indexOf(char)
|
||||
val closing = ")]}".indexOf(char)
|
||||
if (opening >= 0) balance[opening]--
|
||||
if (closing >= 0) balance[closing]++
|
||||
}
|
||||
var end = url.length
|
||||
while (end > 0) {
|
||||
val last = url[end - 1]
|
||||
val closing = ")]}".indexOf(last)
|
||||
val unmatched = closing >= 0 && balance[closing] > 0
|
||||
if (last !in ".,;:!?" && !unmatched) break
|
||||
if (closing >= 0) balance[closing]--
|
||||
end--
|
||||
}
|
||||
url = url.substring(0, end)
|
||||
if (!isWebUrl(url)) return@mapNotNull null
|
||||
}
|
||||
MessageLink(match.range.first, match.range.first + url.length, url)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.utun.chat.data
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/** Общие с Qt адреса и диапазоны UTF-16; разбор длинного хвоста не задерживает UI. */
|
||||
class MessageLinksTest {
|
||||
private fun assertLinks(text: String, expected: List<String>) {
|
||||
val links = MessageLinks.parse(text)
|
||||
assertEquals(text.take(200), expected, links.map { it.url })
|
||||
var end = 0
|
||||
for (link in links) {
|
||||
assertTrue(link.start >= end)
|
||||
assertEquals(link.url, text.substring(link.start, link.end))
|
||||
end = link.end
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sharedQtAndAndroidCases() {
|
||||
val fixture = File(requireNotNull(System.getProperty("utun.messageLinkCases")))
|
||||
var count = 0
|
||||
fixture.forEachLine { line ->
|
||||
if (line.isNotEmpty() && !line.startsWith("#")) {
|
||||
val columns = line.split('\t')
|
||||
assertLinks(columns.first().replace("\\n", "\n"), columns.drop(1))
|
||||
count++
|
||||
}
|
||||
}
|
||||
assertTrue("Expected shared link cases", count >= 15)
|
||||
}
|
||||
|
||||
@Test fun openingOnlyAcceptsCompleteWebUrls() {
|
||||
for (url in listOf("http://example.com/", "HTTPS://пример.рф/путь", "https://[::1]:65535/",
|
||||
"http://example.com:0/", "http://example.com:/", "http://example.com:00080/")) {
|
||||
assertTrue(url, MessageLinks.isWebUrl(url))
|
||||
}
|
||||
for (url in listOf("utun://abc+/==", "ftp://example.com/", "https://", "https://example.com/a b", "https://example.com/%GG")) {
|
||||
assertFalse(url, MessageLinks.isWebUrl(url))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun malformedAuthorityIsNeitherAnnotatedNorOpened() {
|
||||
for (url in listOf("http://example.com:-1/", "http://example.com:+80/", "http://example.com:-0/", "http://example.com\\foo/")) {
|
||||
assertFalse(url, MessageLinks.isWebUrl(url))
|
||||
assertLinks(url, emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun bracketTypesHaveIndependentBalances() {
|
||||
for (path in listOf("a(b)", "a[0]", "a{0}", "a([{}])", "a((b)", "a[b[0]")) {
|
||||
val url = "https://example.com/$path"
|
||||
assertLinks("✨ $url.,;:!?", listOf(url))
|
||||
}
|
||||
assertLinks("https://example.com/a(b)))! next", listOf("https://example.com/a(b)"))
|
||||
assertLinks("https://example.com/a[0]}).", listOf("https://example.com/a[0]"))
|
||||
assertLinks("https://example.com/a)(b)", listOf("https://example.com/a)(b"))
|
||||
}
|
||||
|
||||
@Test(timeout = 5_000) fun longMixedTailKeepsOriginalRangesWithoutRepeatedCopies() {
|
||||
val first = "https://example.com/a([{}])"
|
||||
val second = "http://example.org/b"
|
||||
val text = "👋 $first" + ")]},.!?".repeat(20_000) + " $second"
|
||||
assertLinks(text, listOf(first, second))
|
||||
assertEquals(3, MessageLinks.parse(text).first().start)
|
||||
}
|
||||
|
||||
@Test fun textWithoutLinksStaysUnannotated() {
|
||||
for (text in listOf("", "Обычный текст 👋", "www.example.com", "http:// https://?x=1")) {
|
||||
assertLinks(text, emptyList())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user