- Adds nembed

- Redesigns NIP-19 returns to allow nembeds and give more nuance to the UI.
This commit is contained in:
Vitor Pamplona
2024-02-27 15:39:15 -05:00
parent 87fabd54de
commit f78a252c8f
23 changed files with 710 additions and 517 deletions
@@ -27,12 +27,10 @@ import com.vitorpamplona.amethyst.service.checkNotInMainThread
import com.vitorpamplona.amethyst.service.relays.Relay
import com.vitorpamplona.amethyst.ui.components.BundledInsert
import com.vitorpamplona.quartz.encoders.ATag
import com.vitorpamplona.quartz.encoders.Hex
import com.vitorpamplona.quartz.encoders.HexKey
import com.vitorpamplona.quartz.encoders.HexValidator
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.encoders.decodeEventIdAsHexOrNull
import com.vitorpamplona.quartz.encoders.decodePublicKeyAsHexOrNull
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.events.AddressableEvent
import com.vitorpamplona.quartz.events.AdvertisedRelayListEvent
import com.vitorpamplona.quartz.events.AppDefinitionEvent
@@ -1578,13 +1576,7 @@ object LocalCache {
fun findNotesStartingWith(text: String): List<Note> {
checkNotInMainThread()
val key =
try {
Nip19Bech32.uriToRoute(text)?.hex ?: Hex.decode(text).toHexKey()
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
val key = decodeEventIdAsHexOrNull(text)
if (key != null) {
val note = getNoteIfExists(key)
@@ -1631,14 +1623,7 @@ object LocalCache {
fun findChannelsStartingWith(text: String): List<Channel> {
checkNotInMainThread()
val key =
try {
Nip19Bech32.uriToRoute(text)?.hex ?: Hex.decode(text).toHexKey()
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
val key = decodeEventIdAsHexOrNull(text)
if (key != null && channels[key] != null) {
return listOfNotNull(channels[key])
}
@@ -24,9 +24,12 @@ import com.vitorpamplona.amethyst.service.relays.COMMON_FEED_TYPES
import com.vitorpamplona.amethyst.service.relays.FeedType
import com.vitorpamplona.amethyst.service.relays.JsonFilter
import com.vitorpamplona.amethyst.service.relays.TypedFilter
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.encoders.ATag
import com.vitorpamplona.quartz.encoders.Hex
import com.vitorpamplona.quartz.encoders.HexValidator
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.encoders.bechToBytes
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.events.AudioHeaderEvent
import com.vitorpamplona.quartz.events.AudioTrackEvent
@@ -66,83 +69,118 @@ object NostrSearchEventOrUserDataSource : NostrDataSource("SearchEventFeed") {
null
}
Nip19Bech32.uriToRoute(mySearchString)?.hex ?: isAStraightHex
when (val parsed = Nip19Bech32.uriToRoute(mySearchString)?.entity) {
is Nip19Bech32.NSec -> KeyPair(privKey = parsed.hex.bechToBytes()).pubKey.toHexKey()
is Nip19Bech32.NPub -> parsed.hex
is Nip19Bech32.NProfile -> parsed.hex
is Nip19Bech32.Note -> parsed.hex
is Nip19Bech32.NEvent -> parsed.hex
is Nip19Bech32.NEmbed -> parsed.event.id
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> parsed.atag
else -> isAStraightHex
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
// downloads all the reactions to a given event.
return listOfNotNull(
val directReferenceFilters =
hexToWatch?.let {
TypedFilter(
types = COMMON_FEED_TYPES,
filter =
JsonFilter(
ids = listOfNotNull(hexToWatch),
if (it.contains(":")) {
// naddr
listOfNotNull(
ATag.parse(it, null)?.let { aTag ->
TypedFilter(
types = COMMON_FEED_TYPES,
filter =
JsonFilter(
kinds = listOf(MetadataEvent.KIND, aTag.kind),
authors = listOfNotNull(aTag.pubKeyHex),
// just to be sure
limit = 5,
),
)
},
)
} else {
// event ids
listOf(
TypedFilter(
types = COMMON_FEED_TYPES,
filter =
JsonFilter(
ids = listOfNotNull(hexToWatch),
),
),
)
},
hexToWatch?.let {
// authors
TypedFilter(
types = COMMON_FEED_TYPES,
filter =
JsonFilter(
kinds = listOf(MetadataEvent.KIND),
authors = listOfNotNull(hexToWatch),
// just to be sure
limit = 5,
),
),
)
}
} ?: emptyList()
// downloads all the reactions to a given event.
return directReferenceFilters +
listOfNotNull(
TypedFilter(
types = COMMON_FEED_TYPES,
types = setOf(FeedType.SEARCH),
filter =
JsonFilter(
kinds = listOf(MetadataEvent.KIND),
authors = listOfNotNull(hexToWatch),
search = mySearchString,
limit = 100,
),
)
},
TypedFilter(
types = setOf(FeedType.SEARCH),
filter =
JsonFilter(
kinds = listOf(MetadataEvent.KIND),
search = mySearchString,
limit = 100,
),
),
TypedFilter(
types = setOf(FeedType.SEARCH),
filter =
JsonFilter(
kinds =
listOf(
TextNoteEvent.KIND,
LongTextNoteEvent.KIND,
BadgeDefinitionEvent.KIND,
PeopleListEvent.KIND,
BookmarkListEvent.KIND,
AudioHeaderEvent.KIND,
AudioTrackEvent.KIND,
PinListEvent.KIND,
PollNoteEvent.KIND,
ChannelCreateEvent.KIND,
),
search = mySearchString,
limit = 100,
),
),
TypedFilter(
types = setOf(FeedType.SEARCH),
filter =
JsonFilter(
kinds =
listOf(
ChannelMetadataEvent.KIND,
ClassifiedsEvent.KIND,
CommunityDefinitionEvent.KIND,
EmojiPackEvent.KIND,
HighlightEvent.KIND,
LiveActivitiesEvent.KIND,
PollNoteEvent.KIND,
NNSEvent.KIND,
),
search = mySearchString,
limit = 100,
),
),
)
),
TypedFilter(
types = setOf(FeedType.SEARCH),
filter =
JsonFilter(
kinds =
listOf(
TextNoteEvent.KIND,
LongTextNoteEvent.KIND,
BadgeDefinitionEvent.KIND,
PeopleListEvent.KIND,
BookmarkListEvent.KIND,
AudioHeaderEvent.KIND,
AudioTrackEvent.KIND,
PinListEvent.KIND,
PollNoteEvent.KIND,
ChannelCreateEvent.KIND,
),
search = mySearchString,
limit = 100,
),
),
TypedFilter(
types = setOf(FeedType.SEARCH),
filter =
JsonFilter(
kinds =
listOf(
ChannelMetadataEvent.KIND,
ClassifiedsEvent.KIND,
CommunityDefinitionEvent.KIND,
EmojiPackEvent.KIND,
HighlightEvent.KIND,
LiveActivitiesEvent.KIND,
PollNoteEvent.KIND,
NNSEvent.KIND,
),
search = mySearchString,
limit = 100,
),
),
)
}
val searchChannel = requestNewChannel()
@@ -45,6 +45,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.accompanist.adaptive.calculateDisplayFeatures
import com.vitorpamplona.amethyst.LocalPreferences
import com.vitorpamplona.amethyst.ServiceManager
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.service.HttpClientManager
import com.vitorpamplona.amethyst.service.lang.LanguageTranslatorService
import com.vitorpamplona.amethyst.service.notifications.PushNotificationUtils
@@ -311,11 +312,12 @@ fun uriToRoute(uri: String?): String? {
if (uri?.startsWith("nostr:Hashtag?id=") == true) {
Route.Hashtag.route.replace("{id}", uri.removePrefix("nostr:Hashtag?id="))
} else {
val nip19 = Nip19Bech32.uriToRoute(uri)
when (nip19?.type) {
Nip19Bech32.Type.USER -> "User/${nip19.hex}"
Nip19Bech32.Type.NOTE -> "Note/${nip19.hex}"
Nip19Bech32.Type.EVENT -> {
val nip19 = Nip19Bech32.uriToRoute(uri)?.entity
when (nip19) {
is Nip19Bech32.NPub -> "User/${nip19.hex}"
is Nip19Bech32.NProfile -> "User/${nip19.hex}"
is Nip19Bech32.Note -> "Note/${nip19.hex}"
is Nip19Bech32.NEvent -> {
if (nip19.kind == PrivateDmEvent.KIND) {
nip19.author?.let { "RoomByAuthor/$it" }
} else if (
@@ -328,14 +330,21 @@ fun uriToRoute(uri: String?): String? {
"Event/${nip19.hex}"
}
}
Nip19Bech32.Type.ADDRESS ->
is Nip19Bech32.NAddress -> {
if (nip19.kind == CommunityDefinitionEvent.KIND) {
"Community/${nip19.hex}"
"Community/${nip19.atag}"
} else if (nip19.kind == LiveActivitiesEvent.KIND) {
"Channel/${nip19.hex}"
"Channel/${nip19.atag}"
} else {
"Event/${nip19.hex}"
"Event/${nip19.atag}"
}
}
is Nip19Bech32.NEmbed -> {
if (LocalCache.getNoteIfExists(nip19.event.id) == null) {
LocalCache.verifyAndConsume(nip19.event, null)
}
"Event/${nip19.event.id}"
}
else -> null
}
}
@@ -68,17 +68,23 @@ class NewMessageTagger(
paragraph.split(' ').forEach { word: String ->
val results = parseDirtyWordForKey(word)
if (results?.key?.type == Nip19Bech32.Type.USER) {
addUserToMentions(dao.getOrCreateUser(results.key.hex))
} else if (results?.key?.type == Nip19Bech32.Type.NOTE) {
addNoteToReplyTos(dao.getOrCreateNote(results.key.hex))
} else if (results?.key?.type == Nip19Bech32.Type.EVENT) {
addNoteToReplyTos(dao.getOrCreateNote(results.key.hex))
} else if (results?.key?.type == Nip19Bech32.Type.ADDRESS) {
val note = dao.checkGetOrCreateAddressableNote(results.key.hex)
if (note != null) {
addNoteToReplyTos(note)
when (val entity = results?.key?.entity) {
is Nip19Bech32.NPub -> addUserToMentions(dao.getOrCreateUser(entity.hex))
is Nip19Bech32.NProfile -> addUserToMentions(dao.getOrCreateUser(entity.hex))
is Nip19Bech32.Note -> addNoteToReplyTos(dao.getOrCreateNote(entity.hex))
is Nip19Bech32.NEvent -> addNoteToReplyTos(dao.getOrCreateNote(entity.hex))
is Nip19Bech32.NEmbed -> addNoteToReplyTos(dao.getOrCreateNote(entity.event.id))
is Nip19Bech32.NAddress -> {
val note = dao.checkGetOrCreateAddressableNote(entity.atag)
if (note != null) {
addNoteToReplyTos(note)
}
}
is Nip19Bech32.NSec -> {}
is Nip19Bech32.NRelay -> {}
}
}
}
@@ -92,27 +98,45 @@ class NewMessageTagger(
.split(' ')
.map { word: String ->
val results = parseDirtyWordForKey(word)
if (results?.key?.type == Nip19Bech32.Type.USER) {
val user = dao.getOrCreateUser(results.key.hex)
when (val entity = results?.key?.entity) {
is Nip19Bech32.NPub -> {
getNostrAddress(dao.getOrCreateUser(entity.hex).pubkeyNpub(), results.restOfWord)
}
is Nip19Bech32.NProfile -> {
getNostrAddress(dao.getOrCreateUser(entity.hex).pubkeyNpub(), results.restOfWord)
}
getNostrAddress(user.pubkeyNpub(), results.restOfWord)
} else if (results?.key?.type == Nip19Bech32.Type.NOTE) {
val note = dao.getOrCreateNote(results.key.hex)
is Nip19Bech32.Note -> {
getNostrAddress(dao.getOrCreateNote(entity.hex).toNEvent(), results.restOfWord)
}
is Nip19Bech32.NEvent -> {
getNostrAddress(dao.getOrCreateNote(entity.hex).toNEvent(), results.restOfWord)
}
getNostrAddress(note.toNEvent(), results.restOfWord)
} else if (results?.key?.type == Nip19Bech32.Type.EVENT) {
val note = dao.getOrCreateNote(results.key.hex)
is Nip19Bech32.NAddress -> {
val note = dao.checkGetOrCreateAddressableNote(entity.atag)
if (note != null) {
getNostrAddress(note.idNote(), results.restOfWord)
} else {
word
}
}
getNostrAddress(note.toNEvent(), results.restOfWord)
} else if (results?.key?.type == Nip19Bech32.Type.ADDRESS) {
val note = dao.checkGetOrCreateAddressableNote(results.key.hex)
if (note != null) {
getNostrAddress(note.idNote(), results.restOfWord)
} else {
is Nip19Bech32.NEmbed -> {
word
}
is Nip19Bech32.NSec -> {
word
}
is Nip19Bech32.NRelay -> {
word
}
else -> {
word
}
} else {
word
}
}
.joinToString(" ")
@@ -135,7 +159,7 @@ class NewMessageTagger(
}
}
@Immutable data class DirtyKeyInfo(val key: Nip19Bech32.Return, val restOfWord: String)
@Immutable data class DirtyKeyInfo(val key: Nip19Bech32.ParseReturn, val restOfWord: String)
fun parseDirtyWordForKey(mightBeAKey: String): DirtyKeyInfo? {
var key = mightBeAKey
@@ -61,9 +61,11 @@ import com.vitorpamplona.amethyst.model.User
import com.vitorpamplona.amethyst.ui.note.LoadChannel
import com.vitorpamplona.amethyst.ui.note.toShortenHex
import com.vitorpamplona.amethyst.ui.screen.loggedIn.AccountViewModel
import com.vitorpamplona.quartz.encoders.HexKey
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.encoders.Nip30CustomEmoji
import com.vitorpamplona.quartz.events.ChannelCreateEvent
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.ImmutableListOfLists
import com.vitorpamplona.quartz.events.PrivateDmEvent
import com.vitorpamplona.quartz.events.toImmutableListOfLists
@@ -72,45 +74,63 @@ import kotlinx.collections.immutable.ImmutableMap
@Composable
fun ClickableRoute(
nip19: Nip19Bech32.Return,
word: String,
nip19: Nip19Bech32.ParseReturn,
accountViewModel: AccountViewModel,
nav: (String) -> Unit,
) {
when (nip19.type) {
Nip19Bech32.Type.USER -> {
DisplayUser(nip19, accountViewModel, nav)
when (val entity = nip19.entity) {
is Nip19Bech32.NPub -> DisplayUser(entity.hex, nip19.additionalChars, accountViewModel, nav)
is Nip19Bech32.NProfile -> DisplayUser(entity.hex, nip19.additionalChars, accountViewModel, nav)
is Nip19Bech32.Note -> DisplayEvent(entity.hex, null, nip19.additionalChars, accountViewModel, nav)
is Nip19Bech32.NEvent -> DisplayEvent(entity.hex, entity.kind, nip19.additionalChars, accountViewModel, nav)
is Nip19Bech32.NEmbed -> LoadAndDisplayEvent(entity.event, nip19.additionalChars, accountViewModel, nav)
is Nip19Bech32.NAddress -> DisplayAddress(entity, nip19.additionalChars, accountViewModel, nav)
is Nip19Bech32.NRelay -> {
Text(word)
}
Nip19Bech32.Type.ADDRESS -> {
DisplayAddress(nip19, accountViewModel, nav)
}
Nip19Bech32.Type.NOTE -> {
DisplayNote(nip19, accountViewModel, nav)
}
Nip19Bech32.Type.EVENT -> {
DisplayEvent(nip19, accountViewModel, nav)
is Nip19Bech32.NSec -> {
Text(word)
}
else -> {
Text(
remember { "@${nip19.hex}${nip19.additionalChars}" },
)
Text(word)
}
}
}
@Composable
private fun DisplayEvent(
nip19: Nip19Bech32.Return,
fun LoadOrCreateNote(
event: Event,
accountViewModel: AccountViewModel,
content: @Composable (Note?) -> Unit,
) {
var note by
remember(event.id) { mutableStateOf<Note?>(accountViewModel.getNoteIfExists(event.id)) }
if (note == null) {
LaunchedEffect(key1 = event.id) {
accountViewModel.checkGetOrCreateNote(event) { note = it }
}
}
content(note)
}
@Composable
private fun LoadAndDisplayEvent(
event: Event,
additionalChars: String,
accountViewModel: AccountViewModel,
nav: (String) -> Unit,
) {
LoadNote(nip19.hex, accountViewModel) {
LoadOrCreateNote(event, accountViewModel) {
if (it != null) {
DisplayNoteLink(it, nip19, accountViewModel, nav)
DisplayNoteLink(it, event.id, event.kind, additionalChars, accountViewModel, nav)
} else {
CreateClickableText(
clickablePart = remember(nip19) { "@${nip19.hex.toShortenHex()}" },
suffix = nip19.additionalChars,
route = remember(nip19) { "Event/${nip19.hex}" },
clickablePart = remember(event.id) { "@${event.toNIP19()}" },
suffix = additionalChars,
route = remember(event.id) { "Event/${event.id}" },
nav = nav,
)
}
@@ -118,19 +138,21 @@ private fun DisplayEvent(
}
@Composable
private fun DisplayNote(
nip19: Nip19Bech32.Return,
private fun DisplayEvent(
hex: HexKey,
kind: Int?,
additionalChars: String,
accountViewModel: AccountViewModel,
nav: (String) -> Unit,
) {
LoadNote(nip19.hex, accountViewModel = accountViewModel) {
LoadNote(hex, accountViewModel) {
if (it != null) {
DisplayNoteLink(it, nip19, accountViewModel, nav)
DisplayNoteLink(it, hex, kind, additionalChars, accountViewModel, nav)
} else {
CreateClickableText(
clickablePart = remember(nip19) { "@${nip19.hex.toShortenHex()}" },
suffix = nip19.additionalChars,
route = remember(nip19) { "Event/${nip19.hex}" },
clickablePart = remember(hex) { "@${hex.toShortenHex()}" },
suffix = additionalChars,
route = remember(hex) { "Event/$hex" },
nav = nav,
)
}
@@ -140,7 +162,9 @@ private fun DisplayNote(
@Composable
private fun DisplayNoteLink(
it: Note,
nip19: Nip19Bech32.Return,
hex: HexKey,
kind: Int?,
addedCharts: String,
accountViewModel: AccountViewModel,
nav: (String) -> Unit,
) {
@@ -150,21 +174,20 @@ private fun DisplayNoteLink(
val channelHex = remember(noteState) { note.channelHex() }
val noteIdDisplayNote = remember(noteState) { "@${note.idDisplayNote()}" }
val addedCharts = nip19.additionalChars
if (note.event is ChannelCreateEvent || nip19.kind == ChannelCreateEvent.KIND) {
if (note.event is ChannelCreateEvent || kind == ChannelCreateEvent.KIND) {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Channel/${nip19.hex}" },
route = remember(noteState) { "Channel/$hex" },
nav = nav,
)
} else if (note.event is PrivateDmEvent || nip19.kind == PrivateDmEvent.KIND) {
} else if (note.event is PrivateDmEvent || kind == PrivateDmEvent.KIND) {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route =
remember(noteState) { (note.author?.pubkeyHex ?: nip19.hex).let { "RoomByAuthor/$it" } },
remember(noteState) { (note.author?.pubkeyHex ?: hex).let { "RoomByAuthor/$it" } },
nav = nav,
)
} else if (channelHex != null) {
@@ -186,7 +209,7 @@ private fun DisplayNoteLink(
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Event/${nip19.hex}" },
route = remember(noteState) { "Event/$hex" },
nav = nav,
)
}
@@ -194,27 +217,28 @@ private fun DisplayNoteLink(
@Composable
private fun DisplayAddress(
nip19: Nip19Bech32.Return,
nip19: Nip19Bech32.NAddress,
additionalChars: String,
accountViewModel: AccountViewModel,
nav: (String) -> Unit,
) {
var noteBase by remember(nip19) { mutableStateOf(accountViewModel.getNoteIfExists(nip19.hex)) }
var noteBase by remember(nip19) { mutableStateOf(accountViewModel.getNoteIfExists(nip19.atag)) }
if (noteBase == null) {
LaunchedEffect(key1 = nip19.hex) {
accountViewModel.checkGetOrCreateAddressableNote(nip19.hex) { noteBase = it }
LaunchedEffect(key1 = nip19.atag) {
accountViewModel.checkGetOrCreateAddressableNote(nip19.atag) { noteBase = it }
}
}
noteBase?.let {
val noteState by it.live().metadata.observeAsState()
val route = remember(noteState) { "Note/${nip19.hex}" }
val route = remember(noteState) { "Note/${nip19.atag}" }
val displayName = remember(noteState) { "@${noteState?.note?.idDisplayNote()}" }
CreateClickableText(
clickablePart = displayName,
suffix = nip19.additionalChars,
suffix = additionalChars,
route = route,
nav = nav,
)
@@ -222,35 +246,36 @@ private fun DisplayAddress(
if (noteBase == null) {
Text(
remember { "@${nip19.hex}${nip19.additionalChars}" },
remember { "@${nip19.atag}$additionalChars" },
)
}
}
@Composable
private fun DisplayUser(
nip19: Nip19Bech32.Return,
userHex: HexKey,
additionalChars: String,
accountViewModel: AccountViewModel,
nav: (String) -> Unit,
) {
var userBase by
remember(nip19) {
remember(userHex) {
mutableStateOf(
accountViewModel.getUserIfExists(nip19.hex),
accountViewModel.getUserIfExists(userHex),
)
}
if (userBase == null) {
LaunchedEffect(key1 = nip19.hex) {
accountViewModel.checkGetOrCreateUser(nip19.hex) { userBase = it }
LaunchedEffect(key1 = userHex) {
accountViewModel.checkGetOrCreateUser(userHex) { userBase = it }
}
}
userBase?.let { RenderUserAsClickableText(it, nip19, nav) }
userBase?.let { RenderUserAsClickableText(it, additionalChars, nav) }
if (userBase == null) {
Text(
remember { "@${nip19.hex}${nip19.additionalChars}" },
remember { "@${userHex}$additionalChars" },
)
}
}
@@ -258,7 +283,7 @@ private fun DisplayUser(
@Composable
private fun RenderUserAsClickableText(
baseUser: User,
nip19: Nip19Bech32.Return,
additionalChars: String,
nav: (String) -> Unit,
) {
val userState by baseUser.live().metadata.observeAsState()
@@ -281,7 +306,7 @@ private fun RenderUserAsClickableText(
tags = userTags,
)
nip19.additionalChars.ifBlank { null }?.let {
additionalChars.ifBlank { null }?.let {
Text(text = it, maxLines = 1)
}
}
@@ -25,6 +25,7 @@ import android.util.Patterns
import com.vitorpamplona.amethyst.commons.RichTextParser
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.service.checkNotInMainThread
import com.vitorpamplona.quartz.encoders.ATag
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.events.ImmutableListOfLists
import kotlinx.coroutines.CancellationException
@@ -64,58 +65,80 @@ class MarkdownParser {
return null
}
private fun getDisplayNameFromNip19(nip19: Nip19Bech32.Return): Pair<String, String>? {
if (nip19.type == Nip19Bech32.Type.USER) {
LocalCache.getUserIfExists(nip19.hex)?.let {
return Pair(it.toBestDisplayName(), it.pubkeyNpub())
private suspend fun getDisplayNameFromNip19(nip19: Nip19Bech32.Entity): Pair<String, String>? {
return when (nip19) {
is Nip19Bech32.NSec -> null
is Nip19Bech32.NPub -> {
LocalCache.getUserIfExists(nip19.hex)?.let {
return Pair(it.toBestDisplayName(), it.pubkeyNpub())
}
}
} else if (nip19.type == Nip19Bech32.Type.NOTE) {
LocalCache.getNoteIfExists(nip19.hex)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
is Nip19Bech32.NProfile -> {
LocalCache.getUserIfExists(nip19.hex)?.let {
return Pair(it.toBestDisplayName(), it.pubkeyNpub())
}
}
} else if (nip19.type == Nip19Bech32.Type.ADDRESS) {
LocalCache.getAddressableNoteIfExists(nip19.hex)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
is Nip19Bech32.Note -> {
LocalCache.getNoteIfExists(nip19.hex)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
}
}
} else if (nip19.type == Nip19Bech32.Type.EVENT) {
LocalCache.getNoteIfExists(nip19.hex)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
is Nip19Bech32.NEvent -> {
LocalCache.getNoteIfExists(nip19.hex)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
}
}
}
is Nip19Bech32.NEmbed -> {
if (LocalCache.getNoteIfExists(nip19.event.id) == null) {
LocalCache.verifyAndConsume(nip19.event, null)
}
return null
LocalCache.getNoteIfExists(nip19.event.id)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
}
}
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> {
LocalCache.getAddressableNoteIfExists(nip19.atag)?.let {
return Pair(it.idDisplayNote(), it.toNEvent())
}
}
else -> null
}
}
fun returnNIP19References(
content: String,
tags: ImmutableListOfLists<String>?,
): List<Nip19Bech32.Return> {
): List<Nip19Bech32.Entity> {
checkNotInMainThread()
val listOfReferences = mutableListOf<Nip19Bech32.Return>()
val listOfReferences = mutableListOf<Nip19Bech32.Entity>()
content.split('\n').forEach { paragraph ->
paragraph.split(' ').forEach { word: String ->
if (RichTextParser.startsWithNIP19Scheme(word)) {
val parsedNip19 = Nip19Bech32.uriToRoute(word)
parsedNip19?.let { listOfReferences.add(it) }
parsedNip19?.let { listOfReferences.add(it.entity) }
}
}
}
tags?.lists?.forEach {
if (it[0] == "p" && it.size > 1) {
listOfReferences.add(Nip19Bech32.Return(Nip19Bech32.Type.USER, it[1], null, null, null, ""))
listOfReferences.add(Nip19Bech32.NProfile(it[1], listOfNotNull(it.getOrNull(2))))
} else if (it[0] == "e" && it.size > 1) {
listOfReferences.add(Nip19Bech32.Return(Nip19Bech32.Type.NOTE, it[1], null, null, null, ""))
listOfReferences.add(Nip19Bech32.NEvent(it[1], listOfNotNull(it.getOrNull(2)), null, null))
} else if (it[0] == "a" && it.size > 1) {
listOfReferences.add(Nip19Bech32.Return(Nip19Bech32.Type.ADDRESS, it[1], null, null, null, ""))
ATag.parseAtag(it[1], it.getOrNull(2))?.let { atag ->
listOfReferences.add(Nip19Bech32.NAddress(it[1], listOfNotNull(atag.relay), atag.pubKeyHex, atag.kind))
}
}
}
return listOfReferences
}
fun returnMarkdownWithSpecialContent(
suspend fun returnMarkdownWithSpecialContent(
content: String,
tags: ImmutableListOfLists<String>?,
): String {
@@ -135,8 +158,8 @@ class MarkdownParser {
} else if (RichTextParser.startsWithNIP19Scheme(word)) {
val parsedNip19 = Nip19Bech32.uriToRoute(word)
returnContent +=
if (parsedNip19 !== null) {
val pair = getDisplayNameFromNip19(parsedNip19)
if (parsedNip19?.entity !== null) {
val pair = getDisplayNameFromNip19(parsedNip19.entity)
if (pair != null) {
val (displayName, nip19) = pair
"[$displayName](nostr:$nip19) "
@@ -106,6 +106,7 @@ import com.vitorpamplona.amethyst.ui.theme.innerPostModifier
import com.vitorpamplona.amethyst.ui.theme.markdownStyle
import com.vitorpamplona.amethyst.ui.uriToRoute
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.encoders.HexKey
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.events.EmptyTagList
import com.vitorpamplona.quartz.events.ImmutableListOfLists
@@ -507,9 +508,7 @@ private fun RefreshableContent(
var markdownWithSpecialContent by remember(content) { mutableStateOf<String?>(content) }
ObserverAllNIP19References(content, tags, accountViewModel) {
accountViewModel.returnMarkdownWithSpecialContent(content, tags) {
newMarkdownWithSpecialContent,
->
accountViewModel.returnMarkdownWithSpecialContent(content, tags) { newMarkdownWithSpecialContent ->
if (markdownWithSpecialContent != newMarkdownWithSpecialContent) {
markdownWithSpecialContent = newMarkdownWithSpecialContent
}
@@ -526,7 +525,7 @@ fun ObserverAllNIP19References(
accountViewModel: AccountViewModel,
onRefresh: () -> Unit,
) {
var nip19References by remember(content) { mutableStateOf<List<Nip19Bech32.Return>>(emptyList()) }
var nip19References by remember(content) { mutableStateOf<List<Nip19Bech32.Entity>>(emptyList()) }
LaunchedEffect(key1 = content) {
accountViewModel.returnNIP19References(content, tags) {
@@ -540,33 +539,37 @@ fun ObserverAllNIP19References(
@Composable
fun ObserveNIP19(
it: Nip19Bech32.Return,
entity: Nip19Bech32.Entity,
accountViewModel: AccountViewModel,
onRefresh: () -> Unit,
) {
if (it.type == Nip19Bech32.Type.NOTE || it.type == Nip19Bech32.Type.EVENT || it.type == Nip19Bech32.Type.ADDRESS) {
ObserveNIP19Event(it, accountViewModel, onRefresh)
} else if (it.type == Nip19Bech32.Type.USER) {
ObserveNIP19User(it, accountViewModel, onRefresh)
when (val parsed = entity) {
is Nip19Bech32.NPub -> ObserveNIP19User(parsed.hex, accountViewModel, onRefresh)
is Nip19Bech32.NProfile -> ObserveNIP19User(parsed.hex, accountViewModel, onRefresh)
is Nip19Bech32.Note -> ObserveNIP19Event(parsed.hex, accountViewModel, onRefresh)
is Nip19Bech32.NEvent -> ObserveNIP19Event(parsed.hex, accountViewModel, onRefresh)
is Nip19Bech32.NEmbed -> ObserveNIP19Event(parsed.event.id, accountViewModel, onRefresh)
is Nip19Bech32.NAddress -> ObserveNIP19Event(parsed.atag, accountViewModel, onRefresh)
is Nip19Bech32.NSec -> {}
is Nip19Bech32.NRelay -> {}
}
}
@Composable
private fun ObserveNIP19Event(
it: Nip19Bech32.Return,
hex: HexKey,
accountViewModel: AccountViewModel,
onRefresh: () -> Unit,
) {
var baseNote by remember(it) { mutableStateOf<Note?>(accountViewModel.getNoteIfExists(it.hex)) }
var baseNote by remember(hex) { mutableStateOf<Note?>(accountViewModel.getNoteIfExists(hex)) }
if (baseNote == null) {
LaunchedEffect(key1 = it.hex) {
if (
it.type == Nip19Bech32.Type.NOTE || it.type == Nip19Bech32.Type.EVENT || it.type == Nip19Bech32.Type.ADDRESS
) {
accountViewModel.checkGetOrCreateNote(it.hex) { note ->
launch(Dispatchers.Main) { baseNote = note }
}
LaunchedEffect(key1 = hex) {
accountViewModel.checkGetOrCreateNote(hex) { note ->
launch(Dispatchers.Main) { baseNote = note }
}
}
}
@@ -590,18 +593,16 @@ fun ObserveNote(
@Composable
private fun ObserveNIP19User(
it: Nip19Bech32.Return,
hex: HexKey,
accountViewModel: AccountViewModel,
onRefresh: () -> Unit,
) {
var baseUser by remember(it) { mutableStateOf<User?>(accountViewModel.getUserIfExists(it.hex)) }
var baseUser by remember(hex) { mutableStateOf<User?>(accountViewModel.getUserIfExists(hex)) }
if (baseUser == null) {
LaunchedEffect(key1 = it.hex) {
if (it.type == Nip19Bech32.Type.USER) {
accountViewModel.checkGetOrCreateUser(it.hex)?.let { user ->
launch(Dispatchers.Main) { baseUser = user }
}
LaunchedEffect(key1 = hex) {
accountViewModel.checkGetOrCreateUser(hex)?.let { user ->
launch(Dispatchers.Main) { baseUser = user }
}
}
}
@@ -634,7 +635,9 @@ fun BechLink(
var loadedLink by remember { mutableStateOf<LoadedBechLink?>(null) }
if (loadedLink == null) {
LaunchedEffect(key1 = word) { accountViewModel.parseNIP19(word) { loadedLink = it } }
LaunchedEffect(key1 = word) {
accountViewModel.parseNIP19(word) { loadedLink = it }
}
}
if (canPreview && loadedLink?.baseNote != null) {
@@ -648,7 +651,7 @@ fun BechLink(
)
}
} else if (loadedLink?.nip19 != null) {
ClickableRoute(loadedLink?.nip19!!, accountViewModel, nav)
ClickableRoute(word, loadedLink?.nip19!!, accountViewModel, nav)
} else {
val text =
remember(word) {
@@ -77,10 +77,8 @@ import com.vitorpamplona.amethyst.ui.screen.loggedOff.LoginOrSignupScreen
import com.vitorpamplona.amethyst.ui.theme.AccountPictureModifier
import com.vitorpamplona.amethyst.ui.theme.Size10dp
import com.vitorpamplona.amethyst.ui.theme.Size55dp
import com.vitorpamplona.quartz.encoders.decodePublicKey
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.encoders.decodePublicKeyAsHexOrNull
import com.vitorpamplona.quartz.events.toImmutableListOfLists
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -149,12 +147,9 @@ fun DisplayAccount(
) {
var baseUser by remember {
mutableStateOf<User?>(
LocalCache.getUserIfExists(
decodePublicKey(
acc.npub,
)
.toHexKey(),
),
decodePublicKeyAsHexOrNull(acc.npub)?.let {
LocalCache.getUserIfExists(it)
},
)
}
@@ -162,13 +157,8 @@ fun DisplayAccount(
LaunchedEffect(key1 = acc.npub) {
launch(Dispatchers.IO) {
baseUser =
try {
LocalCache.getOrCreateUser(
decodePublicKey(acc.npub).toHexKey(),
)
} catch (e: Exception) {
if (e is CancellationException) throw e
null
decodePublicKeyAsHexOrNull(acc.npub)?.let {
LocalCache.getOrCreateUser(it)
}
}
}
@@ -99,6 +99,7 @@ import com.vitorpamplona.amethyst.ui.theme.DividerThickness
import com.vitorpamplona.amethyst.ui.theme.Font14SP
import com.vitorpamplona.amethyst.ui.theme.placeholderText
import com.vitorpamplona.quartz.encoders.Nip47WalletConnect
import com.vitorpamplona.quartz.encoders.decodePrivateKeyAsHexOrNull
import com.vitorpamplona.quartz.encoders.decodePublicKey
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.events.LnZapEvent
@@ -165,14 +166,7 @@ class UpdateZapAmountViewModel(val account: Account) : ViewModel() {
addedWSS
}
val unverifiedPrivKey = walletConnectSecret.text.ifBlank { null }
val privKeyHex =
try {
unverifiedPrivKey?.let { decodePublicKey(it).toHexKey() }
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
val privKeyHex = walletConnectSecret.text.ifBlank { null }?.let { decodePrivateKeyAsHexOrNull(it) }
if (pubkeyHex != null) {
account?.changeZapPaymentRequest(
@@ -29,28 +29,14 @@ import com.google.zxing.client.android.Intents
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.amethyst.ui.uriToRoute
import kotlinx.coroutines.CancellationException
@Composable
fun NIP19QrCodeScanner(onScan: (String?) -> Unit) {
SimpleQrCodeScanner {
try {
val nip19 = Nip19Bech32.uriToRoute(it)
val startingPage =
when (nip19?.type) {
Nip19Bech32.Type.USER -> "User/${nip19.hex}"
Nip19Bech32.Type.NOTE -> "Note/${nip19.hex}"
Nip19Bech32.Type.EVENT -> "Event/${nip19.hex}"
Nip19Bech32.Type.ADDRESS -> "Note/${nip19.hex}"
else -> null
}
if (startingPage != null) {
onScan(startingPage)
} else {
onScan(null)
}
onScan(uriToRoute(it))
} catch (e: Throwable) {
if (e is CancellationException) throw e
Log.e("NIP19 Scanner", "Error parsing $it", e)
@@ -85,8 +85,20 @@ class AccountStateViewModel() : ViewModel() {
loginWithExternalSigner: Boolean = false,
packageName: String = "",
) = withContext(Dispatchers.IO) {
val parsed = Nip19Bech32.uriToRoute(key)
val pubKeyParsed = parsed?.hex?.hexToByteArray()
val parsed = Nip19Bech32.uriToRoute(key)?.entity
val pubKeyParsed =
when (parsed) {
is Nip19Bech32.NSec -> null
is Nip19Bech32.NPub -> parsed.hex.hexToByteArray()
is Nip19Bech32.NProfile -> parsed.hex.hexToByteArray()
is Nip19Bech32.Note -> null
is Nip19Bech32.NEvent -> null
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> null
else -> null
}
val proxy = HttpClientManager.initProxy(useProxy, "127.0.0.1", proxyPort)
if (loginWithExternalSigner && pubKeyParsed == null) {
@@ -868,6 +868,22 @@ class AccountViewModel(val account: Account, val settings: SettingsState) : View
viewModelScope.launch(Dispatchers.IO) { onResult(checkGetOrCreateNote(key)) }
}
fun checkGetOrCreateNote(
event: Event,
onResult: (Note?) -> Unit,
) {
viewModelScope.launch(Dispatchers.IO) {
var note = checkGetOrCreateNote(event.id)
if (note == null) {
LocalCache.verifyAndConsume(event, null)
note = checkGetOrCreateNote(event.id)
}
onResult(note)
}
}
fun getNoteIfExists(hex: HexKey): Note? {
return LocalCache.getNoteIfExists(hex)
}
@@ -970,7 +986,7 @@ class AccountViewModel(val account: Account, val settings: SettingsState) : View
fun returnNIP19References(
content: String,
tags: ImmutableListOfLists<String>?,
onNewReferences: (List<Nip19Bech32.Return>) -> Unit,
onNewReferences: (List<Nip19Bech32.Entity>) -> Unit,
) {
viewModelScope.launch(Dispatchers.IO) {
onNewReferences(MarkdownParser().returnNIP19References(content, tags))
@@ -987,17 +1003,32 @@ class AccountViewModel(val account: Account, val settings: SettingsState) : View
}
}
fun parseNIP19(
suspend fun parseNIP19(
str: String,
onNote: (LoadedBechLink) -> Unit,
) {
viewModelScope.launch(Dispatchers.IO) {
withContext(Dispatchers.IO) {
Nip19Bech32.uriToRoute(str)?.let {
var returningNote: Note? = null
if (
it.type == Nip19Bech32.Type.NOTE || it.type == Nip19Bech32.Type.EVENT || it.type == Nip19Bech32.Type.ADDRESS
) {
LocalCache.checkGetOrCreateNote(it.hex)?.let { note -> returningNote = note }
when (val parsed = it.entity) {
is Nip19Bech32.NSec -> {}
is Nip19Bech32.NPub -> {}
is Nip19Bech32.NProfile -> {}
is Nip19Bech32.Note -> LocalCache.checkGetOrCreateNote(parsed.hex)?.let { note -> returningNote = note }
is Nip19Bech32.NEvent -> LocalCache.checkGetOrCreateNote(parsed.hex)?.let { note -> returningNote = note }
is Nip19Bech32.NEmbed -> {
if (LocalCache.getNoteIfExists(parsed.event.id) == null) {
LocalCache.verifyAndConsume(parsed.event, null)
}
LocalCache.checkGetOrCreateNote(parsed.event.id)?.let { note ->
returningNote = note
}
}
is Nip19Bech32.NRelay -> {}
is Nip19Bech32.NAddress -> LocalCache.checkGetOrCreateNote(parsed.atag)?.let { note -> returningNote = note }
else -> {}
}
onNote(LoadedBechLink(returningNote, it))
@@ -1298,7 +1329,7 @@ class HasNotificationDot(bottomNavigationItems: ImmutableList<Route>) {
}
}
@Immutable data class LoadedBechLink(val baseNote: Note?, val nip19: Nip19Bech32.Return)
@Immutable data class LoadedBechLink(val baseNote: Note?, val nip19: Nip19Bech32.ParseReturn)
public fun <T, K> allOrNothingSigningOperations(
remainingTos: List<T>,
@@ -26,6 +26,7 @@ import com.vitorpamplona.amethyst.ui.actions.Dao
import com.vitorpamplona.amethyst.ui.actions.NewMessageTagger
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
@@ -54,10 +55,10 @@ class NewMessageTaggerKeyParseTest {
val result =
NewMessageTagger(message = "", dao = dao)
.parseDirtyWordForKey("note1z5e2m0smx6d7e2d0zaq8d3rnd7httm6j0uf8tf90yqqjrs842czshwtkmn")
assertEquals(Nip19Bech32.Type.NOTE, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.Note)
assertEquals(
"1532adbe1b369beca9af174076c4736faeb5ef527f1275a4af200121c0f55605",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.Note)?.hex,
)
assertEquals("", result?.restOfWord)
}
@@ -67,10 +68,10 @@ class NewMessageTaggerKeyParseTest {
val result =
NewMessageTagger(message = "", dao = dao)
.parseDirtyWordForKey("npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z")
assertEquals(Nip19Bech32.Type.USER, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.NPub)
assertEquals(
"460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.NPub)?.hex,
)
assertEquals("", result?.restOfWord)
}
@@ -80,10 +81,10 @@ class NewMessageTaggerKeyParseTest {
val result =
NewMessageTagger(message = "", dao = dao)
.parseDirtyWordForKey("note1z5e2m0smx6d7e2d0zaq8d3rnd7httm6j0uf8tf90yqqjrs842czshwtkmn,")
assertEquals(Nip19Bech32.Type.NOTE, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.Note)
assertEquals(
"1532adbe1b369beca9af174076c4736faeb5ef527f1275a4af200121c0f55605",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.Note)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -93,10 +94,10 @@ class NewMessageTaggerKeyParseTest {
val result =
NewMessageTagger(message = "", dao = dao)
.parseDirtyWordForKey("npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z,")
assertEquals(Nip19Bech32.Type.USER, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.NPub)
assertEquals(
"460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.NPub)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -106,10 +107,10 @@ class NewMessageTaggerKeyParseTest {
val result =
NewMessageTagger(message = "", dao = dao)
.parseDirtyWordForKey("@note1z5e2m0smx6d7e2d0zaq8d3rnd7httm6j0uf8tf90yqqjrs842czshwtkmn,")
assertEquals(Nip19Bech32.Type.NOTE, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.Note)
assertEquals(
"1532adbe1b369beca9af174076c4736faeb5ef527f1275a4af200121c0f55605",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.Note)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -119,10 +120,10 @@ class NewMessageTaggerKeyParseTest {
val result =
NewMessageTagger(message = "", dao = dao)
.parseDirtyWordForKey("@npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z,")
assertEquals(Nip19Bech32.Type.USER, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.NPub)
assertEquals(
"460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.NPub)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -134,10 +135,10 @@ class NewMessageTaggerKeyParseTest {
.parseDirtyWordForKey(
"nostr:note1z5e2m0smx6d7e2d0zaq8d3rnd7httm6j0uf8tf90yqqjrs842czshwtkmn,",
)
assertEquals(Nip19Bech32.Type.NOTE, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.Note)
assertEquals(
"1532adbe1b369beca9af174076c4736faeb5ef527f1275a4af200121c0f55605",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.Note)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -149,10 +150,10 @@ class NewMessageTaggerKeyParseTest {
.parseDirtyWordForKey(
"nostr:npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z,",
)
assertEquals(Nip19Bech32.Type.USER, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.NPub)
assertEquals(
"460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.NPub)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -164,10 +165,10 @@ class NewMessageTaggerKeyParseTest {
.parseDirtyWordForKey(
"Nostr:note1z5e2m0smx6d7e2d0zaq8d3rnd7httm6j0uf8tf90yqqjrs842czshwtkmn,",
)
assertEquals(Nip19Bech32.Type.NOTE, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.Note)
assertEquals(
"1532adbe1b369beca9af174076c4736faeb5ef527f1275a4af200121c0f55605",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.Note)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -179,10 +180,10 @@ class NewMessageTaggerKeyParseTest {
.parseDirtyWordForKey(
"nOstr:npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z,",
)
assertEquals(Nip19Bech32.Type.USER, result?.key?.type)
assertTrue(result?.key?.entity is Nip19Bech32.NPub)
assertEquals(
"460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c",
result?.key?.hex,
(result?.key?.entity as? Nip19Bech32.NPub)?.hex,
)
assertEquals(",", result?.restOfWord)
}
@@ -22,9 +22,8 @@ package com.vitorpamplona.quartz
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.encoders.Bech32
import com.vitorpamplona.quartz.encoders.Hex
import com.vitorpamplona.quartz.encoders.bechToBytes
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.FhirResourceEvent
import com.vitorpamplona.quartz.events.TextNoteEvent
@@ -35,17 +34,13 @@ import junit.framework.TestCase.assertTrue
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.io.ByteArrayOutputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.time.measureTimedValue
@RunWith(AndroidJUnit4::class)
class NIP19EmbedTests {
@Test
fun testEmbedEvent() {
fun testEmbedKind1Event() {
val signer =
NostrSignerInternal(
KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")),
@@ -64,12 +59,11 @@ class NIP19EmbedTests {
assertNotNull(textNote)
val bech32 = Bech32.encodeBytes(hrp = "n", textNote!!.toJson().toByteArray(Charsets.UTF_8), Bech32.Encoding.Bech32)
val bech32 = Nip19Bech32.createNEmbed(textNote!!)
println(bech32)
val decoded = String(bech32.bechToBytes())
val decodedNote = Event.fromJson(decoded)
val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event
assertTrue(decodedNote.hasValidSignature())
@@ -96,52 +90,19 @@ class NIP19EmbedTests {
assertNotNull(eyeglassesPrescriptionEvent)
val bech32 = Bech32.encodeBytes(hrp = "nembed", eyeglassesPrescriptionEvent!!.toJson().toByteArray(Charsets.UTF_8), Bech32.Encoding.Bech32)
val bech32 = Nip19Bech32.createNEmbed(eyeglassesPrescriptionEvent!!)
println(eyeglassesPrescriptionEvent!!.toJson())
println(bech32)
val decoded = String(bech32.bechToBytes())
val decodedNote = Event.fromJson(decoded)
assertTrue(decodedNote.hasValidSignature())
assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson())
}
@Test
fun testVisionPrescriptionEmbedEventCompression() {
val signer =
NostrSignerInternal(
KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")),
)
var eyeglassesPrescriptionEvent: Event? = null
val countDownLatch = CountDownLatch(1)
FhirResourceEvent.create(fhirPayload = visionPrescriptionFhir, signer = signer) {
eyeglassesPrescriptionEvent = it
countDownLatch.countDown()
}
Assert.assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
assertNotNull(eyeglassesPrescriptionEvent)
val bech32 = Bech32.encodeBytes(hrp = "nembed", gzip(eyeglassesPrescriptionEvent!!.toJson()), Bech32.Encoding.Bech32)
println(eyeglassesPrescriptionEvent!!.toJson())
println(bech32)
val decoded = ungzip(bech32.bechToBytes())
val decodedNote = Event.fromJson(decoded)
val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event
assertTrue(decodedNote.hasValidSignature())
assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson())
}
/*
@Test
fun testCompressionSizes() {
val signer =
@@ -167,24 +128,15 @@ class NIP19EmbedTests {
Bech32.encodeBytes(hrp = "nembed", json.toByteArray(), Bech32.Encoding.Bech32)
Bech32.encodeBytes(hrp = "nembed", gzip(json), Bech32.Encoding.Bech32)
val (bech32json, elapsedjson) = measureTimedValue { Bech32.encodeBytes(hrp = "nembed", json.toByteArray(), Bech32.Encoding.Bech32) }
val (bech32gzip, elapsedgzip) = measureTimedValue { Bech32.encodeBytes(hrp = "nembed", gzip(json), Bech32.Encoding.Bech32) }
val (bech32json, elapsedjson) = measureTimedValue { json.toByteArray().toNEmbed() }
val (bech32gzip, elapsedgzip) = measureTimedValue { gzip(json).toNEmbed() }
println("Raw JSON ${json.length} chars")
println("Bech32 JSON ${bech32json.length} chars in $elapsedjson")
println("Bech32 GZIP ${bech32gzip.length} chars in $elapsedgzip")
assertTrue(true)
}
}*/
val visionPrescriptionFhir = "{\"resourceType\":\"VisionPrescription\",\"status\":\"active\",\"created\":\"2014-06-15\",\"patient\":{\"reference\":\"Patient/example\"},\"dateWritten\":\"2014-06-15\",\"prescriber\":{\"reference\":\"Practitioner/example\"},\"lensSpecification\":[{\"eye\":\"right\",\"sphere\":-2,\"prism\":[{\"amount\":0.5,\"base\":\"down\"}],\"add\":2},{\"eye\":\"left\",\"sphere\":-1,\"cylinder\":-0.5,\"axis\":180,\"prism\":[{\"amount\":0.5,\"base\":\"up\"}],\"add\":2}]}"
}
fun gzip(content: String): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(Charsets.UTF_8).use { it.write(content) }
val array = bos.toByteArray()
return array
}
fun ungzip(content: ByteArray): String = GZIPInputStream(content.inputStream()).bufferedReader(Charsets.UTF_8).use { it.readText() }
@@ -271,18 +271,6 @@ object Bech32 {
}
}
fun ByteArray.toNsec() = Bech32.encodeBytes(hrp = "nsec", this, Bech32.Encoding.Bech32)
fun ByteArray.toNpub() = Bech32.encodeBytes(hrp = "npub", this, Bech32.Encoding.Bech32)
fun ByteArray.toNote() = Bech32.encodeBytes(hrp = "note", this, Bech32.Encoding.Bech32)
fun ByteArray.toNEvent() = Bech32.encodeBytes(hrp = "nevent", this, Bech32.Encoding.Bech32)
fun ByteArray.toNAddress() = Bech32.encodeBytes(hrp = "naddr", this, Bech32.Encoding.Bech32)
fun ByteArray.toLnUrl() = Bech32.encodeBytes(hrp = "lnurl", this, Bech32.Encoding.Bech32)
fun String.bechToBytes(hrp: String? = null): ByteArray {
val decodedForm = Bech32.decodeBytes(this)
hrp?.also {
@@ -23,7 +23,12 @@ package com.vitorpamplona.quartz.encoders
import android.util.Log
import androidx.compose.runtime.Immutable
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.events.Event
import kotlinx.coroutines.CancellationException
import java.io.ByteArrayOutputStream
import java.util.regex.Pattern
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
object Nip19Bech32 {
enum class Type {
@@ -43,21 +48,40 @@ object Nip19Bech32 {
val nip19regex =
Pattern.compile(
"(nostr:)?@?(nsec1|npub1|nevent1|naddr1|note1|nprofile1|nrelay1)([qpzry9x8gf2tvdw0s3jn54khce6mua7l]+)([\\S]*)",
"(nostr:)?@?(nsec1|npub1|nevent1|naddr1|note1|nprofile1|nrelay1|nembed1)([qpzry9x8gf2tvdw0s3jn54khce6mua7l]+)([\\S]*)",
Pattern.CASE_INSENSITIVE,
)
@Immutable
data class Return(
val type: Type,
val hex: String,
val relay: String? = null,
val author: String? = null,
val kind: Int? = null,
val additionalChars: String = "",
)
data class ParseReturn(val entity: Entity, val additionalChars: String = "")
fun uriToRoute(uri: String?): Return? {
interface Entity
@Immutable
data class NSec(val hex: String) : Entity
@Immutable
data class NPub(val hex: String) : Entity
@Immutable
data class Note(val hex: String) : Entity
@Immutable
data class NProfile(val hex: String, val relay: List<String>) : Entity
@Immutable
data class NEvent(val hex: String, val relay: List<String>, val author: String?, val kind: Int?) : Entity
@Immutable
data class NAddress(val atag: String, val relay: List<String>, val author: String, val kind: Int) : Entity
@Immutable
data class NRelay(val relay: List<String>) : Entity
@Immutable
data class NEmbed(val event: Event) : Entity
fun uriToRoute(uri: String?): ParseReturn? {
if (uri == null) return null
try {
@@ -66,12 +90,11 @@ object Nip19Bech32 {
return null
}
val uriScheme = matcher.group(1) // nostr:
val type = matcher.group(2) // npub1
val key = matcher.group(3) // bech32
val additionalChars = matcher.group(4) // additional chars
return parseComponents(uriScheme, type, key, additionalChars)
return parseComponents(type!!, key, additionalChars)
} catch (e: Throwable) {
Log.e("NIP19 Parser", "Issue trying to Decode NIP19 $uri: ${e.message}", e)
}
@@ -80,28 +103,24 @@ object Nip19Bech32 {
}
fun parseComponents(
uriScheme: String?,
type: String,
key: String?,
additionalChars: String?,
): Return? {
): ParseReturn? {
return try {
val bytes = (type + key).bechToBytes()
val parsed =
when (type.lowercase()) {
"npub1" -> npub(bytes)
"note1" -> note(bytes)
"nprofile1" -> nprofile(bytes)
"nevent1" -> nevent(bytes)
"nrelay1" -> nrelay(bytes)
"naddr1" -> naddr(bytes)
else -> null
}
if (parsed?.hex?.isBlank() == true) {
null
} else {
parsed?.copy(additionalChars = additionalChars ?: "")
when (type.lowercase()) {
"npub1" -> npub(bytes)
"note1" -> note(bytes)
"nprofile1" -> nprofile(bytes)
"nevent1" -> nevent(bytes)
"nrelay1" -> nrelay(bytes)
"naddr1" -> naddr(bytes)
"nembed1" -> nembed(bytes)
else -> null
}?.let {
ParseReturn(it, additionalChars ?: "")
}
} catch (e: Throwable) {
Log.w("NIP19 Parser", "Issue trying to Decode NIP19 $key: ${e.message}", e)
@@ -109,52 +128,71 @@ object Nip19Bech32 {
}
}
private fun npub(bytes: ByteArray): Return {
return Return(Type.USER, bytes.toHexKey())
private fun nembed(bytes: ByteArray): NEmbed? {
if (bytes.isEmpty()) return null
return NEmbed(Event.fromJson(ungzip(bytes)))
}
private fun note(bytes: ByteArray): Return {
return Return(Type.NOTE, bytes.toHexKey())
private fun npub(bytes: ByteArray): NPub? {
if (bytes.isEmpty()) return null
return NPub(bytes.toHexKey())
}
private fun nprofile(bytes: ByteArray): Return? {
private fun note(bytes: ByteArray): Note? {
if (bytes.isEmpty()) return null
return Note(bytes.toHexKey())
}
private fun nprofile(bytes: ByteArray): NProfile? {
if (bytes.isEmpty()) return null
val tlv = Tlv.parse(bytes)
val hex = tlv.firstAsHex(TlvTypes.SPECIAL) ?: return null
val relay = tlv.firstAsString(TlvTypes.RELAY)
val relay = tlv.asStringList(TlvTypes.RELAY) ?: emptyList()
return Return(Type.USER, hex, relay)
if (hex.isBlank()) return null
return NProfile(hex, relay)
}
private fun nevent(bytes: ByteArray): Return? {
private fun nevent(bytes: ByteArray): NEvent? {
if (bytes.isEmpty()) return null
val tlv = Tlv.parse(bytes)
val hex = tlv.firstAsHex(TlvTypes.SPECIAL) ?: return null
val relay = tlv.firstAsString(TlvTypes.RELAY)
val relay = tlv.asStringList(TlvTypes.RELAY) ?: emptyList()
val author = tlv.firstAsHex(TlvTypes.AUTHOR)
val kind = tlv.firstAsInt(TlvTypes.KIND.id)
return Return(Type.EVENT, hex, relay, author, kind)
if (hex.isBlank()) return null
return NEvent(hex, relay, author, kind)
}
private fun nrelay(bytes: ByteArray): Return? {
val relayUrl = Tlv.parse(bytes).firstAsString(TlvTypes.SPECIAL.id) ?: return null
private fun nrelay(bytes: ByteArray): NRelay? {
if (bytes.isEmpty()) return null
return Return(Type.RELAY, relayUrl)
val relayUrl = Tlv.parse(bytes).asStringList(TlvTypes.SPECIAL.id) ?: return null
return NRelay(relayUrl)
}
private fun naddr(bytes: ByteArray): Return? {
private fun naddr(bytes: ByteArray): NAddress? {
if (bytes.isEmpty()) return null
val tlv = Tlv.parse(bytes)
val d = tlv.firstAsString(TlvTypes.SPECIAL.id) ?: ""
val relay = tlv.firstAsString(TlvTypes.RELAY.id)
val relay = tlv.asStringList(TlvTypes.RELAY.id) ?: emptyList()
val author = tlv.firstAsHex(TlvTypes.AUTHOR.id) ?: return null
val kind = tlv.firstAsInt(TlvTypes.KIND.id) ?: return null
return Return(Type.ADDRESS, "$kind:$author:$d", relay, author, kind)
return NAddress("$kind:$author:$d", relay, author, kind)
}
public fun createNEvent(
fun createNEvent(
idHex: String,
author: String?,
kind: Int?,
@@ -170,34 +208,97 @@ object Nip19Bech32 {
.build()
.toNEvent()
}
fun createNEmbed(event: Event): String {
return gzip(event.toJson()).toNEmbed()
}
fun gzip(content: String): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(Charsets.UTF_8).use { it.write(content) }
val array = bos.toByteArray()
return array
}
fun ungzip(content: ByteArray): String = GZIPInputStream(content.inputStream()).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
fun decodePublicKey(key: String): ByteArray {
val parsed = Nip19Bech32.uriToRoute(key)
val pubKeyParsed = parsed?.hex?.hexToByteArray()
fun ByteArray.toNsec() = Bech32.encodeBytes(hrp = "nsec", this, Bech32.Encoding.Bech32)
return if (key.startsWith("nsec")) {
KeyPair(privKey = key.bechToBytes()).pubKey
} else if (pubKeyParsed != null) {
pubKeyParsed
} else {
Hex.decode(key)
fun ByteArray.toNpub() = Bech32.encodeBytes(hrp = "npub", this, Bech32.Encoding.Bech32)
fun ByteArray.toNote() = Bech32.encodeBytes(hrp = "note", this, Bech32.Encoding.Bech32)
fun ByteArray.toNEvent() = Bech32.encodeBytes(hrp = "nevent", this, Bech32.Encoding.Bech32)
fun ByteArray.toNAddress() = Bech32.encodeBytes(hrp = "naddr", this, Bech32.Encoding.Bech32)
fun ByteArray.toLnUrl() = Bech32.encodeBytes(hrp = "lnurl", this, Bech32.Encoding.Bech32)
fun ByteArray.toNEmbed() = Bech32.encodeBytes(hrp = "nembed", this, Bech32.Encoding.Bech32)
fun decodePublicKey(key: String): ByteArray {
return when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> KeyPair(privKey = key.bechToBytes()).pubKey
is Nip19Bech32.NPub -> parsed.hex.hexToByteArray()
is Nip19Bech32.NProfile -> parsed.hex.hexToByteArray()
else -> Hex.decode(key) // crashes on purpose
}
}
fun decodePrivateKeyAsHexOrNull(key: String): HexKey? {
return try {
when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> parsed.hex
is Nip19Bech32.NPub -> null
is Nip19Bech32.NProfile -> null
is Nip19Bech32.Note -> null
is Nip19Bech32.NEvent -> null
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> null
else -> Hex.decode(key).toHexKey()
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
fun decodePublicKeyAsHexOrNull(key: String): HexKey? {
return try {
val parsed = Nip19Bech32.uriToRoute(key)
val pubKeyParsed = parsed?.hex
if (key.startsWith("nsec")) {
KeyPair(privKey = key.bechToBytes()).pubKey.toHexKey()
} else if (pubKeyParsed != null) {
pubKeyParsed
} else {
Hex.decode(key).toHexKey()
when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> KeyPair(privKey = key.bechToBytes()).pubKey.toHexKey()
is Nip19Bech32.NPub -> parsed.hex
is Nip19Bech32.NProfile -> parsed.hex
is Nip19Bech32.Note -> null
is Nip19Bech32.NEvent -> null
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> null
else -> Hex.decode(key).toHexKey()
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
fun decodeEventIdAsHexOrNull(key: String): HexKey? {
return try {
when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> null
is Nip19Bech32.NPub -> null
is Nip19Bech32.NProfile -> null
is Nip19Bech32.Note -> parsed.hex
is Nip19Bech32.NEvent -> parsed.hex
is Nip19Bech32.NAddress -> parsed.atag
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
else -> Hex.decode(key).toHexKey()
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
@@ -237,3 +338,5 @@ fun Tlv.firstAsInt(type: Nip19Bech32.TlvTypes) = firstAsInt(type.id)
fun Tlv.firstAsHex(type: Nip19Bech32.TlvTypes) = firstAsHex(type.id)
fun Tlv.firstAsString(type: Nip19Bech32.TlvTypes) = firstAsString(type.id)
fun Tlv.asStringList(type: Nip19Bech32.TlvTypes) = asStringList(type.id)
@@ -94,6 +94,8 @@ class Tlv(val data: Map<Byte, List<ByteArray>>) {
fun firstAsString(type: Byte) = data[type]?.firstOrNull()?.toString(Charsets.UTF_8)
fun asStringList(type: Byte) = data[type]?.map { it.toString(Charsets.UTF_8) }
companion object {
fun parse(data: ByteArray): Tlv {
val result = mutableMapOf<Byte, MutableList<ByteArray>>()
@@ -100,16 +100,18 @@ open class BaseTextNoteEvent(
val matcher2 = nip19regex.matcher(content)
while (matcher2.find()) {
val uriScheme = matcher2.group(1) // nostr:
val type = matcher2.group(2) // npub1
val key = matcher2.group(3) // bech32
val additionalChars = matcher2.group(4) // additional chars
try {
val parsed = Nip19Bech32.parseComponents(uriScheme, type, key, additionalChars)
val parsed = Nip19Bech32.parseComponents(type, key, additionalChars)?.entity
if (parsed != null) {
if (parsed.type == Nip19Bech32.Type.USER) {
if (parsed is Nip19Bech32.NProfile) {
returningList.add(parsed.hex)
}
if (parsed is Nip19Bech32.NPub) {
returningList.add(parsed.hex)
}
}
@@ -145,16 +147,18 @@ open class BaseTextNoteEvent(
val matcher2 = nip19regex.matcher(content)
while (matcher2.find()) {
val uriScheme = matcher2.group(1) // nostr:
val type = matcher2.group(2) // npub1
val key = matcher2.group(3) // bech32
val additionalChars = matcher2.group(4) // additional chars
val parsed = Nip19Bech32.parseComponents(uriScheme, type, key, additionalChars)
val parsed = Nip19Bech32.parseComponents(type, key, additionalChars)?.entity
if (parsed != null) {
if (parsed.type == Nip19Bech32.Type.EVENT || parsed.type == Nip19Bech32.Type.ADDRESS || parsed.type == Nip19Bech32.Type.NOTE) {
citations.add(parsed.hex)
when (parsed) {
is Nip19Bech32.NEvent -> citations.add(parsed.hex)
is Nip19Bech32.NAddress -> citations.add(parsed.atag)
is Nip19Bech32.Note -> citations.add(parsed.hex)
is Nip19Bech32.NEmbed -> citations.add(parsed.event.id)
}
}
}
@@ -48,17 +48,18 @@ class ContactListEvent(
@delegate:Transient
val verifiedFollowKeySet: Set<HexKey> by lazy {
tags
.filter { it.size > 1 && it[0] == "p" }
.mapNotNull {
try {
tags.mapNotNullTo(HashSet()) {
try {
if (it.size > 1 && it[0] == "p") {
decodePublicKey(it[1]).toHexKey()
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
} else {
null
}
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
null
}
.toSet()
}
}
@delegate:Transient
@@ -77,27 +78,29 @@ class ContactListEvent(
@delegate:Transient
val verifiedFollowKeySetAndMe: Set<HexKey> by lazy { verifiedFollowKeySet + pubKey }
fun unverifiedFollowKeySet() = tags.filter { it[0] == "p" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowKeySet() = tags.filter { it.size > 1 && it[0] == "p" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowTagSet() = tags.filter { it[0] == "t" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowTagSet() = tags.filter { it.size > 1 && it[0] == "t" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowGeohashSet() = tags.filter { it[0] == "g" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowGeohashSet() = tags.filter { it.size > 1 && it[0] == "g" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowAddressSet() = tags.filter { it[0] == "a" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowAddressSet() = tags.filter { it.size > 1 && it[0] == "a" }.mapNotNull { it.getOrNull(1) }
fun follows() =
tags
.filter { it[0] == "p" }
.mapNotNull {
try {
tags.mapNotNull {
try {
if (it.size > 1 && it[0] == "p") {
Contact(decodePublicKey(it[1]).toHexKey(), it.getOrNull(2))
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
} else {
null
}
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
null
}
}
fun followsTags() = tags.filter { it[0] == "t" }.mapNotNull { it.getOrNull(2) }
fun followsTags() = tags.filter { it.size > 1 && it[0] == "t" }.mapNotNull { it.getOrNull(1) }
fun relays(): Map<String, ReadWrite>? =
try {
@@ -28,7 +28,7 @@ public class StreamSerializationContext {
}
public void writeBool(boolean value) {
if (value == true) {
if (value) {
this.writeByte((byte) 0xff);
} else {
this.writeByte((byte) 0x00);
@@ -58,7 +58,7 @@ public class StreamSerializationContext {
}
public void writeByte(byte value) {
this.buffer.add(new Byte(value));
this.buffer.add(Byte.valueOf(value));
}
public void writeByte(Byte value) {
@@ -66,8 +66,8 @@ public class StreamSerializationContext {
}
public void writeBytes(byte[] value) {
for (int i = 0; i < value.length; i++) {
this.writeByte(value[i]);
for (byte b : value) {
this.writeByte(b);
}
}
@@ -150,15 +150,12 @@ class NostrSignerExternal(
event: LnZapRequestEvent,
onReady: (LnZapPrivateEvent) -> Unit,
) {
return launcher.decryptZapEvent(event) {
val event =
try {
Event.fromJson(it)
} catch (e: Exception) {
Log.e("NostrExternalSigner", "Unable to parse returned decrypted Zap: $it")
null
}
(event as? LnZapPrivateEvent)?.let { onReady(event) }
return launcher.decryptZapEvent(event) { jsonEvent ->
try {
(Event.fromJson(jsonEvent) as? LnZapPrivateEvent)?.let { onReady(it) }
} catch (e: Exception) {
Log.e("NostrExternalSigner", "Unable to parse returned decrypted Zap: $jsonEvent")
}
}
}
}
@@ -21,6 +21,8 @@
package com.vitorpamplona.quartz.encoders
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
class NIP19ParserTest {
@@ -32,7 +34,7 @@ class NIP19ParserTest {
)
assertEquals(
"30023:460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c:",
result?.hex,
(result?.entity as? Nip19Bech32.NAddress)?.atag,
)
}
@@ -44,7 +46,7 @@ class NIP19ParserTest {
)
assertEquals(
"30023:d0debf9fb12def81f43d7c69429bb784812ac1e4d2d53a202db6aac7ea4b466c:guide-wireguard",
result?.hex,
(result?.entity as? Nip19Bech32.NAddress)?.atag,
)
}
@@ -54,12 +56,12 @@ class NIP19ParserTest {
Nip19Bech32.uriToRoute(
"naddr1qqyrswtyv5mnjv3sqy28wumn8ghj7un9d3shjtnyv9kh2uewd9hsygx3uczxts4hwue9ayfn7ggq62anzstde2qs749pm9tx2csuthhpjvpsgqqqw4rs8pmj38",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
assertTrue(result?.entity is Nip19Bech32.NAddress)
assertEquals(
"30023:d1e60465c2b777325e9133f2100d2bb31416dca810f54a1d95665621c5dee193:89de7920",
result?.hex,
(result?.entity as? Nip19Bech32.NAddress)?.atag,
)
assertEquals("wss://relay.damus.io", result?.relay)
assertEquals("wss://relay.damus.io", (result?.entity as? Nip19Bech32.NAddress)?.relay?.get(0))
}
@Test
@@ -132,13 +134,14 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"naddr1qq2hs7p30p6kcunxxamkgcnyd33xxve3veshyq3qyujphdcz69z6jafxpnldae3xtymdekfeatkt3r4qusr3w5krqspqxpqqqpaxjlg805f",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
)?.entity as? Nip19Bech32.NAddress
assertNotNull(result)
assertEquals(
"31337:27241bb702d145a975260cfedee6265936dcd939eaecb88ea0e4071752c30402:xx1xulrf7wdbdlbc31far",
result?.hex,
result?.atag,
)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals("27241bb702d145a975260cfedee6265936dcd939eaecb88ea0e4071752c30402", result?.author)
assertEquals(31337, result?.kind)
}
@@ -148,13 +151,14 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"naddr1qpqrvvfnvccrzdryxgunzvtxvgukge34xfjnqdpcv9sk2desxgmrscesvserzd3h8ycrywphvg6nsvf58ycnqef3v5mnsvt98pjnqdfs8ypzq3huhccxt6h34eupz3jeynjgjgek8lel2f4adaea0svyk94a3njdqvzqqqr4gudhrkyk",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
)?.entity as? Nip19Bech32.NAddress
assertNotNull(result)
assertEquals(
"30023:46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d:613f014d2911fb9df52e048aae70268c0d216790287b5814910e1e781e8e0509",
result?.hex,
result?.atag,
)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals("46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d", result?.author)
assertEquals(30023, result?.kind)
}
@@ -164,13 +168,14 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"naddr1qq9rzd3h8y6nqwf5xyuqygzxljlrqe027xh8sy2xtyjwfzfrxcll8afxh4hh847psjckhkxwf5psgqqqw4rsty50fx",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
)?.entity as? Nip19Bech32.NAddress
assertNotNull(result)
assertEquals(
"30023:46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d:1679509418",
result?.hex,
result?.atag,
)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals("46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d", result?.author)
assertEquals(30023, result?.kind)
}
@@ -178,10 +183,11 @@ class NIP19ParserTest {
@Test
fun nEventParserTest() {
val result =
Nip19Bech32.uriToRoute("nostr:nevent1qqs0tsw8hjacs4fppgdg7f5yhgwwfkyua4xcs3re9wwkpkk2qeu6mhql22rcy")
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
Nip19Bech32.uriToRoute("nostr:nevent1qqs0tsw8hjacs4fppgdg7f5yhgwwfkyua4xcs3re9wwkpkk2qeu6mhql22rcy")?.entity as? Nip19Bech32.NEvent
assertNotNull(result)
assertEquals("f5c1c7bcbb8855210a1a8f2684ba1ce4d89ced4d8844792b9d60daca0679addc", result?.hex)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals(null, result?.author)
assertEquals(null, result?.kind)
}
@@ -191,10 +197,11 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqstvrl6wftd8ht4g0vrp6m30tjs6pdxcvk977g769dcvlptkzu4ftqppamhxue69uhkummnw3ezumt0d5pzp78lz8r60568sd2a8dx3wnj6gume02gxaf92vx4fk67qv5kpagt6qvzqqqqqqygqr86c",
)
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
)?.entity as? Nip19Bech32.NEvent
assertNotNull(result)
assertEquals("b60ffa7256d3dd7543d830eb717ae50d05a6c32c5f791ed15b867c2bb0b954ac", result?.hex)
assertEquals("wss://nostr.mom", result?.relay)
assertEquals("wss://nostr.mom", result?.relay?.get(0))
assertEquals("f8ff11c7a7d3478355d3b4d174e5a473797a906ea4aa61aa9b6bc0652c1ea17a", result?.author)
assertEquals(1, result?.kind)
}
@@ -204,11 +211,11 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqsplpuwsgrrmq85rfup6w3w777rxmcmadu590emfx6z4msj2844euqpz3mhxue69uhhyetvv9ujuerpd46hxtnfdupzq3svyhng9ld8sv44950j957j9vchdktj7cxumsep9mvvjthc2pjuqvzqqqqqqye3a70w",
)
)?.entity as? Nip19Bech32.NEvent
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
assertNotNull(result)
assertEquals("1f878e82063d80f41a781d3a2ef7bc336f1beb7942bf3b49b42aee1251eb5cf0", result?.hex)
assertEquals("wss://relay.damus.io", result?.relay)
assertEquals("wss://relay.damus.io", result?.relay?.get(0))
assertEquals("460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c", result?.author)
assertEquals(1, result?.kind)
}
@@ -218,13 +225,13 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqsg6gechd3dhzx38n4z8a2lylzgsmmgeamhmtzz72m9ummsnf0xjfspsdmhxue69uhkummn9ekx7mpvwaehxw309ahx7um5wghx77r5wghxgetk93mhxue69uhhyetvv9ujumn0wd68ytnzvuk8wumn8ghj7mn0wd68ytn9d9h82mny0fmkzmn6d9njuumsv93k2trhwden5te0wfjkccte9ehx7um5wghxyctwvsk8wumn8ghj7un9d3shjtnyv9kh2uewd9hs3kqsdn",
)
)?.entity as? Nip19Bech32.NEvent
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
assertNotNull(result)
assertEquals("8d2338bb62db88d13cea23f55f27c4886f68cf777dac42f2b65e6f709a5e6926", result?.hex)
assertEquals(
"wss://nos.lol,wss://nostr.oxtr.dev,wss://relay.nostr.bg,wss://nostr.einundzwanzig.space,wss://relay.nostr.band,wss://relay.damus.io",
result?.relay,
result?.relay?.joinToString(","),
)
}
@@ -233,11 +240,11 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqsyxq8v0730nz38dupnjzp5jegkyz4gu2ptwcps4v32hjnrap0q0espz3mhxue69uhhyetvv9ujuerpd46hxtnfdupzq3svyhng9ld8sv44950j957j9vchdktj7cxumsep9mvvjthc2pjuqvzqqqqqqyn3t9gj",
)
)?.entity as? Nip19Bech32.NEvent
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
assertNotNull(result)
assertEquals("4300ec7fa2f98a276f033908349651620aa8e282b76030ab22abca63e85e07e6", result?.hex)
assertEquals("wss://relay.damus.io", result?.relay)
assertEquals("wss://relay.damus.io", result?.relay?.get(0))
assertEquals("460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c", result?.author)
assertEquals(1, result?.kind)
}
@@ -21,7 +21,7 @@
package com.vitorpamplona.quartz.encoders
import org.junit.Assert
import org.junit.Ignore
import org.junit.Assert.assertNotNull
import org.junit.Test
class Nip19Bech32Test {
@@ -44,58 +44,74 @@ class Nip19Bech32Test {
val actual =
Nip19Bech32.uriToRoute("nostr:npub1hv7k2s755n697sptva8vkh9jz40lzfzklnwj6ekewfmxp5crwdjs27007y")
Assert.assertEquals(Nip19Bech32.Type.USER, actual?.type)
Assert.assertTrue(actual?.entity is Nip19Bech32.NPub)
Assert.assertEquals(
"bb3d6543d4a4f45f402b674ecb5cb2155ff12456fcdd2d66d9727660d3037365",
actual?.hex,
(actual?.entity as? Nip19Bech32.NPub)?.hex,
)
}
@Test()
fun uri_to_route_note() {
val actual =
Nip19Bech32.uriToRoute("nostr:note1stqea6wmwezg9x6yyr6qkukw95ewtdukyaztycws65l8wppjmtpscawevv")
val result =
Nip19Bech32.uriToRoute("nostr:note1stqea6wmwezg9x6yyr6qkukw95ewtdukyaztycws65l8wppjmtpscawevv")?.entity as? Nip19Bech32.Note
Assert.assertEquals(Nip19Bech32.Type.NOTE, actual?.type)
assertNotNull(result)
Assert.assertEquals(
"82c19ee9db7644829b4420f40b72ce2d32e5b7962744b261d0d53e770432dac3",
actual?.hex,
result?.hex,
)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_nprofile() {
val actual = Nip19Bech32.uriToRoute("nostr:nprofile")
Assert.assertEquals(Nip19Bech32.Type.USER, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_nevent() {
fun uri_to_route_incomplete_nevent() {
val actual = Nip19Bech32.uriToRoute("nostr:nevent")
Assert.assertEquals(Nip19Bech32.Type.USER, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_nrelay() {
fun uri_to_route_incomplete_nrelay() {
val actual = Nip19Bech32.uriToRoute("nostr:nrelay")
Assert.assertEquals(Nip19Bech32.Type.RELAY, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_naddr() {
fun uri_to_route_incomplete_naddr() {
val actual = Nip19Bech32.uriToRoute("nostr:naddr")
Assert.assertEquals(Nip19Bech32.Type.ADDRESS, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Test()
fun uri_to_route_complete_nprofile() {
val actual = Nip19Bech32.uriToRoute("nostr:nprofile1qy2hwumn8ghj7un9d3shjtnyv9kh2uewd9hj7qgwwaehxw309ahx7uewd3hkctcpr9mhxue69uhhyetvv9ujuumwdae8gtnnda3kjctv9uqzq9thu3vem5gvsc6f3l3uyz7c92h6lq56t9wws0zulzkrgc6nrvym5jfztf")
Assert.assertTrue(actual?.entity is Nip19Bech32.NProfile)
Assert.assertEquals("1577e4599dd10c863498fe3c20bd82aafaf829a595ce83c5cf8ac3463531b09b", (actual?.entity as? Nip19Bech32.NProfile)?.hex)
}
@Test()
fun uri_to_route_complete_nevent() {
val actual = Nip19Bech32.uriToRoute("nostr:nevent1qy2hwumn8ghj7un9d3shjtnyv9kh2uewd9hj7qgwwaehxw309ahx7uewd3hkctcpr9mhxue69uhhyetvv9ujuumwdae8gtnnda3kjctv9uq36amnwvaz7tmjv4kxz7fwvd5xjcmpvahhqmr9vfejucm0d5hsz9mhwden5te0wfjkccte9ec8y6tdv9kzumn9wshsz8thwden5te0dehhxarj9ekh2arfdeuhwctvd3jhgtnrdakj7qg3waehxw309ucngvpwvcmh5tnfduhszythwden5te0dehhxarj9emkjmn99uq3jamnwvaz7tmhv4kxxmmdv5hxummnw3ezuamfdejj7qpqvsup5xk3e2quedxjvn2gjppc0lqny5dmnr2ypc9tftwmdxta0yjqrd6n50")
Assert.assertTrue(actual?.entity is Nip19Bech32.NEvent)
Assert.assertEquals("64381a1ad1ca81ccb4d264d48904387fc13251bb98d440e0ab4addb6997d7924", (actual?.entity as? Nip19Bech32.NEvent)?.hex)
}
@Test()
fun uri_to_route_complete_naddr() {
val actual = Nip19Bech32.uriToRoute("nostr:naddr1qqyxzmt9w358jum5qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqzypd7v3r24z33cydnk3fmlrd0exe5dlej3506zxs05q4puerp765mzqcyqqq8scsq6mk7u")
Assert.assertTrue(actual?.entity is Nip19Bech32.NAddress)
Assert.assertEquals("30818:5be6446aa8a31c11b3b453bf8dafc9b346ff328d1fa11a0fa02a1e6461f6a9b1:amethyst", (actual?.entity as? Nip19Bech32.NAddress)?.atag)
}
}