Compare commits
2 Commits
v0.2.6
...
43618533a5
| Author | SHA1 | Date | |
|---|---|---|---|
| 43618533a5 | |||
| 9c9d9ae882 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -17,4 +17,3 @@ captures
|
|||||||
!*.xcworkspace/contents.xcworkspacedata
|
!*.xcworkspace/contents.xcworkspacedata
|
||||||
**/xcshareddata/WorkspaceSettings.xcsettings
|
**/xcshareddata/WorkspaceSettings.xcsettings
|
||||||
node_modules/
|
node_modules/
|
||||||
.artifacts/
|
|
||||||
@@ -69,7 +69,7 @@ android {
|
|||||||
minSdk = libs.versions.android.minSdk.get().toInt()
|
minSdk = libs.versions.android.minSdk.get().toInt()
|
||||||
targetSdk = libs.versions.android.targetSdk.get().toInt()
|
targetSdk = libs.versions.android.targetSdk.get().toInt()
|
||||||
versionCode = 1
|
versionCode = 1
|
||||||
versionName = "0.2.6"
|
versionName = "0.2.4"
|
||||||
}
|
}
|
||||||
packaging {
|
packaging {
|
||||||
resources {
|
resources {
|
||||||
|
|||||||
@@ -7,8 +7,6 @@
|
|||||||
android:required="false" />
|
android:required="false" />
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.CAMERA" />
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
package su.reya.coop
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.net.ConnectivityManager
|
|
||||||
import android.net.Network
|
|
||||||
import android.net.NetworkCapabilities
|
|
||||||
import android.net.NetworkRequest
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
|
||||||
|
|
||||||
class AndroidConnectivityMonitor(context: Context) : ConnectivityMonitor {
|
|
||||||
private val manager =
|
|
||||||
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
|
||||||
|
|
||||||
private val _isMobileData = MutableStateFlow(checkIsMobileData())
|
|
||||||
override val isMobileData: StateFlow<Boolean> = _isMobileData.asStateFlow()
|
|
||||||
|
|
||||||
init {
|
|
||||||
val networkRequest = NetworkRequest.Builder()
|
|
||||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
||||||
.build()
|
|
||||||
|
|
||||||
manager.registerNetworkCallback(
|
|
||||||
networkRequest,
|
|
||||||
object : ConnectivityManager.NetworkCallback() {
|
|
||||||
override fun onAvailable(network: Network) {
|
|
||||||
_isMobileData.value = checkIsMobileData()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onLost(network: Network) {
|
|
||||||
_isMobileData.value = checkIsMobileData()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCapabilitiesChanged(
|
|
||||||
network: Network,
|
|
||||||
networkCapabilities: NetworkCapabilities
|
|
||||||
) {
|
|
||||||
_isMobileData.value = checkIsMobileData()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun checkIsMobileData(): Boolean {
|
|
||||||
val activeNetwork = manager.activeNetwork ?: return false
|
|
||||||
val capabilities = manager.getNetworkCapabilities(activeNetwork) ?: return false
|
|
||||||
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,12 +4,16 @@ import android.app.Activity
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.foundation.isSystemInDarkTheme
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||||
import androidx.compose.material3.MaterialExpressiveTheme
|
import androidx.compose.material3.MaterialExpressiveTheme
|
||||||
import androidx.compose.material3.MotionScheme
|
import androidx.compose.material3.MotionScheme
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.Typography
|
import androidx.compose.material3.Typography
|
||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.material3.dynamicDarkColorScheme
|
import androidx.compose.material3.dynamicDarkColorScheme
|
||||||
@@ -23,6 +27,8 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.staticCompositionLocalOf
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.core.util.Consumer
|
import androidx.core.util.Consumer
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
@@ -39,7 +45,6 @@ import androidx.navigation3.ui.NavDisplay
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import su.reya.coop.repository.AccountRepository
|
import su.reya.coop.repository.AccountRepository
|
||||||
import su.reya.coop.repository.ChatRepository
|
import su.reya.coop.repository.ChatRepository
|
||||||
import su.reya.coop.repository.SettingsRepository
|
|
||||||
import su.reya.coop.screens.ContactListScreen
|
import su.reya.coop.screens.ContactListScreen
|
||||||
import su.reya.coop.screens.HomeScreen
|
import su.reya.coop.screens.HomeScreen
|
||||||
import su.reya.coop.screens.ImportScreen
|
import su.reya.coop.screens.ImportScreen
|
||||||
@@ -51,27 +56,17 @@ import su.reya.coop.screens.ProfileScreen
|
|||||||
import su.reya.coop.screens.RelayScreen
|
import su.reya.coop.screens.RelayScreen
|
||||||
import su.reya.coop.screens.RequestListScreen
|
import su.reya.coop.screens.RequestListScreen
|
||||||
import su.reya.coop.screens.ScanScreen
|
import su.reya.coop.screens.ScanScreen
|
||||||
import su.reya.coop.screens.SettingsScreen
|
|
||||||
import su.reya.coop.screens.UpdateProfileScreen
|
import su.reya.coop.screens.UpdateProfileScreen
|
||||||
import su.reya.coop.screens.chat.ChatScreen
|
import su.reya.coop.screens.chat.ChatScreen
|
||||||
import su.reya.coop.viewmodel.AccountViewModel
|
import su.reya.coop.viewmodel.AccountViewModel
|
||||||
import su.reya.coop.viewmodel.ChatScreenViewModel
|
import su.reya.coop.viewmodel.ChatScreenViewModel
|
||||||
import su.reya.coop.viewmodel.ChatViewModel
|
import su.reya.coop.viewmodel.ChatViewModel
|
||||||
import su.reya.coop.viewmodel.ProfileCache
|
import su.reya.coop.viewmodel.ProfileCache
|
||||||
import su.reya.coop.viewmodel.SettingsViewModel
|
|
||||||
|
|
||||||
val LocalProfileCache = staticCompositionLocalOf<ProfileCache> {
|
val LocalProfileCache = staticCompositionLocalOf<ProfileCache> {
|
||||||
error("No ProfileCache provided")
|
error("No ProfileCache provided")
|
||||||
}
|
}
|
||||||
|
|
||||||
val LocalSettings = staticCompositionLocalOf<Settings> {
|
|
||||||
error("No Settings provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
val LocalConnectivity = staticCompositionLocalOf<Boolean> {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
val LocalSnackbarHostState = staticCompositionLocalOf<SnackbarHostState> {
|
val LocalSnackbarHostState = staticCompositionLocalOf<SnackbarHostState> {
|
||||||
error("No SnackbarHostState provided")
|
error("No SnackbarHostState provided")
|
||||||
}
|
}
|
||||||
@@ -90,8 +85,6 @@ fun App(
|
|||||||
profileCache: ProfileCache,
|
profileCache: ProfileCache,
|
||||||
accountRepository: AccountRepository,
|
accountRepository: AccountRepository,
|
||||||
chatRepository: ChatRepository,
|
chatRepository: ChatRepository,
|
||||||
settingsRepository: SettingsRepository,
|
|
||||||
connectivityMonitor: ConnectivityMonitor,
|
|
||||||
) {
|
) {
|
||||||
val viewModelFactory = remember {
|
val viewModelFactory = remember {
|
||||||
object : ViewModelProvider.Factory {
|
object : ViewModelProvider.Factory {
|
||||||
@@ -105,10 +98,6 @@ fun App(
|
|||||||
accountRepository
|
accountRepository
|
||||||
)
|
)
|
||||||
|
|
||||||
modelClass.isAssignableFrom(SettingsViewModel::class.java) -> SettingsViewModel(
|
|
||||||
settingsRepository
|
|
||||||
)
|
|
||||||
|
|
||||||
else -> throw IllegalArgumentException("Unknown ViewModel class")
|
else -> throw IllegalArgumentException("Unknown ViewModel class")
|
||||||
}
|
}
|
||||||
@Suppress("UNCHECKED_CAST")
|
@Suppress("UNCHECKED_CAST")
|
||||||
@@ -119,7 +108,6 @@ fun App(
|
|||||||
|
|
||||||
val accountViewModel: AccountViewModel = viewModel(factory = viewModelFactory)
|
val accountViewModel: AccountViewModel = viewModel(factory = viewModelFactory)
|
||||||
val chatViewModel: ChatViewModel = viewModel(factory = viewModelFactory)
|
val chatViewModel: ChatViewModel = viewModel(factory = viewModelFactory)
|
||||||
val settingsViewModel: SettingsViewModel = viewModel(factory = viewModelFactory)
|
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val activity = context as? ComponentActivity
|
val activity = context as? ComponentActivity
|
||||||
@@ -131,27 +119,19 @@ fun App(
|
|||||||
val accountState by accountViewModel.state.collectAsStateWithLifecycle()
|
val accountState by accountViewModel.state.collectAsStateWithLifecycle()
|
||||||
val signerRequired = accountState.signerRequired
|
val signerRequired = accountState.signerRequired
|
||||||
|
|
||||||
// Get the settings
|
|
||||||
val settings by settingsViewModel.settings.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
// Get connectivity status
|
|
||||||
val isMobileData by connectivityMonitor.isMobileData.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
// Snackbar
|
// Snackbar
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
|
||||||
// Check if dark theme enabled
|
// Check if dark theme enabled
|
||||||
val darkMode = when (settings.theme) {
|
val darkMode = isSystemInDarkTheme()
|
||||||
Theme.Light -> false
|
|
||||||
Theme.Dark -> true
|
|
||||||
Theme.System -> isSystemInDarkTheme()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enabled the dynamic color scheme
|
// Enabled the dynamic color scheme
|
||||||
val colorScheme = when {
|
val colorScheme = when {
|
||||||
// Enable the dynamic color scheme for Android 12+
|
// Enable the dynamic color scheme for Android 12+
|
||||||
settings.dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||||
if (darkMode) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
if (isSystemInDarkTheme()) dynamicDarkColorScheme(context) else dynamicLightColorScheme(
|
||||||
|
context
|
||||||
|
)
|
||||||
}
|
}
|
||||||
// When dark mode is enabled, use the dark color scheme
|
// When dark mode is enabled, use the dark color scheme
|
||||||
darkMode -> darkColorScheme()
|
darkMode -> darkColorScheme()
|
||||||
@@ -159,6 +139,10 @@ fun App(
|
|||||||
else -> expressiveLightColorScheme()
|
else -> expressiveLightColorScheme()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BackHandler(enabled = backStack.size > 1) {
|
||||||
|
navigator.goBack()
|
||||||
|
}
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
launch {
|
launch {
|
||||||
accountViewModel.errorEvents.collect { message ->
|
accountViewModel.errorEvents.collect { message ->
|
||||||
@@ -216,12 +200,11 @@ fun App(
|
|||||||
) {
|
) {
|
||||||
CompositionLocalProvider(
|
CompositionLocalProvider(
|
||||||
LocalProfileCache provides profileCache,
|
LocalProfileCache provides profileCache,
|
||||||
LocalSettings provides settings,
|
|
||||||
LocalConnectivity provides isMobileData,
|
|
||||||
LocalSnackbarHostState provides snackbarHostState,
|
LocalSnackbarHostState provides snackbarHostState,
|
||||||
LocalNavigator provides navigator,
|
LocalNavigator provides navigator,
|
||||||
LocalScanResult provides qrScanResult,
|
LocalScanResult provides qrScanResult,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
NavDisplay(
|
NavDisplay(
|
||||||
backStack = backStack,
|
backStack = backStack,
|
||||||
onBack = {
|
onBack = {
|
||||||
@@ -252,12 +235,14 @@ fun App(
|
|||||||
NewIdentityScreen(accountViewModel)
|
NewIdentityScreen(accountViewModel)
|
||||||
}
|
}
|
||||||
entry<Screen.Chat> { key ->
|
entry<Screen.Chat> { key ->
|
||||||
val factory = remember(key) {
|
val initialRoom = remember(key.id) { chatRepository.getChatRoom(key.id) }
|
||||||
|
|
||||||
|
if (initialRoom != null) {
|
||||||
|
val factory = remember(initialRoom) {
|
||||||
object : ViewModelProvider.Factory {
|
object : ViewModelProvider.Factory {
|
||||||
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
return ChatScreenViewModel(
|
return ChatScreenViewModel(
|
||||||
key.id,
|
initialRoom,
|
||||||
key.screening,
|
key.screening,
|
||||||
accountRepository,
|
accountRepository,
|
||||||
chatRepository
|
chatRepository
|
||||||
@@ -272,6 +257,12 @@ fun App(
|
|||||||
),
|
),
|
||||||
accountViewModel
|
accountViewModel
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
// Handle the rare case where the room isn't in DB (e.g., invalid deep link)
|
||||||
|
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
Text("Room not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
entry<Screen.NewChat> {
|
entry<Screen.NewChat> {
|
||||||
NewChatScreen(accountViewModel, chatViewModel)
|
NewChatScreen(accountViewModel, chatViewModel)
|
||||||
@@ -294,9 +285,6 @@ fun App(
|
|||||||
entry<Screen.Relay> {
|
entry<Screen.Relay> {
|
||||||
RelayScreen(accountViewModel)
|
RelayScreen(accountViewModel)
|
||||||
}
|
}
|
||||||
entry<Screen.Settings> {
|
|
||||||
SettingsScreen(settingsViewModel)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import su.reya.coop.nostr.NostrManager
|
|||||||
import su.reya.coop.repository.AccountRepository
|
import su.reya.coop.repository.AccountRepository
|
||||||
import su.reya.coop.repository.ChatRepository
|
import su.reya.coop.repository.ChatRepository
|
||||||
import su.reya.coop.repository.MediaRepository
|
import su.reya.coop.repository.MediaRepository
|
||||||
import su.reya.coop.repository.SettingsRepository
|
|
||||||
import su.reya.coop.viewmodel.ProfileCache
|
import su.reya.coop.viewmodel.ProfileCache
|
||||||
import kotlin.system.exitProcess
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
@@ -26,30 +25,16 @@ class MainActivity : ComponentActivity() {
|
|||||||
private val profileCache by lazy { ProfileCache(NostrManager.instance) }
|
private val profileCache by lazy { ProfileCache(NostrManager.instance) }
|
||||||
private val scope = MainScope()
|
private val scope = MainScope()
|
||||||
|
|
||||||
private val connectivityMonitor by lazy { AndroidConnectivityMonitor(this@MainActivity) }
|
|
||||||
|
|
||||||
private val settingsRepository by lazy {
|
|
||||||
val storage = AppStore(this@MainActivity)
|
|
||||||
SettingsRepository(storage, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
private val accountRepository by lazy {
|
private val accountRepository by lazy {
|
||||||
val storage = AppStore(this@MainActivity)
|
val storage = AppStore(this@MainActivity)
|
||||||
val mediaRepository = MediaRepository(settingsRepository)
|
val mediaRepository = MediaRepository()
|
||||||
val androidSigner = AndroidExternalSigner(this@MainActivity, externalSignerLauncher)
|
val androidSigner = AndroidExternalSigner(this@MainActivity, externalSignerLauncher)
|
||||||
AccountRepository(
|
AccountRepository(NostrManager.instance, storage, mediaRepository, scope, androidSigner)
|
||||||
NostrManager.instance,
|
|
||||||
storage,
|
|
||||||
mediaRepository,
|
|
||||||
settingsRepository,
|
|
||||||
scope,
|
|
||||||
androidSigner
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private val chatRepository by lazy {
|
private val chatRepository by lazy {
|
||||||
val mediaRepository = MediaRepository(settingsRepository)
|
val mediaRepository = MediaRepository()
|
||||||
ChatRepository(NostrManager.instance, mediaRepository, settingsRepository, scope)
|
ChatRepository(NostrManager.instance, mediaRepository, scope)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
@@ -97,8 +82,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
profileCache = profileCache,
|
profileCache = profileCache,
|
||||||
accountRepository = accountRepository,
|
accountRepository = accountRepository,
|
||||||
chatRepository = chatRepository,
|
chatRepository = chatRepository,
|
||||||
settingsRepository = settingsRepository,
|
|
||||||
connectivityMonitor = connectivityMonitor,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,7 +58,4 @@ sealed interface Screen : NavKey {
|
|||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data object Relay : Screen
|
data object Relay : Screen
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data object Settings : Screen
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ import android.os.Build
|
|||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
|
||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
import androidx.lifecycle.ProcessLifecycleOwner
|
import androidx.lifecycle.ProcessLifecycleOwner
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
@@ -28,6 +28,8 @@ private const val GROUP_KEY_MESSAGES = "su.reya.coop.MESSAGES"
|
|||||||
|
|
||||||
class NostrForegroundService : Service() {
|
class NostrForegroundService : Service() {
|
||||||
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
|
|
||||||
|
var ioDispatcher: CoroutineDispatcher = Dispatchers.IO
|
||||||
private val nostr by lazy { NostrManager.instance }
|
private val nostr by lazy { NostrManager.instance }
|
||||||
private var notificationJob: Job? = null
|
private var notificationJob: Job? = null
|
||||||
|
|
||||||
@@ -189,13 +191,4 @@ class NostrForegroundService : Service() {
|
|||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
serviceScope.cancel()
|
serviceScope.cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
|
||||||
super.onTaskRemoved(rootIntent)
|
|
||||||
if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
|
|
||||||
Log.d("Coop", "Stopping service on task removed because notifications are disabled")
|
|
||||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,8 +73,7 @@ fun ContactListScreen(
|
|||||||
) {
|
) {
|
||||||
val navigator = LocalNavigator.current
|
val navigator = LocalNavigator.current
|
||||||
val snackbarHostState = LocalSnackbarHostState.current
|
val snackbarHostState = LocalSnackbarHostState.current
|
||||||
val accountState by accountViewModel.state.collectAsStateWithLifecycle()
|
val contactList by accountViewModel.contactList.collectAsStateWithLifecycle()
|
||||||
val contactList = accountState.contactList
|
|
||||||
var openAddContactDialog by remember { mutableStateOf(false) }
|
var openAddContactDialog by remember { mutableStateOf(false) }
|
||||||
var contactToDelete by remember { mutableStateOf<PublicKey?>(null) }
|
var contactToDelete by remember { mutableStateOf<PublicKey?>(null) }
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import android.os.Build
|
|||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -25,8 +24,6 @@ import androidx.compose.foundation.lazy.LazyColumn
|
|||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material3.Badge
|
|
||||||
import androidx.compose.material3.BadgedBox
|
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.ButtonDefaults
|
import androidx.compose.material3.ButtonDefaults
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
@@ -89,7 +86,6 @@ import coop.composeapp.generated.resources.ic_new_chat
|
|||||||
import coop.composeapp.generated.resources.ic_qr
|
import coop.composeapp.generated.resources.ic_qr
|
||||||
import coop.composeapp.generated.resources.ic_request
|
import coop.composeapp.generated.resources.ic_request
|
||||||
import coop.composeapp.generated.resources.ic_scanner
|
import coop.composeapp.generated.resources.ic_scanner
|
||||||
import kotlinx.coroutines.flow.flowOf
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import org.jetbrains.compose.resources.painterResource
|
import org.jetbrains.compose.resources.painterResource
|
||||||
import rust.nostr.sdk.PublicKey
|
import rust.nostr.sdk.PublicKey
|
||||||
@@ -102,9 +98,9 @@ import su.reya.coop.RoomKind
|
|||||||
import su.reya.coop.RoomUiState
|
import su.reya.coop.RoomUiState
|
||||||
import su.reya.coop.Screen
|
import su.reya.coop.Screen
|
||||||
import su.reya.coop.ago
|
import su.reya.coop.ago
|
||||||
|
import su.reya.coop.flow
|
||||||
import su.reya.coop.shared.Avatar
|
import su.reya.coop.shared.Avatar
|
||||||
import su.reya.coop.shared.getExpressiveFontFamily
|
import su.reya.coop.shared.getExpressiveFontFamily
|
||||||
import su.reya.coop.uiStateFlow
|
|
||||||
import su.reya.coop.viewmodel.AccountViewModel
|
import su.reya.coop.viewmodel.AccountViewModel
|
||||||
import su.reya.coop.viewmodel.ChatViewModel
|
import su.reya.coop.viewmodel.ChatViewModel
|
||||||
|
|
||||||
@@ -128,13 +124,13 @@ fun HomeScreen(
|
|||||||
val userProfile by accountViewModel.currentUserProfile.collectAsStateWithLifecycle()
|
val userProfile by accountViewModel.currentUserProfile.collectAsStateWithLifecycle()
|
||||||
val chatRooms by chatViewModel.chatRooms.collectAsStateWithLifecycle()
|
val chatRooms by chatViewModel.chatRooms.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val accountState by accountViewModel.state.collectAsStateWithLifecycle()
|
val isRelayListEmpty by accountViewModel.isRelayListEmpty.collectAsStateWithLifecycle()
|
||||||
val isRelayListEmpty = accountState.isRelayListEmpty
|
|
||||||
val isBannerDismissed = accountState.isNotificationBannerDismissed
|
|
||||||
|
|
||||||
val isSyncing by chatViewModel.isSyncing.collectAsStateWithLifecycle()
|
val isSyncing by chatViewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
val isPartialProcessedGiftWrap by chatViewModel.isPartialProcessedGiftWrap.collectAsStateWithLifecycle()
|
val isPartialProcessedGiftWrap by chatViewModel.isPartialProcessedGiftWrap.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val accountState by accountViewModel.state.collectAsStateWithLifecycle()
|
||||||
|
val isBannerDismissed = accountState.isNotificationBannerDismissed
|
||||||
|
|
||||||
val expandedFab by remember { derivedStateOf { listState.firstVisibleItemIndex == 0 } }
|
val expandedFab by remember { derivedStateOf { listState.firstVisibleItemIndex == 0 } }
|
||||||
var showBottomSheet by remember { mutableStateOf(false) }
|
var showBottomSheet by remember { mutableStateOf(false) }
|
||||||
var isRefreshing by remember { mutableStateOf(false) }
|
var isRefreshing by remember { mutableStateOf(false) }
|
||||||
@@ -253,9 +249,7 @@ fun HomeScreen(
|
|||||||
modifier = Modifier.padding(top = innerPadding.calculateTopPadding()),
|
modifier = Modifier.padding(top = innerPadding.calculateTopPadding()),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
AnimatedVisibility(
|
if (!isNotificationEnabled && !isBannerDismissed) {
|
||||||
visible = !isNotificationEnabled && !isBannerDismissed,
|
|
||||||
) {
|
|
||||||
Surface(
|
Surface(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -378,9 +372,6 @@ fun HomeScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
items(ongoing, key = { it.id }) { room ->
|
items(ongoing, key = { it.id }) { room ->
|
||||||
Row(
|
|
||||||
modifier = Modifier.animateItem()
|
|
||||||
) {
|
|
||||||
ChatRoom(
|
ChatRoom(
|
||||||
room = room,
|
room = room,
|
||||||
onClick = { navigator.navigate(Screen.Chat(room.id)) }
|
onClick = { navigator.navigate(Screen.Chat(room.id)) }
|
||||||
@@ -391,7 +382,6 @@ fun HomeScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -630,16 +620,13 @@ fun NewRequests(requests: List<Room>) {
|
|||||||
val firstRoom = requests.getOrNull(0)
|
val firstRoom = requests.getOrNull(0)
|
||||||
val secondRoom = requests.getOrNull(1)
|
val secondRoom = requests.getOrNull(1)
|
||||||
|
|
||||||
val firstRoomState by remember(firstRoom?.id) {
|
val firstRoomState by (firstRoom as Room).flow(profileCache)
|
||||||
firstRoom?.uiStateFlow(profileCache) ?: flowOf(RoomUiState())
|
.collectAsStateWithLifecycle(RoomUiState())
|
||||||
}.collectAsStateWithLifecycle(RoomUiState())
|
val secondRoomState by (secondRoom ?: firstRoom).flow(profileCache)
|
||||||
|
.collectAsStateWithLifecycle(RoomUiState())
|
||||||
val secondRoomState by remember(secondRoom?.id) {
|
|
||||||
(secondRoom ?: firstRoom)?.uiStateFlow(profileCache) ?: flowOf(RoomUiState())
|
|
||||||
}.collectAsStateWithLifecycle(RoomUiState())
|
|
||||||
|
|
||||||
val supportingText = when {
|
val supportingText = when {
|
||||||
total == 1 && firstRoom != null -> {
|
total == 1 -> {
|
||||||
val message = firstRoom.lastMessage ?: ""
|
val message = firstRoom.lastMessage ?: ""
|
||||||
"${firstRoomState.name}: $message"
|
"${firstRoomState.name}: $message"
|
||||||
}
|
}
|
||||||
@@ -657,22 +644,11 @@ fun NewRequests(requests: List<Room>) {
|
|||||||
else -> ""
|
else -> ""
|
||||||
}
|
}
|
||||||
|
|
||||||
val totalUnread = requests.sumOf { it.unreadCount }
|
|
||||||
|
|
||||||
ListItem(
|
ListItem(
|
||||||
modifier = Modifier.clickable {
|
modifier = Modifier.clickable {
|
||||||
navigator.navigate(Screen.RequestList)
|
navigator.navigate(Screen.RequestList)
|
||||||
},
|
},
|
||||||
leadingContent = {
|
leadingContent = {
|
||||||
BadgedBox(
|
|
||||||
badge = {
|
|
||||||
if (totalUnread > 0) {
|
|
||||||
Badge {
|
|
||||||
Text(totalUnread.toString())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(48.dp)
|
.size(48.dp)
|
||||||
@@ -692,24 +668,18 @@ fun NewRequests(requests: List<Room>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
},
|
},
|
||||||
headlineContent = {
|
headlineContent = {
|
||||||
Text(
|
Text(
|
||||||
text = "Requests",
|
text = "Requests",
|
||||||
style = MaterialTheme.typography.titleMediumEmphasized.copy(
|
style = MaterialTheme.typography.titleMediumEmphasized
|
||||||
fontWeight = if (totalUnread > 0) FontWeight.SemiBold else FontWeight.Normal
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
supportingContent = {
|
supportingContent = {
|
||||||
if (supportingText.isNotEmpty()) {
|
if (supportingText.isNotEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
text = supportingText,
|
text = supportingText,
|
||||||
style = MaterialTheme.typography.bodyMedium.copy(
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = if (totalUnread > 0) FontWeight.SemiBold else FontWeight.Normal,
|
|
||||||
color = if (totalUnread > 0) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.outline
|
|
||||||
),
|
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis
|
overflow = TextOverflow.Ellipsis
|
||||||
)
|
)
|
||||||
@@ -725,41 +695,27 @@ fun NewRequests(requests: List<Room>) {
|
|||||||
@Composable
|
@Composable
|
||||||
fun ChatRoom(room: Room, onClick: () -> Unit) {
|
fun ChatRoom(room: Room, onClick: () -> Unit) {
|
||||||
val profileCache = LocalProfileCache.current
|
val profileCache = LocalProfileCache.current
|
||||||
val roomState by remember(room.id) { room.uiStateFlow(profileCache) }
|
val roomState by room.flow(profileCache).collectAsStateWithLifecycle(RoomUiState())
|
||||||
.collectAsStateWithLifecycle(RoomUiState())
|
|
||||||
|
|
||||||
ListItem(
|
ListItem(
|
||||||
modifier = Modifier.clickable(onClick = onClick),
|
modifier = Modifier.clickable(onClick = onClick),
|
||||||
leadingContent = {
|
leadingContent = {
|
||||||
BadgedBox(
|
|
||||||
badge = {
|
|
||||||
if (room.unreadCount > 0) {
|
|
||||||
Badge {
|
|
||||||
Text(room.unreadCount.toString())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
Avatar(picture = roomState.picture, description = roomState.picture)
|
Avatar(picture = roomState.picture, description = roomState.picture)
|
||||||
}
|
|
||||||
},
|
},
|
||||||
headlineContent = {
|
headlineContent = {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = roomState.name,
|
text = roomState.name,
|
||||||
style = MaterialTheme.typography.titleMediumEmphasized.copy(
|
style = MaterialTheme.typography.titleMediumEmphasized,
|
||||||
fontWeight = if (room.unreadCount > 0) FontWeight.SemiBold else FontWeight.Normal
|
|
||||||
),
|
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f)
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = room.createdAt.ago(),
|
text = room.createdAt.ago(),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.outline,
|
color = MaterialTheme.colorScheme.outline
|
||||||
textAlign = TextAlign.End,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -767,10 +723,7 @@ fun ChatRoom(room: Room, onClick: () -> Unit) {
|
|||||||
if (!room.lastMessage.isNullOrBlank()) {
|
if (!room.lastMessage.isNullOrBlank()) {
|
||||||
Text(
|
Text(
|
||||||
text = room.lastMessage ?: "",
|
text = room.lastMessage ?: "",
|
||||||
style = MaterialTheme.typography.bodyMedium.copy(
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = if (room.unreadCount > 0) FontWeight.SemiBold else FontWeight.Normal,
|
|
||||||
color = if (room.unreadCount > 0) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.outline
|
|
||||||
),
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
)
|
)
|
||||||
@@ -795,7 +748,7 @@ fun BottomMenuList(
|
|||||||
"Update Profile" to { navigator.navigate(Screen.UpdateProfile) },
|
"Update Profile" to { navigator.navigate(Screen.UpdateProfile) },
|
||||||
"Contact List" to { navigator.navigate(Screen.ContactList) },
|
"Contact List" to { navigator.navigate(Screen.ContactList) },
|
||||||
"Relay Management" to { navigator.navigate(Screen.Relay) },
|
"Relay Management" to { navigator.navigate(Screen.Relay) },
|
||||||
"Settings" to { navigator.navigate(Screen.Settings) }
|
"Settings" to { }
|
||||||
)
|
)
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
|
|||||||
@@ -101,6 +101,13 @@ fun ImportScreen(viewModel: AccountViewModel) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Show import errors via snackbar
|
||||||
|
LaunchedEffect(accountState.importError) {
|
||||||
|
accountState.importError?.let {
|
||||||
|
snackbarHostState.showSnackbar(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceContainer,
|
containerColor = MaterialTheme.colorScheme.surfaceContainer,
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||||
|
|||||||
@@ -75,8 +75,7 @@ fun NewChatScreen(
|
|||||||
val snackbarHostState = LocalSnackbarHostState.current
|
val snackbarHostState = LocalSnackbarHostState.current
|
||||||
val navigator = LocalNavigator.current
|
val navigator = LocalNavigator.current
|
||||||
val qrScanResult = LocalScanResult.current
|
val qrScanResult = LocalScanResult.current
|
||||||
val accountState by accountViewModel.state.collectAsStateWithLifecycle()
|
val contactList by accountViewModel.contactList.collectAsStateWithLifecycle()
|
||||||
val contactList = accountState.contactList
|
|
||||||
var query by remember { mutableStateOf("") }
|
var query by remember { mutableStateOf("") }
|
||||||
|
|
||||||
val createGroup = remember { mutableStateOf(false) }
|
val createGroup = remember { mutableStateOf(false) }
|
||||||
@@ -186,8 +185,8 @@ fun NewChatScreen(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
text = { Text("Next") },
|
text = { Text("Next") },
|
||||||
containerColor = MaterialTheme.colorScheme.tertiaryContainer,
|
containerColor = MaterialTheme.colorScheme.tertiary,
|
||||||
contentColor = MaterialTheme.colorScheme.onTertiaryContainer,
|
contentColor = MaterialTheme.colorScheme.onTertiary,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -398,7 +397,7 @@ fun ContactListItem(
|
|||||||
supportingContent = { Text(text = pubkey.short()) },
|
supportingContent = { Text(text = pubkey.short()) },
|
||||||
content = {
|
content = {
|
||||||
Text(
|
Text(
|
||||||
text = profile?.name ?: "Unknown",
|
text = profile?.name ?: "",
|
||||||
style = MaterialTheme.typography.titleMediumEmphasized,
|
style = MaterialTheme.typography.titleMediumEmphasized,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,6 +70,13 @@ fun OnboardingScreen(viewModel: AccountViewModel) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Show connection errors
|
||||||
|
LaunchedEffect(accountState.importError) {
|
||||||
|
accountState.importError?.let {
|
||||||
|
snackbarHostState.showSnackbar(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val logoPainter = painterResource(Res.drawable.coop)
|
val logoPainter = painterResource(Res.drawable.coop)
|
||||||
val expressiveFont = getExpressiveFontFamily()
|
val expressiveFont = getExpressiveFontFamily()
|
||||||
|
|
||||||
|
|||||||
@@ -95,15 +95,14 @@ fun RelayScreen(viewModel: AccountViewModel) {
|
|||||||
var openAddRelayDialog by remember { mutableStateOf(false) }
|
var openAddRelayDialog by remember { mutableStateOf(false) }
|
||||||
var relayToDelete by remember { mutableStateOf<String?>(null) }
|
var relayToDelete by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
val accountState by viewModel.state.collectAsStateWithLifecycle()
|
|
||||||
val loadedRelayList = accountState.userRelayList
|
|
||||||
val loadedMsgRelayList = accountState.userMsgRelayList
|
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
viewModel.loadCurrentUserRelayList()
|
viewModel.loadCurrentUserRelayList()
|
||||||
viewModel.loadCurrentUserMsgRelayList()
|
viewModel.loadCurrentUserMsgRelayList()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val loadedRelayList by viewModel.userRelayList.collectAsStateWithLifecycle()
|
||||||
|
val loadedMsgRelayList by viewModel.userMsgRelayList.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
LaunchedEffect(loadedRelayList) {
|
LaunchedEffect(loadedRelayList) {
|
||||||
if (loadedRelayList.isNotEmpty()) {
|
if (loadedRelayList.isNotEmpty()) {
|
||||||
relayList.clear()
|
relayList.clear()
|
||||||
|
|||||||
@@ -1,291 +0,0 @@
|
|||||||
package su.reya.coop.screens
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import android.provider.Settings as AndroidSettings
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.selection.selectable
|
|
||||||
import androidx.compose.foundation.selection.selectableGroup
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.IconButton
|
|
||||||
import androidx.compose.material3.ListItemDefaults
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.OutlinedTextField
|
|
||||||
import androidx.compose.material3.RadioButton
|
|
||||||
import androidx.compose.material3.Scaffold
|
|
||||||
import androidx.compose.material3.SegmentedListItem
|
|
||||||
import androidx.compose.material3.SnackbarHost
|
|
||||||
import androidx.compose.material3.Switch
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.material3.TextButton
|
|
||||||
import androidx.compose.material3.TopAppBar
|
|
||||||
import androidx.compose.material3.TopAppBarDefaults
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.semantics.Role
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import coop.composeapp.generated.resources.Res
|
|
||||||
import coop.composeapp.generated.resources.ic_arrow_back
|
|
||||||
import org.jetbrains.compose.resources.painterResource
|
|
||||||
import su.reya.coop.LocalNavigator
|
|
||||||
import su.reya.coop.LocalSnackbarHostState
|
|
||||||
import su.reya.coop.MediaConfig
|
|
||||||
import su.reya.coop.Theme
|
|
||||||
import su.reya.coop.viewmodel.SettingsViewModel
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
|
||||||
@Composable
|
|
||||||
fun SettingsScreen(viewModel: SettingsViewModel) {
|
|
||||||
val navigator = LocalNavigator.current
|
|
||||||
val context = LocalContext.current
|
|
||||||
val snackbarHostState = LocalSnackbarHostState.current
|
|
||||||
val settings by viewModel.settings.collectAsState()
|
|
||||||
|
|
||||||
var showThemeDialog by remember { mutableStateOf(false) }
|
|
||||||
var showMediaDialog by remember { mutableStateOf(false) }
|
|
||||||
var showBlossomDialog by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
Scaffold(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceContainer,
|
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
|
||||||
topBar = {
|
|
||||||
TopAppBar(
|
|
||||||
title = {
|
|
||||||
Text(
|
|
||||||
text = "Settings",
|
|
||||||
style = MaterialTheme.typography.titleMediumEmphasized
|
|
||||||
)
|
|
||||||
},
|
|
||||||
colors = TopAppBarDefaults.topAppBarColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceContainer,
|
|
||||||
),
|
|
||||||
navigationIcon = {
|
|
||||||
IconButton(onClick = { navigator.goBack() }) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(Res.drawable.ic_arrow_back),
|
|
||||||
contentDescription = "Back"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
},
|
|
||||||
) { innerPadding ->
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(innerPadding)
|
|
||||||
.verticalScroll(rememberScrollState())
|
|
||||||
.padding(horizontal = 16.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(24.dp)
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "General",
|
|
||||||
style = MaterialTheme.typography.titleSmall,
|
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.padding(horizontal = 8.dp)
|
|
||||||
)
|
|
||||||
Column(
|
|
||||||
verticalArrangement = Arrangement.spacedBy(ListItemDefaults.SegmentedGap)
|
|
||||||
) {
|
|
||||||
SegmentedListItem(
|
|
||||||
onClick = { viewModel.update { it.copy(screening = !it.screening) } },
|
|
||||||
shapes = ListItemDefaults.segmentedShapes(index = 0, count = 4),
|
|
||||||
content = { Text("Screening") },
|
|
||||||
supportingContent = { Text("Filter unknown contacts") },
|
|
||||||
trailingContent = {
|
|
||||||
Switch(
|
|
||||||
checked = settings.screening,
|
|
||||||
onCheckedChange = { viewModel.update { s -> s.copy(screening = it) } }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
SegmentedListItem(
|
|
||||||
onClick = { showMediaDialog = true },
|
|
||||||
shapes = ListItemDefaults.segmentedShapes(index = 1, count = 4),
|
|
||||||
content = { Text("Media Preview") },
|
|
||||||
supportingContent = {
|
|
||||||
Text(
|
|
||||||
when (settings.media) {
|
|
||||||
MediaConfig.Disabled -> "Disabled"
|
|
||||||
MediaConfig.DisabledForMobileData -> "Disabled for Mobile Data"
|
|
||||||
MediaConfig.AlwaysEnabled -> "Always Enabled"
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
SegmentedListItem(
|
|
||||||
onClick = { showBlossomDialog = true },
|
|
||||||
shapes = ListItemDefaults.segmentedShapes(index = 2, count = 4),
|
|
||||||
content = { Text("Blossom Server") },
|
|
||||||
supportingContent = { Text(settings.blossomServer ?: "Default") }
|
|
||||||
)
|
|
||||||
SegmentedListItem(
|
|
||||||
onClick = {
|
|
||||||
val intent = Intent(AndroidSettings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
|
|
||||||
putExtra(AndroidSettings.EXTRA_APP_PACKAGE, context.packageName)
|
|
||||||
}
|
|
||||||
context.startActivity(intent)
|
|
||||||
},
|
|
||||||
shapes = ListItemDefaults.segmentedShapes(index = 3, count = 4),
|
|
||||||
content = { Text("Notifications") },
|
|
||||||
supportingContent = { Text("System notification settings") }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Column(
|
|
||||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "Appearance",
|
|
||||||
style = MaterialTheme.typography.titleSmall,
|
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.padding(horizontal = 8.dp)
|
|
||||||
)
|
|
||||||
Column(
|
|
||||||
verticalArrangement = Arrangement.spacedBy(ListItemDefaults.SegmentedGap)
|
|
||||||
) {
|
|
||||||
SegmentedListItem(
|
|
||||||
onClick = { showThemeDialog = true },
|
|
||||||
shapes = ListItemDefaults.segmentedShapes(index = 0, count = 2),
|
|
||||||
content = { Text("Theme") },
|
|
||||||
supportingContent = { Text(settings.theme.name) }
|
|
||||||
)
|
|
||||||
SegmentedListItem(
|
|
||||||
onClick = { viewModel.update { it.copy(dynamicColor = !it.dynamicColor) } },
|
|
||||||
shapes = ListItemDefaults.segmentedShapes(index = 1, count = 2),
|
|
||||||
content = { Text("Dynamic Color") },
|
|
||||||
trailingContent = {
|
|
||||||
Switch(
|
|
||||||
checked = settings.dynamicColor,
|
|
||||||
onCheckedChange = {
|
|
||||||
viewModel.update { s -> s.copy(dynamicColor = it) }
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showThemeDialog) {
|
|
||||||
OptionDialog(
|
|
||||||
title = "Select Theme",
|
|
||||||
options = Theme.entries.map { it.name },
|
|
||||||
selected = settings.theme.name,
|
|
||||||
onSelected = { name ->
|
|
||||||
viewModel.update { it.copy(theme = Theme.valueOf(name)) }
|
|
||||||
showThemeDialog = false
|
|
||||||
},
|
|
||||||
onDismiss = { showThemeDialog = false }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showMediaDialog) {
|
|
||||||
OptionDialog(
|
|
||||||
title = "Media Preview",
|
|
||||||
options = listOf("Disabled", "Disabled for Mobile Data", "Always Enabled"),
|
|
||||||
selected = when (settings.media) {
|
|
||||||
MediaConfig.Disabled -> "Disabled"
|
|
||||||
MediaConfig.DisabledForMobileData -> "Disabled for Mobile Data"
|
|
||||||
MediaConfig.AlwaysEnabled -> "Always Enabled"
|
|
||||||
},
|
|
||||||
onSelected = { choice ->
|
|
||||||
val newConfig = when (choice) {
|
|
||||||
"Disabled" -> MediaConfig.Disabled
|
|
||||||
"Disabled for Mobile Data" -> MediaConfig.DisabledForMobileData
|
|
||||||
else -> MediaConfig.AlwaysEnabled
|
|
||||||
}
|
|
||||||
viewModel.update { it.copy(media = newConfig) }
|
|
||||||
showMediaDialog = false
|
|
||||||
},
|
|
||||||
onDismiss = { showMediaDialog = false }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showBlossomDialog) {
|
|
||||||
var text by remember { mutableStateOf(settings.blossomServer ?: "") }
|
|
||||||
AlertDialog(
|
|
||||||
onDismissRequest = { showBlossomDialog = false },
|
|
||||||
title = { Text("Blossom Server URL") },
|
|
||||||
text = {
|
|
||||||
OutlinedTextField(
|
|
||||||
value = text,
|
|
||||||
onValueChange = { text = it },
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
placeholder = { Text("https://...") },
|
|
||||||
singleLine = true
|
|
||||||
)
|
|
||||||
},
|
|
||||||
confirmButton = {
|
|
||||||
TextButton(onClick = {
|
|
||||||
viewModel.update { it.copy(blossomServer = text.ifBlank { null }) }
|
|
||||||
showBlossomDialog = false
|
|
||||||
}) {
|
|
||||||
Text("Save")
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
TextButton(onClick = { showBlossomDialog = false }) {
|
|
||||||
Text("Cancel")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun OptionDialog(
|
|
||||||
title: String,
|
|
||||||
options: List<String>,
|
|
||||||
selected: String,
|
|
||||||
onSelected: (String) -> Unit,
|
|
||||||
onDismiss: () -> Unit
|
|
||||||
) {
|
|
||||||
AlertDialog(
|
|
||||||
onDismissRequest = onDismiss,
|
|
||||||
title = { Text(title) },
|
|
||||||
text = {
|
|
||||||
Column(modifier = Modifier.selectableGroup()) {
|
|
||||||
options.forEach { text ->
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.selectable(
|
|
||||||
selected = (text == selected),
|
|
||||||
onClick = { onSelected(text) },
|
|
||||||
role = Role.RadioButton
|
|
||||||
)
|
|
||||||
.padding(vertical = 12.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically
|
|
||||||
) {
|
|
||||||
RadioButton(selected = (text == selected), onClick = null)
|
|
||||||
Spacer(Modifier.size(16.dp))
|
|
||||||
Text(text = text, style = MaterialTheme.typography.bodyLarge)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
confirmButton = {}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
package su.reya.coop.screens.chat
|
package su.reya.coop.screens.chat
|
||||||
|
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.expandVertically
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.shrinkVertically
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -38,9 +43,6 @@ import coil3.compose.AsyncImage
|
|||||||
import rust.nostr.sdk.EventId
|
import rust.nostr.sdk.EventId
|
||||||
import rust.nostr.sdk.PublicKey
|
import rust.nostr.sdk.PublicKey
|
||||||
import rust.nostr.sdk.UnsignedEvent
|
import rust.nostr.sdk.UnsignedEvent
|
||||||
import su.reya.coop.LocalConnectivity
|
|
||||||
import su.reya.coop.LocalSettings
|
|
||||||
import su.reya.coop.MediaConfig
|
|
||||||
import su.reya.coop.URL_REGEX
|
import su.reya.coop.URL_REGEX
|
||||||
import su.reya.coop.formatAsTime
|
import su.reya.coop.formatAsTime
|
||||||
import su.reya.coop.isImageUrl
|
import su.reya.coop.isImageUrl
|
||||||
@@ -59,27 +61,14 @@ data class MessageModel(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun rememberMessageModel(event: UnsignedEvent, currentUser: PublicKey? = null): MessageModel {
|
fun rememberMessageModel(event: UnsignedEvent, currentUser: PublicKey? = null): MessageModel {
|
||||||
val settings = LocalSettings.current
|
return remember(event, currentUser) {
|
||||||
val isMobileData = LocalConnectivity.current
|
|
||||||
|
|
||||||
return remember(event, currentUser, settings, isMobileData) {
|
|
||||||
val id = event.ensureId().id()!!
|
val id = event.ensureId().id()!!
|
||||||
val isMine = currentUser == event.author()
|
val isMine = currentUser == event.author()
|
||||||
val content = event.content()
|
val content = event.content()
|
||||||
val replyEventIds = event.tags().eventIds()
|
val replyEventIds = event.tags().eventIds()
|
||||||
|
|
||||||
val showMedia = when (settings.media) {
|
val images = URL_REGEX.findAll(content).map { it.value }.filter { it.isImageUrl() }.toList()
|
||||||
MediaConfig.AlwaysEnabled -> true
|
val cleanedContent = content.removeImageUrls()
|
||||||
MediaConfig.Disabled -> false
|
|
||||||
MediaConfig.DisabledForMobileData -> !isMobileData
|
|
||||||
}
|
|
||||||
|
|
||||||
val images = if (showMedia) {
|
|
||||||
URL_REGEX.findAll(content).map { it.value }.filter { it.isImageUrl() }.toList()
|
|
||||||
} else {
|
|
||||||
emptyList()
|
|
||||||
}
|
|
||||||
val cleanedContent = if (showMedia) content.removeImageUrls() else content
|
|
||||||
|
|
||||||
val annotatedString = buildAnnotatedString {
|
val annotatedString = buildAnnotatedString {
|
||||||
var lastIndex = 0
|
var lastIndex = 0
|
||||||
@@ -188,7 +177,11 @@ fun ChatMessage(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isMessageClicked) {
|
AnimatedVisibility(
|
||||||
|
visible = isMessageClicked,
|
||||||
|
enter = fadeIn() + expandVertically(),
|
||||||
|
exit = fadeOut() + shrinkVertically()
|
||||||
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = model.timestamp,
|
text = model.timestamp,
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
|||||||
@@ -93,14 +93,12 @@ import org.jetbrains.compose.resources.painterResource
|
|||||||
import rust.nostr.sdk.UnsignedEvent
|
import rust.nostr.sdk.UnsignedEvent
|
||||||
import su.reya.coop.LocalNavigator
|
import su.reya.coop.LocalNavigator
|
||||||
import su.reya.coop.LocalProfileCache
|
import su.reya.coop.LocalProfileCache
|
||||||
import su.reya.coop.LocalSettings
|
|
||||||
import su.reya.coop.LocalSnackbarHostState
|
import su.reya.coop.LocalSnackbarHostState
|
||||||
import su.reya.coop.Room
|
|
||||||
import su.reya.coop.RoomUiState
|
import su.reya.coop.RoomUiState
|
||||||
import su.reya.coop.Screen
|
import su.reya.coop.Screen
|
||||||
|
import su.reya.coop.flow
|
||||||
import su.reya.coop.formatAsGroup
|
import su.reya.coop.formatAsGroup
|
||||||
import su.reya.coop.shared.Avatar
|
import su.reya.coop.shared.Avatar
|
||||||
import su.reya.coop.uiStateFlow
|
|
||||||
import su.reya.coop.viewmodel.AccountViewModel
|
import su.reya.coop.viewmodel.AccountViewModel
|
||||||
import su.reya.coop.viewmodel.ChatScreenViewModel
|
import su.reya.coop.viewmodel.ChatScreenViewModel
|
||||||
|
|
||||||
@@ -116,29 +114,14 @@ fun ChatScreen(
|
|||||||
val clipboardManager = LocalClipboard.current
|
val clipboardManager = LocalClipboard.current
|
||||||
val navigator = LocalNavigator.current
|
val navigator = LocalNavigator.current
|
||||||
val profileCache = LocalProfileCache.current
|
val profileCache = LocalProfileCache.current
|
||||||
val settings = LocalSettings.current
|
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val listState = rememberLazyListState()
|
val listState = rememberLazyListState()
|
||||||
|
|
||||||
val id = viewModel.id
|
|
||||||
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||||
val chatRooms by viewModel.chatRooms.collectAsStateWithLifecycle()
|
val pubkey = currentUser?.publicKey
|
||||||
val room by remember(id) { derivedStateOf { chatRooms.firstOrNull { it.id == id } } }
|
|
||||||
|
|
||||||
// Show empty screen
|
val room by viewModel.room.collectAsStateWithLifecycle()
|
||||||
if (room == null) {
|
val roomState by room.flow(profileCache, pubkey).collectAsStateWithLifecycle(RoomUiState())
|
||||||
Box(
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
contentAlignment = Alignment.Center
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "Something went wrong.",
|
|
||||||
style = MaterialTheme.typography.titleMediumEmphasized,
|
|
||||||
color = MaterialTheme.colorScheme.onSurface
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val loading = viewModel.loading
|
val loading = viewModel.loading
|
||||||
val newOtherMessages = viewModel.newOtherMessages
|
val newOtherMessages = viewModel.newOtherMessages
|
||||||
@@ -148,10 +131,6 @@ fun ChatScreen(
|
|||||||
val groupedMessages =
|
val groupedMessages =
|
||||||
remember { derivedStateOf { messages.groupBy { it.createdAt().formatAsGroup() } } }
|
remember { derivedStateOf { messages.groupBy { it.createdAt().formatAsGroup() } } }
|
||||||
|
|
||||||
val roomState by remember(id, currentUser?.publicKey) {
|
|
||||||
(room as Room).uiStateFlow(profileCache, currentUser?.publicKey)
|
|
||||||
}.collectAsStateWithLifecycle(RoomUiState())
|
|
||||||
|
|
||||||
var text by remember { mutableStateOf("") }
|
var text by remember { mutableStateOf("") }
|
||||||
var selectedMessage by remember { mutableStateOf<Pair<MessageModel, Rect>?>(null) }
|
var selectedMessage by remember { mutableStateOf<Pair<MessageModel, Rect>?>(null) }
|
||||||
var replyingTo by remember { mutableStateOf<MessageModel?>(null) }
|
var replyingTo by remember { mutableStateOf<MessageModel?>(null) }
|
||||||
@@ -196,9 +175,7 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Box(
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
modifier = Modifier.fillMaxSize()
|
|
||||||
) {
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
modifier = Modifier.blur(blurAmount),
|
modifier = Modifier.blur(blurAmount),
|
||||||
contentWindowInsets = ScaffoldDefaults.contentWindowInsets.union(WindowInsets.ime),
|
contentWindowInsets = ScaffoldDefaults.contentWindowInsets.union(WindowInsets.ime),
|
||||||
@@ -210,7 +187,7 @@ fun ChatScreen(
|
|||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier.clickable {
|
modifier = Modifier.clickable {
|
||||||
room?.members?.firstOrNull()?.let { pubkey ->
|
room.members.firstOrNull()?.let { pubkey ->
|
||||||
navigator.navigate(Screen.Profile(pubkey.toBech32()))
|
navigator.navigate(Screen.Profile(pubkey.toBech32()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -267,8 +244,8 @@ fun ChatScreen(
|
|||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(bottom = innerPadding.calculateBottomPadding())
|
.padding(bottom = innerPadding.calculateBottomPadding())
|
||||||
) {
|
) {
|
||||||
if (requireScreening && settings.screening) {
|
if (requireScreening) {
|
||||||
room?.let { ScreenerCard(accountViewModel, it) }
|
ScreenerCard(accountViewModel, room)
|
||||||
}
|
}
|
||||||
|
|
||||||
when (messages.isNotEmpty()) {
|
when (messages.isNotEmpty()) {
|
||||||
@@ -286,8 +263,7 @@ fun ChatScreen(
|
|||||||
items = messagesInGroup,
|
items = messagesInGroup,
|
||||||
key = { it.ensureId().id()?.toHex()!! }
|
key = { it.ensureId().id()?.toHex()!! }
|
||||||
) { event ->
|
) { event ->
|
||||||
val model =
|
val model = rememberMessageModel(event, pubkey)
|
||||||
rememberMessageModel(event, currentUser?.publicKey)
|
|
||||||
|
|
||||||
val replyPreview =
|
val replyPreview =
|
||||||
remember(model.replyEventIds, messages.size) {
|
remember(model.replyEventIds, messages.size) {
|
||||||
@@ -298,12 +274,12 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier.fillMaxWidth(),
|
||||||
.fillMaxWidth()
|
|
||||||
.animateItem(),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(2.dp)
|
verticalArrangement = Arrangement.spacedBy(2.dp)
|
||||||
) {
|
) {
|
||||||
replyPreview?.let { ReplyPreview(it, model.isMine) }
|
replyPreview?.let {
|
||||||
|
ReplyPreview(it, model.isMine)
|
||||||
|
}
|
||||||
ChatMessage(
|
ChatMessage(
|
||||||
model = model,
|
model = model,
|
||||||
modifier = Modifier.graphicsLayer {
|
modifier = Modifier.graphicsLayer {
|
||||||
@@ -351,7 +327,7 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
when (requireScreening && settings.screening) {
|
when (requireScreening) {
|
||||||
true -> {
|
true -> {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -385,11 +361,9 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
AnimatedVisibility(visible = replyingTo != null) {
|
|
||||||
replyingTo?.let {
|
replyingTo?.let {
|
||||||
ReplyBox(it) { replyingTo = null }
|
ReplyBox(it) { replyingTo = null }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
ChatInput(
|
ChatInput(
|
||||||
value = text,
|
value = text,
|
||||||
onValueChange = { text = it },
|
onValueChange = { text = it },
|
||||||
@@ -427,6 +401,7 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
AnimatedVisibility(
|
AnimatedVisibility(
|
||||||
visible = selectedMessage != null,
|
visible = selectedMessage != null,
|
||||||
enter = fadeIn(),
|
enter = fadeIn(),
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package su.reya.coop.shared
|
package su.reya.coop.shared
|
||||||
|
|
||||||
import androidx.compose.foundation.Image
|
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -14,9 +13,6 @@ import coil3.compose.AsyncImage
|
|||||||
import coop.composeapp.generated.resources.Res
|
import coop.composeapp.generated.resources.Res
|
||||||
import coop.composeapp.generated.resources.avatar
|
import coop.composeapp.generated.resources.avatar
|
||||||
import org.jetbrains.compose.resources.painterResource
|
import org.jetbrains.compose.resources.painterResource
|
||||||
import su.reya.coop.LocalConnectivity
|
|
||||||
import su.reya.coop.LocalSettings
|
|
||||||
import su.reya.coop.MediaConfig
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun Avatar(
|
fun Avatar(
|
||||||
@@ -26,17 +22,8 @@ fun Avatar(
|
|||||||
size: Dp = 48.dp,
|
size: Dp = 48.dp,
|
||||||
shape: Shape = CircleShape
|
shape: Shape = CircleShape
|
||||||
) {
|
) {
|
||||||
val settings = LocalSettings.current
|
|
||||||
val isMobileData = LocalConnectivity.current
|
|
||||||
val placeholder = painterResource(Res.drawable.avatar)
|
val placeholder = painterResource(Res.drawable.avatar)
|
||||||
|
|
||||||
val showMedia = when (settings.media) {
|
|
||||||
MediaConfig.AlwaysEnabled -> true
|
|
||||||
MediaConfig.Disabled -> false
|
|
||||||
MediaConfig.DisabledForMobileData -> !isMobileData
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showMedia) {
|
|
||||||
AsyncImage(
|
AsyncImage(
|
||||||
model = picture,
|
model = picture,
|
||||||
contentDescription = description,
|
contentDescription = description,
|
||||||
@@ -48,14 +35,4 @@ fun Avatar(
|
|||||||
error = placeholder,
|
error = placeholder,
|
||||||
placeholder = placeholder
|
placeholder = placeholder
|
||||||
)
|
)
|
||||||
} else {
|
|
||||||
Image(
|
|
||||||
painter = placeholder,
|
|
||||||
contentDescription = description,
|
|
||||||
modifier = modifier
|
|
||||||
.size(size)
|
|
||||||
.clip(shape),
|
|
||||||
contentScale = ContentScale.Crop
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package su.reya.coop
|
|
||||||
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
|
|
||||||
interface ConnectivityMonitor {
|
|
||||||
val isMobileData: StateFlow<Boolean>
|
|
||||||
}
|
|
||||||
@@ -30,8 +30,7 @@ data class Room(
|
|||||||
val subject: String?,
|
val subject: String?,
|
||||||
val members: Set<PublicKey>,
|
val members: Set<PublicKey>,
|
||||||
val kind: RoomKind = RoomKind.default(),
|
val kind: RoomKind = RoomKind.default(),
|
||||||
val lastMessage: String? = null,
|
val lastMessage: String? = null
|
||||||
val unreadCount: Int = 0
|
|
||||||
) : Comparable<Room> {
|
) : Comparable<Room> {
|
||||||
override fun compareTo(other: Room): Int {
|
override fun compareTo(other: Room): Int {
|
||||||
return this.createdAt.asSecs().compareTo(other.createdAt.asSecs())
|
return this.createdAt.asSecs().compareTo(other.createdAt.asSecs())
|
||||||
@@ -72,7 +71,7 @@ data class RoomUiState(
|
|||||||
val isGroup: Boolean = false
|
val isGroup: Boolean = false
|
||||||
)
|
)
|
||||||
|
|
||||||
fun Room.uiStateFlow(
|
fun Room.flow(
|
||||||
profileCache: ProfileCache,
|
profileCache: ProfileCache,
|
||||||
currentUser: PublicKey? = null
|
currentUser: PublicKey? = null
|
||||||
): Flow<RoomUiState> {
|
): Flow<RoomUiState> {
|
||||||
@@ -114,7 +113,12 @@ fun UnsignedEvent.roomId(): Long {
|
|||||||
pubkeys.add(this.author())
|
pubkeys.add(this.author())
|
||||||
pubkeys.addAll(this.tags().publicKeys())
|
pubkeys.addAll(this.tags().publicKeys())
|
||||||
|
|
||||||
return pubkeys.map { it.toBech32() }.distinct().sorted().hashCode().toLong()
|
// Sort and hash the list of public keys
|
||||||
|
val sortedUniqueKeys = pubkeys
|
||||||
|
.distinctBy { it.toBech32() }
|
||||||
|
.sortedBy { it.toBech32() }
|
||||||
|
|
||||||
|
return sortedUniqueKeys.hashCode().toLong()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Timestamp.formatAsTime(): String {
|
fun Timestamp.formatAsTime(): String {
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
package su.reya.coop
|
|
||||||
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Settings(
|
|
||||||
val theme: Theme = Theme.System,
|
|
||||||
val dynamicColor: Boolean = true,
|
|
||||||
val media: MediaConfig = MediaConfig.AlwaysEnabled,
|
|
||||||
val screening: Boolean = true,
|
|
||||||
val blossomServer: String? = "https://blossom.band",
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
enum class Theme {
|
|
||||||
Light, Dark, System
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
enum class MediaConfig {
|
|
||||||
Disabled, DisabledForMobileData, AlwaysEnabled
|
|
||||||
}
|
|
||||||
@@ -39,11 +39,12 @@ class MessageManager(private val nostr: Nostr) {
|
|||||||
private val client: Client? get() = nostr.client
|
private val client: Client? get() = nostr.client
|
||||||
private val signer: UniversalSigner get() = nostr.signer
|
private val signer: UniversalSigner get() = nostr.signer
|
||||||
|
|
||||||
|
val sentEvents: MutableMap<EventId, List<RelayUrl>> = mutableMapOf()
|
||||||
|
val rumorMap: MutableMap<EventId, EventId> = mutableMapOf()
|
||||||
|
|
||||||
private val _messageSyncState = MutableStateFlow(MessageSyncState())
|
private val _messageSyncState = MutableStateFlow(MessageSyncState())
|
||||||
val messageSyncState = _messageSyncState.asStateFlow()
|
val messageSyncState = _messageSyncState.asStateFlow()
|
||||||
|
|
||||||
val rumorMap: MutableMap<EventId, EventId> = mutableMapOf()
|
|
||||||
|
|
||||||
fun updateSyncState(update: (MessageSyncState) -> MessageSyncState) {
|
fun updateSyncState(update: (MessageSyncState) -> MessageSyncState) {
|
||||||
_messageSyncState.update(update)
|
_messageSyncState.update(update)
|
||||||
}
|
}
|
||||||
@@ -72,8 +73,6 @@ class MessageManager(private val nostr: Nostr) {
|
|||||||
target = ReqTarget.manual(target),
|
target = ReqTarget.manual(target),
|
||||||
id = "gift-wraps"
|
id = "gift-wraps"
|
||||||
)
|
)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to fetch user messages: ${e.message}", e)
|
throw IllegalStateException("Failed to fetch user messages: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -226,8 +225,6 @@ class MessageManager(private val nostr: Nostr) {
|
|||||||
// Filter out events without public keys (receivers)
|
// Filter out events without public keys (receivers)
|
||||||
?.filter { it.tags().publicKeys().isNotEmpty() }
|
?.filter { it.tags().publicKeys().isNotEmpty() }
|
||||||
?.sortedByDescending { it.createdAt().asSecs() } ?: emptyList()
|
?.sortedByDescending { it.createdAt().asSecs() } ?: emptyList()
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to get chat room messages: ${e.message}", e)
|
throw IllegalStateException("Failed to get chat room messages: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -251,8 +248,6 @@ class MessageManager(private val nostr: Nostr) {
|
|||||||
connectMsgRelays(event)
|
connectMsgRelays(event)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to fetch relays: ${e.message}", e)
|
throw IllegalStateException("Failed to fetch relays: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -332,6 +327,9 @@ class MessageManager(private val nostr: Nostr) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
if (output != null) {
|
if (output != null) {
|
||||||
|
// Keep track of sent events
|
||||||
|
sentEvents[output.id] = emptyList()
|
||||||
|
|
||||||
// Keep track of rumor IDs
|
// Keep track of rumor IDs
|
||||||
val id = rumor.id() ?: throw IllegalStateException("Rumor ID is null")
|
val id = rumor.id() ?: throw IllegalStateException("Rumor ID is null")
|
||||||
rumorMap[id] = output.id
|
rumorMap[id] = output.id
|
||||||
@@ -342,8 +340,6 @@ class MessageManager(private val nostr: Nostr) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to send message: ${e.message}", e)
|
throw IllegalStateException("Failed to send message: ${e.message}", e)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ import kotlinx.coroutines.flow.MutableSharedFlow
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asSharedFlow
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.supervisorScope
|
import kotlinx.coroutines.supervisorScope
|
||||||
import kotlinx.coroutines.withTimeoutOrNull
|
|
||||||
import rust.nostr.sdk.AsyncNostrSigner
|
import rust.nostr.sdk.AsyncNostrSigner
|
||||||
import rust.nostr.sdk.Client
|
import rust.nostr.sdk.Client
|
||||||
import rust.nostr.sdk.ClientBuilder
|
import rust.nostr.sdk.ClientBuilder
|
||||||
@@ -108,6 +108,14 @@ class Nostr(
|
|||||||
relays.connectBootstrapRelays()
|
relays.connectBootstrapRelays()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun reconnect() {
|
||||||
|
relays.reconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun disconnect() {
|
||||||
|
relays.disconnect()
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun prune() {
|
suspend fun prune() {
|
||||||
try {
|
try {
|
||||||
client?.database()?.wipe()
|
client?.database()?.wipe()
|
||||||
@@ -154,10 +162,7 @@ class Nostr(
|
|||||||
|
|
||||||
// Trigger new message notification
|
// Trigger new message notification
|
||||||
if (rumor != null) {
|
if (rumor != null) {
|
||||||
val isSelfMessage = rumor.author() == signer.publicKeyFlow.value
|
if (rumor.createdAt().asSecs() >= now.asSecs()) {
|
||||||
val isNew = rumor.createdAt().asSecs() >= now.asSecs()
|
|
||||||
|
|
||||||
if (isNew && !isSelfMessage) {
|
|
||||||
onNewMessage(rumor)
|
onNewMessage(rumor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -177,6 +182,8 @@ class Nostr(
|
|||||||
|
|
||||||
when (notification) {
|
when (notification) {
|
||||||
is ClientNotification.Message -> {
|
is ClientNotification.Message -> {
|
||||||
|
val relayUrl = notification.relayUrl
|
||||||
|
|
||||||
when (val message = notification.message.asEnum()) {
|
when (val message = notification.message.asEnum()) {
|
||||||
is RelayMessageEnum.EventMsg -> {
|
is RelayMessageEnum.EventMsg -> {
|
||||||
val event = message.event
|
val event = message.event
|
||||||
@@ -230,6 +237,14 @@ class Nostr(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
is RelayMessageEnum.Ok -> {
|
||||||
|
if (messages.sentEvents.containsKey(message.eventId)) {
|
||||||
|
val currentRelays =
|
||||||
|
messages.sentEvents[message.eventId] ?: emptyList()
|
||||||
|
messages.sentEvents[message.eventId] = currentRelays + relayUrl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
/* Ignore other message types */
|
/* Ignore other message types */
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ import rust.nostr.sdk.ReqTarget
|
|||||||
import rust.nostr.sdk.SendEventTarget
|
import rust.nostr.sdk.SendEventTarget
|
||||||
import rust.nostr.sdk.SubscribeAutoCloseOptions
|
import rust.nostr.sdk.SubscribeAutoCloseOptions
|
||||||
import rust.nostr.sdk.Timestamp
|
import rust.nostr.sdk.Timestamp
|
||||||
import kotlin.coroutines.cancellation.CancellationException
|
|
||||||
import kotlin.time.Duration
|
import kotlin.time.Duration
|
||||||
|
|
||||||
class ProfileManager(private val nostr: Nostr) {
|
class ProfileManager(private val nostr: Nostr) {
|
||||||
@@ -81,8 +80,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
val opts = SubscribeAutoCloseOptions().exitPolicy(ReqExitPolicy.ExitOnEose)
|
val opts = SubscribeAutoCloseOptions().exitPolicy(ReqExitPolicy.ExitOnEose)
|
||||||
|
|
||||||
client?.subscribe(target = target, id = "user-metadata", closeOn = opts)
|
client?.subscribe(target = target, id = "user-metadata", closeOn = opts)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to fetch user metadata: ${e.message}", e)
|
throw IllegalStateException("Failed to fetch user metadata: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -95,8 +92,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
val relays = RelayManager.BOOTSTRAP_RELAYS.map { RelayUrl.parse(it) }
|
val relays = RelayManager.BOOTSTRAP_RELAYS.map { RelayUrl.parse(it) }
|
||||||
|
|
||||||
client?.sync(filter, relays)
|
client?.sync(filter, relays)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("Failed to sync mutual contacts: ${e.message}")
|
println("Failed to sync mutual contacts: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -179,8 +174,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return newMetadata
|
return newMetadata
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to update identity: ${e.message}", e)
|
throw IllegalStateException("Failed to update identity: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -193,8 +186,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
val event = client?.database()?.query(filter)?.first() ?: return null
|
val event = client?.database()?.query(filter)?.first() ?: return null
|
||||||
|
|
||||||
Metadata.fromJson(event.content())
|
Metadata.fromJson(event.content())
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("Failed to get latest metadata: ${e.message}")
|
println("Failed to get latest metadata: ${e.message}")
|
||||||
null
|
null
|
||||||
@@ -217,8 +208,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return results
|
return results
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("Failed to get all cache metadata: ${e.message}")
|
println("Failed to get all cache metadata: ${e.message}")
|
||||||
return emptyMap()
|
return emptyMap()
|
||||||
@@ -243,8 +232,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
client?.subscribe(target = ReqTarget.manual(target), closeOn = opts)
|
client?.subscribe(target = ReqTarget.manual(target), closeOn = opts)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to fetch metadata batch: ${e.message}", e)
|
throw IllegalStateException("Failed to fetch metadata batch: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -260,8 +247,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
target = SendEventTarget.broadcast(),
|
target = SendEventTarget.broadcast(),
|
||||||
ackPolicy = AckPolicy.none(),
|
ackPolicy = AckPolicy.none(),
|
||||||
)
|
)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to set contact list: ${e.message}", e)
|
throw IllegalStateException("Failed to set contact list: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -273,8 +258,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
val bodyString: String = response.body()
|
val bodyString: String = response.body()
|
||||||
|
|
||||||
return Nip05Profile.fromJson(address, bodyString)
|
return Nip05Profile.fromJson(address, bodyString)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to fetch profile from address: ${e.message}", e)
|
throw IllegalStateException("Failed to fetch profile from address: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -286,8 +269,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
val profile = profileFromAddress(httpClient, address)
|
val profile = profileFromAddress(httpClient, address)
|
||||||
|
|
||||||
return profile.publicKey()
|
return profile.publicKey()
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to search address: ${e.message}", e)
|
throw IllegalStateException("Failed to search address: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -323,8 +304,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return results
|
return results
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to search nostr: ${e.message}", e)
|
throw IllegalStateException("Failed to search nostr: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -344,8 +323,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return events?.first()?.createdAt()
|
return events?.first()?.createdAt()
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to get latest activity: ${e.message}", e)
|
throw IllegalStateException("Failed to get latest activity: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -363,8 +340,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
val pubkeys = events?.first()?.tags()?.publicKeys() ?: listOf()
|
val pubkeys = events?.first()?.tags()?.publicKeys() ?: listOf()
|
||||||
|
|
||||||
return pubkeys.contains(pubkey)
|
return pubkeys.contains(pubkey)
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to get mutual contacts: ${e.message}", e)
|
throw IllegalStateException("Failed to get mutual contacts: ${e.message}", e)
|
||||||
}
|
}
|
||||||
@@ -386,8 +361,6 @@ class ProfileManager(private val nostr: Nostr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return contacts.toSet()
|
return contacts.toSet()
|
||||||
} catch (e: CancellationException) {
|
|
||||||
throw e
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
throw IllegalStateException("Failed to get mutual contacts: ${e.message}", e)
|
throw IllegalStateException("Failed to get mutual contacts: ${e.message}", e)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ class RelayManager(private val nostr: Nostr) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun setRelayList(relays: Map<RelayUrl, RelayMetadata?>) {
|
suspend fun setRelaylist(relays: Map<RelayUrl, RelayMetadata?>) {
|
||||||
try {
|
try {
|
||||||
val event = EventBuilder.relayList(relays).finalizeAsync(signer)
|
val event = EventBuilder.relayList(relays).finalizeAsync(signer)
|
||||||
|
|
||||||
|
|||||||
@@ -47,17 +47,13 @@ data class AccountState(
|
|||||||
val signerRequired: Boolean? = null,
|
val signerRequired: Boolean? = null,
|
||||||
val isNotificationBannerDismissed: Boolean = false,
|
val isNotificationBannerDismissed: Boolean = false,
|
||||||
val isImporting: Boolean = false,
|
val isImporting: Boolean = false,
|
||||||
val isRelayListEmpty: Boolean = false,
|
val importError: String? = null,
|
||||||
val contactList: Set<PublicKey> = emptySet(),
|
|
||||||
val userRelayList: Map<RelayUrl, RelayMetadata?> = emptyMap(),
|
|
||||||
val userMsgRelayList: List<RelayUrl> = emptyList(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
class AccountRepository(
|
class AccountRepository(
|
||||||
private val nostr: Nostr,
|
private val nostr: Nostr,
|
||||||
private val storage: AppStorage,
|
private val storage: AppStorage,
|
||||||
private val mediaRepository: MediaRepository,
|
private val mediaRepository: MediaRepository,
|
||||||
private val settingsRepository: SettingsRepository,
|
|
||||||
private val scope: CoroutineScope,
|
private val scope: CoroutineScope,
|
||||||
private val externalSignerHandler: ExternalSignerHandler? = null,
|
private val externalSignerHandler: ExternalSignerHandler? = null,
|
||||||
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
|
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
|
||||||
@@ -76,9 +72,23 @@ class AccountRepository(
|
|||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
val currentUserProfile: StateFlow<Profile?> = nostr.signer.publicKeyFlow
|
val currentUserProfile: StateFlow<Profile?> = nostr.signer.publicKeyFlow
|
||||||
.flatMapLatest { if (it != null) currentUserProfileFlow(it) else flowOf(null) }
|
.flatMapLatest { pubkey ->
|
||||||
|
if (pubkey != null) currentUserProfileFlow(pubkey) else flowOf(null)
|
||||||
|
}
|
||||||
.stateIn(scope, SharingStarted.WhileSubscribed(5000), null)
|
.stateIn(scope, SharingStarted.WhileSubscribed(5000), null)
|
||||||
|
|
||||||
|
private val _contactList = MutableStateFlow<Set<PublicKey>>(emptySet())
|
||||||
|
val contactList: StateFlow<Set<PublicKey>> = _contactList.asStateFlow()
|
||||||
|
|
||||||
|
private val _isRelayListEmpty = MutableStateFlow(false)
|
||||||
|
val isRelayListEmpty: StateFlow<Boolean> = _isRelayListEmpty.asStateFlow()
|
||||||
|
|
||||||
|
private val _userRelayList = MutableStateFlow<Map<RelayUrl, RelayMetadata?>>(emptyMap())
|
||||||
|
val userRelayList: StateFlow<Map<RelayUrl, RelayMetadata?>> = _userRelayList.asStateFlow()
|
||||||
|
|
||||||
|
private val _userMsgRelayList = MutableStateFlow<List<RelayUrl>>(emptyList())
|
||||||
|
val userMsgRelayList: StateFlow<List<RelayUrl>> = _userMsgRelayList.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
checkNotificationBannerDismissedStatus()
|
checkNotificationBannerDismissedStatus()
|
||||||
login()
|
login()
|
||||||
@@ -106,7 +116,7 @@ class AccountRepository(
|
|||||||
} ?: emptyList()
|
} ?: emptyList()
|
||||||
|
|
||||||
// Automatically update the warning state
|
// Automatically update the warning state
|
||||||
_state.update { it.copy(isRelayListEmpty = relays.isEmpty()) }
|
_isRelayListEmpty.value = relays.isEmpty()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,7 +229,7 @@ class AccountRepository(
|
|||||||
|
|
||||||
fun importIdentity(secret: String, password: String? = null) {
|
fun importIdentity(secret: String, password: String? = null) {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
_state.update { it.copy(isImporting = true) }
|
_state.update { it.copy(isImporting = true, importError = null) }
|
||||||
try {
|
try {
|
||||||
val (signer, decryptedSecret) = createSigner(secret, password)
|
val (signer, decryptedSecret) = createSigner(secret, password)
|
||||||
|
|
||||||
@@ -229,14 +239,14 @@ class AccountRepository(
|
|||||||
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Import failed: ${e.message}")
|
showError("Import failed: ${e.message}")
|
||||||
_state.update { it.copy(isImporting = false) }
|
_state.update { it.copy(isImporting = false, importError = e.message) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun connectExternalSigner() {
|
fun connectExternalSigner() {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
_state.update { it.copy(isImporting = true) }
|
_state.update { it.copy(isImporting = true, importError = null) }
|
||||||
try {
|
try {
|
||||||
val handler =
|
val handler =
|
||||||
externalSignerHandler ?: throw IllegalStateException("Signer not available")
|
externalSignerHandler ?: throw IllegalStateException("Signer not available")
|
||||||
@@ -266,7 +276,7 @@ class AccountRepository(
|
|||||||
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("External signer connection failed: ${e.message}")
|
showError("External signer connection failed: ${e.message}")
|
||||||
_state.update { it.copy(isImporting = false) }
|
_state.update { it.copy(isImporting = false, importError = e.message) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -278,7 +288,7 @@ class AccountRepository(
|
|||||||
contentType: String? = null
|
contentType: String? = null
|
||||||
) {
|
) {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
_state.update { it.copy(isImporting = true) }
|
_state.update { it.copy(isImporting = true, importError = null) }
|
||||||
try {
|
try {
|
||||||
val keys = Keys.generate()
|
val keys = Keys.generate()
|
||||||
val secret = keys.secretKey().toBech32()
|
val secret = keys.secretKey().toBech32()
|
||||||
@@ -297,7 +307,7 @@ class AccountRepository(
|
|||||||
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
_state.update { it.copy(signerRequired = false, isImporting = false) }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Identity creation failed: ${e.message}")
|
showError("Identity creation failed: ${e.message}")
|
||||||
_state.update { it.copy(isImporting = false) }
|
_state.update { it.copy(isImporting = false, importError = e.message) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -345,13 +355,14 @@ class AccountRepository(
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
nostr.waitUntilInitialized()
|
nostr.waitUntilInitialized()
|
||||||
nostr.profiles.contactListUpdates.collect { contacts ->
|
nostr.profiles.contactListUpdates.collect { contacts ->
|
||||||
_state.update { it.copy(contactList = contacts.toSet()) }
|
_contactList.value = contacts.toSet()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun resetInternalState() {
|
fun resetInternalState() {
|
||||||
_state.update { it.copy(contactList = emptySet(), isRelayListEmpty = false) }
|
_contactList.value = emptySet()
|
||||||
|
_isRelayListEmpty.value = false
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addContact(address: String) {
|
fun addContact(address: String) {
|
||||||
@@ -367,12 +378,12 @@ class AccountRepository(
|
|||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pubkey in _state.value.contactList) return@launch
|
if (pubkey in _contactList.value) return@launch
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val updated = _state.value.contactList + pubkey
|
val updated = _contactList.value + pubkey
|
||||||
nostr.profiles.setContactList(updated.toList())
|
nostr.profiles.setContactList(updated.toList())
|
||||||
_state.update { it.copy(contactList = it.contactList + pubkey) }
|
_contactList.update { it + pubkey }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -381,12 +392,12 @@ class AccountRepository(
|
|||||||
|
|
||||||
fun removeContact(publicKey: PublicKey) {
|
fun removeContact(publicKey: PublicKey) {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
if (publicKey !in _state.value.contactList) return@launch
|
if (publicKey !in _contactList.value) return@launch
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val updated = _state.value.contactList - publicKey
|
val updated = _contactList.value - publicKey
|
||||||
nostr.profiles.setContactList(updated.toList())
|
nostr.profiles.setContactList(updated.toList())
|
||||||
_state.update { it.copy(contactList = it.contactList - publicKey) }
|
_contactList.update { it - publicKey }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -449,7 +460,7 @@ class AccountRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun dismissRelayWarning() {
|
fun dismissRelayWarning() {
|
||||||
_state.update { it.copy(isRelayListEmpty = false) }
|
_isRelayListEmpty.value = false
|
||||||
}
|
}
|
||||||
|
|
||||||
fun refetchMsgRelays() {
|
fun refetchMsgRelays() {
|
||||||
@@ -476,8 +487,7 @@ class AccountRepository(
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val user = nostr.signer.getPublicKeyAsync() ?: throw Exception("User not found")
|
val user = nostr.signer.getPublicKeyAsync() ?: throw Exception("User not found")
|
||||||
val relayList = nostr.relays.getRelayList(user)
|
_userRelayList.value = nostr.relays.getRelayList(user)
|
||||||
_state.update { it.copy(userRelayList = relayList) }
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -501,7 +511,7 @@ class AccountRepository(
|
|||||||
val relays = currentUserRelayListInternal().toMutableMap()
|
val relays = currentUserRelayListInternal().toMutableMap()
|
||||||
relays[relayUrl] = RelayMetadata.WRITE
|
relays[relayUrl] = RelayMetadata.WRITE
|
||||||
|
|
||||||
nostr.relays.setRelayList(relays)
|
nostr.relays.setRelaylist(relays)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -515,7 +525,7 @@ class AccountRepository(
|
|||||||
val relays = currentUserRelayListInternal().toMutableMap()
|
val relays = currentUserRelayListInternal().toMutableMap()
|
||||||
relays[relayUrl] = RelayMetadata.READ
|
relays[relayUrl] = RelayMetadata.READ
|
||||||
|
|
||||||
nostr.relays.setRelayList(relays)
|
nostr.relays.setRelaylist(relays)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -529,7 +539,7 @@ class AccountRepository(
|
|||||||
val relays = currentUserRelayListInternal().toMutableMap()
|
val relays = currentUserRelayListInternal().toMutableMap()
|
||||||
relays.remove(relayUrl)
|
relays.remove(relayUrl)
|
||||||
|
|
||||||
nostr.relays.setRelayList(relays)
|
nostr.relays.setRelaylist(relays)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
@@ -540,8 +550,7 @@ class AccountRepository(
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val user = nostr.signer.getPublicKeyAsync() ?: throw Exception("User not found")
|
val user = nostr.signer.getPublicKeyAsync() ?: throw Exception("User not found")
|
||||||
val msgRelays = nostr.relays.getMsgRelays(user)
|
_userMsgRelayList.value = nostr.relays.getMsgRelays(user)
|
||||||
_state.update { it.copy(userMsgRelayList = msgRelays) }
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
showError("Error: ${e.message}")
|
showError("Error: ${e.message}")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import kotlinx.coroutines.flow.MutableSharedFlow
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.asSharedFlow
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
@@ -22,7 +21,6 @@ import rust.nostr.sdk.PublicKey
|
|||||||
import rust.nostr.sdk.Tag
|
import rust.nostr.sdk.Tag
|
||||||
import rust.nostr.sdk.UnsignedEvent
|
import rust.nostr.sdk.UnsignedEvent
|
||||||
import su.reya.coop.Room
|
import su.reya.coop.Room
|
||||||
import su.reya.coop.RoomKind
|
|
||||||
import su.reya.coop.nostr.Nostr
|
import su.reya.coop.nostr.Nostr
|
||||||
import su.reya.coop.roomId
|
import su.reya.coop.roomId
|
||||||
import su.reya.coop.viewmodel.ErrorHost
|
import su.reya.coop.viewmodel.ErrorHost
|
||||||
@@ -36,12 +34,15 @@ data class ChatState(
|
|||||||
class ChatRepository(
|
class ChatRepository(
|
||||||
private val nostr: Nostr,
|
private val nostr: Nostr,
|
||||||
private val mediaRepository: MediaRepository,
|
private val mediaRepository: MediaRepository,
|
||||||
private val settingsRepository: SettingsRepository,
|
|
||||||
private val scope: CoroutineScope,
|
private val scope: CoroutineScope,
|
||||||
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
|
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
|
||||||
) : ErrorHost by createErrorHost() {
|
) : ErrorHost by createErrorHost() {
|
||||||
private val _state = MutableStateFlow(ChatState())
|
private val _state = MutableStateFlow(ChatState())
|
||||||
val state = _state.asStateFlow()
|
val state = _state.stateIn(
|
||||||
|
scope,
|
||||||
|
SharingStarted.WhileSubscribed(5000),
|
||||||
|
ChatState()
|
||||||
|
)
|
||||||
|
|
||||||
private val _newEvents = MutableSharedFlow<UnsignedEvent>(
|
private val _newEvents = MutableSharedFlow<UnsignedEvent>(
|
||||||
replay = 0,
|
replay = 0,
|
||||||
@@ -50,16 +51,13 @@ class ChatRepository(
|
|||||||
)
|
)
|
||||||
val newEvents = _newEvents.asSharedFlow()
|
val newEvents = _newEvents.asSharedFlow()
|
||||||
|
|
||||||
val chatRooms = state
|
val chatRooms = state.map { it.rooms.values.sortedByDescending { it.createdAt.asSecs() } }
|
||||||
.map { it.rooms.values.sortedByDescending { it.createdAt.asSecs() } }
|
|
||||||
.stateIn(scope, SharingStarted.WhileSubscribed(5000), emptyList())
|
.stateIn(scope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||||
|
|
||||||
val isSyncing = nostr.messages.messageSyncState
|
val isSyncing = nostr.messages.messageSyncState.map { it.isSyncing }
|
||||||
.map { it.isSyncing }
|
|
||||||
.stateIn(scope, SharingStarted.WhileSubscribed(5000), false)
|
.stateIn(scope, SharingStarted.WhileSubscribed(5000), false)
|
||||||
|
|
||||||
val isPartialProcessedGiftWrap = state
|
val isPartialProcessedGiftWrap = state.map { it.isPartialProcessedGiftWrap }
|
||||||
.map { it.isPartialProcessedGiftWrap }
|
|
||||||
.stateIn(scope, SharingStarted.WhileSubscribed(5000), false)
|
.stateIn(scope, SharingStarted.WhileSubscribed(5000), false)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
@@ -84,7 +82,18 @@ class ChatRepository(
|
|||||||
// Observe new messages
|
// Observe new messages
|
||||||
launch {
|
launch {
|
||||||
nostr.newEvents.collect { event ->
|
nostr.newEvents.collect { event ->
|
||||||
updateRoomState(event)
|
val roomId = event.roomId()
|
||||||
|
val existingRoom = _state.value.rooms[roomId]
|
||||||
|
|
||||||
|
if (existingRoom == null) {
|
||||||
|
val currentUser = nostr.signer.getPublicKeyAsync() ?: return@collect
|
||||||
|
val newRoom = Room.new(event, currentUser)
|
||||||
|
_state.update { it.copy(rooms = it.rooms + (newRoom.id to newRoom)) }
|
||||||
|
} else {
|
||||||
|
updateRoomList(roomId, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
_newEvents.tryEmit(event)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,39 +139,13 @@ class ChatRepository(
|
|||||||
return _state.value.rooms[id]
|
return _state.value.rooms[id]
|
||||||
}
|
}
|
||||||
|
|
||||||
fun markAsRead(roomId: Long) {
|
|
||||||
_state.update { currentState ->
|
|
||||||
val rooms = currentState.rooms.toMutableMap()
|
|
||||||
val room = rooms[roomId]
|
|
||||||
if (room != null && room.unreadCount > 0) {
|
|
||||||
rooms[roomId] = room.copy(unreadCount = 0)
|
|
||||||
currentState.copy(rooms = rooms)
|
|
||||||
} else {
|
|
||||||
currentState
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun refreshChatRooms() {
|
fun refreshChatRooms() {
|
||||||
scope.launch(defaultDispatcher) {
|
scope.launch(defaultDispatcher) {
|
||||||
try {
|
try {
|
||||||
val dbRooms = nostr.messages.getChatRooms() ?: emptySet()
|
val rooms = nostr.messages.getChatRooms() ?: emptySet()
|
||||||
_state.update { currentState ->
|
_state.update { currentState ->
|
||||||
val newMap = currentState.rooms.toMutableMap()
|
val newMap = currentState.rooms.toMutableMap()
|
||||||
dbRooms.forEach { dbRoom ->
|
rooms.forEach { room -> newMap[room.id] = room }
|
||||||
val existing = newMap[dbRoom.id]
|
|
||||||
// Only update if the database version is newer or equal
|
|
||||||
if (existing == null || dbRoom.createdAt.asSecs() >= existing.createdAt.asSecs()) {
|
|
||||||
// Preserve Ongoing kind and unreadCount status if already marked as such in memory
|
|
||||||
val mergedKind =
|
|
||||||
if (existing?.kind == RoomKind.Ongoing) RoomKind.Ongoing else dbRoom.kind
|
|
||||||
val mergedUnreadCount = existing?.unreadCount ?: 0
|
|
||||||
newMap[dbRoom.id] = dbRoom.copy(
|
|
||||||
kind = mergedKind,
|
|
||||||
unreadCount = mergedUnreadCount
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
currentState.copy(rooms = newMap)
|
currentState.copy(rooms = newMap)
|
||||||
}
|
}
|
||||||
} catch (e: CancellationException) {
|
} catch (e: CancellationException) {
|
||||||
@@ -211,10 +194,9 @@ class ChatRepository(
|
|||||||
content = message,
|
content = message,
|
||||||
subject = room.subject,
|
subject = room.subject,
|
||||||
replies = replies,
|
replies = replies,
|
||||||
onRumorCreated = {
|
onRumorCreated = { event ->
|
||||||
scope.launch(defaultDispatcher) {
|
updateRoomList(roomId, event)
|
||||||
updateRoomState(it, roomId)
|
scope.launch(defaultDispatcher) { _newEvents.tryEmit(event) }
|
||||||
}
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -241,44 +223,26 @@ class ChatRepository(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun updateRoomState(event: UnsignedEvent, roomId: Long = event.roomId()) {
|
fun isMessageSent(id: EventId): Boolean {
|
||||||
val currentUser = nostr.signer.getPublicKeyAsync() ?: return
|
val giftWrapId = nostr.messages.rumorMap[id]
|
||||||
|
|
||||||
_state.update { currentState ->
|
if (giftWrapId != null) {
|
||||||
val rooms = currentState.rooms.toMutableMap()
|
val isSent = nostr.messages.sentEvents[giftWrapId]?.isNotEmpty() ?: false
|
||||||
val existingRoom = rooms[roomId]
|
return isSent
|
||||||
|
|
||||||
val isFromMe = event.author() == currentUser
|
|
||||||
val newKind =
|
|
||||||
if (isFromMe) RoomKind.Ongoing else (existingRoom?.kind ?: RoomKind.Request)
|
|
||||||
|
|
||||||
if (existingRoom == null) {
|
|
||||||
// New room discovery
|
|
||||||
val newRoom = Room.new(event, currentUser, roomId).copy(
|
|
||||||
kind = newKind,
|
|
||||||
unreadCount = if (isFromMe) 0 else 1
|
|
||||||
)
|
|
||||||
rooms[newRoom.id] = newRoom
|
|
||||||
} else if (event.createdAt().asSecs() >= existingRoom.createdAt.asSecs()) {
|
|
||||||
// Only update preview if message is newer (handles sync/late arrivals)
|
|
||||||
rooms[roomId] = existingRoom.copy(
|
|
||||||
lastMessage = event.content(),
|
|
||||||
createdAt = event.createdAt(),
|
|
||||||
kind = newKind,
|
|
||||||
unreadCount = if (isFromMe) existingRoom.unreadCount else existingRoom.unreadCount + 1
|
|
||||||
)
|
|
||||||
} else if (isFromMe && existingRoom.kind != RoomKind.Ongoing) {
|
|
||||||
// Even if it's an older message, if it's from me, the room is ongoing
|
|
||||||
rooms[roomId] = existingRoom.copy(kind = RoomKind.Ongoing)
|
|
||||||
} else {
|
} else {
|
||||||
// Don't update the room list state for older messages
|
return false
|
||||||
return@update currentState
|
|
||||||
}
|
}
|
||||||
currentState.copy(rooms = rooms)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify subscribers about the new event (for the active chat screen)
|
private fun updateRoomList(roomId: Long, newMessage: UnsignedEvent) {
|
||||||
_newEvents.tryEmit(event)
|
_state.update { currentState ->
|
||||||
|
val room = currentState.rooms[roomId] ?: return@update currentState
|
||||||
|
val updatedRoom = room.copy(
|
||||||
|
lastMessage = newMessage.content(),
|
||||||
|
createdAt = newMessage.createdAt()
|
||||||
|
)
|
||||||
|
currentState.copy(rooms = currentState.rooms + (roomId to updatedRoom))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun resetInternalState() {
|
fun resetInternalState() {
|
||||||
|
|||||||
@@ -8,9 +8,7 @@ import kotlinx.serialization.json.Json
|
|||||||
import rust.nostr.sdk.AsyncNostrSigner
|
import rust.nostr.sdk.AsyncNostrSigner
|
||||||
import su.reya.coop.blossom.BlossomClient
|
import su.reya.coop.blossom.BlossomClient
|
||||||
|
|
||||||
class MediaRepository(
|
class MediaRepository {
|
||||||
private val settingsRepository: SettingsRepository
|
|
||||||
) {
|
|
||||||
private val httpClient = HttpClient {
|
private val httpClient = HttpClient {
|
||||||
install(ContentNegotiation) {
|
install(ContentNegotiation) {
|
||||||
json(Json {
|
json(Json {
|
||||||
@@ -27,9 +25,12 @@ class MediaRepository(
|
|||||||
contentType: String? = "image/jpeg"
|
contentType: String? = "image/jpeg"
|
||||||
): String? {
|
): String? {
|
||||||
return try {
|
return try {
|
||||||
val url = settingsRepository.settings.value.blossomServer ?: "https://blossom.band"
|
val blossom = BlossomClient(url = "https://blossom.band", client = httpClient)
|
||||||
val blossom = BlossomClient(url, httpClient)
|
val descriptor = blossom.upload(
|
||||||
val descriptor = blossom.upload(file = file, contentType = contentType, signer = signer)
|
file = file,
|
||||||
|
contentType = contentType,
|
||||||
|
signer = signer,
|
||||||
|
)
|
||||||
descriptor?.url
|
descriptor?.url
|
||||||
} catch (e: CancellationException) {
|
} catch (e: CancellationException) {
|
||||||
throw e
|
throw e
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
package su.reya.coop.repository
|
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.serialization.encodeToString
|
|
||||||
import kotlinx.serialization.json.Json
|
|
||||||
import su.reya.coop.AppStorage
|
|
||||||
import su.reya.coop.Settings
|
|
||||||
|
|
||||||
class SettingsRepository(
|
|
||||||
private val storage: AppStorage,
|
|
||||||
private val scope: CoroutineScope
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
private const val KEY_SETTINGS = "app_settings"
|
|
||||||
}
|
|
||||||
|
|
||||||
private val json = Json {
|
|
||||||
ignoreUnknownKeys = true
|
|
||||||
encodeDefaults = true
|
|
||||||
}
|
|
||||||
|
|
||||||
private val _settings = MutableStateFlow(Settings())
|
|
||||||
val settings: StateFlow<Settings> = _settings.asStateFlow()
|
|
||||||
|
|
||||||
init {
|
|
||||||
scope.launch {
|
|
||||||
_settings.value = load()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun update(transform: (Settings) -> Settings) {
|
|
||||||
scope.launch {
|
|
||||||
val newSettings = transform(_settings.value)
|
|
||||||
_settings.value = newSettings
|
|
||||||
save(newSettings)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun save(settings: Settings) {
|
|
||||||
val jsonString = json.encodeToString(settings)
|
|
||||||
storage.set(KEY_SETTINGS, jsonString)
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun load(): Settings {
|
|
||||||
val jsonString = storage.get(KEY_SETTINGS)
|
|
||||||
return if (jsonString != null) {
|
|
||||||
try {
|
|
||||||
json.decodeFromString<Settings>(jsonString)
|
|
||||||
} catch (_: Exception) {
|
|
||||||
Settings()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Settings()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,8 @@ package su.reya.coop.viewmodel
|
|||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import rust.nostr.sdk.PublicKey
|
import rust.nostr.sdk.PublicKey
|
||||||
|
import rust.nostr.sdk.RelayMetadata
|
||||||
|
import rust.nostr.sdk.RelayUrl
|
||||||
import rust.nostr.sdk.Timestamp
|
import rust.nostr.sdk.Timestamp
|
||||||
import su.reya.coop.Profile
|
import su.reya.coop.Profile
|
||||||
import su.reya.coop.repository.AccountRepository
|
import su.reya.coop.repository.AccountRepository
|
||||||
@@ -14,6 +16,10 @@ class AccountViewModel(
|
|||||||
val state: StateFlow<AccountState> = repository.state
|
val state: StateFlow<AccountState> = repository.state
|
||||||
val isUpdatingProfile: StateFlow<Boolean> = repository.isUpdatingProfile
|
val isUpdatingProfile: StateFlow<Boolean> = repository.isUpdatingProfile
|
||||||
val currentUserProfile: StateFlow<Profile?> = repository.currentUserProfile
|
val currentUserProfile: StateFlow<Profile?> = repository.currentUserProfile
|
||||||
|
val contactList: StateFlow<Set<PublicKey>> = repository.contactList
|
||||||
|
val isRelayListEmpty: StateFlow<Boolean> = repository.isRelayListEmpty
|
||||||
|
val userRelayList: StateFlow<Map<RelayUrl, RelayMetadata?>> = repository.userRelayList
|
||||||
|
val userMsgRelayList: StateFlow<List<RelayUrl>> = repository.userMsgRelayList
|
||||||
|
|
||||||
fun logout(onLogout: () -> Unit = {}) = repository.logout(onLogout)
|
fun logout(onLogout: () -> Unit = {}) = repository.logout(onLogout)
|
||||||
fun dismissNotificationBanner() = repository.dismissNotificationBanner()
|
fun dismissNotificationBanner() = repository.dismissNotificationBanner()
|
||||||
|
|||||||
@@ -7,30 +7,40 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import rust.nostr.sdk.EventId
|
import rust.nostr.sdk.EventId
|
||||||
import rust.nostr.sdk.UnsignedEvent
|
import rust.nostr.sdk.UnsignedEvent
|
||||||
import su.reya.coop.Profile
|
|
||||||
import su.reya.coop.Room
|
import su.reya.coop.Room
|
||||||
import su.reya.coop.repository.AccountRepository
|
import su.reya.coop.repository.AccountRepository
|
||||||
import su.reya.coop.repository.ChatRepository
|
import su.reya.coop.repository.ChatRepository
|
||||||
import su.reya.coop.roomId
|
import su.reya.coop.roomId
|
||||||
|
|
||||||
class ChatScreenViewModel(
|
class ChatScreenViewModel(
|
||||||
val id: Long,
|
initialRoom: Room,
|
||||||
screening: Boolean,
|
screening: Boolean,
|
||||||
accountRepository: AccountRepository,
|
accountRepository: AccountRepository,
|
||||||
private val chatRepository: ChatRepository,
|
private val chatRepository: ChatRepository,
|
||||||
) : ViewModel(), ErrorHost by chatRepository {
|
) : ViewModel(), ErrorHost by chatRepository {
|
||||||
val currentUser: StateFlow<Profile?> = accountRepository.currentUserProfile
|
|
||||||
val chatRooms: StateFlow<List<Room>> = chatRepository.chatRooms
|
|
||||||
|
|
||||||
var loading by mutableStateOf(true)
|
var loading by mutableStateOf(true)
|
||||||
var newOtherMessages by mutableIntStateOf(0)
|
var newOtherMessages by mutableIntStateOf(0)
|
||||||
var requireScreening by mutableStateOf(screening)
|
var requireScreening by mutableStateOf(screening)
|
||||||
val messages = mutableStateListOf<UnsignedEvent>()
|
val messages = mutableStateListOf<UnsignedEvent>()
|
||||||
|
|
||||||
|
val currentUser = accountRepository.currentUserProfile
|
||||||
|
val id = initialRoom.id
|
||||||
|
|
||||||
|
val room: StateFlow<Room> = chatRepository.chatRooms
|
||||||
|
.map { rooms -> rooms.find { it.id == id } ?: initialRoom }
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
|
initialValue = initialRoom
|
||||||
|
)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
loadMessages()
|
loadMessages()
|
||||||
connect()
|
connect()
|
||||||
@@ -42,8 +52,6 @@ class ChatScreenViewModel(
|
|||||||
messages.clear()
|
messages.clear()
|
||||||
messages.addAll(initialMessages.distinctBy { it.id() })
|
messages.addAll(initialMessages.distinctBy { it.id() })
|
||||||
loading = false
|
loading = false
|
||||||
// Mark the room as read once messages are loaded
|
|
||||||
chatRepository.markAsRead(id)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +65,6 @@ class ChatScreenViewModel(
|
|||||||
if (event.roomId() == id) {
|
if (event.roomId() == id) {
|
||||||
if (messages.none { it.id() == event.id() }) {
|
if (messages.none { it.id() == event.id() }) {
|
||||||
messages.add(0, event)
|
messages.add(0, event)
|
||||||
chatRepository.markAsRead(id)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
newOtherMessages++
|
newOtherMessages++
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import kotlin.time.Duration.Companion.milliseconds
|
|||||||
|
|
||||||
class ProfileCache(
|
class ProfileCache(
|
||||||
private val nostr: Nostr,
|
private val nostr: Nostr,
|
||||||
defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
|
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
|
||||||
) : ErrorHost by createErrorHost() {
|
) : ErrorHost by createErrorHost() {
|
||||||
private val scope = CoroutineScope(SupervisorJob() + defaultDispatcher)
|
private val scope = CoroutineScope(SupervisorJob() + defaultDispatcher)
|
||||||
private val profiles = MutableStateFlow<Map<PublicKey, MutableStateFlow<Profile?>>>(emptyMap())
|
private val profiles = MutableStateFlow<Map<PublicKey, MutableStateFlow<Profile?>>>(emptyMap())
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
package su.reya.coop.viewmodel
|
|
||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import su.reya.coop.Settings
|
|
||||||
import su.reya.coop.repository.SettingsRepository
|
|
||||||
|
|
||||||
class SettingsViewModel(
|
|
||||||
private val repository: SettingsRepository
|
|
||||||
) : ViewModel() {
|
|
||||||
val settings: StateFlow<Settings> = repository.settings
|
|
||||||
|
|
||||||
fun update(transform: (Settings) -> Settings) {
|
|
||||||
repository.update(transform)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user