Merge upstream/main into feat/desktop-advanced-search

Resolve conflicts:
- RelayStatus.kt: keep both relay URLs
- SearchScreen.kt: keep advanced search implementation
- SinglePaneLayout.kt: add missing Spacer import

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
nrobi144
2026-03-12 13:22:15 +02:00
363 changed files with 17702 additions and 2051 deletions
@@ -5,14 +5,14 @@
<string name="login_subtitle">Sign in to your Nostr account</string>
<string name="login_subtitle_desktop">A Nostr client for desktop</string>
<string name="login_card_title">Login with your Nostr key</string>
<string name="login_card_subtitle">Use nsec for full access or npub for read-only</string>
<string name="login_card_subtitle">nsec for full access, bunker:// for remote signer, or npub for read-only</string>
<string name="login_with_key">Login with Key</string>
<string name="login_button">Login</string>
<string name="login_generate_new">Generate New Key</string>
<string name="login_generate_button">Generate New</string>
<string name="login_key_hint">Enter your private key (nsec) or public key (npub)</string>
<string name="login_key_label">nsec or npub</string>
<string name="login_key_placeholder">nsec1... or npub1...</string>
<string name="login_key_label">nsec, bunker://, or npub</string>
<string name="login_key_placeholder">nsec1… / bunker://… / npub1</string>
<string name="login_show_key">Show key</string>
<string name="login_hide_key">Hide key</string>
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.domain.nip46
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip46RemoteSigner.signer.NostrSignerRemote
data class BunkerLoginResult(
val signer: NostrSignerRemote,
val pubKeyHex: HexKey,
)
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.domain.nip46
import com.vitorpamplona.quartz.nip01Core.relay.client.INostrClient
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
import com.vitorpamplona.quartz.nip46RemoteSigner.signer.NostrSignerRemote
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeout
object BunkerLoginUseCase {
const val RELAY_CONNECT_TIMEOUT_MS = 15_000L
suspend fun execute(
bunkerUri: String,
ephemeralSigner: NostrSignerInternal,
client: INostrClient,
): BunkerLoginResult {
val remoteSigner = NostrSignerRemote.fromBunkerUri(bunkerUri, ephemeralSigner, client)
remoteSigner.openSubscription()
// Wait for websocket to be ready before sending connect request
withTimeout(RELAY_CONNECT_TIMEOUT_MS) {
client.connectedRelaysFlow().first { connected ->
remoteSigner.relays.any { it in connected }
}
}
remoteSigner.connect()
val pubkey = remoteSigner.getPublicKey()
return BunkerLoginResult(remoteSigner, pubkey)
}
}
@@ -0,0 +1,218 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.domain.nip46
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.OptimizedJsonMapper
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.relay.client.INostrClient
import com.vitorpamplona.quartz.nip01Core.relay.client.reqs.req
import com.vitorpamplona.quartz.nip01Core.relay.filters.Filter
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
import com.vitorpamplona.quartz.nip46RemoteSigner.BunkerMessage
import com.vitorpamplona.quartz.nip46RemoteSigner.BunkerRequest
import com.vitorpamplona.quartz.nip46RemoteSigner.BunkerRequestConnect
import com.vitorpamplona.quartz.nip46RemoteSigner.BunkerResponse
import com.vitorpamplona.quartz.nip46RemoteSigner.BunkerResponseAck
import com.vitorpamplona.quartz.nip46RemoteSigner.NostrConnectEvent
import com.vitorpamplona.quartz.nip46RemoteSigner.signer.NostrSignerRemote
import com.vitorpamplona.quartz.utils.Hex
import com.vitorpamplona.quartz.utils.SecureRandom
import com.vitorpamplona.quartz.utils.TimeUtils
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeout
object NostrConnectLoginUseCase {
const val NOSTRCONNECT_TIMEOUT_MS = 120_000L
data class NostrConnectUri(
val uri: String,
val ephemeralKeyPair: KeyPair,
val ephemeralSigner: NostrSignerInternal,
val relays: Set<NormalizedRelayUrl>,
val secret: String,
)
data class ConnectRequestData(
val requestId: String?,
val signerPubkey: HexKey,
val userPubkey: HexKey,
)
fun generateUri(
ephemeralKeyPair: KeyPair,
relays: List<String>,
appName: String,
): NostrConnectUri {
val ephemeralSigner = NostrSignerInternal(ephemeralKeyPair)
val ephemeralPubKey = ephemeralKeyPair.pubKey.toHexKey()
val secret = generateSecret()
val relayParams = relays.joinToString("&") { "relay=$it" }
val uri = "nostrconnect://$ephemeralPubKey?$relayParams&secret=$secret&name=$appName"
val normalizedRelays = relays.map { NormalizedRelayUrl(it) }.toSet()
return NostrConnectUri(
uri = uri,
ephemeralKeyPair = ephemeralKeyPair,
ephemeralSigner = ephemeralSigner,
relays = normalizedRelays,
secret = secret,
)
}
suspend fun awaitAndLogin(
uriData: NostrConnectUri,
client: INostrClient,
): BunkerLoginResult {
val connectData =
waitForConnectRequest(
ephemeralSigner = uriData.ephemeralSigner,
ephemeralPubKey = uriData.ephemeralKeyPair.pubKey.toHexKey(),
relays = uriData.relays,
expectedSecret = uriData.secret,
client = client,
)
if (connectData.requestId != null) {
sendAckResponse(uriData.ephemeralSigner, connectData, uriData.relays, client)
}
val remoteSigner =
NostrSignerRemote(
signer = uriData.ephemeralSigner,
remotePubkey = connectData.signerPubkey,
relays = uriData.relays,
client = client,
)
remoteSigner.openSubscription()
val verifiedPubkey = remoteSigner.getPublicKey()
return BunkerLoginResult(remoteSigner, verifiedPubkey)
}
private suspend fun waitForConnectRequest(
ephemeralSigner: NostrSignerInternal,
ephemeralPubKey: HexKey,
relays: Set<NormalizedRelayUrl>,
expectedSecret: String,
client: INostrClient,
): ConnectRequestData {
val deferred = CompletableDeferred<NostrConnectEvent>()
val subscription =
client.req(
relays = relays.toList(),
filter =
Filter(
kinds = listOf(NostrConnectEvent.KIND),
tags = mapOf("p" to listOf(ephemeralPubKey)),
since = TimeUtils.now() - 60,
),
) { event ->
if (event is NostrConnectEvent && !deferred.isCompleted) {
deferred.complete(event)
}
}
try {
val event =
withTimeout(NOSTRCONNECT_TIMEOUT_MS) {
deferred.await()
}
val signerPubkey = event.talkingWith(ephemeralSigner.pubKey)
val decryptedJson = ephemeralSigner.decrypt(event.content, signerPubkey)
val message = OptimizedJsonMapper.fromJsonTo<BunkerMessage>(decryptedJson)
return when (message) {
is BunkerRequest -> {
if (message.method != BunkerRequestConnect.METHOD_NAME) {
throw Exception("Expected 'connect' method, got '${message.method}'")
}
val userPubkey =
message.params.getOrNull(0)
?: throw Exception("Missing user pubkey in connect request")
val receivedSecret = message.params.getOrNull(1)
if (receivedSecret != expectedSecret) {
throw Exception("Secret mismatch in connect request")
}
ConnectRequestData(
requestId = message.id,
signerPubkey = signerPubkey,
userPubkey = userPubkey,
)
}
is BunkerResponse -> {
if (message.error != null) {
throw Exception("Signer rejected connection: ${message.error}")
}
val userPubkey =
message.result
?.takeIf { it.length == 64 && Hex.isHex(it) }
?: signerPubkey
ConnectRequestData(
requestId = null,
signerPubkey = signerPubkey,
userPubkey = userPubkey,
)
}
else -> {
throw Exception("Unexpected NIP-46 message format")
}
}
} finally {
subscription.close()
}
}
private suspend fun sendAckResponse(
ephemeralSigner: NostrSignerInternal,
connectData: ConnectRequestData,
relays: Set<NormalizedRelayUrl>,
client: INostrClient,
) {
val ackResponse = BunkerResponseAck(id = connectData.requestId!!)
val ackEvent =
NostrConnectEvent.create(
message = ackResponse,
remoteKey = connectData.signerPubkey,
signer = ephemeralSigner,
)
client.send(ackEvent, relays)
}
private fun generateSecret(): String {
val bytes = ByteArray(32)
SecureRandom().nextBytes(bytes)
return bytes.joinToString("") { "%02x".format(it) }
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.domain.nip46
sealed class SignerConnectionState {
data object NotRemote : SignerConnectionState()
data object Connected : SignerConnectionState()
data object Disconnected : SignerConnectionState()
}
@@ -890,7 +890,7 @@ open class Note(
return true
}
if (author?.containsAny(accountChoices.hiddenWordsCase) == true) return true
if (author?.metadataOrNull()?.anyPropertyContains(accountChoices.hiddenWordsCase) == true) return true
}
return false
@@ -36,7 +36,6 @@ import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent
import com.vitorpamplona.quartz.nip19Bech32.entities.NProfile
import com.vitorpamplona.quartz.nip19Bech32.toNpub
import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent
import com.vitorpamplona.quartz.utils.DualCase
import com.vitorpamplona.quartz.utils.Hex
interface UserDependencies
@@ -141,8 +140,6 @@ class User(
fun relayStateOrNull(): UserRelaysCache? = relays
fun relayState(): UserRelaysCache = relays ?: UserRelaysCache().also { relays = it }
fun containsAny(hiddenWordsCase: List<DualCase>) = metadataOrNull()?.containsAny(hiddenWordsCase) == true
}
fun Set<User>.toHexSet() = mapTo(LinkedHashSet(size)) { it.pubkeyHex }
@@ -28,7 +28,6 @@ import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata
import com.vitorpamplona.quartz.nip39ExtIdentities.IdentityClaimTag
import com.vitorpamplona.quartz.nip39ExtIdentities.identityClaims
import com.vitorpamplona.quartz.utils.DualCase
import com.vitorpamplona.quartz.utils.containsAny
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
@@ -60,48 +59,16 @@ class UserMetadataCache {
fun shouldUpdateWith(event: MetadataEvent) = event.createdAt > (flow.value?.createdAt ?: 0)
fun anyNameStartsWith(username: String): Boolean = flow.value?.info?.anyNameStartsWith(username) ?: false
fun anyNameOrAddressContains(terms: List<DualCase>): Boolean = flow.value?.info?.anyNameOrAddressContains(terms) ?: false
fun containsAny(hiddenWordsCase: List<DualCase>): Boolean {
fun anyNameStartsWith(terms: List<DualCase>): Boolean = flow.value?.info?.anyNameStartsWith(terms) ?: false
fun anyAddressStartsWith(terms: List<DualCase>): Boolean = flow.value?.info?.anyAddressStartsWith(terms) ?: false
fun anyPropertyContains(hiddenWordsCase: List<DualCase>): Boolean {
if (hiddenWordsCase.isEmpty()) return false
flow.value?.let { userInfo ->
val info = userInfo.info
if (info.name?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.displayName?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.picture?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.banner?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.about?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.lud06?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.lud16?.containsAny(hiddenWordsCase) == true) {
return true
}
if (info.nip05?.containsAny(hiddenWordsCase) == true) {
return true
}
}
return false
return flow.value?.info?.anyPropertyContains(hiddenWordsCase) ?: false
}
fun bestName(): String? = flow.value?.info?.bestName()
@@ -22,7 +22,7 @@ package com.vitorpamplona.amethyst.commons.model.nip05DnsIdentifiers
import androidx.compose.runtime.Stable
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip05DnsIdentifiers.Nip05Client
import com.vitorpamplona.quartz.nip05DnsIdentifiers.INip05Client
import com.vitorpamplona.quartz.nip05DnsIdentifiers.Nip05Id
import com.vitorpamplona.quartz.utils.TimeUtils
import kotlinx.coroutines.flow.MutableStateFlow
@@ -49,7 +49,7 @@ sealed interface Nip05State {
fun reset() = verificationState.tryEmit(Nip05VerifState.NotStarted)
suspend fun checkAndUpdate(nip05Client: Nip05Client) {
suspend fun checkAndUpdate(nip05Client: INip05Client) {
if (verificationState.value.isExpired()) {
markAsVerifying()
try {
@@ -44,10 +44,11 @@ class ExpandableTextCutOffCalculator {
if (min > TOO_FAR_SEARCH_THE_OTHER_WAY) {
// if it is still too big, finds the first space or new line BEFORE the cut off.
val newString = content.take(SHORT_TEXT_LENGTH)
val firstSpaceBeforeCut =
newString.lastIndexOf(' ').let { if (it < 0) content.length else it }
newString.lastIndexOf(' ').let { if (it < 0) newString.length else it }
val firstNewLineBeforeCut =
newString.lastIndexOf('\n').let { if (it < 0) content.length else it }
newString.lastIndexOf('\n').let { if (it < 0) newString.length else it }
maxOf(firstSpaceBeforeCut, firstNewLineBeforeCut)
} else {
@@ -20,8 +20,6 @@
*/
package com.vitorpamplona.amethyst.commons.richtext
import com.linkedin.urls.detection.UrlDetector
import com.linkedin.urls.detection.UrlDetectorOptions
import com.vitorpamplona.amethyst.commons.emojicoder.EmojiCoder
import com.vitorpamplona.amethyst.commons.model.ImmutableListOfLists
import com.vitorpamplona.quartz.experimental.inlineMetadata.Nip54InlineMetadata
@@ -39,7 +37,6 @@ import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toImmutableMap
import kotlinx.collections.immutable.toImmutableSet
import kotlinx.collections.immutable.toPersistentList
import java.net.MalformedURLException
import java.net.URISyntaxException
@@ -101,27 +98,43 @@ class RichTextParser {
}
}
fun parseValidUrls(content: String): LinkedHashSet<String> {
val urls = UrlDetector(content, UrlDetectorOptions.Default).detect()
fun fixMissingSpaces(
input: String,
urlList: Set<String>,
): String {
if (urlList.isEmpty()) return input
return urls.mapNotNullTo(LinkedHashSet(urls.size)) {
if (it.originalUrl.contains("@")) {
if (Patterns.EMAIL_ADDRESS.matches(it.originalUrl)) {
null
} else {
it.originalUrl
}
} else if (isNumber(it.originalUrl)) {
null // avoids urls that look like 123.22
} else if (it.originalUrl.contains("")) {
null // avoids Japanese characters as fake urls
} else {
if (HTTPRegex.matches(it.originalUrl)) {
it.originalUrl
} else {
null
}
// Escape and join words: (word1|word2)
val wordsPattern = urlList.sortedByDescending { it.length }.joinToString("|") { Regex.escape(it) }
// Regex breakdown:
// ([^ ])? -> Group 1: Optional character that is NOT a space or new line (Prefix)
// ($wordsPattern) -> Group 2: One of your target words
// ([^ ])? -> Group 3: Optional character that is NOT a space or new line (Suffix)
val regex = Regex("([^ \n])?($wordsPattern)([^ \n])?")
return regex.replace(input) { match ->
val prefix = match.groups[1]?.value ?: ""
val word = match.groups[2]?.value ?: ""
val suffix = match.groups[3]?.value ?: ""
val result = StringBuilder()
// Add prefix + space if the prefix exists
if (prefix.isNotEmpty()) {
result.append(prefix)
result.append(" ")
}
result.append(word)
// Add space + suffix if the suffix exists
if (suffix.isNotEmpty()) {
result.append(" ")
result.append(suffix)
}
result.toString()
}
}
@@ -131,30 +144,41 @@ class RichTextParser {
callbackUri: String?,
): RichTextViewerState {
val imetas = tags.lists.imetasByUrl()
val urlSet = parseValidUrls(content)
val urlSet = UrlParser().parseValidUrls(content)
val imagesForPager =
urlSet.mapNotNull { fullUrl -> createMediaContent(fullUrl, imetas, content, callbackUri) }.associateBy { it.url }
val mediaContents =
urlSet.withScheme.mapNotNull { fullUrl ->
createMediaContent(fullUrl, imetas, content, callbackUri)
} +
urlSet.withoutScheme.mapNotNull { fullUrl ->
createMediaContent(fullUrl, imetas, content, callbackUri)
}
val imageUrls = imagesForPager.filterValues { it is MediaUrlImage }.keys
val videoUrls = imagesForPager.filterValues { it is MediaUrlVideo }.keys
val mediaForPager = mediaContents.associateBy { it.url }
val imageUrls = mediaForPager.filterValues { it is MediaUrlImage }.keys
val videoUrls = mediaForPager.filterValues { it is MediaUrlVideo }.keys
val emojiMap = CustomEmoji.createEmojiMap(tags.lists)
val segments = findTextSegments(content, imageUrls, videoUrls, urlSet, emojiMap, tags)
val allUrls = urlSet.withScheme + urlSet.withoutScheme + urlSet.emails + urlSet.bech32s + urlSet.relayUrls
val base64Images = segments.map { it.words.filterIsInstance<Base64Segment>() }.flatten()
val newContent = fixMissingSpaces(content, allUrls)
val imagesForPagerWithBase64 =
imagesForPager +
val segments = findTextSegments(newContent, imageUrls, videoUrls, urlSet, emojiMap, tags)
val base64Images = segments.flatMap { it.words.filterIsInstance<Base64Segment>() }
val mediaForPagerWithBase64 =
mediaForPager +
base64Images
.mapNotNull { createMediaContent(it.segmentText, emptyMap(), content, callbackUri) }
.associateBy { it.url }
return RichTextViewerState(
urlSet.toImmutableSet(),
imagesForPagerWithBase64.toImmutableMap(),
imagesForPagerWithBase64.values.toImmutableList(),
urlSet,
mediaForPagerWithBase64.toImmutableMap(),
mediaForPagerWithBase64.values.toImmutableList(),
emojiMap.toImmutableMap(),
segments,
tags,
@@ -165,7 +189,7 @@ class RichTextParser {
content: String,
images: Set<String>,
videos: Set<String>,
urls: Set<String>,
urls: Urls,
emojis: Map<String, String>,
tags: ImmutableListOfLists<String>,
): ImmutableList<ParagraphState> {
@@ -175,18 +199,14 @@ class RichTextParser {
lines.forEach { paragraph ->
val isRTL = isArabic(paragraph)
val wordList = paragraph.trimEnd().split(wordBoundaryRegex).filter { it.isNotEmpty() }
val wordList = paragraph.trimEnd().split(' ')
if (wordList.isEmpty()) {
paragraphSegments.add(ParagraphState(persistentListOf(RegularTextSegment("")), isRTL))
} else {
val segments = ArrayList<Segment>(wordList.size)
wordList.forEach { word ->
segments.add(wordIdentifier(word, images, videos, urls, emojis, tags))
}
paragraphSegments.add(ParagraphState(segments.toPersistentList(), isRTL))
val segments = ArrayList<Segment>(wordList.size)
wordList.forEach { word ->
segments.add(wordIdentifier(word, images, videos, urls, emojis, tags))
}
paragraphSegments.add(ParagraphState(segments.toPersistentList(), isRTL))
}
val segmentsWithGalleries = GalleryParser().processParagraphs(paragraphSegments)
@@ -204,8 +224,6 @@ class RichTextParser {
}.toImmutableList()
}
private fun isNumber(word: String) = numberPattern.matches(word)
private fun isPhoneNumberChar(c: Char): Boolean =
when (c) {
in '0'..'9' -> true
@@ -236,7 +254,7 @@ class RichTextParser {
word: String,
images: Set<String>,
videos: Set<String>,
urls: Set<String>,
urls: Urls,
emojis: Map<String, String>,
tags: ImmutableListOfLists<String>,
): Segment {
@@ -246,13 +264,33 @@ class RichTextParser {
if (Patterns.BASE64_IMAGE.matches(word)) return Base64Segment(word)
}
if (images.contains(word)) return ImageSegment(word)
if (images.contains(word)) {
return if (urls.withoutScheme.contains(word)) {
ImageSegment("https://$word")
} else {
ImageSegment(word)
}
}
if (videos.contains(word)) return VideoSegment(word)
if (videos.contains(word)) {
return if (urls.withoutScheme.contains(word)) {
VideoSegment("https://$word")
} else {
VideoSegment(word)
}
}
if (word.startsWith("ws://") || word.startsWith("wss://")) return RelayUrlSegment(word)
if (urls.withoutScheme.contains(word)) return SchemelessUrlSegment(word)
if (urls.contains(word)) return LinkSegment(word)
if (urls.withScheme.contains(word)) return LinkSegment(word)
if (urls.emails.contains(word)) return EmailSegment(word)
if (urls.bech32s.contains(word)) return BechSegment(word)
if (urls.relayUrls.contains(word)) return RelayUrlSegment(word)
if (startsWithNIP19Scheme(word)) return BechSegment(word)
if (CustomEmoji.fastMightContainEmoji(word, emojis) && emojis.any { word.contains(it.key) }) return EmojiSegment(word)
@@ -262,32 +300,14 @@ class RichTextParser {
if (word.startsWith("cashuA", true) || word.startsWith("cashuB", true)) return CashuSegment(word)
if (word.startsWith("#")) return parseHash(word, tags)
if (word.startsWith('#')) return parseHash(word, tags)
if (EmojiCoder.isCoded(word)) return SecretEmoji(word)
if (word.contains("@")) {
if (Patterns.EMAIL_ADDRESS.matches(word)) return EmailSegment(word)
}
if (startsWithNIP19Scheme(word)) return BechSegment(word)
if (isPotentialPhoneNumber(word) && !isDate(word)) {
if (Patterns.PHONE.matches(word)) return PhoneSegment(word)
}
val indexOfPeriod = word.indexOf(".")
if (indexOfPeriod > 0 && indexOfPeriod < word.length - 1) { // periods cannot be the last one
val schemelessMatcher = noProtocolUrlValidator.find(word)
if (schemelessMatcher != null) {
val url = schemelessMatcher.groups[1]?.value // url
val additionalChars = schemelessMatcher.groups[4]?.value?.ifEmpty { null } // additional chars
if (additionalUrlSchema.find(word) != null && url != null) {
return SchemelessUrlSegment(word, url, additionalChars)
}
}
}
return RegularTextSegment(word)
}
@@ -343,7 +363,7 @@ class RichTextParser {
val noProtocolUrlValidator =
Regex(
"(([a-zA-Z0-9_-]+\\.)*[a-zA-Z][a-zA-Z0-9_-]+[\\.\\:][a-zA-Z0-9_]+([\\/ \\?\\=\\&\\#\\.]?[a-zA-Z0-9_-]+)*\\/?)(.*)",
"(([a-zA-Z0-9_-]+@)?([a-zA-Z0-9_-]+\\.)*[a-zA-Z0-9_-]+[\\.\\:][a-zA-Z0-9_]+([\\/ \\?\\=\\&\\#\\.]?[a-zA-Z0-9_-]+)*\\/?)(.*)",
)
// Splits at spaces AND at ASCII/multibyte character boundaries
@@ -24,11 +24,10 @@ import androidx.compose.runtime.Immutable
import com.vitorpamplona.amethyst.commons.model.ImmutableListOfLists
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.ImmutableSet
@Immutable
class RichTextViewerState(
val urlSet: ImmutableSet<String>,
val urlSet: Urls,
val imagesForPager: ImmutableMap<String, MediaUrlContent>,
val imageList: ImmutableList<MediaUrlContent>,
val customEmoji: ImmutableMap<String, String>,
@@ -140,14 +139,12 @@ class HashTagSegment(
) : Segment(segment)
@Immutable
class SchemelessUrlSegment(
class RelayUrlSegment(
segment: String,
val url: String,
val extras: String?,
) : Segment(segment)
@Immutable
class RelayUrlSegment(
class SchemelessUrlSegment(
segment: String,
) : Segment(segment)
@@ -0,0 +1,107 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.richtext
import androidx.compose.runtime.Stable
import com.vitorpamplona.quartz.utils.DualCase
import com.vitorpamplona.quartz.utils.startsWithAny
import com.vitorpamplona.quartz.utils.urldetector.Url
import com.vitorpamplona.quartz.utils.urldetector.detection.UrlDetector
@Stable
class Urls(
val withScheme: Set<String> = emptySet(),
val withoutScheme: Set<String> = emptySet(),
val emails: Set<String> = emptySet(),
val bech32s: Set<String> = emptySet(),
val relayUrls: Set<String> = emptySet(),
)
val websocketScheme = listOf(DualCase("ws"))
val nostrScheme = listOf(DualCase("nostr"))
val blossomScheme = listOf(DualCase("blossom"))
class UrlParser {
fun Char.isAsciiLetter(): Boolean = (this in 'a'..'z' || this in 'A'..'Z')
fun Url.isValidTopLevelDomain(): Boolean {
/*
According to the TLD Applicant Guidebook published June 2012, ICANN does not allow numbers in TLDs.
*/
val startOfTopDomain = host.lastIndexOf('.') + 1
return if (startOfTopDomain < host.length) {
val topLevelDomain = host.substring(startOfTopDomain)
topLevelDomain.isNotEmpty() && topLevelDomain[0].isAsciiLetter()
} else {
false
}
}
fun Url.wroteWithSchema(): Boolean = urlMarker.hasScheme()
fun Url.isEmail(): Boolean =
urlMarker.hasUsernamePassword() &&
!urlMarker.hasQuery() &&
!urlMarker.hasFragment() &&
originalUrl.contains('@') &&
path == "/"
fun parseValidUrls(content: String): Urls {
val urls = UrlDetector(content).detect()
val completeUrls = mutableSetOf<String>()
val urlsWithoutScheme = mutableSetOf<String>()
val emails = mutableSetOf<String>()
val bech32 = mutableSetOf<String>()
val relays = mutableSetOf<String>()
urls.forEach {
if (it.isValidTopLevelDomain()) {
if (it.wroteWithSchema()) {
if (it.originalUrl.startsWithAny(nostrScheme)) {
bech32.add(it.originalUrl)
} else if (it.originalUrl.startsWithAny(websocketScheme)) {
relays.add(it.originalUrl)
} else {
completeUrls.add(it.originalUrl)
}
} else {
// emails are understood as urls from the detector.
if (it.isEmail()) {
Patterns.EMAIL_ADDRESS.findAll(it.originalUrl).forEach {
emails.add(it.value)
}
} else {
urlsWithoutScheme.add(it.originalUrl)
}
}
}
}
return Urls(
withScheme = completeUrls,
withoutScheme = urlsWithoutScheme,
emails = emails,
bech32s = bech32,
relayUrls = relays,
)
}
}
@@ -0,0 +1,117 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.ui.components
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.PlainTooltip
import androidx.compose.material3.Text
import androidx.compose.material3.TooltipBox
import androidx.compose.material3.TooltipDefaults
import androidx.compose.material3.rememberTooltipState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.commons.domain.nip46.SignerConnectionState
import com.vitorpamplona.quartz.utils.TimeUtils
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BunkerHeartbeatIndicator(
signerConnectionState: SignerConnectionState,
lastPingTimeSec: Long?,
modifier: Modifier = Modifier,
) {
if (signerConnectionState is SignerConnectionState.NotRemote) return
val tooltipState = rememberTooltipState()
val tooltipText =
when (signerConnectionState) {
is SignerConnectionState.Connected -> {
if (lastPingTimeSec != null) {
val agoSeconds = TimeUtils.now() - lastPingTimeSec
"Bunker connected \u2014 last pinged ${agoSeconds}s ago"
} else {
"Bunker connected"
}
}
is SignerConnectionState.Disconnected -> {
"Bunker disconnected"
}
else -> {
""
}
}
TooltipBox(
positionProvider = TooltipDefaults.rememberTooltipPositionProvider(),
tooltip = { PlainTooltip { Text(tooltipText) } },
state = tooltipState,
modifier = modifier,
) {
when (signerConnectionState) {
is SignerConnectionState.Connected -> {
val infiniteTransition = rememberInfiniteTransition(label = "heartbeat")
val scale by infiniteTransition.animateFloat(
initialValue = 0.85f,
targetValue = 1.15f,
animationSpec =
infiniteRepeatable(
animation = tween(800),
repeatMode = RepeatMode.Reverse,
),
label = "heartbeatScale",
)
Icon(
Icons.Default.Favorite,
contentDescription = "Bunker connected",
tint = Color(0xFF4CAF50),
modifier = Modifier.size(20.dp).scale(scale),
)
}
is SignerConnectionState.Disconnected -> {
Icon(
Icons.Default.FavoriteBorder,
contentDescription = "Bunker disconnected",
tint = Color(0xFFF44336),
modifier = Modifier.size(20.dp),
)
}
else -> {}
}
}
}
@@ -20,26 +20,23 @@
*/
package com.vitorpamplona.amethyst.commons.richtext
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.Test
import kotlin.test.assertEquals
@RunWith(AndroidJUnit4::class)
class ExpandableTextCutOffCalculatorTest {
val shortPost: String =
"Goldman Sachs Predicts Modest Gains for S&P 500 in 2024 ( #409962b2 , v0.09)"
val longPost: String =
"Goldman Sachs Predicts Modest Gains for S&P 500 in 2024 ( #409962b2 , v0.09)\n" +
"\n" +
"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIiA/Pgo8c3ZnIHdpZHRoPSIzMjAiIGhlaWdodD0iNjUiIHZpZXdCb3g9IjAgMCAzMjAgNjUiIGZpbGw9ImJsYWNrIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aAogICAgZmlsbC1ydWxlPSJldmVub2RkIgogICAgY2xpcC1ydWxlPSJldmVub2RkIgogICAgZD0iTTguNTk4MjggNDIuMTU1OEM3LjgxMjgxIDQ5LjA1OTkgNS45ODMyNCA0OC44Njg4IDMuNzYzMDYgNDkuNDMzOUMxLjc1MjU1IDQ5Ljk0MzggMi41MTk5MyA1MS4xMjcyIDMuODI2OTIgNTAuOTQwMkM0LjMxMjI1IDUwLjg3MDcgNy45MDU0MSA1MC41MDE4IDEwLjM2MTkgNTAuNTAxOEMxMy44MDI4IDUwLjUwMTggMTYuOTI1NiA1MC44MTM1IDE4LjYwOTMgNTAuODEzNUMxOS4zMTE4IDUwLjgxMzUgMjAuMjMyNCA0OS44NzU0IDE4LjUzMTYgNDkuNDMzOUMxNi41NjQ3IDQ4LjkyNiAxMS43MzkxIDQ5LjQzMzkgMTEuMjc4MyA0MS4xNTEzQzEwLjk0MyAzNS4wOTE0IDExLjUwMTggMTQuMzcxMSAxMS41MDE4IDE0LjM3MTFDMTEuNTAxOCAxMi45MjQxIDExLjcxMzY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pNMTEuNDg0NCAyNi4wNzg2QzExLjQ4NDQgMjUuNDI4NiAxMS4xMTgzIDI0LjQxOCAxNi43NTQ5IDI0LjQxOEMzMy41ODkzIDI0LjQxOCAzMy44ODIgMzMuOTc5IDMzLjg4MiAzOC41OTI5QzMzLjg4MiA0Mi45MTg2IDMyLjQxODYgNDkuNTcxMyAyMS4xNzgzIDQ5LjY5NTlDMTAuNzg2MiA0OS44MTE0IDExLjQ4NDQgNDcuNzUxMiAxMS40ODQ0IDQyLjU1NzlWMjYuMDc4NlpNMTEuNDg3NyA3Ljk0NUMxMS40ODc3IDMuNzYxMyAxMS4xMjM3IDIuNjI1OTUgMTUuNzMzMyAyLjUzMzk4QzI0LjU0OTEgMi4zNTkyMyAzMC43NzU0IDcuMDg0NTUgMzAuNTk1NSAxNC44NzA1QzMwLjQ5NTUgMTkuMTAxMiAyNy41ODg4IDIyLjc3NiAxNy45NDcxIDIyLjYyODhDMTEuMzYyMSAyMi41MjY2IDExLjQ4NzcgMjIuMTUyNiAxMS40ODc3IDE5Ljg0MjFWNy45NDVaIgogICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCA1LjQxNzk3KSIKICAvPgo8L3N2Zz4K\n" +
"Goldman Sachs analysts predict that the S&P 500 will have a 4.2% price gain and end at 4,700 by the end of 2024, representing a modest increase from recent levels. They believe that the U.S. economy will continue to expand at a modest pace and that earnings will rise by 5%. The forecast includes an equity market valuation at an 18 times multiple. Goldman Sachs also predicts that the 'Magnificent 7' bundle of mega-caps, including Nvidia, Microsoft, Alphabet, Apple, Amazon.com, Meta Platforms, and Tesla, will outperform the rest of the S&P 500 in 2024. They suggest that there are more attractive investment opportunities in quality stocks, growth stocks with high ROIC, and beaten-down cyclicals. According to Lombard Odier, the US economy is expected to experience a mild slowdown in 2024, leading to two interest rate cuts from the Federal Reserve. Despite slower but still positive nominal growth, corporate earnings growth is expected to remain positive into 2024, allowing room for US stocks to advance. The S&P 500's stock index has seen a rebound, supported by strong US consumer spending and cost cuts in the corporate sector. However, corporate profits in the US have already experienced a recession, recording three quarters of year-on-year declines. The article discusses the factors contributing to the apparent 'divergence' between corporate profits and the broader economy. The author expects the S&P 500 to finish 2024 around 4,800 points. The article also mentions the potential risks to the outlook for equities, including a classic economic recession in the US and the possibility of a more bullish environment with a faster recovery in US manufacturing. The article briefly touches on the relative performance of European and emerging markets. \n" +
"\n" +
"AuMDkwODY4NyAwIC0wLjUxODcyNyAwLjk0MDE1OCAxLjA0OTAyIDEuNTY5NjVDMi40MzU4NCAyLjEyNDU1IDYuMjIzNzYgMS44ODY0NSA2LjIyMzc2IDcuMzY3OTdWNDIuODUxOFpNMTEuNDg0NCAyNi4wNzg2QzExLjQ4NDQgMjUuNDI4NiAxMS4xMTgzIDI0LjQxOCAxNi43NTQ5IDI0LjQxOEMzMy41ODkzIDI0LjQxOCAzMy44ODIgMzMuOTc5IDMzLjg4MiAzOC41OTI5QzMzLjg4MiA0Mi45MTg2IDMyLjQxODYgNDkuNTcxMyAyMS4xNzgzIDQ5LjY5NTlDMTAuNzg2MiA0OS44MTE0IDExLjQ4NDQgNDcuNzUxMiAxMS40ODQ0IDQyLjU1NzlWMjYuMDc4NlpNMTEuNDg3NyA3Ljk0NUMxMS40ODc3IDMuNzYxMyAxMS4xMjM3IDIuNjI1OTUgMTUuNzMzMyAyLjUzMzk4QzI0LjU0OTEgMi4zNTkyMyAzMC43NzU0IDcuMDg0NTUgMzAuNTk1NSAxNC44NzA1QzMwLjQ5NTUgMTkuMTAxMiAyNy41ODg4IDIyLjc3NiAxNy45NDcxIDIyLjYyODhDMTEuMzYyMSAyMi41MjY2IDExLjQ4NzcgMjIuMTUyNiAxMS40ODc3IDE5Ljg0MjFWNy45NDVaIgogICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCA1LjQxNzk3KSIKICAvPgo8L3N2Zz4K"
val longPost: String =
"Goldman Sachs Predicts Modest Gains for S&P 500 in 2024 ( #409962b2 , v0.09)\n" +
"\n" + image + "\n" +
"#GoldmanSachs #S&P500 #stockmarket #economy #earnings \n" +
"\n" +
"References:\n" +
@@ -56,4 +53,9 @@ class ExpandableTextCutOffCalculatorTest {
fun testLostPost() {
assertEquals(77, ExpandableTextCutOffCalculator.indexToCutOff(longPost))
}
@Test
fun testImage() {
assertEquals(350, ExpandableTextCutOffCalculator.indexToCutOff(image))
}
}
@@ -20,13 +20,12 @@
*/
package com.vitorpamplona.amethyst.commons.richtext
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.amethyst.commons.model.EmptyTagList
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.DefaultAsserter.assertTrue
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class GalleryParserTest {
@Test
fun testMixedImageAndVideoRenderedIndividually() {
@@ -39,23 +38,23 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should have 3 paragraphs (text, image, video)
Assert.assertEquals(3, state.paragraphs.size)
assertEquals(3, state.paragraphs.size)
// First paragraph is text
Assert.assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[0].words.size)
assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[0].words.size)
// Second paragraph is image (rendered individually, not as gallery)
Assert.assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[1].words.size)
Assert.assertTrue(state.paragraphs[1].words[0] is ImageSegment)
Assert.assertEquals("https://image.tmdb.org/t/p/original/ekfIcBvqfqKbI6m227NFipBNh7O.jpg", state.paragraphs[1].words[0].segmentText)
assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[1].words.size)
assertTrue(state.paragraphs[1].words[0] is ImageSegment)
assertEquals("https://image.tmdb.org/t/p/original/ekfIcBvqfqKbI6m227NFipBNh7O.jpg", state.paragraphs[1].words[0].segmentText)
// Third paragraph is video (rendered individually)
Assert.assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[2].words.size)
Assert.assertTrue(state.paragraphs[2].words[0] is VideoSegment)
Assert.assertEquals("https://archive.org/download/cinema-horror-sci-fi/Renfield.2023.ia.mp4", state.paragraphs[2].words[0].segmentText)
assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[2].words.size)
assertTrue(state.paragraphs[2].words[0] is VideoSegment)
assertEquals("https://archive.org/download/cinema-horror-sci-fi/Renfield.2023.ia.mp4", state.paragraphs[2].words[0].segmentText)
}
@Test
@@ -72,27 +71,27 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should have 6 paragraphs (text, image, video, text, image, video)
Assert.assertEquals(6, state.paragraphs.size)
assertEquals(6, state.paragraphs.size)
// First set: text, image, video
Assert.assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[0].words.size)
Assert.assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
Assert.assertTrue(state.paragraphs[1].words[0] is ImageSegment)
Assert.assertEquals("https://image.tmdb.org/t/p/original/ekfIcBvqfqKbI6m227NFipBNh7O.jpg", state.paragraphs[1].words[0].segmentText)
Assert.assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
Assert.assertTrue(state.paragraphs[2].words[0] is VideoSegment)
Assert.assertEquals("https://archive.org/download/cinema-horror-sci-fi/Renfield.2023.ia.mp4", state.paragraphs[2].words[0].segmentText)
assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[0].words.size)
assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[1].words[0] is ImageSegment)
assertEquals("https://image.tmdb.org/t/p/original/ekfIcBvqfqKbI6m227NFipBNh7O.jpg", state.paragraphs[1].words[0].segmentText)
assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[2].words[0] is VideoSegment)
assertEquals("https://archive.org/download/cinema-horror-sci-fi/Renfield.2023.ia.mp4", state.paragraphs[2].words[0].segmentText)
// Second set: text, image, video
Assert.assertTrue(state.paragraphs[3] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[3].words.size)
Assert.assertTrue(state.paragraphs[4] !is ImageGalleryParagraph)
Assert.assertTrue(state.paragraphs[4].words[0] is ImageSegment)
Assert.assertEquals("https://image.tmdb.org/t/p/original/ekfIcBvqfqKbI6m227NFipBNh7O.jpg", state.paragraphs[4].words[0].segmentText)
Assert.assertTrue(state.paragraphs[5] !is ImageGalleryParagraph)
Assert.assertTrue(state.paragraphs[5].words[0] is VideoSegment)
Assert.assertEquals("https://archive.org/download/cinema-horror-sci-fi/Renfield.2023.ia.mp4", state.paragraphs[5].words[0].segmentText)
assertTrue(state.paragraphs[3] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[3].words.size)
assertTrue(state.paragraphs[4] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[4].words[0] is ImageSegment)
assertEquals("https://image.tmdb.org/t/p/original/ekfIcBvqfqKbI6m227NFipBNh7O.jpg", state.paragraphs[4].words[0].segmentText)
assertTrue(state.paragraphs[5] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[5].words[0] is VideoSegment)
assertEquals("https://archive.org/download/cinema-horror-sci-fi/Renfield.2023.ia.mp4", state.paragraphs[5].words[0].segmentText)
}
@Test
@@ -106,13 +105,13 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should have 2 image segments (image + video URLs)
Assert.assertEquals(2, state.paragraphs.size)
assertEquals(2, state.paragraphs.size)
// Should render as gallery (1 gallery with 2 images)
Assert.assertTrue("Should render 1 gallery", state.paragraphs[1] is ImageGalleryParagraph)
Assert.assertEquals("Gallery should contain 2 images", 2, state.paragraphs[1].words.size)
Assert.assertEquals("https://example.com/image1.jpg", state.paragraphs[1].words[0].segmentText)
Assert.assertEquals("https://example.com/image2.png", state.paragraphs[1].words[1].segmentText)
assertTrue("Should render 1 gallery", state.paragraphs[1] is ImageGalleryParagraph)
assertEquals(2, state.paragraphs[1].words.size, "Gallery should contain 2 images")
assertEquals("https://example.com/image1.jpg", state.paragraphs[1].words[0].segmentText)
assertEquals("https://example.com/image2.png", state.paragraphs[1].words[1].segmentText)
}
@Test
@@ -125,13 +124,13 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should have 2 image segments (image + video URLs)
Assert.assertEquals(2, state.paragraphs.size)
assertEquals(2, state.paragraphs.size)
// Should render as gallery (1 gallery with 2 images)
Assert.assertTrue("Should render 1 gallery", state.paragraphs[1] is ImageGalleryParagraph)
Assert.assertEquals("Gallery should contain 2 images", 2, state.paragraphs[1].words.size)
Assert.assertEquals("https://example.com/image1.jpg", state.paragraphs[1].words[0].segmentText)
Assert.assertEquals("https://example.com/image2.png", state.paragraphs[1].words[1].segmentText)
assertTrue("Should render 1 gallery", state.paragraphs[1] is ImageGalleryParagraph)
assertEquals(2, state.paragraphs[1].words.size, "Gallery should contain 2 images")
assertEquals("https://example.com/image1.jpg", state.paragraphs[1].words[0].segmentText)
assertEquals("https://example.com/image2.png", state.paragraphs[1].words[1].segmentText)
}
@Test
@@ -142,9 +141,9 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should render individually (not as gallery)
Assert.assertTrue("Should render 1 individual image", state.paragraphs[1] !is ImageGalleryParagraph)
Assert.assertTrue("Should not render as gallery", state.paragraphs[0] !is ImageGalleryParagraph)
Assert.assertEquals("https://example.com/image.jpg", state.paragraphs[1].words[0].segmentText)
assertTrue("Should render 1 individual image", state.paragraphs[1] !is ImageGalleryParagraph)
assertTrue("Should not render as gallery", state.paragraphs[0] !is ImageGalleryParagraph)
assertEquals("https://example.com/image.jpg", state.paragraphs[1].words[0].segmentText)
}
@Test
@@ -154,10 +153,10 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should render individually (not as gallery)
Assert.assertEquals("I played The Typing of the Dead a lot when I was younger, and now I just found out that there's a new take on it: The Last Sentence. Tempted!", state.paragraphs[0].words[0].segmentText)
Assert.assertTrue("Should render as gallery", state.paragraphs[1] is ImageGalleryParagraph)
Assert.assertEquals("https://relay.dergigi.com/d6a3e33b101fe219ef251ac6261c10392c2af9918c3c252d4c202016b0b4ec83.jpg", state.paragraphs[1].words[0].segmentText)
Assert.assertEquals("https://relay.dergigi.com/d60c9c562912573f214c2b1958cc20bf8913cd718d2ed9e020621e3e3120634b.jpg", state.paragraphs[1].words[1].segmentText)
assertEquals("I played The Typing of the Dead a lot when I was younger, and now I just found out that there's a new take on it: The Last Sentence. Tempted!", state.paragraphs[0].words[0].segmentText)
assertTrue("Should render as gallery", state.paragraphs[1] is ImageGalleryParagraph)
assertEquals("https://relay.dergigi.com/d6a3e33b101fe219ef251ac6261c10392c2af9918c3c252d4c202016b0b4ec83.jpg", state.paragraphs[1].words[0].segmentText)
assertEquals("https://relay.dergigi.com/d60c9c562912573f214c2b1958cc20bf8913cd718d2ed9e020621e3e3120634b.jpg", state.paragraphs[1].words[1].segmentText)
}
@Test
@@ -171,23 +170,23 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should have 4 paragraphs (text, image, video, hashtags)
Assert.assertEquals(4, state.paragraphs.size)
assertEquals(4, state.paragraphs.size)
// First paragraph is text
Assert.assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
// Second paragraph is image (rendered individually, not as gallery)
Assert.assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
Assert.assertTrue(state.paragraphs[1].words[0] is ImageSegment)
Assert.assertEquals("https://image.tmdb.org/t/p/original/1r7iOhXSbbuUTORNEUOvCUkQ86K.jpg", state.paragraphs[1].words[0].segmentText)
assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[1].words[0] is ImageSegment)
assertEquals("https://image.tmdb.org/t/p/original/1r7iOhXSbbuUTORNEUOvCUkQ86K.jpg", state.paragraphs[1].words[0].segmentText)
// Third paragraph is video (rendered individually)
Assert.assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
Assert.assertTrue(state.paragraphs[2].words[0] is VideoSegment)
Assert.assertEquals("https://archive.org/download/the-crow-1994_20231024/The%20Crow%201994.rar/The%20Crow%201994.1080p.BluRay.x264%20.%20NVEE%2FThe%20Crow%201994.1080p.BluRay.x264%20.%20NVEE.mp4", state.paragraphs[2].words[0].segmentText)
assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[2].words[0] is VideoSegment)
assertEquals("https://archive.org/download/the-crow-1994_20231024/The%20Crow%201994.rar/The%20Crow%201994.1080p.BluRay.x264%20.%20NVEE%2FThe%20Crow%201994.1080p.BluRay.x264%20.%20NVEE.mp4", state.paragraphs[2].words[0].segmentText)
// Fourth paragraph is hashtags
Assert.assertTrue(state.paragraphs[3] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[3] !is ImageGalleryParagraph)
}
@Test
@@ -201,25 +200,25 @@ class GalleryParserTest {
val state = RichTextParser().parseText(text, EmptyTagList, null)
// Should have 4 paragraphs (text, image, video, hashtags)
Assert.assertEquals(4, state.paragraphs.size)
assertEquals(4, state.paragraphs.size)
// First paragraph is text
Assert.assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
Assert.assertEquals("Desperado (1995)", state.paragraphs[0].words[0].segmentText)
assertTrue(state.paragraphs[0] !is ImageGalleryParagraph)
assertEquals("Desperado (1995)", state.paragraphs[0].words[0].segmentText)
// Second paragraph is image (rendered individually, not as gallery)
Assert.assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[1].words.size)
Assert.assertTrue(state.paragraphs[1].words[0] is ImageSegment)
Assert.assertEquals("https://media.themoviedb.org/t/p/w440_and_h660_face/e3gwpBeXpvGZsxUya9zNym5QXrw.jpg", state.paragraphs[1].words[0].segmentText)
assertTrue(state.paragraphs[1] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[1].words.size)
assertTrue(state.paragraphs[1].words[0] is ImageSegment)
assertEquals("https://media.themoviedb.org/t/p/w440_and_h660_face/e3gwpBeXpvGZsxUya9zNym5QXrw.jpg", state.paragraphs[1].words[0].segmentText)
// Third paragraph is video (rendered individually)
Assert.assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
Assert.assertEquals(1, state.paragraphs[2].words.size)
Assert.assertTrue(state.paragraphs[2].words[0] is VideoSegment)
Assert.assertEquals("https://archive.org/download/desperado.-1995.1080p.-blu-ray.x-264.-yify/Desperado.1995.1080p.BluRay.x264.YIFY.mp4", state.paragraphs[2].words[0].segmentText)
assertTrue(state.paragraphs[2] !is ImageGalleryParagraph)
assertEquals(1, state.paragraphs[2].words.size)
assertTrue(state.paragraphs[2].words[0] is VideoSegment)
assertEquals("https://archive.org/download/desperado.-1995.1080p.-blu-ray.x-264.-yify/Desperado.1995.1080p.BluRay.x264.YIFY.mp4", state.paragraphs[2].words[0].segmentText)
// Fourth paragraph is hashtags
Assert.assertTrue(state.paragraphs[3] !is ImageGalleryParagraph)
assertTrue(state.paragraphs[3] !is ImageGalleryParagraph)
}
}
@@ -55,7 +55,55 @@ class RichTextParserMultibyteTest {
// user@example.com should not be in urlSet
assertTrue(
"user@example.com should not be in urlSet",
!state.urlSet.contains("user@example.com"),
!state.urlSet.withScheme.contains("user@example.com") && !state.urlSet.withoutScheme.contains("user@example.com"),
)
}
@Test
fun testHttpWithoutSpaces() {
// Multibyte characters around an email address should not produce URL/Link segments
val text =
"Vitor, vocêhttp://test.com? \uD83E\uDD7A"
val state =
RichTextParser()
.parseText(text, EmptyTagList, null)
assertEquals(
"Vitor, você http://test.com ? \uD83E\uDD7A",
state.paragraphs.joinToString("\n") { it.words.joinToString(" ") { it.segmentText } },
)
}
@Test
fun testHttpWithoutSpacesJapan() {
// Multibyte characters around an email address should not produce URL/Link segments
val text =
"Vitor, vocêhttp://test.comほげほげ"
val state =
RichTextParser()
.parseText(text, EmptyTagList, null)
assertEquals(
"Vitor, você http://test.com ほげほげ",
state.paragraphs.joinToString("\n") { it.words.joinToString(" ") { it.segmentText } },
)
}
@Test
fun testHttpWithoutSpacesJapan2() {
// Multibyte characters around an email address should not produce URL/Link segments
val text =
"Vitor, vocêhttp://test.com。ほげほげ"
val state =
RichTextParser()
.parseText(text, EmptyTagList, null)
assertEquals(
"Vitor, você http://test.com 。ほげほげ",
state.paragraphs.joinToString("\n") { it.words.joinToString(" ") { it.segmentText } },
)
}
@@ -65,11 +113,29 @@ class RichTextParserMultibyteTest {
val text =
"Vitor, você tem como colocar alguma forma de aviso se o link vai carregar uma imagem ou um vídeo? \uD83E\uDD7A"
val regex = Regex("(?<=[\\u0000-\\u00FF])(?=[\\u0100-\\uFFFF])|(?<=[\\u0100-\\uFFFF])(?=[\\u0000-\\u00FF])| +")
val state =
RichTextParser()
.parseText(text, EmptyTagList, null)
assertEquals(
"Vitor,-você-tem-como-colocar-alguma-forma-de-aviso-se-o-link-vai-carregar-uma-imagem-ou-um-vídeo?-\uD83E\uDD7A",
text.split(regex).joinToString("-"),
"Vitor, você tem como colocar alguma forma de aviso se o link vai carregar uma imagem ou um vídeo? \uD83E\uDD7A",
state.paragraphs.joinToString("\n") { it.words.joinToString(" ") { it.segmentText } },
)
}
@Test
fun testFullTextWithMultibyteAndQuotes() {
// Multibyte characters around an email address should not produce URL/Link segments
val text =
"Ive been thinking lately about how I believe there will more than likely be models unattainable by most. Think Bloomberg Terminal. Where their cost of tokens is too high for the average lay person, but their level of “cognition” is unmatched by anything else. Im sure there will even be many closed models that are invite only. Crazy times ahead."
val state =
RichTextParser()
.parseText(text, EmptyTagList, null)
assertEquals(
"Ive been thinking lately about how I believe there will more than likely be models unattainable by most. Think Bloomberg Terminal. Where their cost of tokens is too high for the average lay person, but their level of “cognition” is unmatched by anything else. Im sure there will even be many closed models that are invite only. Crazy times ahead.",
state.paragraphs.joinToString("\n") { it.words.joinToString(" ") { it.segmentText } },
)
}
@@ -93,7 +159,7 @@ class RichTextParserMultibyteTest {
val urlSegments = allSegments.filterIsInstance<SchemelessUrlSegment>()
assertTrue("Should have SchemelessUrlSegment", urlSegments.isNotEmpty())
assertTrue("URL should be example.com", urlSegments.any { it.url == "example.com" })
assertTrue("URL should be example.com", urlSegments.any { it.segmentText == "example.com" })
val textSegments = allSegments.filterIsInstance<RegularTextSegment>()
assertTrue("Should have prefix ああ", textSegments.any { it.segmentText == "ああ" })
@@ -108,7 +174,7 @@ class RichTextParserMultibyteTest {
val urlSegments = allSegments.filterIsInstance<SchemelessUrlSegment>()
assertTrue("Should have SchemelessUrlSegment", urlSegments.isNotEmpty())
assertTrue("URL should be example.com", urlSegments.any { it.url == "example.com" })
assertTrue("URL should be example.com", urlSegments.any { it.segmentText == "example.com" })
val textSegments = allSegments.filterIsInstance<RegularTextSegment>()
assertTrue("Should have suffix ああ", textSegments.any { it.segmentText == "ああ" })
@@ -0,0 +1,294 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.richtext
import kotlin.test.Test
import kotlin.test.assertEquals
class UrlParserTest {
val parser = UrlParser()
fun test(
text: String,
expected: Urls,
) {
val urlSet = parser.parseValidUrls(text)
assertEquals(expected.withScheme, urlSet.withScheme)
assertEquals(expected.withoutScheme, urlSet.withoutScheme)
assertEquals(expected.emails, urlSet.emails)
}
@Test
fun testSimpleText() =
test(
"test. com",
Urls(),
)
@Test
fun testBasicUrl() =
test(
"http://test.com",
Urls(withScheme = setOf("http://test.com")),
)
@Test
fun testNoSchemaUrl() =
test(
"test.com",
Urls(withoutScheme = setOf("test.com")),
)
@Test
fun testNoSchemaUrlPrefixMultibyte() =
test(
"ほtest.com",
Urls(withoutScheme = setOf("test.com")),
)
@Test
fun testNoSchemaUrlSuffixMultibyte() =
test(
"test.comほ",
Urls(withoutScheme = setOf("test.com")),
)
@Test
fun testNoSchemaUrlWithParams() =
test(
"test.com/some/me/hey?param=value#some=value",
Urls(withoutScheme = setOf("test.com/some/me/hey?param=value#some=value")),
)
@Test
fun testNoSchemaUrlWithParamsWithOtherWords() =
test(
"Hi there, check my website test.com/some/me/hey?param=value#some=value .",
Urls(withoutScheme = setOf("test.com/some/me/hey?param=value#some=value")),
)
@Test
fun testBasicUrlWithoutSpaceBefore() =
test(
"ahttp://test.com",
Urls(withScheme = setOf("http://test.com")),
)
@Test
fun testBasicUrlWithoutSpaceBeforeMultiByte() =
test(
"ほhttp://test.com",
Urls(withScheme = setOf("http://test.com")),
)
@Test
fun testBasicUrlWithoutSpaceAfter() =
test(
"http://test.comほ",
Urls(withScheme = setOf("http://test.com")),
)
@Test
fun testBasicUrlWithMultibytePath() =
test(
"http://test.com/ほ",
Urls(withScheme = setOf("http://test.com/ほ")),
)
@Test
fun testBasicUrls() =
test(
"http://test.com http://test2.com",
Urls(withScheme = setOf("http://test.com", "http://test2.com")),
)
@Test
fun testEmail() =
test(
"vitor@vitorpamplona.com",
Urls(emails = setOf("vitor@vitorpamplona.com")),
)
@Test
fun testEmailWithMultibytePrefix() =
test(
"ほvitor@vitorpamplona.com",
Urls(emails = setOf("vitor@vitorpamplona.com")),
)
@Test
fun testEmailWithMultibyteSuffix() =
test(
"vitor@vitorpamplona.comほ",
Urls(emails = setOf("vitor@vitorpamplona.com")),
)
@Test
fun testEmailWithMultibyteBoth() =
test(
"ほvitor@vitorpamplona.comほ",
Urls(emails = setOf("vitor@vitorpamplona.com")),
)
@Test
fun testUrlWithUserAndMultibyteSuffix() =
test(
"http://vitor@vitorpamplona.comほ",
Urls(withScheme = setOf("http://vitor@vitorpamplona.com")),
)
@Test
fun testUrlWithUserAndMultibytePrefix() =
test(
"ほhttp://vitor@vitorpamplona.com",
Urls(withScheme = setOf("http://vitor@vitorpamplona.com")),
)
@Test
fun testNostrUrls() =
test(
"nostr:npub142gywvjkq0dv6nupggyn2euhx4nduwc7yz5f24ah9rpmunr2s39se3xrj0",
Urls(bech32s = setOf("nostr:npub142gywvjkq0dv6nupggyn2euhx4nduwc7yz5f24ah9rpmunr2s39se3xrj0")),
)
@Test
fun testUrlsWithUsernameAndPath() =
test(
"miceliomad@miceliomad.github.io/nostr/",
Urls(withoutScheme = setOf("miceliomad@miceliomad.github.io/nostr/")),
)
@Test
fun testUrlsWithQuery() =
test(
" universe.nostrich.land?lang=zh ",
Urls(withoutScheme = setOf("universe.nostrich.land?lang=zh")),
)
@Test
fun testUrlsWithSchemaPathAndQuery() =
test(
"https://miceliomad.github.io/nostr/test?me=you",
Urls(withScheme = setOf("https://miceliomad.github.io/nostr/test?me=you")),
)
@Test
fun testUrlsWithPathAndQuery() =
test(
"miceliomad.github.io/nostr/test?me=you",
Urls(withoutScheme = setOf("miceliomad.github.io/nostr/test?me=you")),
)
@Test
fun testAvifFileNameComplete() =
test(
"https://bae.st/media/66b08dde784287ed8f92c455bc62076a04671ccb44097550626a532185a5d3ed.avif?name=81ca16-b665-4f57-80cb-11a58461fb61.avif",
Urls(withScheme = setOf("https://bae.st/media/66b08dde784287ed8f92c455bc62076a04671ccb44097550626a532185a5d3ed.avif?name=81ca16-b665-4f57-80cb-11a58461fb61.avif")),
)
@Test
fun testAvifFileName() =
test(
"81ca16-b665-4f57-80cb-11a58461fb61.avif",
Urls(withoutScheme = setOf("81ca16-b665-4f57-80cb-11a58461fb61.avif")),
)
@Test
fun testMultiLine() =
test(
"""
22.8K (3.2%) nos.lol
22.7K (3.1%) universe.nostrich.land?lang=zh
22.5K (3.1%) universe.nostrich.land?lang=en
""".trimIndent(),
Urls(withoutScheme = setOf("nos.lol", "universe.nostrich.land?lang=zh", "universe.nostrich.land?lang=en")),
)
@Test
fun testEmailWithDashes() =
test(
"freeverification@Nostr-Check.com",
Urls(emails = setOf("freeverification@Nostr-Check.com")),
)
@Test
fun testEmailWithManyDashes() =
test(
"free-veri-fica-tion@No-str-Ch-eck.com",
Urls(emails = setOf("free-veri-fica-tion@No-str-Ch-eck.com")),
)
@Test
fun testEmailWithUnderscore() =
test(
"vi_t_or@vitorpamplona.com",
Urls(emails = setOf("vi_t_or@vitorpamplona.com")),
)
@Test
fun testEmailsWithPeriod() =
test(
"john.smith@gmail.com",
Urls(emails = setOf("john.smith@gmail.com")),
)
@Test
fun testStrangeError() =
test(
"neomobius_at_mstdn.jp@mostr.pub",
Urls(emails = setOf("neomobius_at_mstdn.jp@mostr.pub")),
)
@Test
fun testRelayUrl() =
test(
"wss://test.com",
Urls(relayUrls = setOf("wss://test.com")),
)
@Test
fun testBech12() =
test(
"nostr:npub142gywvjkq0dv6nupggyn2euhx4nduwc7yz5f24ah9rpmunr2s39se3xrj0",
Urls(bech32s = setOf("nostr:npub142gywvjkq0dv6nupggyn2euhx4nduwc7yz5f24ah9rpmunr2s39se3xrj0")),
)
@Test
fun testJapaneseUrls() =
test(
"我进入你的主页很卡顿,也许是你的关注人数或者其他数据太多了,其他人主页没有这么卡顿。来自amethyst客户端",
Urls(withScheme = emptySet()),
)
@Test
fun testHour() =
test(
"10.00hr,",
Urls(withScheme = emptySet()),
)
@Test
fun testBlossom() =
test(
"blossom:b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.pdf?xs=cdn.satellite.earth",
Urls(withScheme = setOf("blossom:b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.pdf?xs=cdn.satellite.earth")),
)
}