clean up view models
This commit is contained in:
@@ -1,13 +0,0 @@
|
||||
package su.reya.coop.repository
|
||||
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
|
||||
object ErrorRepository {
|
||||
private val _errors = Channel<String>(Channel.BUFFERED)
|
||||
val errors = _errors.receiveAsFlow()
|
||||
|
||||
fun showError(message: String) {
|
||||
_errors.trySend(message)
|
||||
}
|
||||
}
|
||||
@@ -23,15 +23,16 @@ import kotlin.time.Duration.Companion.seconds
|
||||
data class AuthState(
|
||||
val signerRequired: Boolean? = null,
|
||||
val isNotificationBannerDismissed: Boolean = false,
|
||||
val isImporting: Boolean = false,
|
||||
val importError: String? = null,
|
||||
)
|
||||
|
||||
class AuthViewModel(
|
||||
private val nostr: Nostr,
|
||||
private val storage: AppStorage,
|
||||
private val mediaRepository: MediaRepository,
|
||||
private val externalSignerHandler: ExternalSignerHandler? = null,
|
||||
) : BaseViewModel() {
|
||||
private val mediaRepository = MediaRepository()
|
||||
|
||||
companion object {
|
||||
private const val KEY_USER_SIGNER = "user_signer"
|
||||
private const val KEY_APP_KEYS = "app_keys"
|
||||
@@ -161,65 +162,98 @@ class AuthViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun importIdentity(secret: String, password: String? = null) {
|
||||
val (signer, decryptedSecret) = createSigner(secret, password)
|
||||
// Update signer
|
||||
nostr.setSigner(signer)
|
||||
// Persist the secret in the secret storage
|
||||
storage.setSecret(KEY_USER_SIGNER, decryptedSecret ?: secret)
|
||||
// Update local states
|
||||
_state.update { it.copy(signerRequired = false) }
|
||||
fun importIdentity(secret: String, password: String? = null) {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(isImporting = true, importError = null) }
|
||||
try {
|
||||
val (signer, decryptedSecret) = createSigner(secret, password)
|
||||
// Update signer
|
||||
nostr.setSigner(signer)
|
||||
// Persist the secret in the secret storage
|
||||
storage.setSecret(KEY_USER_SIGNER, decryptedSecret ?: secret)
|
||||
// Update local states
|
||||
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
||||
} catch (e: Exception) {
|
||||
showError("Import failed: ${e.message}")
|
||||
_state.update { it.copy(isImporting = false, importError = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun connectExternalSigner() {
|
||||
val handler = externalSignerHandler ?: throw IllegalStateException("Signer not available")
|
||||
fun connectExternalSigner() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(isImporting = true, importError = null) }
|
||||
try {
|
||||
val handler = externalSignerHandler
|
||||
?: throw IllegalStateException("Signer not available")
|
||||
|
||||
val permissions = SignerPermissions.toJson(
|
||||
listOf(
|
||||
SignerPermissions.signEvent(0),
|
||||
SignerPermissions.signEvent(3),
|
||||
SignerPermissions.signEvent(10000),
|
||||
SignerPermissions.signEvent(10050),
|
||||
SignerPermissions.signEvent(10063),
|
||||
SignerPermissions.signEvent(22242),
|
||||
SignerPermissions.signEvent(30030),
|
||||
SignerPermissions.signEvent(30315),
|
||||
SignerPermissions.nip44Encrypt(),
|
||||
SignerPermissions.nip44Decrypt(),
|
||||
)
|
||||
)
|
||||
val permissions = SignerPermissions.toJson(
|
||||
listOf(
|
||||
SignerPermissions.signEvent(0),
|
||||
SignerPermissions.signEvent(3),
|
||||
SignerPermissions.signEvent(10000),
|
||||
SignerPermissions.signEvent(10050),
|
||||
SignerPermissions.signEvent(10063),
|
||||
SignerPermissions.signEvent(22242),
|
||||
SignerPermissions.signEvent(30030),
|
||||
SignerPermissions.signEvent(30315),
|
||||
SignerPermissions.nip44Encrypt(),
|
||||
SignerPermissions.nip44Decrypt(),
|
||||
)
|
||||
)
|
||||
|
||||
val result = handler.getPublicKey(permissions) ?: throw Exception("Rejected")
|
||||
val signer = ExternalSignerProxy(handler, result.pubkey)
|
||||
val result = handler.getPublicKey(permissions) ?: throw Exception("Rejected")
|
||||
val signer = ExternalSignerProxy(handler, result.pubkey)
|
||||
|
||||
// Update signer
|
||||
nostr.setSigner(signer)
|
||||
// Store the signer in the secret storage
|
||||
storage.setSecret(KEY_USER_SIGNER, "nip55://${result.packageName}/${result.pubkey.toHex()}")
|
||||
// Update local states
|
||||
_state.update { it.copy(signerRequired = false) }
|
||||
// Update signer
|
||||
nostr.setSigner(signer)
|
||||
// Store the signer in the secret storage
|
||||
storage.setSecret(
|
||||
KEY_USER_SIGNER,
|
||||
"nip55://${result.packageName}/${result.pubkey.toHex()}"
|
||||
)
|
||||
// Update local states
|
||||
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
||||
} catch (e: Exception) {
|
||||
showError("External signer connection failed: ${e.message}")
|
||||
_state.update { it.copy(isImporting = false, importError = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun isExternalSignerAvailable(): Boolean {
|
||||
return externalSignerHandler?.isAvailable() == true
|
||||
}
|
||||
|
||||
suspend fun createIdentity(
|
||||
fun createIdentity(
|
||||
name: String,
|
||||
bio: String?,
|
||||
picture: ByteArray?,
|
||||
contentType: String? = null
|
||||
) {
|
||||
val keys = Keys.generate()
|
||||
val secret = keys.secretKey().toBech32()
|
||||
val avatarUrl = picture?.let {
|
||||
mediaRepository.blossomUpload(keys, it, contentType ?: "image/jpeg")
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(isImporting = true, importError = null) }
|
||||
try {
|
||||
val keys = Keys.generate()
|
||||
val secret = keys.secretKey().toBech32()
|
||||
val avatarUrl = picture?.let {
|
||||
mediaRepository.blossomUpload(keys, it, contentType ?: "image/jpeg")
|
||||
}
|
||||
// Create identity
|
||||
nostr.profiles.createIdentity(
|
||||
keys = keys,
|
||||
name = name,
|
||||
bio = bio,
|
||||
picture = avatarUrl
|
||||
)
|
||||
// Persist the secret in the secret storage
|
||||
storage.setSecret(KEY_USER_SIGNER, secret)
|
||||
// Update local states
|
||||
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
||||
} catch (e: Exception) {
|
||||
showError("Identity creation failed: ${e.message}")
|
||||
_state.update { it.copy(isImporting = false, importError = e.message) }
|
||||
}
|
||||
}
|
||||
// Create identity
|
||||
nostr.profiles.createIdentity(keys = keys, name = name, bio = bio, picture = avatarUrl)
|
||||
// Persist the secret in the secret storage
|
||||
storage.setSecret(KEY_USER_SIGNER, secret)
|
||||
// Update local states
|
||||
_state.update { it.copy(signerRequired = false) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package su.reya.coop.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import su.reya.coop.repository.ErrorRepository
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
|
||||
abstract class BaseViewModel : ViewModel() {
|
||||
private val _errorEvents = MutableSharedFlow<String>(extraBufferCapacity = 10)
|
||||
val errorEvents = _errorEvents.asSharedFlow()
|
||||
|
||||
protected fun showError(message: String) {
|
||||
ErrorRepository.showError(message)
|
||||
_errorEvents.tryEmit(message)
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,10 @@ data class ChatState(
|
||||
val isPartialProcessedGiftWrap: Boolean = false,
|
||||
)
|
||||
|
||||
class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
private val mediaRepository = MediaRepository()
|
||||
|
||||
class ChatViewModel(
|
||||
private val nostr: Nostr,
|
||||
private val mediaRepository: MediaRepository,
|
||||
) : BaseViewModel() {
|
||||
private val _state = MutableStateFlow(ChatState())
|
||||
val state = combine(
|
||||
_state,
|
||||
@@ -175,6 +176,7 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
fun sendMessage(roomId: Long, message: String, replies: List<EventId> = emptyList()) {
|
||||
if (message.isEmpty()) {
|
||||
showError("Message cannot be empty")
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
@@ -195,7 +197,7 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun sendFileMessage(
|
||||
fun sendFileMessage(
|
||||
roomId: Long,
|
||||
file: ByteArray?,
|
||||
contentType: String? = "image/jpeg",
|
||||
@@ -203,11 +205,13 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
) {
|
||||
if (file == null) return
|
||||
|
||||
try {
|
||||
val uri = mediaRepository.blossomUpload(nostr.signer.get(), file, contentType)
|
||||
if (uri != null) sendMessage(roomId, uri, replies)
|
||||
} catch (e: Exception) {
|
||||
throw IllegalArgumentException("Error: ${e.message}")
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val uri = mediaRepository.blossomUpload(nostr.signer.get(), file, contentType)
|
||||
if (uri != null) sendMessage(roomId, uri, replies)
|
||||
} catch (e: Exception) {
|
||||
showError("File upload failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package su.reya.coop.viewmodel
|
||||
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -10,11 +9,9 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
@@ -39,30 +36,12 @@ data class NostrAppState(
|
||||
val isRelayListEmpty: Boolean = false,
|
||||
)
|
||||
|
||||
class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
private val mediaRepository = MediaRepository()
|
||||
|
||||
private val alwaysRunTasks = flow {
|
||||
coroutineScope {
|
||||
val observerJob = launch { runObserver() }
|
||||
val batchingJob = launch { runMetadataBatching() }
|
||||
try {
|
||||
emit(Unit)
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
observerJob.cancel()
|
||||
batchingJob.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class NostrViewModel(
|
||||
private val nostr: Nostr,
|
||||
private val mediaRepository: MediaRepository,
|
||||
) : BaseViewModel() {
|
||||
private val _appState = MutableStateFlow(NostrAppState())
|
||||
val appState: StateFlow<NostrAppState> =
|
||||
combine(_appState, alwaysRunTasks) { state, _ -> state }.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = NostrAppState()
|
||||
)
|
||||
val appState: StateFlow<NostrAppState> = _appState.asStateFlow()
|
||||
|
||||
private val _contactList = MutableStateFlow<Set<PublicKey>>(emptySet())
|
||||
val contactList = _contactList.asStateFlow()
|
||||
@@ -83,6 +62,10 @@ class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
|
||||
|
||||
init {
|
||||
// Launch continuous background observers
|
||||
viewModelScope.launch { runObserver() }
|
||||
viewModelScope.launch { runMetadataBatching() }
|
||||
|
||||
// Automatically reconnect bootstrap relays
|
||||
reconnect()
|
||||
|
||||
@@ -116,7 +99,7 @@ class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun runMetadataBatching() = coroutineScope {
|
||||
private suspend fun runMetadataBatching() {
|
||||
// Wait until the client is ready
|
||||
nostr.waitUntilInitialized()
|
||||
|
||||
@@ -192,9 +175,7 @@ class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
|
||||
private fun requestMetadata(pubkey: PublicKey) {
|
||||
if (seenPublicKeys.add(pubkey)) {
|
||||
viewModelScope.launch {
|
||||
metadataRequestChannel.send(pubkey)
|
||||
}
|
||||
metadataRequestChannel.trySend(pubkey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,32 +205,36 @@ class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
|
||||
_appState.update { it.copy(isRelayListEmpty = false) }
|
||||
}
|
||||
|
||||
suspend fun updateProfile(
|
||||
fun updateProfile(
|
||||
name: String? = null,
|
||||
bio: String? = null,
|
||||
picture: ByteArray? = null,
|
||||
contentType: String? = null
|
||||
) {
|
||||
_appState.update { it.copy(isBusy = true) }
|
||||
try {
|
||||
val avatarUrl =
|
||||
picture?.let {
|
||||
mediaRepository.blossomUpload(
|
||||
nostr.signer.get(),
|
||||
it,
|
||||
contentType ?: "image/jpeg"
|
||||
)
|
||||
}
|
||||
val newMetadata = nostr.profiles.updateProfile(name, bio, avatarUrl)
|
||||
val currentUser = nostr.signer.getPublicKeyAsync() ?: throw Exception("User not found")
|
||||
viewModelScope.launch {
|
||||
_appState.update { it.copy(isBusy = true) }
|
||||
try {
|
||||
val avatarUrl =
|
||||
picture?.let {
|
||||
mediaRepository.blossomUpload(
|
||||
nostr.signer.get(),
|
||||
it,
|
||||
contentType ?: "image/jpeg"
|
||||
)
|
||||
}
|
||||
val newMetadata = nostr.profiles.updateProfile(name, bio, avatarUrl)
|
||||
val currentUser =
|
||||
nostr.signer.getPublicKeyAsync() ?: throw Exception("User not found")
|
||||
|
||||
// Update the metadata state after successfully published
|
||||
updateMetadata(currentUser, Profile(currentUser, newMetadata))
|
||||
// Update the metadata state after successfully published
|
||||
updateMetadata(currentUser, Profile(currentUser, newMetadata))
|
||||
|
||||
// Update local state
|
||||
_appState.update { it.copy(isBusy = false) }
|
||||
} catch (e: Exception) {
|
||||
showError("Error: ${e.message}")
|
||||
// Update local state
|
||||
_appState.update { it.copy(isBusy = false) }
|
||||
} catch (e: Exception) {
|
||||
showError("Error: ${e.message}")
|
||||
_appState.update { it.copy(isBusy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user