add simple create identity flow

This commit is contained in:
2026-04-27 12:14:54 +07:00
parent 3240382498
commit feffda519f
14 changed files with 301 additions and 116 deletions

View File

@@ -3,13 +3,22 @@ package su.reya.coop
import rust.nostr.sdk.Client
import rust.nostr.sdk.ClientBuilder
import rust.nostr.sdk.ClientOptions
import rust.nostr.sdk.EventBuilder
import rust.nostr.sdk.Keys
import rust.nostr.sdk.Metadata
import rust.nostr.sdk.MetadataRecord
import rust.nostr.sdk.NostrDatabase
import rust.nostr.sdk.NostrGossip
import rust.nostr.sdk.NostrSigner
import rust.nostr.sdk.RelayUrl
class Nostr {
var client: Client? = null
private set
var signer: NostrSigner? = null
private set
var deviceSigner: NostrSigner? = null
private set
fun init(dbPath: String) {
val lmdb = NostrDatabase.lmdb(dbPath)
@@ -29,4 +38,25 @@ class Nostr {
suspend fun disconnect() {
this.client?.shutdown()
}
suspend fun createIdentity(keys: Keys, name: String, bio: String, picture: String?) {
signer = NostrSigner.keys(keys)
// Construct metadata
val metadata = Metadata.fromRecord(
MetadataRecord(
name = name,
displayName = name,
about = bio,
picture = picture
)
)
// Construct event and sign it
val builder = EventBuilder.metadata(metadata).build(keys.publicKey())
val event = this.signer?.signEvent(builder) ?: return
// Send event to relays
this.client?.sendEvent(event)
}
}

View File

@@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import rust.nostr.sdk.Keys
import su.reya.coop.storage.SecretStorage
class NostrViewModel(
@@ -16,6 +17,9 @@ class NostrViewModel(
private val _isConnected = MutableStateFlow(false)
val isConnected = _isConnected.asStateFlow()
private val _isCreating = MutableStateFlow(false)
val isCreating = _isCreating.asStateFlow()
fun initAndConnect(dbPath: String) {
// Initialize nostr client
nostr.init(dbPath)
@@ -32,6 +36,24 @@ class NostrViewModel(
}
}
fun createIdentity(name: String, bio: String, picture: String?) {
viewModelScope.launch {
try {
val keys = Keys.generate()
val secret = keys.secretKey().toBech32()
// Set loading state
_isCreating.value = true
// Create identity
nostr.createIdentity(keys, name, bio, picture)
// Save secret to the secret storage
secretStore.set("user_signer", secret)
} catch (e: Exception) {
_isCreating.value = false
println(e)
}
}
}
override fun onCleared() {
super.onCleared()
// Ensure all relays are disconnect