Compare commits
14 Commits
ad54477d11
...
temp
| Author | SHA1 | Date | |
|---|---|---|---|
| 66deae6fc3 | |||
| 96ee5ea45e | |||
| dc5b4b3fb0 | |||
| a1278f7558 | |||
| 6b91d388a2 | |||
| 8c053905ce | |||
| 2381d4ca0a | |||
| 2daab8d0f7 | |||
| 10453287a7 | |||
| fc3b3cfcb3 | |||
| f11b8dc6f4 | |||
| 167f980f29 | |||
| d428af4ac4 | |||
| 63bae014c5 |
@@ -92,6 +92,7 @@ dependencies {
|
|||||||
implementation(projects.feature.photoviewer)
|
implementation(projects.feature.photoviewer)
|
||||||
implementation(projects.feature.createchat)
|
implementation(projects.feature.createchat)
|
||||||
|
|
||||||
|
implementation(projects.core.logger)
|
||||||
implementation(projects.core.common)
|
implementation(projects.core.common)
|
||||||
implementation(projects.core.ui)
|
implementation(projects.core.ui)
|
||||||
implementation(projects.core.data)
|
implementation(projects.core.data)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
xmlns:tools="http://schemas.android.com/tools">
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package dev.meloda.fast
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.util.Log
|
|
||||||
import androidx.appcompat.app.AppCompatDelegate
|
import androidx.appcompat.app.AppCompatDelegate
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.os.LocaleListCompat
|
import androidx.core.os.LocaleListCompat
|
||||||
@@ -23,66 +22,37 @@ import dev.meloda.fast.datastore.AppSettings
|
|||||||
import dev.meloda.fast.datastore.UserSettings
|
import dev.meloda.fast.datastore.UserSettings
|
||||||
import dev.meloda.fast.domain.GetCurrentAccountUseCase
|
import dev.meloda.fast.domain.GetCurrentAccountUseCase
|
||||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.model.BaseError
|
import dev.meloda.fast.model.BaseError
|
||||||
import dev.meloda.fast.model.api.domain.VkUser
|
import dev.meloda.fast.model.api.domain.VkUser
|
||||||
import dev.meloda.fast.navigation.Main
|
import dev.meloda.fast.navigation.Main
|
||||||
import dev.meloda.fast.settings.navigation.Settings
|
import dev.meloda.fast.settings.navigation.Settings
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
interface MainViewModel {
|
class MainViewModel(
|
||||||
|
|
||||||
val startDestination: StateFlow<Any?>
|
|
||||||
val isNeedToReplaceWithAuth: StateFlow<Boolean>
|
|
||||||
val currentUser: StateFlow<VkUser?>
|
|
||||||
|
|
||||||
val isNeedToShowNotificationsDeniedDialog: StateFlow<Boolean>
|
|
||||||
val isNeedToShowNotificationsRationaleDialog: StateFlow<Boolean>
|
|
||||||
val isNeedToCheckNotificationsPermission: StateFlow<Boolean>
|
|
||||||
val isNeedToRequestNotifications: StateFlow<Boolean>
|
|
||||||
|
|
||||||
fun onError(error: BaseError)
|
|
||||||
|
|
||||||
fun onNavigatedToAuth()
|
|
||||||
|
|
||||||
fun onAppResumed(intent: Intent)
|
|
||||||
|
|
||||||
@OptIn(ExperimentalPermissionsApi::class)
|
|
||||||
fun onPermissionCheckStatus(status: PermissionStatus)
|
|
||||||
fun onPermissionsRequested()
|
|
||||||
|
|
||||||
fun onNotificationsDeniedDialogConfirmClicked()
|
|
||||||
fun onNotificationsDeniedDialogCancelClicked()
|
|
||||||
fun onNotificationsDeniedDialogDismissed()
|
|
||||||
fun onNotificationsRationaleDialogDismissed()
|
|
||||||
fun onNotificationsRationaleDialogCancelClicked()
|
|
||||||
|
|
||||||
fun onUserAuthenticated()
|
|
||||||
}
|
|
||||||
|
|
||||||
class MainViewModelImpl(
|
|
||||||
private val getCurrentAccountUseCase: GetCurrentAccountUseCase,
|
private val getCurrentAccountUseCase: GetCurrentAccountUseCase,
|
||||||
private val loadUserByIdUseCase: LoadUserByIdUseCase,
|
private val loadUserByIdUseCase: LoadUserByIdUseCase,
|
||||||
private val userSettings: UserSettings,
|
private val userSettings: UserSettings,
|
||||||
private val longPollController: LongPollController
|
private val longPollController: LongPollController,
|
||||||
) : MainViewModel, ViewModel() {
|
private val logger: FastLogger
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
override val startDestination = MutableStateFlow<Any?>(null)
|
val startDestination = MutableStateFlow<Any?>(null)
|
||||||
override val isNeedToReplaceWithAuth = MutableStateFlow(false)
|
val isNeedToReplaceWithAuth = MutableStateFlow(false)
|
||||||
override val currentUser = MutableStateFlow<VkUser?>(null)
|
val currentUser = MutableStateFlow<VkUser?>(null)
|
||||||
|
|
||||||
override val isNeedToShowNotificationsDeniedDialog = MutableStateFlow(false)
|
val isNeedToShowNotificationsDeniedDialog = MutableStateFlow(false)
|
||||||
override val isNeedToShowNotificationsRationaleDialog = MutableStateFlow(false)
|
val isNeedToShowNotificationsRationaleDialog = MutableStateFlow(false)
|
||||||
override val isNeedToCheckNotificationsPermission = MutableStateFlow(false)
|
val isNeedToCheckNotificationsPermission = MutableStateFlow(false)
|
||||||
override val isNeedToRequestNotifications = MutableStateFlow(false)
|
val isNeedToRequestNotifications = MutableStateFlow(false)
|
||||||
|
|
||||||
private var openNotificationsSettings = false
|
private var openNotificationsSettings = false
|
||||||
private var openAppSettings = false
|
private var openAppSettings = false
|
||||||
|
|
||||||
override fun onError(error: BaseError) {
|
fun onError(error: BaseError) {
|
||||||
when (error) {
|
when (error) {
|
||||||
BaseError.SessionExpired,
|
BaseError.SessionExpired,
|
||||||
BaseError.AccountBlocked -> {
|
BaseError.AccountBlocked -> {
|
||||||
@@ -93,11 +63,11 @@ class MainViewModelImpl(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNavigatedToAuth() {
|
fun onNavigatedToAuth() {
|
||||||
isNeedToReplaceWithAuth.update { false }
|
isNeedToReplaceWithAuth.update { false }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onAppResumed(intent: Intent) {
|
fun onAppResumed(intent: Intent) {
|
||||||
openNotificationsSettings =
|
openNotificationsSettings =
|
||||||
intent.hasCategory(NotificationCompat.INTENT_CATEGORY_NOTIFICATION_PREFERENCES)
|
intent.hasCategory(NotificationCompat.INTENT_CATEGORY_NOTIFICATION_PREFERENCES)
|
||||||
openAppSettings =
|
openAppSettings =
|
||||||
@@ -124,7 +94,7 @@ class MainViewModelImpl(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ExperimentalPermissionsApi
|
@ExperimentalPermissionsApi
|
||||||
override fun onPermissionCheckStatus(status: PermissionStatus) {
|
fun onPermissionCheckStatus(status: PermissionStatus) {
|
||||||
isNeedToCheckNotificationsPermission.update { false }
|
isNeedToCheckNotificationsPermission.update { false }
|
||||||
|
|
||||||
when (status) {
|
when (status) {
|
||||||
@@ -146,33 +116,33 @@ class MainViewModelImpl(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onPermissionsRequested() {
|
fun onPermissionsRequested() {
|
||||||
isNeedToRequestNotifications.update { false }
|
isNeedToRequestNotifications.update { false }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNotificationsDeniedDialogConfirmClicked() {
|
fun onNotificationsDeniedDialogConfirmClicked() {
|
||||||
isNeedToRequestNotifications.update { true }
|
isNeedToRequestNotifications.update { true }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNotificationsDeniedDialogCancelClicked() {
|
fun onNotificationsDeniedDialogCancelClicked() {
|
||||||
isNeedToShowNotificationsDeniedDialog.update { false }
|
isNeedToShowNotificationsDeniedDialog.update { false }
|
||||||
disableBackgroundLongPoll()
|
disableBackgroundLongPoll()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNotificationsDeniedDialogDismissed() {
|
fun onNotificationsDeniedDialogDismissed() {
|
||||||
isNeedToShowNotificationsDeniedDialog.update { false }
|
isNeedToShowNotificationsDeniedDialog.update { false }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNotificationsRationaleDialogDismissed() {
|
fun onNotificationsRationaleDialogDismissed() {
|
||||||
isNeedToShowNotificationsRationaleDialog.update { false }
|
isNeedToShowNotificationsRationaleDialog.update { false }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNotificationsRationaleDialogCancelClicked() {
|
fun onNotificationsRationaleDialogCancelClicked() {
|
||||||
isNeedToShowNotificationsRationaleDialog.update { false }
|
isNeedToShowNotificationsRationaleDialog.update { false }
|
||||||
disableBackgroundLongPoll()
|
disableBackgroundLongPoll()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onUserAuthenticated() {
|
fun onUserAuthenticated() {
|
||||||
loadProfile()
|
loadProfile()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,9 +171,18 @@ class MainViewModelImpl(
|
|||||||
|
|
||||||
private fun loadAccounts() {
|
private fun loadAccounts() {
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
val currentAccount = getCurrentAccountUseCase()
|
val currentAccount = getCurrentAccountUseCase()?.mapToDto()
|
||||||
|
|
||||||
Log.d("MainViewModel", "currentAccount: $currentAccount")
|
logger.debug(
|
||||||
|
this@MainViewModel::class,
|
||||||
|
"loadAccounts(): currentAccount: %s"
|
||||||
|
.format(
|
||||||
|
currentAccount?.copy(
|
||||||
|
accessToken = if (currentAccount.accessToken.isNotEmpty()) "<redacted>"
|
||||||
|
else "null"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
listenLongPollState()
|
listenLongPollState()
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import com.skydoves.compose.stability.runtime.ComposeStabilityAnalyzer
|
|||||||
import dev.meloda.fast.auth.BuildConfig
|
import dev.meloda.fast.auth.BuildConfig
|
||||||
import dev.meloda.fast.common.di.applicationModule
|
import dev.meloda.fast.common.di.applicationModule
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.logger.FastLogLevel
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.presentation.CrashActivity
|
import dev.meloda.fast.presentation.CrashActivity
|
||||||
import org.koin.android.ext.android.get
|
import org.koin.android.ext.android.get
|
||||||
import org.koin.android.ext.koin.androidContext
|
import org.koin.android.ext.koin.androidContext
|
||||||
@@ -30,6 +32,14 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
|||||||
|
|
||||||
initKoin()
|
initKoin()
|
||||||
initCrashHandler()
|
initCrashHandler()
|
||||||
|
|
||||||
|
val logLevel =
|
||||||
|
if (BuildConfig.DEBUG) FastLogLevel.DEBUG
|
||||||
|
else FastLogLevel.ERROR
|
||||||
|
|
||||||
|
get<FastLogger>()
|
||||||
|
.apply { setLogLevel(logLevel) }
|
||||||
|
.also { FastLogger.setInstance(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun newImageLoader(): ImageLoader = get()
|
override fun newImageLoader(): ImageLoader = get()
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package dev.meloda.fast.common.di
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.Resources
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.preference.PreferenceManager
|
||||||
|
import org.koin.android.ext.koin.androidContext
|
||||||
|
import org.koin.core.module.dsl.factoryOf
|
||||||
|
import org.koin.dsl.module
|
||||||
|
|
||||||
|
val androidModule = module {
|
||||||
|
// TODO: 14/05/2024, Danil Nikolaev: extract all operations with preferences to standalone class
|
||||||
|
factoryOf(PreferenceManager::getDefaultSharedPreferences)
|
||||||
|
factory<Resources> { androidContext().resources }
|
||||||
|
factory<PowerManager> { androidContext().getSystemService(Context.POWER_SERVICE) as PowerManager }
|
||||||
|
factory<ConnectivityManager> { androidContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager }
|
||||||
|
}
|
||||||
@@ -1,16 +1,13 @@
|
|||||||
package dev.meloda.fast.common.di
|
package dev.meloda.fast.common.di
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.res.Resources
|
|
||||||
import android.os.PowerManager
|
|
||||||
import androidx.preference.PreferenceManager
|
|
||||||
import coil.ImageLoader
|
import coil.ImageLoader
|
||||||
import coil.annotation.ExperimentalCoilApi
|
import coil.annotation.ExperimentalCoilApi
|
||||||
import dev.meloda.fast.MainViewModelImpl
|
import dev.meloda.fast.MainViewModel
|
||||||
import dev.meloda.fast.auth.authModule
|
import dev.meloda.fast.auth.authModule
|
||||||
import dev.meloda.fast.chatmaterials.di.chatMaterialsModule
|
import dev.meloda.fast.chatmaterials.di.chatMaterialsModule
|
||||||
import dev.meloda.fast.common.LongPollController
|
import dev.meloda.fast.common.LongPollController
|
||||||
import dev.meloda.fast.common.LongPollControllerImpl
|
import dev.meloda.fast.common.LongPollControllerImpl
|
||||||
|
import dev.meloda.fast.common.NetworkStateListener
|
||||||
import dev.meloda.fast.common.provider.Provider
|
import dev.meloda.fast.common.provider.Provider
|
||||||
import dev.meloda.fast.common.provider.ResourceProvider
|
import dev.meloda.fast.common.provider.ResourceProvider
|
||||||
import dev.meloda.fast.common.provider.ResourceProviderImpl
|
import dev.meloda.fast.common.provider.ResourceProviderImpl
|
||||||
@@ -19,13 +16,15 @@ import dev.meloda.fast.convos.di.createChatModule
|
|||||||
import dev.meloda.fast.domain.di.domainModule
|
import dev.meloda.fast.domain.di.domainModule
|
||||||
import dev.meloda.fast.friends.di.friendsModule
|
import dev.meloda.fast.friends.di.friendsModule
|
||||||
import dev.meloda.fast.languagepicker.di.languagePickerModule
|
import dev.meloda.fast.languagepicker.di.languagePickerModule
|
||||||
|
import dev.meloda.fast.logger.loggerModule
|
||||||
import dev.meloda.fast.messageshistory.di.messagesHistoryModule
|
import dev.meloda.fast.messageshistory.di.messagesHistoryModule
|
||||||
import dev.meloda.fast.photoviewer.di.photoViewModule
|
import dev.meloda.fast.photoviewer.di.photoViewModule
|
||||||
|
import dev.meloda.fast.presentation.NetworkObserver
|
||||||
import dev.meloda.fast.profile.di.profileModule
|
import dev.meloda.fast.profile.di.profileModule
|
||||||
import dev.meloda.fast.provider.ApiLanguageProvider
|
import dev.meloda.fast.provider.ApiLanguageProvider
|
||||||
import dev.meloda.fast.service.longpolling.di.longPollModule
|
import dev.meloda.fast.service.longpolling.di.longPollModule
|
||||||
import dev.meloda.fast.settings.di.settingsModule
|
import dev.meloda.fast.settings.di.settingsModule
|
||||||
import org.koin.android.ext.koin.androidContext
|
import org.koin.core.module.dsl.factoryOf
|
||||||
import org.koin.core.module.dsl.singleOf
|
import org.koin.core.module.dsl.singleOf
|
||||||
import org.koin.core.module.dsl.viewModelOf
|
import org.koin.core.module.dsl.viewModelOf
|
||||||
import org.koin.core.qualifier.qualifier
|
import org.koin.core.qualifier.qualifier
|
||||||
@@ -49,24 +48,25 @@ val applicationModule = module {
|
|||||||
createChatModule
|
createChatModule
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: 14/05/2024, Danil Nikolaev: extract all operations with preferences to standalone class
|
includes(loggerModule)
|
||||||
singleOf(PreferenceManager::getDefaultSharedPreferences)
|
includes(androidModule)
|
||||||
single<Resources> { androidContext().resources }
|
|
||||||
factory<PowerManager> { androidContext().getSystemService(Context.POWER_SERVICE) as PowerManager }
|
|
||||||
|
|
||||||
singleOf(::ApiLanguageProvider) bind Provider::class
|
factoryOf(::ApiLanguageProvider) bind Provider::class
|
||||||
|
|
||||||
viewModelOf(::MainViewModelImpl) {
|
viewModelOf(::MainViewModel) { qualifier = qualifier("main") }
|
||||||
qualifier = qualifier("main")
|
|
||||||
}
|
|
||||||
|
|
||||||
single<ImageLoader> {
|
single<ImageLoader> {
|
||||||
ImageLoader.Builder(get())
|
ImageLoader.Builder(get())
|
||||||
.crossfade(true)
|
.crossfade(true)
|
||||||
.build()
|
.build()
|
||||||
.also { it.diskCache?.directory?.toFile()?.listFiles() }
|
.also {
|
||||||
|
it.diskCache?.directory?.toFile()?.listFiles()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
singleOf(::LongPollControllerImpl) bind LongPollController::class
|
singleOf(::LongPollControllerImpl) bind LongPollController::class
|
||||||
singleOf(::ResourceProviderImpl) bind ResourceProvider::class
|
singleOf(::ResourceProviderImpl) bind ResourceProvider::class
|
||||||
|
|
||||||
|
singleOf(::NetworkStateListener)
|
||||||
|
singleOf(::NetworkObserver) { qualifier = qualifier("main") }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,25 +9,28 @@ import android.content.res.Configuration
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.util.Log
|
|
||||||
import androidx.activity.SystemBarStyle
|
import androidx.activity.SystemBarStyle
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.toArgb
|
import androidx.compose.ui.graphics.toArgb
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||||
import dev.meloda.fast.MainViewModel
|
import dev.meloda.fast.MainViewModel
|
||||||
import dev.meloda.fast.MainViewModelImpl
|
|
||||||
import dev.meloda.fast.common.AppConstants
|
import dev.meloda.fast.common.AppConstants
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.service.OnlineService
|
import dev.meloda.fast.service.OnlineService
|
||||||
import dev.meloda.fast.service.longpolling.LongPollingService
|
import dev.meloda.fast.service.longpolling.LongPollingService
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
|
import dev.meloda.fast.ui.common.LocalLogger
|
||||||
|
import org.koin.android.ext.android.get
|
||||||
import org.koin.androidx.compose.koinViewModel
|
import org.koin.androidx.compose.koinViewModel
|
||||||
|
import org.koin.compose.koinInject
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
|
|
||||||
@@ -64,27 +67,28 @@ class MainActivity : AppCompatActivity() {
|
|||||||
requestNotificationPermissions()
|
requestNotificationPermissions()
|
||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
val logger: FastLogger = koinInject()
|
||||||
LaunchedEffect(viewModel) {
|
|
||||||
Log.d("VM_CREATE", "onCreate: viewModel: $viewModel")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
val viewModel: MainViewModel = koinViewModel()
|
||||||
LifecycleResumeEffect(true) {
|
LifecycleResumeEffect(true) {
|
||||||
viewModel.onAppResumed(intent)
|
viewModel.onAppResumed(intent)
|
||||||
onPauseOrDispose {}
|
onPauseOrDispose {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CompositionLocalProvider(LocalLogger provides logger) {
|
||||||
RootScreen(
|
RootScreen(
|
||||||
toggleLongPollService = { enable, inBackground ->
|
toggleLongPollService = { enable, inBackground ->
|
||||||
toggleLongPollService(
|
toggleLongPollService(
|
||||||
enable = enable,
|
enable = enable,
|
||||||
inBackground = inBackground ?: AppSettings.Experimental.longPollInBackground
|
inBackground = inBackground
|
||||||
|
?: AppSettings.Experimental.longPollInBackground
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
toggleOnlineService = ::toggleOnlineService
|
toggleOnlineService = ::toggleOnlineService
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun createNotificationChannels() {
|
private fun createNotificationChannels() {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
@@ -178,6 +182,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
stopServices()
|
stopServices()
|
||||||
|
get<LongPollEventsHandler>().onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ import dev.chrisbanes.haze.HazeState
|
|||||||
import dev.chrisbanes.haze.hazeEffect
|
import dev.chrisbanes.haze.hazeEffect
|
||||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||||
import dev.chrisbanes.haze.materials.HazeMaterials
|
import dev.chrisbanes.haze.materials.HazeMaterials
|
||||||
import dev.meloda.fast.convos.navigation.ConvoGraph
|
import dev.meloda.fast.convos.model.ConvoNavigationIntent
|
||||||
import dev.meloda.fast.convos.navigation.convosGraph
|
import dev.meloda.fast.convos.navigation.convosGraph
|
||||||
import dev.meloda.fast.friends.navigation.Friends
|
import dev.meloda.fast.friends.navigation.Friends
|
||||||
import dev.meloda.fast.friends.navigation.friendsScreen
|
import dev.meloda.fast.friends.navigation.friendsScreen
|
||||||
@@ -198,19 +198,20 @@ fun MainScreen(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
convosGraph(
|
convosGraph(
|
||||||
|
handleNavigationIntent = { intent ->
|
||||||
|
when (intent) {
|
||||||
|
ConvoNavigationIntent.Back -> {}
|
||||||
|
ConvoNavigationIntent.Archive -> {}
|
||||||
|
ConvoNavigationIntent.CreateChat -> onNavigateToCreateChat()
|
||||||
|
is ConvoNavigationIntent.MessagesHistory -> {
|
||||||
|
onNavigateToMessagesHistory(intent.convoId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
activity = activity,
|
activity = activity,
|
||||||
onError = onError,
|
|
||||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
|
||||||
onNavigateToCreateChat = onNavigateToCreateChat,
|
|
||||||
onScrolledToTop = {
|
|
||||||
tabReselected = tabReselected.toMutableMap().also {
|
|
||||||
it[ConvoGraph] = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
profileScreen(
|
profileScreen(
|
||||||
activity = activity,
|
activity = activity,
|
||||||
onError = onError,
|
|
||||||
onSettingsButtonClicked = onSettingsButtonClicked,
|
onSettingsButtonClicked = onSettingsButtonClicked,
|
||||||
onPhotoClicked = onPhotoClicked
|
onPhotoClicked = onPhotoClicked
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package dev.meloda.fast.presentation
|
||||||
|
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.LinkProperties
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
|
import android.os.Build
|
||||||
|
import dev.meloda.fast.common.NetworkStateListener
|
||||||
|
import dev.meloda.fast.common.model.NetworkState
|
||||||
|
import dev.meloda.fast.common.model.NetworkStatus
|
||||||
|
import dev.meloda.fast.common.model.NetworkType
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
|
internal class NetworkObserver(
|
||||||
|
private val connectivityManager: ConnectivityManager,
|
||||||
|
private val logger: FastLogger,
|
||||||
|
private val networkStateListener: NetworkStateListener
|
||||||
|
) {
|
||||||
|
|
||||||
|
private val networks = ConcurrentHashMap<Network, NetworkModel>()
|
||||||
|
|
||||||
|
private var clearCallbacks: (() -> Unit)? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
startListener()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun syncNetworkState() {
|
||||||
|
val state = if (networks.values.any { it.isInternetAvailable() }) {
|
||||||
|
NetworkState.CONNECTED
|
||||||
|
} else {
|
||||||
|
NetworkState.DISCONNECTED
|
||||||
|
}
|
||||||
|
|
||||||
|
networkStateListener.updateNetworkState(state)
|
||||||
|
log("STATE: $state")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startListener() {
|
||||||
|
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
log("onAvailable(): network: $network")
|
||||||
|
|
||||||
|
networks[network] = mapNetworkModel(
|
||||||
|
network = network,
|
||||||
|
capabilities = connectivityManager.getNetworkCapabilities(network),
|
||||||
|
properties = connectivityManager.getLinkProperties(network),
|
||||||
|
status = NetworkStatus.AVAILABLE,
|
||||||
|
assumeInternet = true
|
||||||
|
)
|
||||||
|
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onUnavailable() {
|
||||||
|
log("onUnavailable()")
|
||||||
|
|
||||||
|
networks.clear()
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
log("onLost() network: $network")
|
||||||
|
|
||||||
|
networks.remove(network)
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCapabilitiesChanged(
|
||||||
|
network: Network,
|
||||||
|
networkCapabilities: NetworkCapabilities
|
||||||
|
) {
|
||||||
|
log("onCapabilitiesChanged(): network: $network; caps: $networkCapabilities")
|
||||||
|
|
||||||
|
val current = networks[network]
|
||||||
|
networks[network] = mapNetworkModel(
|
||||||
|
network = network,
|
||||||
|
capabilities = networkCapabilities,
|
||||||
|
from = current,
|
||||||
|
status = current?.status ?: NetworkStatus.AVAILABLE
|
||||||
|
)
|
||||||
|
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBlockedStatusChanged(
|
||||||
|
network: Network,
|
||||||
|
blocked: Boolean
|
||||||
|
) {
|
||||||
|
log("onBlockedStatusChanged(): network: $network; blocked: $blocked")
|
||||||
|
|
||||||
|
networks[network] = mapNetworkModel(
|
||||||
|
network = network,
|
||||||
|
from = networks[network],
|
||||||
|
status = if (blocked) NetworkStatus.BLOCKED else NetworkStatus.UNBLOCKED
|
||||||
|
)
|
||||||
|
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLinkPropertiesChanged(
|
||||||
|
network: Network,
|
||||||
|
linkProperties: LinkProperties
|
||||||
|
) {
|
||||||
|
log("onLinkPropertiesChanged(): network: $network; props: $linkProperties")
|
||||||
|
|
||||||
|
val current = networks[network]
|
||||||
|
networks[network] = mapNetworkModel(
|
||||||
|
network = network,
|
||||||
|
properties = linkProperties,
|
||||||
|
from = current,
|
||||||
|
status = current?.status ?: NetworkStatus.AVAILABLE
|
||||||
|
)
|
||||||
|
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLosing(network: Network, maxMsToLive: Int) {
|
||||||
|
log("onLosing(): network: $network; maxMsToLive: $maxMsToLive")
|
||||||
|
|
||||||
|
val current = networks[network]
|
||||||
|
networks[network] = mapNetworkModel(
|
||||||
|
network = network,
|
||||||
|
maxMsToLive = maxMsToLive.toLong(),
|
||||||
|
from = current,
|
||||||
|
status = current?.status ?: NetworkStatus.AVAILABLE
|
||||||
|
)
|
||||||
|
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReserved(networkCapabilities: NetworkCapabilities) {
|
||||||
|
log("onReserved(): caps: $networkCapabilities")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val request = NetworkRequest.Builder()
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
connectivityManager.registerNetworkCallback(request, callback)
|
||||||
|
clearCallbacks = { connectivityManager.unregisterNetworkCallback(callback) }
|
||||||
|
|
||||||
|
refreshActiveNetwork()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun log(text: String) {
|
||||||
|
logger.debug(this::class, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refreshActiveNetwork() {
|
||||||
|
val network = connectivityManager.activeNetwork
|
||||||
|
if (network == null) {
|
||||||
|
networks.clear()
|
||||||
|
syncNetworkState()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val capabilities = connectivityManager.getNetworkCapabilities(network)
|
||||||
|
if (capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) {
|
||||||
|
networks[network] = mapNetworkModel(
|
||||||
|
network = network,
|
||||||
|
capabilities = capabilities,
|
||||||
|
properties = connectivityManager.getLinkProperties(network),
|
||||||
|
status = NetworkStatus.AVAILABLE
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
syncNetworkState()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapNetworkModel(
|
||||||
|
network: Network,
|
||||||
|
capabilities: NetworkCapabilities? = null,
|
||||||
|
properties: LinkProperties? = null,
|
||||||
|
status: NetworkStatus? = null,
|
||||||
|
maxMsToLive: Long? = null,
|
||||||
|
from: NetworkModel? = null,
|
||||||
|
assumeInternet: Boolean = false
|
||||||
|
): NetworkModel {
|
||||||
|
val caps = capabilities
|
||||||
|
?: from?.networkCapabilities
|
||||||
|
?: connectivityManager.getNetworkCapabilities(network)
|
||||||
|
|
||||||
|
val networkType = when {
|
||||||
|
caps?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true -> NetworkType.CELLULAR
|
||||||
|
caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true -> NetworkType.WIFI
|
||||||
|
else -> from?.type ?: NetworkType.UNKNOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
val hasInternet = if (caps != null) {
|
||||||
|
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ||
|
||||||
|
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||||
|
} else {
|
||||||
|
from?.hasInternet ?: assumeInternet
|
||||||
|
}
|
||||||
|
|
||||||
|
val signalStrength =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
caps?.signalStrength
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
} ?: from?.signalStrength ?: Int.MAX_VALUE
|
||||||
|
|
||||||
|
return NetworkModel(
|
||||||
|
id = network.hashCode(),
|
||||||
|
type = networkType,
|
||||||
|
original = network,
|
||||||
|
hasInternet = hasInternet,
|
||||||
|
signalStrength = signalStrength,
|
||||||
|
status = status ?: from?.status ?: NetworkStatus.UNAVAILABLE,
|
||||||
|
maxMsToLive = maxMsToLive ?: from?.maxMsToLive,
|
||||||
|
networkCapabilities = caps,
|
||||||
|
linkProperties = properties
|
||||||
|
?: from?.linkProperties
|
||||||
|
?: connectivityManager.getLinkProperties(network)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
data class NetworkModel(
|
||||||
|
val id: Int,
|
||||||
|
val type: NetworkType,
|
||||||
|
val original: Network,
|
||||||
|
val hasInternet: Boolean,
|
||||||
|
val signalStrength: Int,
|
||||||
|
val status: NetworkStatus,
|
||||||
|
val maxMsToLive: Long?,
|
||||||
|
val networkCapabilities: NetworkCapabilities?,
|
||||||
|
val linkProperties: LinkProperties?
|
||||||
|
) {
|
||||||
|
fun isStatusOk(): Boolean = status.isOk()
|
||||||
|
|
||||||
|
fun isInternetAvailable(): Boolean = hasInternet && isStatusOk()
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ import android.Manifest
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.util.Log
|
|
||||||
import androidx.activity.compose.LocalActivity
|
import androidx.activity.compose.LocalActivity
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
@@ -39,13 +38,13 @@ import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
|||||||
import com.google.accompanist.permissions.isGranted
|
import com.google.accompanist.permissions.isGranted
|
||||||
import com.google.accompanist.permissions.rememberPermissionState
|
import com.google.accompanist.permissions.rememberPermissionState
|
||||||
import dev.meloda.fast.MainViewModel
|
import dev.meloda.fast.MainViewModel
|
||||||
import dev.meloda.fast.MainViewModelImpl
|
|
||||||
import dev.meloda.fast.auth.authNavGraph
|
import dev.meloda.fast.auth.authNavGraph
|
||||||
import dev.meloda.fast.auth.captcha.presentation.CaptchaScreen
|
import dev.meloda.fast.auth.captcha.presentation.CaptchaScreen
|
||||||
import dev.meloda.fast.auth.navigateToAuth
|
import dev.meloda.fast.auth.navigateToAuth
|
||||||
import dev.meloda.fast.chatmaterials.navigation.chatMaterialsScreen
|
import dev.meloda.fast.chatmaterials.navigation.chatMaterialsScreen
|
||||||
import dev.meloda.fast.chatmaterials.navigation.navigateToChatMaterials
|
import dev.meloda.fast.chatmaterials.navigation.navigateToChatMaterials
|
||||||
import dev.meloda.fast.common.LongPollController
|
import dev.meloda.fast.common.LongPollController
|
||||||
|
import dev.meloda.fast.common.NetworkStateListener
|
||||||
import dev.meloda.fast.common.model.LongPollState
|
import dev.meloda.fast.common.model.LongPollState
|
||||||
import dev.meloda.fast.convos.navigation.createChatScreen
|
import dev.meloda.fast.convos.navigation.createChatScreen
|
||||||
import dev.meloda.fast.convos.navigation.navigateToCreateChat
|
import dev.meloda.fast.convos.navigation.navigateToCreateChat
|
||||||
@@ -60,9 +59,12 @@ import dev.meloda.fast.model.api.domain.VkUser
|
|||||||
import dev.meloda.fast.navigation.Main
|
import dev.meloda.fast.navigation.Main
|
||||||
import dev.meloda.fast.navigation.mainScreen
|
import dev.meloda.fast.navigation.mainScreen
|
||||||
import dev.meloda.fast.photoviewer.presentation.PhotoViewDialog
|
import dev.meloda.fast.photoviewer.presentation.PhotoViewDialog
|
||||||
|
import dev.meloda.fast.settings.model.SettingsNavigationIntent
|
||||||
import dev.meloda.fast.settings.navigation.navigateToSettings
|
import dev.meloda.fast.settings.navigation.navigateToSettings
|
||||||
import dev.meloda.fast.settings.navigation.settingsScreen
|
import dev.meloda.fast.settings.navigation.settingsScreen
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
|
import dev.meloda.fast.ui.common.LocalLogger
|
||||||
|
import dev.meloda.fast.ui.common.LocalNetworkState
|
||||||
import dev.meloda.fast.ui.common.LocalSizeConfig
|
import dev.meloda.fast.ui.common.LocalSizeConfig
|
||||||
import dev.meloda.fast.ui.model.DeviceSize
|
import dev.meloda.fast.ui.model.DeviceSize
|
||||||
import dev.meloda.fast.ui.model.SizeConfig
|
import dev.meloda.fast.ui.model.SizeConfig
|
||||||
@@ -83,6 +85,7 @@ fun RootScreen(
|
|||||||
toggleLongPollService: (enable: Boolean, inBackground: Boolean?) -> Unit,
|
toggleLongPollService: (enable: Boolean, inBackground: Boolean?) -> Unit,
|
||||||
toggleOnlineService: (enable: Boolean) -> Unit
|
toggleOnlineService: (enable: Boolean) -> Unit
|
||||||
) {
|
) {
|
||||||
|
val logger = LocalLogger.current
|
||||||
val resources = LocalResources.current
|
val resources = LocalResources.current
|
||||||
|
|
||||||
val userSettings: UserSettings = koinInject()
|
val userSettings: UserSettings = koinInject()
|
||||||
@@ -91,11 +94,7 @@ fun RootScreen(
|
|||||||
val longPollCurrentState by longPollController.currentState.collectAsStateWithLifecycle()
|
val longPollCurrentState by longPollController.currentState.collectAsStateWithLifecycle()
|
||||||
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
val viewModel: MainViewModel = koinViewModel()
|
||||||
LaunchedEffect(viewModel) {
|
|
||||||
Log.d("VM_CREATE", "RootScreen(): viewModel: $viewModel")
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentUser: VkUser? by viewModel.currentUser.collectAsStateWithLifecycle()
|
val currentUser: VkUser? by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val permissionState =
|
val permissionState =
|
||||||
@@ -126,13 +125,12 @@ fun RootScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
LifecycleResumeEffect(longPollStateToApply) {
|
LifecycleResumeEffect(longPollStateToApply) {
|
||||||
Log.d("LongPollMainActivity", "longPollStateToApply: $longPollStateToApply")
|
logger.debug("RootScreen", "longPollStateToApply: $longPollStateToApply")
|
||||||
if (longPollStateToApply != LongPollState.Background) {
|
if (longPollStateToApply != LongPollState.Background) {
|
||||||
if (longPollStateToApply.isLaunched() && longPollCurrentState.isLaunched()
|
if (longPollStateToApply.isLaunched() && longPollCurrentState.isLaunched()
|
||||||
&& longPollCurrentState != longPollStateToApply
|
&& longPollCurrentState != longPollStateToApply
|
||||||
) {
|
) {
|
||||||
toggleLongPollService(false, null)
|
toggleLongPollService(false, null)
|
||||||
Log.d("LongPoll", "recreate()")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleLongPollService(
|
toggleLongPollService(
|
||||||
@@ -224,10 +222,17 @@ fun RootScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val networkStateListener: NetworkStateListener = koinInject()
|
||||||
|
val networkState by networkStateListener.networkStateFlow.collectAsStateWithLifecycle()
|
||||||
|
LaunchedEffect(networkState) {
|
||||||
|
logger.debug("RootScreen", "NetworkState: $networkState")
|
||||||
|
}
|
||||||
|
|
||||||
CompositionLocalProvider(
|
CompositionLocalProvider(
|
||||||
LocalThemeConfig provides themeConfig,
|
LocalThemeConfig provides themeConfig,
|
||||||
LocalSizeConfig provides sizeConfig,
|
LocalSizeConfig provides sizeConfig,
|
||||||
LocalUser provides currentUser
|
LocalUser provides currentUser,
|
||||||
|
LocalNetworkState provides networkState
|
||||||
) {
|
) {
|
||||||
AppTheme(
|
AppTheme(
|
||||||
useDarkTheme = themeConfig.darkMode,
|
useDarkTheme = themeConfig.darkMode,
|
||||||
@@ -366,18 +371,31 @@ fun RootScreen(
|
|||||||
)
|
)
|
||||||
|
|
||||||
settingsScreen(
|
settingsScreen(
|
||||||
onBack = navController::navigateUp,
|
handleNavigationIntent = { intent ->
|
||||||
onLogOutButtonClicked = { navController.navigateToAuth(true) },
|
when (intent) {
|
||||||
onLanguageItemClicked = navController::navigateToLanguagePicker,
|
SettingsNavigationIntent.Back -> navController.navigateUp()
|
||||||
onRestartRequired = {
|
SettingsNavigationIntent.Language -> navController.navigateToLanguagePicker()
|
||||||
|
SettingsNavigationIntent.Restart -> {
|
||||||
activity?.let {
|
activity?.let {
|
||||||
val intent = Intent(activity, MainActivity::class.java)
|
val intent =
|
||||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
Intent(activity, MainActivity::class.java)
|
||||||
activity.startActivity(intent)
|
intent.setFlags(
|
||||||
|
Intent.FLAG_ACTIVITY_NEW_TASK or
|
||||||
|
Intent.FLAG_ACTIVITY_CLEAR_TASK or
|
||||||
|
Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||||
|
)
|
||||||
activity.finish()
|
activity.finish()
|
||||||
|
activity.startActivity(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SettingsNavigationIntent.LogOut -> {
|
||||||
|
navController.navigateToAuth(true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
languagePickerScreen(onBack = navController::navigateUp)
|
languagePickerScreen(onBack = navController::navigateUp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,9 @@ import android.os.IBinder
|
|||||||
import android.util.Log
|
import android.util.Log
|
||||||
import dev.meloda.fast.common.extensions.createTimerFlow
|
import dev.meloda.fast.common.extensions.createTimerFlow
|
||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.domain.AccountUseCase
|
|
||||||
import dev.meloda.fast.data.processState
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.domain.AccountUseCase
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -24,11 +25,12 @@ import kotlin.time.Duration.Companion.minutes
|
|||||||
|
|
||||||
class OnlineService : Service() {
|
class OnlineService : Service() {
|
||||||
|
|
||||||
|
private val logger: FastLogger by inject()
|
||||||
|
|
||||||
private val job = SupervisorJob()
|
private val job = SupervisorJob()
|
||||||
|
|
||||||
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
|
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
|
||||||
Log.d(TAG, "error: $throwable")
|
logger.error(this::class.java, "CoroutineException", throwable)
|
||||||
throwable.printStackTrace()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private val coroutineContext: CoroutineContext
|
private val coroutineContext: CoroutineContext
|
||||||
@@ -42,17 +44,20 @@ class OnlineService : Service() {
|
|||||||
private var onlineJob: Job? = null
|
private var onlineJob: Job? = null
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? {
|
override fun onBind(intent: Intent?): IBinder? {
|
||||||
Log.d(STATE_TAG, "onBind: intent: $intent")
|
logger.debug(this::class, "STATE: onBind(): intent: $intent")
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (startId > 1) return START_STICKY
|
if (startId > 1) return START_STICKY
|
||||||
|
|
||||||
Log.d(STATE_TAG, "onStartCommand: flags: $flags; startId: $startId\ninstance: $this")
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"STATE: onStartCommand(): flags: %s; startId: %s;\ninstance: %s"
|
||||||
|
.format("$flags", "$startId", "$this")
|
||||||
|
)
|
||||||
|
|
||||||
createTimer()
|
createTimer()
|
||||||
|
|
||||||
return START_STICKY
|
return START_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,13 +73,13 @@ class OnlineService : Service() {
|
|||||||
private fun setOnline() {
|
private fun setOnline() {
|
||||||
if (onlineJob != null) return
|
if (onlineJob != null) return
|
||||||
|
|
||||||
Log.d(TAG, "setOnline()")
|
logger.debug(this::class, "setOnline()")
|
||||||
|
|
||||||
onlineJob = coroutineScope.launch {
|
onlineJob = coroutineScope.launch {
|
||||||
val token = UserConfig.fastToken ?: UserConfig.accessToken
|
val token = UserConfig.fastToken ?: UserConfig.accessToken
|
||||||
|
|
||||||
if (token.isBlank()) {
|
if (token.isBlank()) {
|
||||||
Log.d(TAG, "setOnline: token is empty")
|
logger.debug(this::class, "setOnline(): token is empty")
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,10 +89,10 @@ class OnlineService : Service() {
|
|||||||
).onEach { state ->
|
).onEach { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.w(TAG, "setOnline(): error: $error")
|
logger.error(this@OnlineService::class, "setOnline(): ERROR: $error")
|
||||||
},
|
},
|
||||||
success = { response ->
|
success = { response ->
|
||||||
Log.d(TAG, "setOnline(): success: $response")
|
logger.debug(this@OnlineService::class, "setOnline(): response: $response")
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}.collect()
|
}.collect()
|
||||||
@@ -96,7 +101,7 @@ class OnlineService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
Log.d(STATE_TAG, "onDestroy")
|
logger.debug(this::class, "onDestroy()")
|
||||||
|
|
||||||
timerJob?.cancel("OnlineService destroyed")
|
timerJob?.cancel("OnlineService destroyed")
|
||||||
onlineJob?.cancel("OnlineService destroyed")
|
onlineJob?.cancel("OnlineService destroyed")
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import android.net.Uri
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.util.Log
|
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.ServiceCompat
|
import androidx.core.app.ServiceCompat
|
||||||
import com.conena.nanokt.android.app.stopForegroundCompat
|
import com.conena.nanokt.android.app.stopForegroundCompat
|
||||||
@@ -19,8 +18,10 @@ import dev.meloda.fast.common.model.LongPollState
|
|||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.data.processState
|
import dev.meloda.fast.data.processState
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||||
import dev.meloda.fast.domain.LongPollUseCase
|
import dev.meloda.fast.domain.LongPollUseCase
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
@@ -40,6 +41,8 @@ import kotlin.time.Duration.Companion.seconds
|
|||||||
|
|
||||||
class LongPollingService : Service() {
|
class LongPollingService : Service() {
|
||||||
|
|
||||||
|
private val logger: FastLogger by inject()
|
||||||
|
|
||||||
private val longPollController: LongPollController by inject()
|
private val longPollController: LongPollController by inject()
|
||||||
|
|
||||||
private val job = SupervisorJob()
|
private val job = SupervisorJob()
|
||||||
@@ -56,6 +59,7 @@ class LongPollingService : Service() {
|
|||||||
|
|
||||||
private val longPollUseCase: LongPollUseCase by inject()
|
private val longPollUseCase: LongPollUseCase by inject()
|
||||||
private val updatesParser: LongPollUpdatesParser by inject()
|
private val updatesParser: LongPollUpdatesParser by inject()
|
||||||
|
private val eventsHandler: LongPollEventsHandler by inject()
|
||||||
|
|
||||||
private var currentJob: Job? = null
|
private var currentJob: Job? = null
|
||||||
|
|
||||||
@@ -63,20 +67,21 @@ class LongPollingService : Service() {
|
|||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
Log.d(STATE_TAG, "onCreate()")
|
logger.debug(this::class, "STATE: onCreate()")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? {
|
override fun onBind(intent: Intent?): IBinder? {
|
||||||
Log.d(STATE_TAG, "onBind: intent: $intent")
|
logger.debug(this::class, "STATE: onBind(): intent: $intent")
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (startId > 1) return START_STICKY
|
if (startId > 1) return START_STICKY
|
||||||
|
|
||||||
Log.d(
|
logger.debug(
|
||||||
STATE_TAG,
|
this::class,
|
||||||
"onStartCommand: asForeground: $inBackground; flags: $flags; startId: $startId;\ninstance: $this"
|
"STATE: onStartCommand(): asForeground: %s; flags: %s; startId: %s;\ninstance: %s"
|
||||||
|
.format("$inBackground", "$flags", "$startId", "$this")
|
||||||
)
|
)
|
||||||
|
|
||||||
startJob()
|
startJob()
|
||||||
@@ -131,11 +136,15 @@ class LongPollingService : Service() {
|
|||||||
|
|
||||||
private fun startPolling(): Job {
|
private fun startPolling(): Job {
|
||||||
if (job.isCompleted || job.isCancelled) {
|
if (job.isCompleted || job.isCancelled) {
|
||||||
Log.d(STATE_TAG, "Job is completed or cancelled")
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"startPolling(): Job is already done. isCompleted: %s; isCancelled: %s"
|
||||||
|
.format("${job.isCompleted}", "${job.isCancelled}")
|
||||||
|
)
|
||||||
throw Exception("Job is over")
|
throw Exception("Job is over")
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(STATE_TAG, "Starting job...")
|
logger.debug(this::class, "startPolling(): Starting job.")
|
||||||
|
|
||||||
return coroutineScope.launch(coroutineContext) {
|
return coroutineScope.launch(coroutineContext) {
|
||||||
longPollController.updateCurrentState(
|
longPollController.updateCurrentState(
|
||||||
@@ -193,7 +202,7 @@ class LongPollingService : Service() {
|
|||||||
if (updates == null) {
|
if (updates == null) {
|
||||||
failCount++
|
failCount++
|
||||||
} else {
|
} else {
|
||||||
updates.forEach(updatesParser::parseNextUpdate)
|
parseUpdates(updates)
|
||||||
}
|
}
|
||||||
|
|
||||||
lastUpdatesResponse = getUpdatesResponse(serverInfo.copy(ts = newTs))
|
lastUpdatesResponse = getUpdatesResponse(serverInfo.copy(ts = newTs))
|
||||||
@@ -211,11 +220,11 @@ class LongPollingService : Service() {
|
|||||||
).listenValue(coroutineScope) { state ->
|
).listenValue(coroutineScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
success = { response ->
|
success = { response ->
|
||||||
Log.d(TAG, "getServerInfo: serverInfoResponse: $response")
|
logger.debug(this::class, "getServerInfo(): response: $response")
|
||||||
it.resume(response)
|
it.resume(response)
|
||||||
},
|
},
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.e(TAG, "getServerInfo: $error")
|
logger.error(this::class, "getServerInfo(): ERROR: $error")
|
||||||
it.resume(null)
|
it.resume(null)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -235,19 +244,24 @@ class LongPollingService : Service() {
|
|||||||
).listenValue(coroutineScope) { state ->
|
).listenValue(coroutineScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
success = { response ->
|
success = { response ->
|
||||||
Log.d(TAG, "lastUpdateResponse: $response")
|
logger.debug(this::class, "getUpdatesResponse(): response: $response")
|
||||||
it.resume(response)
|
it.resume(response)
|
||||||
},
|
},
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.d(TAG, "getUpdatesResponse: error: $error")
|
logger.debug(this::class, "getUpdatesResponse(): error: $error")
|
||||||
it.resume(null)
|
it.resume(null)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun parseUpdates(updates: List<List<Any>>) {
|
||||||
|
val parsedUpdates = updates.flatMap { updatesParser.parseNextUpdate(it) }
|
||||||
|
eventsHandler.handleEvents(parsedUpdates)
|
||||||
|
}
|
||||||
|
|
||||||
private fun handleError(throwable: Throwable) {
|
private fun handleError(throwable: Throwable) {
|
||||||
Log.e(TAG, "error: $throwable")
|
logger.error(this::class, "CoroutineException", throwable)
|
||||||
|
|
||||||
if (throwable !is NoAccessTokenException) {
|
if (throwable !is NoAccessTokenException) {
|
||||||
throwable.printStackTrace()
|
throwable.printStackTrace()
|
||||||
@@ -262,7 +276,7 @@ class LongPollingService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
Log.d(STATE_TAG, "onDestroy")
|
logger.debug(this::class, "STATE: onDestroy()")
|
||||||
longPollController.updateCurrentState(LongPollState.Stopped)
|
longPollController.updateCurrentState(LongPollState.Stopped)
|
||||||
try {
|
try {
|
||||||
AppSettings.edit { putBoolean(KEY_LONG_POLL_WAS_DESTROYED, true) }
|
AppSettings.edit { putBoolean(KEY_LONG_POLL_WAS_DESTROYED, true) }
|
||||||
@@ -274,7 +288,7 @@ class LongPollingService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onTrimMemory(level: Int) {
|
override fun onTrimMemory(level: Int) {
|
||||||
Log.d(STATE_TAG, "onTrimMemory. Level: $level")
|
logger.debug(this::class, "STATE: onTrimMemory(): Level: $level")
|
||||||
super.onTrimMemory(level)
|
super.onTrimMemory(level)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package dev.meloda.fast.service.longpolling.di
|
package dev.meloda.fast.service.longpolling.di
|
||||||
|
|
||||||
|
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||||
import dev.meloda.fast.domain.LongPollUseCase
|
import dev.meloda.fast.domain.LongPollUseCase
|
||||||
import dev.meloda.fast.domain.LongPollUseCaseImpl
|
import dev.meloda.fast.domain.LongPollUseCaseImpl
|
||||||
@@ -10,4 +11,5 @@ import org.koin.dsl.module
|
|||||||
val longPollModule = module {
|
val longPollModule = module {
|
||||||
singleOf(::LongPollUseCaseImpl) bind LongPollUseCase::class
|
singleOf(::LongPollUseCaseImpl) bind LongPollUseCase::class
|
||||||
singleOf(::LongPollUpdatesParser)
|
singleOf(::LongPollUpdatesParser)
|
||||||
|
singleOf(::LongPollEventsHandler)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package dev.meloda.fast.common
|
||||||
|
|
||||||
|
import dev.meloda.fast.common.model.NetworkState
|
||||||
|
import dev.meloda.fast.common.model.NetworkStatus
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
|
class NetworkStateListener {
|
||||||
|
|
||||||
|
private val networkStatus = MutableStateFlow(NetworkStatus.UNAVAILABLE)
|
||||||
|
val networkStatusFlow = networkStatus.asStateFlow()
|
||||||
|
|
||||||
|
private val networkState = MutableStateFlow(NetworkState.DISCONNECTED)
|
||||||
|
val networkStateFlow = networkState.asStateFlow()
|
||||||
|
|
||||||
|
fun updateNetworkState(state: NetworkState) {
|
||||||
|
networkState.value = state
|
||||||
|
networkStatus.value = when (state) {
|
||||||
|
NetworkState.CONNECTED -> NetworkStatus.AVAILABLE
|
||||||
|
NetworkState.DISCONNECTED -> NetworkStatus.UNAVAILABLE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,13 @@ package dev.meloda.fast.common.extensions
|
|||||||
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asFlow
|
import kotlinx.coroutines.flow.asFlow
|
||||||
import kotlinx.coroutines.flow.flow
|
import kotlinx.coroutines.flow.flow
|
||||||
@@ -13,6 +16,7 @@ import kotlinx.coroutines.flow.launchIn
|
|||||||
import kotlinx.coroutines.flow.onEach
|
import kotlinx.coroutines.flow.onEach
|
||||||
import kotlinx.coroutines.flow.onStart
|
import kotlinx.coroutines.flow.onStart
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
import kotlin.time.Duration
|
import kotlin.time.Duration
|
||||||
import kotlin.time.Duration.Companion.seconds
|
import kotlin.time.Duration.Companion.seconds
|
||||||
@@ -40,6 +44,16 @@ fun <T> MutableList<T>.removeIfCompat(condition: (T) -> Boolean): Boolean {
|
|||||||
return removed
|
return removed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
context(viewModel: ViewModel)
|
||||||
|
fun <T> Flow<T>.listenValue(action: suspend (T) -> Unit): Job =
|
||||||
|
listenValue(viewModel.viewModelScope, action)
|
||||||
|
|
||||||
|
context(viewModel: ViewModel)
|
||||||
|
fun <T> MutableSharedFlow<T>.emitOnMain(value: T) {
|
||||||
|
val flow = this
|
||||||
|
viewModel.viewModelScope.launch { flow.emit(value) }
|
||||||
|
}
|
||||||
|
|
||||||
fun <T> Flow<T>.listenValue(
|
fun <T> Flow<T>.listenValue(
|
||||||
coroutineScope: CoroutineScope,
|
coroutineScope: CoroutineScope,
|
||||||
action: suspend (T) -> Unit
|
action: suspend (T) -> Unit
|
||||||
|
|||||||
+2
-2
@@ -1,13 +1,13 @@
|
|||||||
package dev.meloda.fast.common.model
|
package dev.meloda.fast.common.model
|
||||||
|
|
||||||
enum class LogLevel(val value: Int) {
|
enum class NetworkLogLevel(val value: Int) {
|
||||||
NONE(0),
|
NONE(0),
|
||||||
BASIC(1),
|
BASIC(1),
|
||||||
HEADERS(2),
|
HEADERS(2),
|
||||||
BODY(3);
|
BODY(3);
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun parse(value: Int): LogLevel = entries.firstOrNull { it.value == value }
|
fun parse(value: Int): NetworkLogLevel = entries.firstOrNull { it.value == value }
|
||||||
?: throw IllegalArgumentException("Unknown log level with value: $value")
|
?: throw IllegalArgumentException("Unknown log level with value: $value")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package dev.meloda.fast.common.model
|
||||||
|
|
||||||
|
enum class NetworkState { CONNECTED, DISCONNECTED }
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package dev.meloda.fast.common.model
|
||||||
|
|
||||||
|
enum class NetworkStatus {
|
||||||
|
AVAILABLE, UNAVAILABLE, LOST, BLOCKED, UNBLOCKED;
|
||||||
|
|
||||||
|
fun isOk(): Boolean = when (this) {
|
||||||
|
AVAILABLE, UNBLOCKED -> true
|
||||||
|
UNAVAILABLE, LOST, BLOCKED -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package dev.meloda.fast.common.model
|
||||||
|
|
||||||
|
enum class NetworkType {
|
||||||
|
CELLULAR, WIFI, UNKNOWN
|
||||||
|
}
|
||||||
@@ -3,9 +3,7 @@ package dev.meloda.fast.common.provider
|
|||||||
import android.content.res.Resources
|
import android.content.res.Resources
|
||||||
|
|
||||||
interface ResourceProvider {
|
interface ResourceProvider {
|
||||||
|
|
||||||
val resources: Resources
|
val resources: Resources
|
||||||
|
|
||||||
fun getString(resId: Int): String
|
fun getString(resId: Int): String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ object VkMemoryCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun appendContacts(contacts: List<VkContactDomain>) {
|
fun appendContacts(contacts: List<VkContactDomain>) {
|
||||||
contacts.forEach { contact -> VkMemoryCache.contacts[contact.userId] = contact }
|
contacts.forEach { contact -> VkMemoryCache[contact.userId] = contact }
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun set(userid: Long, user: VkUser) {
|
operator fun set(userid: Long, user: VkUser) {
|
||||||
|
|||||||
@@ -129,6 +129,10 @@ class ConvosRepositoryImpl(
|
|||||||
val groupsList = response.groups.orEmpty().map(VkGroupData::mapToDomain)
|
val groupsList = response.groups.orEmpty().map(VkGroupData::mapToDomain)
|
||||||
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
||||||
|
|
||||||
|
VkMemoryCache.appendUsers(profilesList)
|
||||||
|
VkMemoryCache.appendGroups(groupsList)
|
||||||
|
VkMemoryCache.appendContacts(contactsList)
|
||||||
|
|
||||||
val usersMap = VkUsersMap.forUsers(profilesList)
|
val usersMap = VkUsersMap.forUsers(profilesList)
|
||||||
val groupsMap = VkGroupsMap.forGroups(groupsList)
|
val groupsMap = VkGroupsMap.forGroups(groupsList)
|
||||||
|
|
||||||
@@ -147,10 +151,6 @@ class ConvosRepositoryImpl(
|
|||||||
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
||||||
}
|
}
|
||||||
|
|
||||||
VkMemoryCache.appendUsers(profilesList)
|
|
||||||
VkMemoryCache.appendGroups(groupsList)
|
|
||||||
VkMemoryCache.appendContacts(contactsList)
|
|
||||||
|
|
||||||
convos
|
convos
|
||||||
},
|
},
|
||||||
errorMapper = { error ->
|
errorMapper = { error ->
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package dev.meloda.fast.data.api.friends
|
package dev.meloda.fast.data.api.friends
|
||||||
|
|
||||||
|
import com.slack.eithernet.ApiResult
|
||||||
|
import com.slack.eithernet.successOrElse
|
||||||
import dev.meloda.fast.common.VkConstants
|
import dev.meloda.fast.common.VkConstants
|
||||||
import dev.meloda.fast.data.VkMemoryCache
|
import dev.meloda.fast.data.VkMemoryCache
|
||||||
import dev.meloda.fast.database.dao.UserDao
|
import dev.meloda.fast.database.dao.UserDao
|
||||||
import dev.meloda.fast.model.FriendsInfo
|
import dev.meloda.fast.model.FriendsInfo
|
||||||
|
import dev.meloda.fast.model.api.data.VkContactData
|
||||||
import dev.meloda.fast.model.api.data.VkUserData
|
import dev.meloda.fast.model.api.data.VkUserData
|
||||||
import dev.meloda.fast.model.api.domain.VkUser
|
import dev.meloda.fast.model.api.domain.VkUser
|
||||||
import dev.meloda.fast.model.api.domain.asEntity
|
import dev.meloda.fast.model.api.domain.asEntity
|
||||||
@@ -13,8 +16,6 @@ import dev.meloda.fast.network.RestApiErrorDomain
|
|||||||
import dev.meloda.fast.network.mapApiDefault
|
import dev.meloda.fast.network.mapApiDefault
|
||||||
import dev.meloda.fast.network.mapApiResult
|
import dev.meloda.fast.network.mapApiResult
|
||||||
import dev.meloda.fast.network.service.friends.FriendsService
|
import dev.meloda.fast.network.service.friends.FriendsService
|
||||||
import com.slack.eithernet.ApiResult
|
|
||||||
import com.slack.eithernet.successOrElse
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.async
|
import kotlinx.coroutines.async
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -51,14 +52,18 @@ class FriendsRepositoryImpl(
|
|||||||
order = order,
|
order = order,
|
||||||
count = count,
|
count = count,
|
||||||
offset = offset,
|
offset = offset,
|
||||||
fields = VkConstants.USER_FIELDS
|
fields = VkConstants.USER_FIELDS,
|
||||||
|
extended = true
|
||||||
)
|
)
|
||||||
service.getFriends(requestModel.map).mapApiResult(
|
service.getFriends(requestModel.map).mapApiResult(
|
||||||
successMapper = { apiResponse ->
|
successMapper = { apiResponse ->
|
||||||
val response = apiResponse.requireResponse()
|
val response = apiResponse.requireResponse()
|
||||||
|
|
||||||
val users = response.items.map(VkUserData::mapToDomain)
|
val users = response.items.map(VkUserData::mapToDomain)
|
||||||
|
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
||||||
|
|
||||||
VkMemoryCache.appendUsers(users)
|
VkMemoryCache.appendUsers(users)
|
||||||
|
VkMemoryCache.appendContacts(contactsList)
|
||||||
|
|
||||||
users
|
users
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,425 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 12,
|
||||||
|
"identityHash": "5eca3b3da167aaf7e772977a1f4e56e2",
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"tableName": "users",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `firstName` TEXT NOT NULL, `lastName` TEXT NOT NULL, `isOnline` INTEGER NOT NULL, `isOnlineMobile` INTEGER NOT NULL, `onlineAppId` INTEGER, `lastSeen` INTEGER, `lastSeenStatus` TEXT, `birthday` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `photo400Orig` TEXT, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "firstName",
|
||||||
|
"columnName": "firstName",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "lastName",
|
||||||
|
"columnName": "lastName",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isOnline",
|
||||||
|
"columnName": "isOnline",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isOnlineMobile",
|
||||||
|
"columnName": "isOnlineMobile",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "onlineAppId",
|
||||||
|
"columnName": "onlineAppId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "lastSeen",
|
||||||
|
"columnName": "lastSeen",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "lastSeenStatus",
|
||||||
|
"columnName": "lastSeenStatus",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "birthday",
|
||||||
|
"columnName": "birthday",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo50",
|
||||||
|
"columnName": "photo50",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo100",
|
||||||
|
"columnName": "photo100",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo200",
|
||||||
|
"columnName": "photo200",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo400Orig",
|
||||||
|
"columnName": "photo400Orig",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "groups",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `screenName` TEXT NOT NULL, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `membersCount` INTEGER, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "name",
|
||||||
|
"columnName": "name",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "screenName",
|
||||||
|
"columnName": "screenName",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo50",
|
||||||
|
"columnName": "photo50",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo100",
|
||||||
|
"columnName": "photo100",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo200",
|
||||||
|
"columnName": "photo200",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "membersCount",
|
||||||
|
"columnName": "membersCount",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "messages",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `cmId` INTEGER NOT NULL, `text` TEXT, `isOut` INTEGER NOT NULL, `peerId` INTEGER NOT NULL, `fromId` INTEGER NOT NULL, `date` INTEGER NOT NULL, `randomId` INTEGER NOT NULL, `action` TEXT, `actionMemberId` INTEGER, `actionText` TEXT, `actionCmId` INTEGER, `actionMessage` TEXT, `updateTime` INTEGER, `isImportant` INTEGER NOT NULL, `forwardIds` TEXT, `attachments` TEXT, `replyMessageId` INTEGER, `geoType` TEXT, `pinnedAt` INTEGER, `isPinned` INTEGER NOT NULL, `isDeleted` INTEGER NOT NULL, `isSpam` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "cmId",
|
||||||
|
"columnName": "cmId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "text",
|
||||||
|
"columnName": "text",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isOut",
|
||||||
|
"columnName": "isOut",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "peerId",
|
||||||
|
"columnName": "peerId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "fromId",
|
||||||
|
"columnName": "fromId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "date",
|
||||||
|
"columnName": "date",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "randomId",
|
||||||
|
"columnName": "randomId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "action",
|
||||||
|
"columnName": "action",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "actionMemberId",
|
||||||
|
"columnName": "actionMemberId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "actionText",
|
||||||
|
"columnName": "actionText",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "actionCmId",
|
||||||
|
"columnName": "actionCmId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "actionMessage",
|
||||||
|
"columnName": "actionMessage",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "updateTime",
|
||||||
|
"columnName": "updateTime",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isImportant",
|
||||||
|
"columnName": "isImportant",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "forwardIds",
|
||||||
|
"columnName": "forwardIds",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "attachments",
|
||||||
|
"columnName": "attachments",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "replyMessageId",
|
||||||
|
"columnName": "replyMessageId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "geoType",
|
||||||
|
"columnName": "geoType",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "pinnedAt",
|
||||||
|
"columnName": "pinnedAt",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isPinned",
|
||||||
|
"columnName": "isPinned",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isDeleted",
|
||||||
|
"columnName": "isDeleted",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isSpam",
|
||||||
|
"columnName": "isSpam",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "convos",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `localId` INTEGER NOT NULL, `ownerId` INTEGER, `title` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `isPhantom` INTEGER NOT NULL, `lastCmId` INTEGER NOT NULL, `inReadCmId` INTEGER NOT NULL, `outReadCmId` INTEGER NOT NULL, `inRead` INTEGER NOT NULL, `outRead` INTEGER NOT NULL, `lastMessageId` INTEGER, `unreadCount` INTEGER NOT NULL, `membersCount` INTEGER, `canChangePin` INTEGER NOT NULL, `canChangeInfo` INTEGER NOT NULL, `majorId` INTEGER NOT NULL, `minorId` INTEGER NOT NULL, `pinnedMessageId` INTEGER, `peerType` TEXT NOT NULL, `isArchived` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "localId",
|
||||||
|
"columnName": "localId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "ownerId",
|
||||||
|
"columnName": "ownerId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "title",
|
||||||
|
"columnName": "title",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo50",
|
||||||
|
"columnName": "photo50",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo100",
|
||||||
|
"columnName": "photo100",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "photo200",
|
||||||
|
"columnName": "photo200",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isPhantom",
|
||||||
|
"columnName": "isPhantom",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "lastCmId",
|
||||||
|
"columnName": "lastCmId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "inReadCmId",
|
||||||
|
"columnName": "inReadCmId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "outReadCmId",
|
||||||
|
"columnName": "outReadCmId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "inRead",
|
||||||
|
"columnName": "inRead",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "outRead",
|
||||||
|
"columnName": "outRead",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "lastMessageId",
|
||||||
|
"columnName": "lastMessageId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "unreadCount",
|
||||||
|
"columnName": "unreadCount",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "membersCount",
|
||||||
|
"columnName": "membersCount",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "canChangePin",
|
||||||
|
"columnName": "canChangePin",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "canChangeInfo",
|
||||||
|
"columnName": "canChangeInfo",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "majorId",
|
||||||
|
"columnName": "majorId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "minorId",
|
||||||
|
"columnName": "minorId",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "pinnedMessageId",
|
||||||
|
"columnName": "pinnedMessageId",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "peerType",
|
||||||
|
"columnName": "peerType",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isArchived",
|
||||||
|
"columnName": "isArchived",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"setupQueries": [
|
||||||
|
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||||
|
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '5eca3b3da167aaf7e772977a1f4e56e2')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ import dev.meloda.fast.model.database.VkUserEntity
|
|||||||
VkConvoEntity::class
|
VkConvoEntity::class
|
||||||
],
|
],
|
||||||
|
|
||||||
version = 11
|
version = 12
|
||||||
)
|
)
|
||||||
@TypeConverters(Converters::class)
|
@TypeConverters(Converters::class)
|
||||||
abstract class CacheDatabase : RoomDatabase() {
|
abstract class CacheDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
|||||||
abstract suspend fun getAll(): List<VkConvoEntity>
|
abstract suspend fun getAll(): List<VkConvoEntity>
|
||||||
|
|
||||||
@Query("SELECT * FROM convos WHERE id IN (:ids)")
|
@Query("SELECT * FROM convos WHERE id IN (:ids)")
|
||||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkConvoEntity>
|
abstract suspend fun getAllByIds(ids: List<Long>): List<VkConvoEntity>
|
||||||
|
|
||||||
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
||||||
abstract suspend fun getById(id: Long): VkConvoEntity?
|
abstract suspend fun getById(id: Long): VkConvoEntity?
|
||||||
@@ -23,8 +23,23 @@ abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
|||||||
abstract suspend fun getByIdWithMessage(id: Long): ConvoWithMessage?
|
abstract suspend fun getByIdWithMessage(id: Long): ConvoWithMessage?
|
||||||
|
|
||||||
@Query("DELETE FROM convos WHERE rowid IN (:ids)")
|
@Query("DELETE FROM convos WHERE rowid IN (:ids)")
|
||||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
abstract suspend fun deleteByIds(ids: List<Long>): Int
|
||||||
|
|
||||||
|
@Query("UPDATE convos SET inReadCmId = :cmId, unreadCount = :unreadCount WHERE id = :convoId")
|
||||||
|
abstract suspend fun updateReadIncoming(convoId: Long, cmId: Long, unreadCount: Int): Int
|
||||||
|
|
||||||
|
@Query("UPDATE convos SET outReadCmId = :cmId, unreadCount = :unreadCount WHERE id = :convoId")
|
||||||
|
abstract suspend fun updateReadOutgoing(convoId: Long, cmId: Long, unreadCount: Int): Int
|
||||||
|
|
||||||
|
@Query("UPDATE convos SET isArchived = :isArchived WHERE id = :convoId")
|
||||||
|
abstract suspend fun updateIsArchived(convoId: Long, isArchived: Boolean): Int
|
||||||
|
|
||||||
|
@Query("UPDATE convos SET majorId = :majorId WHERE id = :convoId")
|
||||||
|
abstract suspend fun updateMajorId(convoId: Long, majorId: Int): Int
|
||||||
|
|
||||||
|
@Query("UPDATE convos SET minorId = :minorId WHERE id = :convoId")
|
||||||
|
abstract suspend fun updateMinorId(convoId: Long, minorId: Int): Int
|
||||||
|
|
||||||
|
@Query("UPDATE convos SET lastCmId = :cmId WHERE id = :convoId")
|
||||||
|
abstract suspend fun updateLastCmId(convoId: Long, cmId: Long): Int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import dev.meloda.fast.model.database.VkMessageEntity
|
|||||||
@Dao
|
@Dao
|
||||||
abstract class MessageDao : EntityDao<VkMessageEntity> {
|
abstract class MessageDao : EntityDao<VkMessageEntity> {
|
||||||
|
|
||||||
@Query("SELECT * FROM messages")
|
@Query("SELECT * FROM messages WHERE isDeleted = 0 AND isSpam = 0")
|
||||||
abstract suspend fun getAll(): List<VkMessageEntity>
|
abstract suspend fun getAll(): List<VkMessageEntity>
|
||||||
|
|
||||||
@Query("SELECT * FROM messages WHERE peerId IS (:convoId)")
|
@Query("SELECT * FROM messages WHERE peerId IS (:convoId)")
|
||||||
@@ -21,4 +21,13 @@ abstract class MessageDao : EntityDao<VkMessageEntity> {
|
|||||||
|
|
||||||
@Query("DELETE FROM messages WHERE id IN (:ids)")
|
@Query("DELETE FROM messages WHERE id IN (:ids)")
|
||||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||||
|
|
||||||
|
@Query("UPDATE messages SET isDeleted = :isDeleted WHERE peerId = :convoId AND cmId = :cmId")
|
||||||
|
abstract suspend fun markAsDeleted(convoId: Long, cmId: Long, isDeleted: Boolean): Int
|
||||||
|
|
||||||
|
@Query("UPDATE messages SET isImportant = :isImportant WHERE peerId = :convoId AND cmId = :cmId")
|
||||||
|
abstract suspend fun markAsImportant(convoId: Long, cmId: Long, isImportant: Boolean): Int
|
||||||
|
|
||||||
|
@Query("UPDATE messages SET isSpam = :isSpam WHERE peerId = :convoId AND cmId = :cmId")
|
||||||
|
abstract suspend fun markAsSpam(convoId: Long, cmId: Long, isSpam: Boolean): Int
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package dev.meloda.fast.datastore
|
|||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import androidx.core.content.edit
|
import androidx.core.content.edit
|
||||||
import dev.meloda.fast.common.model.DarkMode
|
import dev.meloda.fast.common.model.DarkMode
|
||||||
import dev.meloda.fast.common.model.LogLevel
|
import dev.meloda.fast.common.model.NetworkLogLevel
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
@@ -238,11 +238,11 @@ object AppSettings {
|
|||||||
)
|
)
|
||||||
set(value) = put(SettingsKeys.KEY_DEBUG_SHOW_CRASH_ALERT, value)
|
set(value) = put(SettingsKeys.KEY_DEBUG_SHOW_CRASH_ALERT, value)
|
||||||
|
|
||||||
var networkLogLevel: LogLevel
|
var networkLogLevel: NetworkLogLevel
|
||||||
get() = get(
|
get() = get(
|
||||||
SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL,
|
SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL,
|
||||||
SettingsKeys.DEFAULT_NETWORK_LOG_LEVEL
|
SettingsKeys.DEFAULT_NETWORK_LOG_LEVEL
|
||||||
).let(LogLevel::parse)
|
).let(NetworkLogLevel::parse)
|
||||||
set(level) = put(SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL, level.value)
|
set(level) = put(SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL, level.value)
|
||||||
|
|
||||||
var showDebugCategory: Boolean
|
var showDebugCategory: Boolean
|
||||||
|
|||||||
@@ -0,0 +1,332 @@
|
|||||||
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
|
import dev.meloda.fast.database.dao.ConvoDao
|
||||||
|
import dev.meloda.fast.database.dao.MessageDao
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
|
import dev.meloda.fast.model.InteractionType
|
||||||
|
import dev.meloda.fast.model.LongPollEvent
|
||||||
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlin.coroutines.CoroutineContext
|
||||||
|
|
||||||
|
typealias EventListener = (event: LongPollParsedEvent) -> Unit
|
||||||
|
typealias EventListenerMap = MutableMap<LongPollEvent, MutableList<EventListener>>
|
||||||
|
|
||||||
|
class LongPollEventsHandler(
|
||||||
|
private val logger: FastLogger,
|
||||||
|
private val convoUseCase: ConvoUseCase,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val convoDao: ConvoDao,
|
||||||
|
private val messageDao: MessageDao,
|
||||||
|
) {
|
||||||
|
private val job = SupervisorJob()
|
||||||
|
|
||||||
|
private val exceptionHandler =
|
||||||
|
CoroutineExceptionHandler { _, throwable ->
|
||||||
|
logger.error(this::class, "CoroutineException", throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val coroutineContext: CoroutineContext
|
||||||
|
get() = Dispatchers.Default + job + exceptionHandler
|
||||||
|
|
||||||
|
private val coroutineScope = CoroutineScope(coroutineContext)
|
||||||
|
|
||||||
|
private val listenersMap: EventListenerMap = mutableMapOf()
|
||||||
|
|
||||||
|
fun handleEvents(events: List<LongPollParsedEvent>) {
|
||||||
|
coroutineScope.launch {
|
||||||
|
// TODO: 30.05.2026, Danil Nikolaev: switch to interactors or something else
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
events.forEach { handleNextEvent(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun handleNextEvent(event: LongPollParsedEvent) {
|
||||||
|
when (event) {
|
||||||
|
is LongPollParsedEvent.AudioMessageListened -> {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatArchived -> {
|
||||||
|
val affectedRows = convoDao.updateIsArchived(
|
||||||
|
convoId = event.convo.id,
|
||||||
|
isArchived = event.convo.isArchived
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"isArchived ${event.convo.isArchived}: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatCleared -> {
|
||||||
|
val affectedRows = convoDao.updateLastCmId(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.toCmId
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"updateLastCmId: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatMajorChanged -> {
|
||||||
|
val affectedRows = convoDao.updateMajorId(
|
||||||
|
convoId = event.peerId,
|
||||||
|
majorId = event.majorId
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"updateMajorId: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatMinorChanged -> {
|
||||||
|
val affectedRows = convoDao.updateMinorId(
|
||||||
|
convoId = event.peerId,
|
||||||
|
minorId = event.minorId
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"updateMinorId: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.Interaction -> {
|
||||||
|
val eventType = when (event.interactionType) {
|
||||||
|
InteractionType.Typing -> LongPollEvent.TYPING
|
||||||
|
InteractionType.VoiceMessage -> LongPollEvent.AUDIO_MESSAGE_RECORDING
|
||||||
|
InteractionType.Photo -> LongPollEvent.PHOTO_UPLOADING
|
||||||
|
InteractionType.Video -> LongPollEvent.VIDEO_UPLOADING
|
||||||
|
InteractionType.File -> LongPollEvent.FILE_UPLOADING
|
||||||
|
}
|
||||||
|
|
||||||
|
emitEvent(eventType, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageCacheClear -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MESSAGE_CACHE_CLEAR, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageDeleted -> {
|
||||||
|
val affectedRows = messageDao.markAsDeleted(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId,
|
||||||
|
isDeleted = true
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"markDeleted: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MESSAGE_DELETED, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageEdited -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MESSAGE_EDITED, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageMarkedAsImportant -> {
|
||||||
|
val affectedRows = messageDao.markAsImportant(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId,
|
||||||
|
isImportant = event.marked
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"markImportant: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MARKED_AS_IMPORTANT, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageMarkedAsNotSpam -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MARKED_AS_NOT_SPAM, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageMarkedAsSpam -> {
|
||||||
|
val affectedRows = messageDao.markAsSpam(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId,
|
||||||
|
isSpam = true
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"markSpam: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MARKED_AS_SPAM, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageRestored -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MESSAGE_RESTORED, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageUpdated -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MESSAGE_UPDATED, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageNew -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.MESSAGE_NEW, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.IncomingMessageRead -> {
|
||||||
|
val affectedRows = convoDao.updateReadIncoming(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId,
|
||||||
|
unreadCount = event.unreadCount
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"inMessageRead: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.INCOMING_MESSAGE_READ, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.OutgoingMessageRead -> {
|
||||||
|
val affectedRows = convoDao.updateReadOutgoing(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId,
|
||||||
|
unreadCount = event.unreadCount
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
this::class,
|
||||||
|
"outMessageRead: updated $affectedRows rows."
|
||||||
|
)
|
||||||
|
|
||||||
|
emitEvent(LongPollEvent.OUTGOING_MESSAGE_READ, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.UnreadCounter -> {
|
||||||
|
emitEvent(LongPollEvent.UNREAD_COUNTER_UPDATE, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T : LongPollParsedEvent> emitEvent(eventType: LongPollEvent, event: T) {
|
||||||
|
listenersMap[eventType]?.forEach { it(event) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T : LongPollParsedEvent> registerListener(
|
||||||
|
eventType: LongPollEvent,
|
||||||
|
listener: (T) -> Unit
|
||||||
|
) {
|
||||||
|
if (listenersMap[eventType] == null) {
|
||||||
|
listenersMap[eventType] = mutableListOf()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
listenersMap[eventType]?.add(listener as EventListener)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T : LongPollParsedEvent> registerListeners(
|
||||||
|
eventTypes: List<LongPollEvent>,
|
||||||
|
listener: (T) -> Unit
|
||||||
|
) {
|
||||||
|
eventTypes.forEach { eventType -> registerListener(eventType, listener) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageSetFlags(block: (LongPollParsedEvent) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MESSAGE_SET_FLAGS, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageMarkAsImportant(block: (LongPollParsedEvent.MessageMarkedAsImportant) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MARKED_AS_IMPORTANT, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageMarkAsSpam(block: (LongPollParsedEvent.MessageMarkedAsSpam) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MARKED_AS_SPAM, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageDelete(block: (LongPollParsedEvent.MessageDeleted) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MESSAGE_DELETED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageClearFlags(block: (LongPollParsedEvent) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MESSAGE_CLEAR_FLAGS, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageMarkAsNotSpam(block: (LongPollParsedEvent.MessageMarkedAsNotSpam) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MARKED_AS_NOT_SPAM, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageRestore(block: (LongPollParsedEvent.MessageRestored) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MESSAGE_RESTORED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageNew(block: (LongPollParsedEvent.MessageNew) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MESSAGE_NEW, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageEdit(block: (LongPollParsedEvent.MessageEdited) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.MESSAGE_EDITED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageIncomingRead(block: (LongPollParsedEvent.IncomingMessageRead) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.INCOMING_MESSAGE_READ, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageOutgoingRead(block: (LongPollParsedEvent.OutgoingMessageRead) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.OUTGOING_MESSAGE_READ, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onChatClear(block: (LongPollParsedEvent.ChatCleared) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.CHAT_CLEARED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onChatMajorChange(block: (LongPollParsedEvent.ChatMajorChanged) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.CHAT_MAJOR_CHANGED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onChatMinorChange(block: (LongPollParsedEvent.ChatMinorChanged) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.CHAT_MINOR_CHANGED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onChatArchive(block: (LongPollParsedEvent.ChatArchived) -> Unit) {
|
||||||
|
registerListener(LongPollEvent.CHAT_ARCHIVED, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onInteraction(block: (LongPollParsedEvent.Interaction) -> Unit) {
|
||||||
|
registerListeners(
|
||||||
|
eventTypes = listOf(
|
||||||
|
LongPollEvent.TYPING,
|
||||||
|
LongPollEvent.AUDIO_MESSAGE_RECORDING,
|
||||||
|
LongPollEvent.PHOTO_UPLOADING,
|
||||||
|
LongPollEvent.VIDEO_UPLOADING,
|
||||||
|
LongPollEvent.FILE_UPLOADING
|
||||||
|
),
|
||||||
|
listener = block
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onDestroy() {
|
||||||
|
listenersMap.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package dev.meloda.fast.domain
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import dev.meloda.fast.common.VkConstants
|
import dev.meloda.fast.common.VkConstants
|
||||||
import dev.meloda.fast.common.extensions.asInt
|
import dev.meloda.fast.common.extensions.asInt
|
||||||
import dev.meloda.fast.common.extensions.asLong
|
import dev.meloda.fast.common.extensions.asLong
|
||||||
@@ -8,10 +7,10 @@ import dev.meloda.fast.common.extensions.listenValue
|
|||||||
import dev.meloda.fast.common.extensions.toList
|
import dev.meloda.fast.common.extensions.toList
|
||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.data.processState
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.model.ApiEvent
|
import dev.meloda.fast.model.ApiEvent
|
||||||
import dev.meloda.fast.model.ConvoFlags
|
import dev.meloda.fast.model.ConvoFlags
|
||||||
import dev.meloda.fast.model.InteractionType
|
import dev.meloda.fast.model.InteractionType
|
||||||
import dev.meloda.fast.model.LongPollEvent
|
|
||||||
import dev.meloda.fast.model.LongPollParsedEvent
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
import dev.meloda.fast.model.MessageFlags
|
import dev.meloda.fast.model.MessageFlags
|
||||||
import dev.meloda.fast.model.api.domain.VkConvo
|
import dev.meloda.fast.model.api.domain.VkConvo
|
||||||
@@ -22,12 +21,12 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.async
|
import kotlinx.coroutines.async
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
import kotlin.coroutines.CoroutineContext
|
import kotlin.coroutines.CoroutineContext
|
||||||
import kotlin.coroutines.resume
|
import kotlin.coroutines.resume
|
||||||
import kotlin.coroutines.suspendCoroutine
|
|
||||||
|
|
||||||
class LongPollUpdatesParser(
|
class LongPollUpdatesParser(
|
||||||
|
private val logger: FastLogger,
|
||||||
private val convoUseCase: ConvoUseCase,
|
private val convoUseCase: ConvoUseCase,
|
||||||
private val messagesUseCase: MessagesUseCase
|
private val messagesUseCase: MessagesUseCase
|
||||||
) {
|
) {
|
||||||
@@ -35,8 +34,7 @@ class LongPollUpdatesParser(
|
|||||||
|
|
||||||
private val exceptionHandler =
|
private val exceptionHandler =
|
||||||
CoroutineExceptionHandler { _, throwable ->
|
CoroutineExceptionHandler { _, throwable ->
|
||||||
Log.e("LongPollUpdatesParser", "error: $throwable")
|
logger.error(this::class, "CoroutineException", throwable)
|
||||||
throwable.printStackTrace()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private val coroutineContext: CoroutineContext
|
private val coroutineContext: CoroutineContext
|
||||||
@@ -44,14 +42,14 @@ class LongPollUpdatesParser(
|
|||||||
|
|
||||||
private val coroutineScope = CoroutineScope(coroutineContext)
|
private val coroutineScope = CoroutineScope(coroutineContext)
|
||||||
|
|
||||||
private val listenersMap: MutableMap<LongPollEvent, MutableList<VkEventCallback<LongPollParsedEvent>>> =
|
suspend fun parseNextUpdate(event: List<Any>): List<LongPollParsedEvent> {
|
||||||
mutableMapOf()
|
|
||||||
|
|
||||||
fun parseNextUpdate(event: List<Any>) {
|
|
||||||
val eventId = event.first().asInt()
|
val eventId = event.first().asInt()
|
||||||
|
|
||||||
when (val eventType = ApiEvent.parseOrNull(eventId)) {
|
return when (val eventType = ApiEvent.parseOrNull(eventId)) {
|
||||||
null -> Log.d("LongPollUpdatesParser", "parseNextUpdate: unknownEvent: $event")
|
null -> {
|
||||||
|
logger.debug(this::class, "parseNextUpdate(): unknownEvent: $event")
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
ApiEvent.MESSAGE_SET_FLAGS -> parseMessageSetFlags(eventType, event)
|
ApiEvent.MESSAGE_SET_FLAGS -> parseMessageSetFlags(eventType, event)
|
||||||
ApiEvent.MESSAGE_CLEAR_FLAGS -> parseMessageClearFlags(eventType, event)
|
ApiEvent.MESSAGE_CLEAR_FLAGS -> parseMessageClearFlags(eventType, event)
|
||||||
@@ -77,8 +75,11 @@ class LongPollUpdatesParser(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageSetFlags(eventType: ApiEvent, event: List<Any>) {
|
private fun parseMessageSetFlags(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseMessageSetFlags(): $eventType: $event")
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
val cmId = event[1].asLong()
|
||||||
val flags = event[2].asInt()
|
val flags = event[2].asInt()
|
||||||
@@ -96,13 +97,6 @@ class LongPollUpdatesParser(
|
|||||||
marked = true
|
marked = true
|
||||||
)
|
)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsImportant>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MessageFlags.SPAM -> {
|
MessageFlags.SPAM -> {
|
||||||
@@ -111,13 +105,6 @@ class LongPollUpdatesParser(
|
|||||||
cmId = cmId
|
cmId = cmId
|
||||||
)
|
)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_SPAM]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsSpam>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MessageFlags.DELETED -> {
|
MessageFlags.DELETED -> {
|
||||||
@@ -136,13 +123,6 @@ class LongPollUpdatesParser(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_DELETED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageDeleted>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MessageFlags.AUDIO_LISTENED -> {
|
MessageFlags.AUDIO_LISTENED -> {
|
||||||
@@ -151,30 +131,27 @@ class LongPollUpdatesParser(
|
|||||||
cmId = cmId
|
cmId = cmId
|
||||||
)
|
)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.AUDIO_MESSAGE_LISTENED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.AudioMessageListened>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
MessageFlags.UNREAD -> Unit
|
||||||
|
MessageFlags.OUTGOING -> Unit
|
||||||
|
MessageFlags.FROM_GROUP_CHAT -> Unit
|
||||||
|
MessageFlags.CANCEL_SPAM -> Unit
|
||||||
|
MessageFlags.DELETED_FOR_ALL -> Unit
|
||||||
|
MessageFlags.DO_NOT_SHOW_NOTIFICATION -> Unit
|
||||||
|
MessageFlags.MESSAGE_WITH_REPLY -> Unit
|
||||||
|
MessageFlags.REACTION -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> Unit
|
return eventsToSend
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
private suspend fun parseMessageClearFlags(
|
||||||
listenersMap[LongPollEvent.MESSAGE_SET_FLAGS]?.let { listeners ->
|
eventType: ApiEvent,
|
||||||
listeners.map { vkEventCallback ->
|
event: List<Any>
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(eventToSend)
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
}
|
logger.debug(this::class, "parseMessageClearFlags(): $eventType: $event")
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageClearFlags(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
val cmId = event[1].asLong()
|
||||||
val flags = event[2].asInt()
|
val flags = event[2].asInt()
|
||||||
@@ -184,7 +161,9 @@ class LongPollUpdatesParser(
|
|||||||
|
|
||||||
val parsedFlags = MessageFlags.parse(flags)
|
val parsedFlags = MessageFlags.parse(flags)
|
||||||
|
|
||||||
coroutineScope.launch {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
val message = loadMessage(peerId = peerId, cmId = cmId)
|
||||||
|
|
||||||
parsedFlags.forEach { flag ->
|
parsedFlags.forEach { flag ->
|
||||||
when (flag) {
|
when (flag) {
|
||||||
MessageFlags.IMPORTANT -> {
|
MessageFlags.IMPORTANT -> {
|
||||||
@@ -194,82 +173,53 @@ class LongPollUpdatesParser(
|
|||||||
marked = false
|
marked = false
|
||||||
)
|
)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsImportant>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MessageFlags.SPAM -> {
|
MessageFlags.SPAM -> {
|
||||||
if (parsedFlags.contains(MessageFlags.CANCEL_SPAM)) {
|
if (parsedFlags.contains(MessageFlags.CANCEL_SPAM)) {
|
||||||
withContext(Dispatchers.IO) {
|
if (message != null) {
|
||||||
val message = loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)
|
|
||||||
message?.let {
|
|
||||||
val eventToSend =
|
val eventToSend =
|
||||||
LongPollParsedEvent.MessageMarkedAsNotSpam(message = message)
|
LongPollParsedEvent.MessageMarkedAsNotSpam(message = message)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_NOT_SPAM]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsNotSpam>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MessageFlags.DELETED -> {
|
MessageFlags.DELETED -> {
|
||||||
withContext(Dispatchers.IO) {
|
if (message != null) {
|
||||||
val message = loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)
|
|
||||||
message?.let {
|
|
||||||
val eventToSend =
|
val eventToSend =
|
||||||
LongPollParsedEvent.MessageRestored(message = message)
|
LongPollParsedEvent.MessageRestored(message = message)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_RESTORED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageRestored>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
MessageFlags.UNREAD -> Unit
|
||||||
listenersMap[LongPollEvent.MESSAGE_CLEAR_FLAGS]?.let { listeners ->
|
MessageFlags.OUTGOING -> Unit
|
||||||
listeners.map { vkEventCallback ->
|
MessageFlags.AUDIO_LISTENED -> Unit
|
||||||
vkEventCallback.onEvent(eventToSend)
|
MessageFlags.FROM_GROUP_CHAT -> Unit
|
||||||
}
|
MessageFlags.CANCEL_SPAM -> Unit
|
||||||
}
|
MessageFlags.DELETED_FOR_ALL -> Unit
|
||||||
}
|
MessageFlags.DO_NOT_SHOW_NOTIFICATION -> Unit
|
||||||
|
MessageFlags.MESSAGE_WITH_REPLY -> Unit
|
||||||
|
MessageFlags.REACTION -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageNew(eventType: ApiEvent, event: List<Any>) {
|
continuation.resume(eventsToSend)
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun parseMessageNew(
|
||||||
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
|
logger.debug(this::class, "parseMessageNew(): $eventType: $event")
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
val cmId = event[1].asLong()
|
||||||
val peerId = event[4].asLong()
|
val peerId = event[4].asLong()
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
val message =
|
val message = async { loadMessage(peerId = peerId, cmId = cmId) }.await()
|
||||||
async { loadMessage(peerId = peerId, cmId = cmId) }.await()
|
|
||||||
|
|
||||||
val convo =
|
val convo =
|
||||||
async {
|
async {
|
||||||
@@ -280,88 +230,84 @@ class LongPollUpdatesParser(
|
|||||||
)
|
)
|
||||||
}.await()
|
}.await()
|
||||||
|
|
||||||
message?.let {
|
if (message != null) {
|
||||||
listenersMap[LongPollEvent.MESSAGE_NEW]?.let {
|
val event = LongPollParsedEvent.MessageNew(
|
||||||
it.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.NewMessage>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.NewMessage(
|
|
||||||
message = message,
|
message = message,
|
||||||
inArchive = convo?.isArchived == true
|
inArchive = convo?.isArchived == true
|
||||||
// TODO: 03-Apr-25, Danil Nikolaev:
|
// TODO: 03-Apr-25, Danil Nikolaev:
|
||||||
// load user settings about restoring chats with
|
// load user settings about restoring chats with
|
||||||
// enabled notifications from archive
|
// enabled notifications from archive
|
||||||
)
|
)
|
||||||
)
|
|
||||||
}
|
continuation.resume(listOf(event))
|
||||||
}
|
} else {
|
||||||
|
continuation.resume(emptyList())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageEdit(eventType: ApiEvent, event: List<Any>) {
|
private suspend fun parseMessageEdit(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
|
logger.debug(this::class, "parseMessageEdit(): $eventType: $event")
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
val cmId = event[1].asLong()
|
||||||
val peerId = event[3].asLong()
|
val peerId = event[3].asLong()
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
loadMessage(
|
val message = loadMessage(peerId = peerId, cmId = cmId)
|
||||||
peerId = peerId,
|
if (message != null) {
|
||||||
cmId = cmId
|
val event = LongPollParsedEvent.MessageEdited(message)
|
||||||
)?.let { message ->
|
continuation.resume(listOf(event))
|
||||||
listenersMap[LongPollEvent.MESSAGE_EDITED]?.let {
|
} else {
|
||||||
it.map { vkEventCallback ->
|
continuation.resume(emptyList())
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.MessageEdited>)
|
|
||||||
.onEvent(LongPollParsedEvent.MessageEdited(message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageReadIncoming(eventType: ApiEvent, event: List<Any>) {
|
private fun parseMessageReadIncoming(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseMessageReadIncoming(): $eventType: $event")
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val cmId = event[2].asLong()
|
val cmId = event[2].asLong()
|
||||||
val unreadCount = event[3].asInt()
|
val unreadCount = event[3].asInt()
|
||||||
|
|
||||||
listenersMap[LongPollEvent.INCOMING_MESSAGE_READ]?.let { listeners ->
|
val event = LongPollParsedEvent.IncomingMessageRead(
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.IncomingMessageRead>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.IncomingMessageRead(
|
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
cmId = cmId,
|
cmId = cmId,
|
||||||
unreadCount = unreadCount
|
unreadCount = unreadCount
|
||||||
)
|
)
|
||||||
)
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageReadOutgoing(eventType: ApiEvent, event: List<Any>) {
|
private fun parseMessageReadOutgoing(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseMessageReadOutgoing(): $eventType: $event")
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val cmId = event[2].asLong()
|
val cmId = event[2].asLong()
|
||||||
val unreadCount = event[3].asInt()
|
val unreadCount = event[3].asInt()
|
||||||
|
|
||||||
listenersMap[LongPollEvent.OUTGOING_MESSAGE_READ]?.let { listeners ->
|
val event = LongPollParsedEvent.OutgoingMessageRead(
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.OutgoingMessageRead>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.OutgoingMessageRead(
|
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
cmId = cmId,
|
cmId = cmId,
|
||||||
unreadCount = unreadCount
|
unreadCount = unreadCount
|
||||||
)
|
)
|
||||||
)
|
|
||||||
}
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseChatClearFlags(eventType: ApiEvent, event: List<Any>) {
|
private suspend fun parseChatClearFlags(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
|
logger.debug(this::class, "parseChatClearFlags(): $eventType: $event")
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val flags = event[2].asInt()
|
val flags = event[2].asInt()
|
||||||
@@ -390,33 +336,32 @@ class LongPollUpdatesParser(
|
|||||||
archived = false
|
archived = false
|
||||||
)
|
)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.ChatArchived>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ConvoFlags.DISABLE_PUSH -> Unit
|
||||||
|
ConvoFlags.DISABLE_SOUND -> Unit
|
||||||
|
ConvoFlags.INCOMING_CHAT_REQUEST -> Unit
|
||||||
|
ConvoFlags.DECLINED_CHAT_REQUEST -> Unit
|
||||||
|
ConvoFlags.MENTION -> Unit
|
||||||
|
ConvoFlags.HIDE_CHAT_FROM_SEARCH -> Unit
|
||||||
|
ConvoFlags.BUSINESS_CHAT -> Unit
|
||||||
|
ConvoFlags.MARKED_MESSAGE -> Unit
|
||||||
|
ConvoFlags.DO_NOT_NOTIFY_MENTIONS_ALL_ONLINE -> Unit
|
||||||
|
ConvoFlags.DO_NOT_NOTIFY_ALL_MENTIONS -> Unit
|
||||||
|
ConvoFlags.MARKED_AS_UNREAD -> Unit
|
||||||
|
ConvoFlags.CALL_IN_PROGRESS -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> Unit
|
continuation.resume(eventsToSend)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
private suspend fun parseChatSetFlags(
|
||||||
listenersMap[LongPollEvent.CHAT_CLEAR_FLAGS]?.let { listeners ->
|
eventType: ApiEvent,
|
||||||
listeners.map { vkEventCallback ->
|
event: List<Any>
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
eventToSend
|
logger.debug(this::class, "parseChatSetFlags(): $eventType: $event")
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseChatSetFlags(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val flags = event[2].asInt()
|
val flags = event[2].asInt()
|
||||||
@@ -445,90 +390,80 @@ class LongPollUpdatesParser(
|
|||||||
archived = true
|
archived = true
|
||||||
)
|
)
|
||||||
eventsToSend += eventToSend
|
eventsToSend += eventToSend
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.ChatArchived>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ConvoFlags.DISABLE_PUSH -> Unit
|
||||||
|
ConvoFlags.DISABLE_SOUND -> Unit
|
||||||
|
ConvoFlags.INCOMING_CHAT_REQUEST -> Unit
|
||||||
|
ConvoFlags.DECLINED_CHAT_REQUEST -> Unit
|
||||||
|
ConvoFlags.MENTION -> Unit
|
||||||
|
ConvoFlags.HIDE_CHAT_FROM_SEARCH -> Unit
|
||||||
|
ConvoFlags.BUSINESS_CHAT -> Unit
|
||||||
|
ConvoFlags.MARKED_MESSAGE -> Unit
|
||||||
|
ConvoFlags.DO_NOT_NOTIFY_MENTIONS_ALL_ONLINE -> Unit
|
||||||
|
ConvoFlags.DO_NOT_NOTIFY_ALL_MENTIONS -> Unit
|
||||||
|
ConvoFlags.MARKED_AS_UNREAD -> Unit
|
||||||
|
ConvoFlags.CALL_IN_PROGRESS -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> Unit
|
continuation.resume(eventsToSend)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
private fun parseMessagesDeleted(
|
||||||
listenersMap[LongPollEvent.CHAT_SET_FLAGS]?.let { listeners ->
|
eventType: ApiEvent,
|
||||||
listeners.map { vkEventCallback ->
|
event: List<Any>
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(
|
): List<LongPollParsedEvent> {
|
||||||
eventToSend
|
logger.debug(this::class, "parseMessagesDeleted(): $eventType: $event")
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessagesDeleted(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val cmId = event[2].asLong()
|
val cmId = event[2].asLong()
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_CLEARED]?.let { listeners ->
|
val event = LongPollParsedEvent.ChatCleared(
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.ChatCleared>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.ChatCleared(
|
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
toCmId = cmId
|
toCmId = cmId
|
||||||
)
|
)
|
||||||
)
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseChatMajorChanged(eventType: ApiEvent, event: List<Any>) {
|
private fun parseChatMajorChanged(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseChatMajorChanged(): $eventType: $event")
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val majorId = event[2].asInt()
|
val majorId = event[2].asInt()
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_MAJOR_CHANGED]?.let { listeners ->
|
val event = LongPollParsedEvent.ChatMajorChanged(
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.ChatMajorChanged>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.ChatMajorChanged(
|
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
majorId = majorId,
|
majorId = majorId,
|
||||||
)
|
)
|
||||||
)
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseChatMinorChanged(eventType: ApiEvent, event: List<Any>) {
|
private fun parseChatMinorChanged(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseChatMinorChanged(): $eventType: $event")
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
val minorId = event[2].asInt()
|
val minorId = event[2].asInt()
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_MINOR_CHANGED]?.let { listeners ->
|
val event = LongPollParsedEvent.ChatMinorChanged(
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.ChatMinorChanged>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.ChatMinorChanged(
|
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
minorId = minorId,
|
minorId = minorId,
|
||||||
)
|
)
|
||||||
)
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseInteraction(eventType: ApiEvent, event: List<Any>) {
|
private fun parseInteraction(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseInteraction(): $eventType: $event")
|
||||||
|
|
||||||
val interactionType = when (eventType) {
|
val interactionType = when (eventType) {
|
||||||
ApiEvent.TYPING -> InteractionType.Typing
|
ApiEvent.TYPING -> InteractionType.Typing
|
||||||
@@ -536,16 +471,7 @@ class LongPollUpdatesParser(
|
|||||||
ApiEvent.PHOTO_UPLOADING -> InteractionType.Photo
|
ApiEvent.PHOTO_UPLOADING -> InteractionType.Photo
|
||||||
ApiEvent.VIDEO_UPLOADING -> InteractionType.Video
|
ApiEvent.VIDEO_UPLOADING -> InteractionType.Video
|
||||||
ApiEvent.FILE_UPLOADING -> InteractionType.File
|
ApiEvent.FILE_UPLOADING -> InteractionType.File
|
||||||
else -> return
|
else -> return emptyList()
|
||||||
}
|
|
||||||
|
|
||||||
val longPollEvent: LongPollEvent = when (eventType) {
|
|
||||||
ApiEvent.TYPING -> LongPollEvent.TYPING
|
|
||||||
ApiEvent.AUDIO_MESSAGE_RECORDING -> LongPollEvent.AUDIO_MESSAGE_RECORDING
|
|
||||||
ApiEvent.PHOTO_UPLOADING -> LongPollEvent.PHOTO_UPLOADING
|
|
||||||
ApiEvent.VIDEO_UPLOADING -> LongPollEvent.VIDEO_UPLOADING
|
|
||||||
ApiEvent.FILE_UPLOADING -> LongPollEvent.FILE_UPLOADING
|
|
||||||
else -> return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
val peerId = event[1].asLong()
|
||||||
@@ -554,26 +480,24 @@ class LongPollUpdatesParser(
|
|||||||
val timestamp = event[4].asInt()
|
val timestamp = event[4].asInt()
|
||||||
|
|
||||||
// if userIds contains only account's id, then we don't need to show our status
|
// if userIds contains only account's id, then we don't need to show our status
|
||||||
if (userIds.isEmpty()) return
|
if (userIds.isEmpty()) return emptyList()
|
||||||
|
|
||||||
listenersMap[longPollEvent]?.let { listeners ->
|
val event = LongPollParsedEvent.Interaction(
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.Interaction>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.Interaction(
|
|
||||||
interactionType = interactionType,
|
interactionType = interactionType,
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
userIds = userIds,
|
userIds = userIds,
|
||||||
totalCount = totalCount,
|
totalCount = totalCount,
|
||||||
timestamp = timestamp
|
timestamp = timestamp
|
||||||
)
|
)
|
||||||
)
|
|
||||||
}
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseUnreadCounterUpdate(eventType: ApiEvent, event: List<Any>) {
|
private fun parseUnreadCounterUpdate(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> {
|
||||||
|
logger.debug(this::class, "parseUnreadCounterUpdate(): $eventType: $event")
|
||||||
|
|
||||||
val unreadCount = event[1].asInt()
|
val unreadCount = event[1].asInt()
|
||||||
val unreadUnmutedCount = event[2].asInt()
|
val unreadUnmutedCount = event[2].asInt()
|
||||||
@@ -583,11 +507,7 @@ class LongPollUpdatesParser(
|
|||||||
val archiveUnreadUnmutedCount = event[8].asInt()
|
val archiveUnreadUnmutedCount = event[8].asInt()
|
||||||
val archiveMentionsCount = event[9].asInt()
|
val archiveMentionsCount = event[9].asInt()
|
||||||
|
|
||||||
listenersMap[LongPollEvent.UNREAD_COUNTER_UPDATE]?.let { listeners ->
|
val event = LongPollParsedEvent.UnreadCounter(
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.UnreadCounter>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.UnreadCounter(
|
|
||||||
unread = unreadCount,
|
unread = unreadCount,
|
||||||
unreadUnmuted = unreadUnmutedCount,
|
unreadUnmuted = unreadUnmutedCount,
|
||||||
showOnlyMuted = showOnlyMuted,
|
showOnlyMuted = showOnlyMuted,
|
||||||
@@ -596,45 +516,45 @@ class LongPollUpdatesParser(
|
|||||||
archiveUnmuted = archiveUnreadUnmutedCount,
|
archiveUnmuted = archiveUnreadUnmutedCount,
|
||||||
archiveMentions = archiveMentionsCount
|
archiveMentions = archiveMentionsCount
|
||||||
)
|
)
|
||||||
)
|
return listOf(event)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageUpdated(eventType: ApiEvent, event: List<Any>) {
|
private suspend fun parseMessageUpdated(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
|
logger.debug(this::class, "parseMessageUpdated(): $eventType: $event")
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
val cmId = event[1].asLong()
|
||||||
val peerId = event[4].asLong()
|
val peerId = event[4].asLong()
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
loadMessage(
|
val message = loadMessage(peerId = peerId, cmId = cmId)
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
if (message != null) {
|
||||||
)?.let { message ->
|
val event = LongPollParsedEvent.MessageUpdated(message)
|
||||||
listenersMap[LongPollEvent.MESSAGE_UPDATED]?.let {
|
continuation.resume(listOf(event))
|
||||||
it.map { vkEventCallback ->
|
} else {
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.MessageUpdated>)
|
continuation.resume(emptyList())
|
||||||
.onEvent(LongPollParsedEvent.MessageUpdated(message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMessageCacheClear(eventType: ApiEvent, event: List<Any>) {
|
private suspend fun parseMessageCacheClear(
|
||||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
eventType: ApiEvent,
|
||||||
|
event: List<Any>
|
||||||
|
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||||
|
logger.debug(this::class, "parseMessageCacheClear(): $eventType: $event")
|
||||||
|
|
||||||
val messageId = event[1].asLong()
|
val messageId = event[1].asLong()
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
loadMessage(messageId = messageId)?.let { message ->
|
val message = loadMessage(messageId = messageId)
|
||||||
listenersMap[LongPollEvent.MESSAGE_CACHE_CLEAR]?.let {
|
if (message != null) {
|
||||||
it.map { vkEventCallback ->
|
val event = LongPollParsedEvent.MessageCacheClear(message)
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.MessageCacheClear>)
|
continuation.resume(listOf(event))
|
||||||
.onEvent(LongPollParsedEvent.MessageCacheClear(message))
|
} else {
|
||||||
}
|
continuation.resume(emptyList())
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -643,7 +563,7 @@ class LongPollUpdatesParser(
|
|||||||
peerId: Long? = null,
|
peerId: Long? = null,
|
||||||
cmId: Long? = null,
|
cmId: Long? = null,
|
||||||
messageId: Long? = null
|
messageId: Long? = null
|
||||||
): VkMessage? = suspendCoroutine { continuation ->
|
): VkMessage? = suspendCancellableCoroutine { continuation ->
|
||||||
require((peerId != null && cmId != null) || messageId != null)
|
require((peerId != null && cmId != null) || messageId != null)
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
@@ -657,7 +577,10 @@ class LongPollUpdatesParser(
|
|||||||
).listenValue(this) { state ->
|
).listenValue(this) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.e("LongPollUpdatesParser", "loadMessage: error: $error")
|
logger.error(
|
||||||
|
this@LongPollUpdatesParser::class,
|
||||||
|
"loadMessage(): ERROR: $error"
|
||||||
|
)
|
||||||
continuation.resume(null)
|
continuation.resume(null)
|
||||||
},
|
},
|
||||||
success = { response ->
|
success = { response ->
|
||||||
@@ -677,7 +600,7 @@ class LongPollUpdatesParser(
|
|||||||
peerId: Long,
|
peerId: Long,
|
||||||
extended: Boolean = false,
|
extended: Boolean = false,
|
||||||
fields: String? = null
|
fields: String? = null
|
||||||
): VkConvo? = suspendCoroutine { continuation ->
|
): VkConvo? = suspendCancellableCoroutine { continuation ->
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
convoUseCase.getById(
|
convoUseCase.getById(
|
||||||
peerIds = listOf(peerId),
|
peerIds = listOf(peerId),
|
||||||
@@ -686,7 +609,10 @@ class LongPollUpdatesParser(
|
|||||||
).listenValue(coroutineScope) { state ->
|
).listenValue(coroutineScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.e("LongPollUpdatesParser", "loadConvo: error: $error")
|
logger.error(
|
||||||
|
this@LongPollUpdatesParser::class,
|
||||||
|
"loadConvo(): ERROR: $error"
|
||||||
|
)
|
||||||
continuation.resume(null)
|
continuation.resume(null)
|
||||||
},
|
},
|
||||||
success = { response ->
|
success = { response ->
|
||||||
@@ -701,107 +627,4 @@ class LongPollUpdatesParser(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
private fun <T : LongPollParsedEvent> registerListener(
|
|
||||||
eventType: LongPollEvent,
|
|
||||||
listener: VkEventCallback<T>
|
|
||||||
) {
|
|
||||||
listenersMap.let { map ->
|
|
||||||
map[eventType] = (map[eventType] ?: mutableListOf())
|
|
||||||
.also {
|
|
||||||
it.add(listener as VkEventCallback<LongPollParsedEvent>)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun <T : LongPollParsedEvent> registerListeners(
|
|
||||||
eventTypes: List<LongPollEvent>,
|
|
||||||
listener: VkEventCallback<T>
|
|
||||||
) {
|
|
||||||
eventTypes.forEach { eventType -> registerListener(eventType, listener) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageSetFlags(block: (LongPollParsedEvent) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MESSAGE_SET_FLAGS, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageMarkedAsImportant(block: (LongPollParsedEvent.MessageMarkedAsImportant) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MARKED_AS_IMPORTANT, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageMarkedAsSpam(block: (LongPollParsedEvent.MessageMarkedAsSpam) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MARKED_AS_SPAM, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageDeleted(block: (LongPollParsedEvent.MessageDeleted) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MESSAGE_DELETED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageClearFlags(block: (LongPollParsedEvent) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MESSAGE_CLEAR_FLAGS, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageMarkedAsNotSpam(block: (LongPollParsedEvent.MessageMarkedAsNotSpam) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MARKED_AS_NOT_SPAM, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageRestored(block: (LongPollParsedEvent.MessageRestored) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MESSAGE_RESTORED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onNewMessage(block: (LongPollParsedEvent.NewMessage) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MESSAGE_NEW, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageEdited(block: (LongPollParsedEvent.MessageEdited) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.MESSAGE_EDITED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageIncomingRead(block: (LongPollParsedEvent.IncomingMessageRead) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.INCOMING_MESSAGE_READ, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onMessageOutgoingRead(block: (LongPollParsedEvent.OutgoingMessageRead) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.OUTGOING_MESSAGE_READ, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onChatCleared(block: (LongPollParsedEvent.ChatCleared) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.CHAT_CLEARED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onChatMajorChanged(block: (LongPollParsedEvent.ChatMajorChanged) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.CHAT_MAJOR_CHANGED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onChatMinorChanged(block: (LongPollParsedEvent.ChatMinorChanged) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.CHAT_MINOR_CHANGED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onChatArchived(block: (LongPollParsedEvent.ChatArchived) -> Unit) {
|
|
||||||
registerListener(LongPollEvent.CHAT_ARCHIVED, assembleEventCallback(block))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onInteractions(block: (LongPollParsedEvent.Interaction) -> Unit) {
|
|
||||||
registerListeners(
|
|
||||||
eventTypes = listOf(
|
|
||||||
LongPollEvent.TYPING,
|
|
||||||
LongPollEvent.AUDIO_MESSAGE_RECORDING,
|
|
||||||
LongPollEvent.PHOTO_UPLOADING,
|
|
||||||
LongPollEvent.VIDEO_UPLOADING,
|
|
||||||
LongPollEvent.FILE_UPLOADING
|
|
||||||
),
|
|
||||||
listener = assembleEventCallback(block)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal inline fun <R : LongPollParsedEvent> assembleEventCallback(
|
|
||||||
crossinline block: (R) -> Unit,
|
|
||||||
): VkEventCallback<R> {
|
|
||||||
return VkEventCallback { event -> block.invoke(event) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun interface VkEventCallback<in T : LongPollParsedEvent> {
|
|
||||||
fun onEvent(event: T)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ fun VkConvo.extractTitle(
|
|||||||
} else {
|
} else {
|
||||||
val userName = user?.let { user ->
|
val userName = user?.let { user ->
|
||||||
if (useContactName) {
|
if (useContactName) {
|
||||||
VkMemoryCache.getContact(user.id)?.name
|
VkMemoryCache.getContact(user.id)?.name ?: user.fullName
|
||||||
} else {
|
} else {
|
||||||
user.fullName
|
user.fullName
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
/build
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
plugins {
|
||||||
|
alias(libs.plugins.fast.android.library)
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "dev.meloda.fast.logger"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.koin.android)
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dev.meloda.fast.logger;
|
||||||
|
|
||||||
|
enum class FastLogLevel {
|
||||||
|
VERBOSE,
|
||||||
|
DEBUG,
|
||||||
|
INFO,
|
||||||
|
WARNING,
|
||||||
|
ERROR,
|
||||||
|
ASSERT;
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun parse(value: Int): FastLogLevel {
|
||||||
|
if (value !in 0..5) throw IllegalArgumentException("Unknown LogLevel value $value")
|
||||||
|
return entries.first { it.ordinal == value }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package dev.meloda.fast.logger
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
class FastLogger {
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private lateinit var instance: FastLogger
|
||||||
|
|
||||||
|
fun setInstance(logger: FastLogger) {
|
||||||
|
if (::instance.isInitialized) {
|
||||||
|
throw IllegalStateException("FastLogger has already been initialized.")
|
||||||
|
}
|
||||||
|
|
||||||
|
instance = logger
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getInstance(): FastLogger {
|
||||||
|
if (!::instance.isInitialized) {
|
||||||
|
throw UninitializedPropertyAccessException("FastLogger is not initialized.")
|
||||||
|
}
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var logLevel: FastLogLevel = FastLogLevel.ERROR
|
||||||
|
|
||||||
|
fun setLogLevel(logLevel: FastLogLevel) {
|
||||||
|
Log.v(this::class.java.simpleName, "Set LogLevel from ${this.logLevel} to $logLevel")
|
||||||
|
this.logLevel = logLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
fun verbose(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
verbose(clazz.simpleName, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun verbose(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
if (shouldLog(FastLogLevel.VERBOSE)) {
|
||||||
|
Log.v(tag, message, throwable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun debug(clazz: KClass<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
debug(clazz.java, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun debug(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
debug(clazz.simpleName, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun debug(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
if (shouldLog(FastLogLevel.DEBUG)) {
|
||||||
|
Log.d(tag, message, throwable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun info(clazz: KClass<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
info(clazz.java, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun info(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
info(clazz.simpleName, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun info(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
if (shouldLog(FastLogLevel.INFO)) {
|
||||||
|
Log.i(tag, message, throwable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun warning(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
warning(clazz.simpleName, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun warning(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
if (shouldLog(FastLogLevel.WARNING)) {
|
||||||
|
Log.w(tag, message, throwable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun error(clazz: KClass<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
error(clazz.java, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun error(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
error(clazz.simpleName, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun error(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
if (shouldLog(FastLogLevel.ERROR)) {
|
||||||
|
Log.e(tag, message, throwable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun assert(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||||
|
assert(clazz.simpleName, message, throwable)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun assert(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
if (shouldLog(FastLogLevel.ASSERT)) {
|
||||||
|
Log.wtf(tag, message, throwable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shouldLog(level: FastLogLevel): Boolean = level.ordinal >= logLevel.ordinal
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package dev.meloda.fast.logger
|
||||||
|
|
||||||
|
import org.koin.core.module.dsl.singleOf
|
||||||
|
import org.koin.dsl.module
|
||||||
|
|
||||||
|
val loggerModule = module {
|
||||||
|
singleOf(::FastLogger)
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package dev.meloda.fast.model
|
||||||
|
|
||||||
|
import dev.meloda.fast.model.database.AccountEntity
|
||||||
|
|
||||||
|
data class AccountDto(
|
||||||
|
val userId: Long,
|
||||||
|
val accessToken: String,
|
||||||
|
val fastToken: String?,
|
||||||
|
val trustedHash: String?,
|
||||||
|
val exchangeToken: String?
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun mapToEntity(): AccountEntity = AccountEntity(
|
||||||
|
userId = userId,
|
||||||
|
accessToken = accessToken,
|
||||||
|
fastToken = fastToken,
|
||||||
|
trustedHash = trustedHash,
|
||||||
|
exchangeToken = exchangeToken
|
||||||
|
)
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return super.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import dev.meloda.fast.model.api.domain.VkMessage
|
|||||||
|
|
||||||
sealed interface LongPollParsedEvent {
|
sealed interface LongPollParsedEvent {
|
||||||
|
|
||||||
data class NewMessage(
|
data class MessageNew(
|
||||||
val message: VkMessage,
|
val message: VkMessage,
|
||||||
val inArchive: Boolean
|
val inArchive: Boolean
|
||||||
) : LongPollParsedEvent
|
) : LongPollParsedEvent
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
package dev.meloda.fast.model.api.data
|
package dev.meloda.fast.model.api.data
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
|
|
||||||
enum class AttachmentType(var value: String) {
|
enum class AttachmentType(var value: String) {
|
||||||
UNKNOWN("unknown"),
|
UNKNOWN("unknown"),
|
||||||
PHOTO("photo"),
|
PHOTO("photo"),
|
||||||
@@ -42,10 +40,6 @@ enum class AttachmentType(var value: String) {
|
|||||||
it.value == value
|
it.value == value
|
||||||
} ?: UNKNOWN
|
} ?: UNKNOWN
|
||||||
|
|
||||||
if (parsedValue == UNKNOWN) {
|
|
||||||
Log.e("AttachmentType", "Unknown attachment type: $value")
|
|
||||||
}
|
|
||||||
|
|
||||||
return parsedValue
|
return parsedValue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,5 +117,6 @@ fun VkMessageData.asDomain(): VkMessage = VkMessage(
|
|||||||
pinnedAt = pinnedAt,
|
pinnedAt = pinnedAt,
|
||||||
isPinned = isPinned == true,
|
isPinned = isPinned == true,
|
||||||
formatData = formatData?.asDomain(),
|
formatData = formatData?.asDomain(),
|
||||||
isSpam = false
|
isSpam = false,
|
||||||
|
isDeleted = false
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -56,5 +56,6 @@ data class VkPinnedMessageData(
|
|||||||
isPinned = true,
|
isPinned = true,
|
||||||
isSpam = false,
|
isSpam = false,
|
||||||
formatData = null,
|
formatData = null,
|
||||||
|
isDeleted = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ data class VkMessage(
|
|||||||
val group: VkGroupDomain?,
|
val group: VkGroupDomain?,
|
||||||
val actionUser: VkUser?,
|
val actionUser: VkUser?,
|
||||||
val actionGroup: VkGroupDomain?,
|
val actionGroup: VkGroupDomain?,
|
||||||
|
|
||||||
|
val isDeleted: Boolean
|
||||||
) {
|
) {
|
||||||
|
|
||||||
fun isPeerChat() = peerId > 2_000_000_000
|
fun isPeerChat() = peerId > 2_000_000_000
|
||||||
@@ -111,7 +113,7 @@ fun VkMessage.asEntity(): VkMessageEntity = VkMessageEntity(
|
|||||||
actionCmId = actionCmId,
|
actionCmId = actionCmId,
|
||||||
actionMessage = actionMessage,
|
actionMessage = actionMessage,
|
||||||
updateTime = updateTime,
|
updateTime = updateTime,
|
||||||
important = isImportant,
|
isImportant = isImportant,
|
||||||
forwardIds = forwards.orEmpty().map(VkMessage::id),
|
forwardIds = forwards.orEmpty().map(VkMessage::id),
|
||||||
// TODO: 05/05/2024, Danil Nikolaev: save attachments
|
// TODO: 05/05/2024, Danil Nikolaev: save attachments
|
||||||
attachments = emptyList(),
|
attachments = emptyList(),
|
||||||
@@ -119,4 +121,6 @@ fun VkMessage.asEntity(): VkMessageEntity = VkMessageEntity(
|
|||||||
geoType = geoType,
|
geoType = geoType,
|
||||||
pinnedAt = pinnedAt,
|
pinnedAt = pinnedAt,
|
||||||
isPinned = isPinned,
|
isPinned = isPinned,
|
||||||
|
isDeleted = isDeleted,
|
||||||
|
isSpam = isSpam
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ data class GetFriendsRequest(
|
|||||||
val order: String?,
|
val order: String?,
|
||||||
val count: Int?,
|
val count: Int?,
|
||||||
val offset: Int?,
|
val offset: Int?,
|
||||||
val fields: String?
|
val fields: String?,
|
||||||
|
val extended: Boolean?
|
||||||
) {
|
) {
|
||||||
|
|
||||||
val map
|
val map
|
||||||
@@ -14,6 +15,7 @@ data class GetFriendsRequest(
|
|||||||
count?.let { this["count"] = it.toString() }
|
count?.let { this["count"] = it.toString() }
|
||||||
offset?.let { this["offset"] = it.toString() }
|
offset?.let { this["offset"] = it.toString() }
|
||||||
fields?.let { this["fields"] = it }
|
fields?.let { this["fields"] = it }
|
||||||
|
extended?.let { this["extended"] = it.toString() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package dev.meloda.fast.model.api.responses
|
package dev.meloda.fast.model.api.responses
|
||||||
|
|
||||||
import dev.meloda.fast.model.api.data.VkUserData
|
|
||||||
import com.squareup.moshi.Json
|
import com.squareup.moshi.Json
|
||||||
import com.squareup.moshi.JsonClass
|
import com.squareup.moshi.JsonClass
|
||||||
|
import dev.meloda.fast.model.api.data.VkContactData
|
||||||
|
import dev.meloda.fast.model.api.data.VkUserData
|
||||||
|
|
||||||
@JsonClass(generateAdapter = true)
|
@JsonClass(generateAdapter = true)
|
||||||
data class GetFriendsResponse(
|
data class GetFriendsResponse(
|
||||||
@Json(name = "count") val count: Int,
|
@Json(name = "count") val count: Int,
|
||||||
@Json(name = "items") val items: List<VkUserData>
|
@Json(name = "items") val items: List<VkUserData>,
|
||||||
|
@Json(name = "contacts") val contacts: List<VkContactData>?
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package dev.meloda.fast.model.database
|
|||||||
|
|
||||||
import androidx.room.Entity
|
import androidx.room.Entity
|
||||||
import androidx.room.PrimaryKey
|
import androidx.room.PrimaryKey
|
||||||
|
import dev.meloda.fast.model.AccountDto
|
||||||
|
|
||||||
@Entity(tableName = "accounts")
|
@Entity(tableName = "accounts")
|
||||||
data class AccountEntity(
|
data class AccountEntity(
|
||||||
@@ -11,4 +12,12 @@ data class AccountEntity(
|
|||||||
val fastToken: String?,
|
val fastToken: String?,
|
||||||
val trustedHash: String?,
|
val trustedHash: String?,
|
||||||
val exchangeToken: String?
|
val exchangeToken: String?
|
||||||
)
|
) {
|
||||||
|
fun mapToDto(): AccountDto = AccountDto(
|
||||||
|
userId = userId,
|
||||||
|
accessToken = accessToken,
|
||||||
|
fastToken = fastToken,
|
||||||
|
trustedHash = trustedHash,
|
||||||
|
exchangeToken = exchangeToken
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,13 +21,15 @@ data class VkMessageEntity(
|
|||||||
val actionCmId: Long?,
|
val actionCmId: Long?,
|
||||||
val actionMessage: String?,
|
val actionMessage: String?,
|
||||||
val updateTime: Int?,
|
val updateTime: Int?,
|
||||||
val important: Boolean,
|
val isImportant: Boolean,
|
||||||
val forwardIds: List<Long>?,
|
val forwardIds: List<Long>?,
|
||||||
val attachments: List<String>?, // TODO: 01/05/2024, Danil Nikolaev: how to store???
|
val attachments: List<String>?, // TODO: 01/05/2024, Danil Nikolaev: how to store???
|
||||||
val replyMessageId: Long?,
|
val replyMessageId: Long?,
|
||||||
val geoType: String?,
|
val geoType: String?,
|
||||||
val pinnedAt: Int?,
|
val pinnedAt: Int?,
|
||||||
val isPinned: Boolean
|
val isPinned: Boolean,
|
||||||
|
val isDeleted: Boolean,
|
||||||
|
val isSpam: Boolean
|
||||||
)
|
)
|
||||||
|
|
||||||
fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
||||||
@@ -45,7 +47,7 @@ fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
|||||||
actionCmId = actionCmId,
|
actionCmId = actionCmId,
|
||||||
actionMessage = actionMessage,
|
actionMessage = actionMessage,
|
||||||
updateTime = updateTime,
|
updateTime = updateTime,
|
||||||
isImportant = important,
|
isImportant = isImportant,
|
||||||
forwards = emptyList(),//forwards.orEmpty().map(VkMessageEntity::asExternalModel),
|
forwards = emptyList(),//forwards.orEmpty().map(VkMessageEntity::asExternalModel),
|
||||||
// TODO: 05/05/2024, Danil Nikolaev: restore attachments
|
// TODO: 05/05/2024, Danil Nikolaev: restore attachments
|
||||||
attachments = attachments.orEmpty().map { VkUnknownAttachment },
|
attachments = attachments.orEmpty().map { VkUnknownAttachment },
|
||||||
@@ -59,4 +61,5 @@ fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
|||||||
isPinned = isPinned,
|
isPinned = isPinned,
|
||||||
isSpam = false,
|
isSpam = false,
|
||||||
formatData = null,
|
formatData = null,
|
||||||
|
isDeleted = isDeleted
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ dependencies {
|
|||||||
api(projects.core.common)
|
api(projects.core.common)
|
||||||
api(projects.core.model)
|
api(projects.core.model)
|
||||||
api(projects.core.datastore)
|
api(projects.core.datastore)
|
||||||
|
api(projects.core.logger)
|
||||||
|
|
||||||
implementation(libs.moshi.kotlin)
|
implementation(libs.moshi.kotlin)
|
||||||
implementation(libs.koin.android)
|
implementation(libs.koin.android)
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
package dev.meloda.fast.network
|
package dev.meloda.fast.network
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import com.slack.eithernet.ApiException
|
import com.slack.eithernet.ApiException
|
||||||
import com.slack.eithernet.errorType
|
import com.slack.eithernet.errorType
|
||||||
import com.slack.eithernet.toType
|
import com.slack.eithernet.toType
|
||||||
import com.squareup.moshi.JsonDataException
|
import com.squareup.moshi.JsonDataException
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import okhttp3.ResponseBody
|
import okhttp3.ResponseBody
|
||||||
import retrofit2.Converter
|
import retrofit2.Converter
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
@@ -16,7 +16,10 @@ import java.lang.reflect.Type
|
|||||||
*
|
*
|
||||||
* допускает Unit как SuccessType в случае невозможности каста ответа в ErrorType
|
* допускает Unit как SuccessType в случае невозможности каста ответа в ErrorType
|
||||||
*/
|
*/
|
||||||
class ResponseConverterFactory(private val converter: JsonConverter) : Converter.Factory() {
|
class ResponseConverterFactory(
|
||||||
|
private val converter: JsonConverter,
|
||||||
|
private val logger: FastLogger
|
||||||
|
) : Converter.Factory() {
|
||||||
|
|
||||||
override fun responseBodyConverter(
|
override fun responseBodyConverter(
|
||||||
type: Type,
|
type: Type,
|
||||||
@@ -29,6 +32,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
|||||||
successType = type,
|
successType = type,
|
||||||
errorRaw = errorRaw,
|
errorRaw = errorRaw,
|
||||||
converter = converter,
|
converter = converter,
|
||||||
|
logger = logger
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +40,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
|||||||
private val successType: Type,
|
private val successType: Type,
|
||||||
private val errorRaw: Class<*>,
|
private val errorRaw: Class<*>,
|
||||||
private val converter: JsonConverter,
|
private val converter: JsonConverter,
|
||||||
|
private val logger: FastLogger
|
||||||
) : Converter<ResponseBody, Any?> {
|
) : Converter<ResponseBody, Any?> {
|
||||||
override fun convert(value: ResponseBody): Any? {
|
override fun convert(value: ResponseBody): Any? {
|
||||||
val string = value.string()
|
val string = value.string()
|
||||||
@@ -53,7 +58,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
|||||||
},
|
},
|
||||||
onFailure = { failure ->
|
onFailure = { failure ->
|
||||||
if (failure is JsonDataException) {
|
if (failure is JsonDataException) {
|
||||||
Log.d("ResponseBodyConverter", "convertJsonDataException: $failure")
|
logger.error(this::class, "convert(): ERROR", failure)
|
||||||
throw ApiException(
|
throw ApiException(
|
||||||
RestApiError(
|
RestApiError(
|
||||||
errorCode = -1,
|
errorCode = -1,
|
||||||
@@ -68,10 +73,11 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
|||||||
converter.fromJson(errorRaw, string)
|
converter.fromJson(errorRaw, string)
|
||||||
}.fold(
|
}.fold(
|
||||||
onSuccess = { errorModel ->
|
onSuccess = { errorModel ->
|
||||||
Log.d("ResponseBodyConverter", "convert: $errorModel")
|
logger.debug(this::class, "convert(): errorModel: $errorModel")
|
||||||
throw ApiException(errorModel)
|
throw ApiException(errorModel)
|
||||||
},
|
},
|
||||||
onFailure = { exception ->
|
onFailure = { exception ->
|
||||||
|
logger.error(this::class, "convert(): INNER: ERROR", exception)
|
||||||
if (!isUnit) {
|
if (!isUnit) {
|
||||||
throw exception
|
throw exception
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import com.slack.eithernet.integration.retrofit.ApiResultConverterFactory
|
|||||||
import com.squareup.moshi.Moshi
|
import com.squareup.moshi.Moshi
|
||||||
import dev.meloda.fast.common.AppConstants
|
import dev.meloda.fast.common.AppConstants
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.network.JsonConverter
|
import dev.meloda.fast.network.JsonConverter
|
||||||
import dev.meloda.fast.network.MoshiConverter
|
import dev.meloda.fast.network.MoshiConverter
|
||||||
import dev.meloda.fast.network.OAuthResultCallFactory
|
import dev.meloda.fast.network.OAuthResultCallFactory
|
||||||
@@ -123,7 +124,12 @@ private fun Scope.buildRetrofit(client: OkHttpClient): Retrofit {
|
|||||||
.baseUrl("${AppConstants.URL_API}/")
|
.baseUrl("${AppConstants.URL_API}/")
|
||||||
.addConverterFactory(ApiResultConverterFactory)
|
.addConverterFactory(ApiResultConverterFactory)
|
||||||
.addCallAdapterFactory(ApiResultCallAdapterFactory)
|
.addCallAdapterFactory(ApiResultCallAdapterFactory)
|
||||||
.addConverterFactory(ResponseConverterFactory(get<JsonConverter>()))
|
.addConverterFactory(
|
||||||
|
ResponseConverterFactory(
|
||||||
|
get<JsonConverter>(),
|
||||||
|
get<FastLogger>()
|
||||||
|
)
|
||||||
|
)
|
||||||
.addConverterFactory(MoshiConverterFactory.create(get()))
|
.addConverterFactory(MoshiConverterFactory.create(get()))
|
||||||
.client(client)
|
.client(client)
|
||||||
.build()
|
.build()
|
||||||
|
|||||||
+11
-13
@@ -1,9 +1,9 @@
|
|||||||
package dev.meloda.fast.network.interceptor
|
package dev.meloda.fast.network.interceptor
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import dev.meloda.fast.common.extensions.listenValue
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
import dev.meloda.fast.datastore.CaptchaTokenResult
|
import dev.meloda.fast.datastore.CaptchaTokenResult
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
@@ -14,11 +14,7 @@ import org.json.JSONObject
|
|||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.atomic.AtomicReference
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
|
|
||||||
class Error14HandlingInterceptor(
|
class Error14HandlingInterceptor(private val logger: FastLogger) : Interceptor {
|
||||||
// private val domains: Set<String> = emptySet(),
|
|
||||||
) : Interceptor {
|
|
||||||
|
|
||||||
private val cookie = AtomicReference<String?>(null)
|
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
private const val CAPTCHA_ERROR_CODE = 14
|
private const val CAPTCHA_ERROR_CODE = 14
|
||||||
@@ -26,6 +22,8 @@ class Error14HandlingInterceptor(
|
|||||||
private val executor = Executors.newSingleThreadExecutor()
|
private val executor = Executors.newSingleThreadExecutor()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val cookie = AtomicReference<String?>(null)
|
||||||
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val request = chain.request().withCookie()
|
val request = chain.request().withCookie()
|
||||||
val response = chain.proceed(request)
|
val response = chain.proceed(request)
|
||||||
@@ -41,23 +39,23 @@ class Error14HandlingInterceptor(
|
|||||||
|
|
||||||
executor.submit {
|
executor.submit {
|
||||||
AppSettings.setCaptchaRedirectUri(redirectUri)
|
AppSettings.setCaptchaRedirectUri(redirectUri)
|
||||||
Log.d("Error14Interceptor", "passCaptchaAndGetToken: $redirectUri")
|
logger.debug(this::class, "passCaptchaAndGetToken: $redirectUri")
|
||||||
|
|
||||||
var job: Job? = null
|
var job: Job? = null
|
||||||
job = AppSettings.getCaptchaResultFlow()
|
job = AppSettings.getCaptchaResultFlow()
|
||||||
.listenValue(CoroutineScope(Dispatchers.IO)) {
|
.listenValue(CoroutineScope(Dispatchers.IO)) {
|
||||||
Log.d("Error14Interceptor", "passCaptchaAndGetToken: $it")
|
logger.debug(this::class, "passCaptchaAndGetToken: $it")
|
||||||
if (it != CaptchaTokenResult.Initial) {
|
if (it != CaptchaTokenResult.Initial) {
|
||||||
synchronized(tokenResult) {
|
synchronized(tokenResult) {
|
||||||
Log.d(
|
logger.debug(
|
||||||
"Error14Interceptor",
|
this::class,
|
||||||
"passCaptchaAndGetToken: SYNCHRONIZED: $it"
|
"passCaptchaAndGetToken: SYNCHRONIZED: $it"
|
||||||
)
|
)
|
||||||
tokenResult.set(wrapResult(it))
|
tokenResult.set(wrapResult(it))
|
||||||
tokenResult.notifyAll()
|
tokenResult.notifyAll()
|
||||||
job?.cancel()
|
job?.cancel()
|
||||||
Log.d(
|
logger.debug(
|
||||||
"Error14Interceptor",
|
this::class,
|
||||||
"passCaptchaAndGetToken: NULL RESULT"
|
"passCaptchaAndGetToken: NULL RESULT"
|
||||||
)
|
)
|
||||||
AppSettings.setCaptchaResult(CaptchaTokenResult.Initial)
|
AppSettings.setCaptchaResult(CaptchaTokenResult.Initial)
|
||||||
@@ -71,7 +69,7 @@ class Error14HandlingInterceptor(
|
|||||||
tokenResult.wait()
|
tokenResult.wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d("Error14Interceptor", "passCaptchaAndGetToken: GET VALUE")
|
logger.debug(this::class, "passCaptchaAndGetToken: GET VALUE")
|
||||||
tokenResult.get().getOrThrow()
|
tokenResult.get().getOrThrow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ android {
|
|||||||
dependencies {
|
dependencies {
|
||||||
api(projects.core.common)
|
api(projects.core.common)
|
||||||
api(projects.core.model)
|
api(projects.core.model)
|
||||||
|
api(projects.core.logger)
|
||||||
implementation(projects.core.presentation)
|
implementation(projects.core.presentation)
|
||||||
|
|
||||||
implementation(libs.haze)
|
implementation(libs.haze)
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package dev.meloda.fast.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.runtime.compositionLocalOf
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
|
|
||||||
|
val LocalLogger = compositionLocalOf { FastLogger.getInstance() }
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package dev.meloda.fast.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.runtime.compositionLocalOf
|
||||||
|
import dev.meloda.fast.common.model.NetworkState
|
||||||
|
|
||||||
|
val LocalNetworkState = compositionLocalOf { NetworkState.DISCONNECTED }
|
||||||
@@ -189,6 +189,7 @@
|
|||||||
<string name="title_application_language">Application language</string>
|
<string name="title_application_language">Application language</string>
|
||||||
<string name="action_refresh">Refresh</string>
|
<string name="action_refresh">Refresh</string>
|
||||||
<string name="title_loading">Loading…</string>
|
<string name="title_loading">Loading…</string>
|
||||||
|
<string name="title_no_network">No network…</string>
|
||||||
<string name="title_convos">Conversations</string>
|
<string name="title_convos">Conversations</string>
|
||||||
<string name="title_archive">Archive</string>
|
<string name="title_archive">Archive</string>
|
||||||
<string name="title_friends">Friends</string>
|
<string name="title_friends">Friends</string>
|
||||||
|
|||||||
+14
-8
@@ -1,7 +1,6 @@
|
|||||||
package dev.meloda.fast.auth.captcha.presentation
|
package dev.meloda.fast.auth.captcha.presentation
|
||||||
|
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.util.Log
|
|
||||||
import android.webkit.JavascriptInterface
|
import android.webkit.JavascriptInterface
|
||||||
import android.webkit.WebResourceRequest
|
import android.webkit.WebResourceRequest
|
||||||
import android.webkit.WebView
|
import android.webkit.WebView
|
||||||
@@ -32,7 +31,9 @@ import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
|||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.viewinterop.AndroidView
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
|
import dev.meloda.fast.ui.common.LocalLogger
|
||||||
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
||||||
import dev.meloda.fast.ui.components.FullScreenDialog
|
import dev.meloda.fast.ui.components.FullScreenDialog
|
||||||
import dev.meloda.fast.ui.components.MaterialDialog
|
import dev.meloda.fast.ui.components.MaterialDialog
|
||||||
@@ -46,6 +47,8 @@ fun CaptchaScreen(
|
|||||||
onBack: () -> Unit = {},
|
onBack: () -> Unit = {},
|
||||||
onResult: (String) -> Unit = {}
|
onResult: (String) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
|
val logger = LocalLogger.current
|
||||||
|
|
||||||
if (captchaRedirectUri != null) {
|
if (captchaRedirectUri != null) {
|
||||||
val focusManager = LocalFocusManager.current
|
val focusManager = LocalFocusManager.current
|
||||||
val keyboardController = LocalSoftwareKeyboardController.current
|
val keyboardController = LocalSoftwareKeyboardController.current
|
||||||
@@ -114,7 +117,10 @@ fun CaptchaScreen(
|
|||||||
view: WebView?,
|
view: WebView?,
|
||||||
request: WebResourceRequest?
|
request: WebResourceRequest?
|
||||||
): Boolean {
|
): Boolean {
|
||||||
Log.i(TAG, "shouldOverrideUrlLoading: $request")
|
logger.info(
|
||||||
|
"CaptchaScreen",
|
||||||
|
"WebViewClient(): shouldOverrideUrlLoading(): request: $request"
|
||||||
|
)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +154,8 @@ fun CaptchaScreen(
|
|||||||
// TODO: 03/05/2026, Danil Nikolaev: show error
|
// TODO: 03/05/2026, Danil Nikolaev: show error
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onCloseRequested = { showExitAlert = true }
|
onCloseRequested = { showExitAlert = true },
|
||||||
|
logger = logger
|
||||||
),
|
),
|
||||||
"AndroidBridge"
|
"AndroidBridge"
|
||||||
)
|
)
|
||||||
@@ -176,19 +183,18 @@ fun CaptchaScreen(
|
|||||||
|
|
||||||
class WebCaptchaListener(
|
class WebCaptchaListener(
|
||||||
private val onSuccessTokenReceived: (String) -> Unit,
|
private val onSuccessTokenReceived: (String) -> Unit,
|
||||||
private val onCloseRequested: (String) -> Unit
|
private val onCloseRequested: (String) -> Unit,
|
||||||
|
private val logger: FastLogger
|
||||||
) {
|
) {
|
||||||
private val tag = "WebCaptchaListener"
|
|
||||||
|
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun VKCaptchaGetResult(arg: String) {
|
fun VKCaptchaGetResult(arg: String) {
|
||||||
onSuccessTokenReceived(arg)
|
onSuccessTokenReceived(arg)
|
||||||
Log.i(tag, "VKCaptchaGetResult($arg)")
|
logger.info(this::class, "VKCaptchaGetResult(): arg: $arg")
|
||||||
}
|
}
|
||||||
|
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun VKCaptchaCloseCaptcha(arg: String) {
|
fun VKCaptchaCloseCaptcha(arg: String) {
|
||||||
onCloseRequested(arg)
|
onCloseRequested(arg)
|
||||||
Log.i(tag, "VKCaptchaCloseCaptcha($arg)")
|
logger.info(this::class, "VKCaptchaCloseCaptcha(): arg: $arg")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package dev.meloda.fast.auth.login
|
|||||||
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.util.Log
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import dev.meloda.fast.auth.login.model.CaptchaArguments
|
import dev.meloda.fast.auth.login.model.CaptchaArguments
|
||||||
@@ -28,7 +27,8 @@ import dev.meloda.fast.datastore.AppSettings
|
|||||||
import dev.meloda.fast.datastore.UserSettings
|
import dev.meloda.fast.datastore.UserSettings
|
||||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||||
import dev.meloda.fast.domain.OAuthUseCase
|
import dev.meloda.fast.domain.OAuthUseCase
|
||||||
import dev.meloda.fast.model.database.AccountEntity
|
import dev.meloda.fast.logger.FastLogger
|
||||||
|
import dev.meloda.fast.model.AccountDto
|
||||||
import dev.meloda.fast.network.OAuthErrorDomain
|
import dev.meloda.fast.network.OAuthErrorDomain
|
||||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -48,7 +48,8 @@ class LoginViewModel(
|
|||||||
private val accountsRepository: AccountsRepository,
|
private val accountsRepository: AccountsRepository,
|
||||||
private val loginValidator: LoginValidator,
|
private val loginValidator: LoginValidator,
|
||||||
private val longPollController: LongPollController,
|
private val longPollController: LongPollController,
|
||||||
private val userSettings: UserSettings
|
private val userSettings: UserSettings,
|
||||||
|
private val logger: FastLogger
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
private val _screenState = MutableStateFlow(LoginScreenState.EMPTY)
|
private val _screenState = MutableStateFlow(LoginScreenState.EMPTY)
|
||||||
val screenState = _screenState.asStateFlow()
|
val screenState = _screenState.asStateFlow()
|
||||||
@@ -189,7 +190,7 @@ class LoginViewModel(
|
|||||||
).listenValue(viewModelScope) { state ->
|
).listenValue(viewModelScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.d("LoginViewModelImpl", "login: error: $error")
|
logger.error(this::class, "getSilentToken(): ERROR: $error")
|
||||||
|
|
||||||
_screenState.updateValue { copy(isLoading = false) }
|
_screenState.updateValue { copy(isLoading = false) }
|
||||||
|
|
||||||
@@ -235,7 +236,7 @@ class LoginViewModel(
|
|||||||
|
|
||||||
// TODO: 30-Mar-25, Danil Nikolaev: get fast's app token
|
// TODO: 30-Mar-25, Danil Nikolaev: get fast's app token
|
||||||
|
|
||||||
val currentAccount = AccountEntity(
|
val currentAccount = AccountDto(
|
||||||
userId = userId,
|
userId = userId,
|
||||||
accessToken = accessToken,
|
accessToken = accessToken,
|
||||||
fastToken = null,
|
fastToken = null,
|
||||||
@@ -250,7 +251,7 @@ class LoginViewModel(
|
|||||||
UserConfig.exchangeToken = account.exchangeToken
|
UserConfig.exchangeToken = account.exchangeToken
|
||||||
}
|
}
|
||||||
|
|
||||||
accountsRepository.storeAccounts(listOf(currentAccount))
|
accountsRepository.storeAccounts(listOf(currentAccount.mapToEntity()))
|
||||||
|
|
||||||
startLongPoll()
|
startLongPoll()
|
||||||
|
|
||||||
|
|||||||
+1
-5
@@ -1,6 +1,5 @@
|
|||||||
package dev.meloda.fast.chatmaterials.util
|
package dev.meloda.fast.chatmaterials.util
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import dev.meloda.fast.chatmaterials.model.UiChatMaterial
|
import dev.meloda.fast.chatmaterials.model.UiChatMaterial
|
||||||
import dev.meloda.fast.common.util.AndroidUtils
|
import dev.meloda.fast.common.util.AndroidUtils
|
||||||
import dev.meloda.fast.model.api.data.AttachmentType
|
import dev.meloda.fast.model.api.data.AttachmentType
|
||||||
@@ -135,8 +134,5 @@ fun VkAttachmentHistoryMessage.asPresentation(): UiChatMaterial? =
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> null
|
||||||
Log.w("ChatMaterialMapper", "Unsupported type: $type")
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,206 +3,244 @@ package dev.meloda.fast.convos
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.res.Resources
|
import android.content.res.Resources
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import androidx.compose.runtime.Immutable
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import coil.ImageLoader
|
import coil.ImageLoader
|
||||||
import coil.request.ImageRequest
|
import coil.request.ImageRequest
|
||||||
import com.conena.nanokt.collections.indexOfFirstOrNull
|
import com.conena.nanokt.collections.indexOfFirstOrNull
|
||||||
|
import dev.meloda.fast.common.NetworkStateListener
|
||||||
import dev.meloda.fast.common.VkConstants
|
import dev.meloda.fast.common.VkConstants
|
||||||
import dev.meloda.fast.common.extensions.createTimerFlow
|
import dev.meloda.fast.common.extensions.createTimerFlow
|
||||||
import dev.meloda.fast.common.extensions.findWithIndex
|
import dev.meloda.fast.common.extensions.findWithIndex
|
||||||
import dev.meloda.fast.common.extensions.listenValue
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
import dev.meloda.fast.common.extensions.setValue
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
import dev.meloda.fast.common.extensions.updateValue
|
import dev.meloda.fast.common.extensions.updateValue
|
||||||
|
import dev.meloda.fast.common.model.NetworkState
|
||||||
import dev.meloda.fast.convos.model.ConvoDialog
|
import dev.meloda.fast.convos.model.ConvoDialog
|
||||||
import dev.meloda.fast.convos.model.ConvoNavigation
|
import dev.meloda.fast.convos.model.ConvoIntent
|
||||||
|
import dev.meloda.fast.convos.model.ConvoNavigationIntent
|
||||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||||
import dev.meloda.fast.convos.model.InteractionJob
|
import dev.meloda.fast.convos.model.InteractionJob
|
||||||
import dev.meloda.fast.convos.model.NewInteractionException
|
import dev.meloda.fast.convos.model.NewInteractionException
|
||||||
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.data.VkUtils
|
import dev.meloda.fast.data.VkUtils
|
||||||
import dev.meloda.fast.data.processState
|
import dev.meloda.fast.data.processState
|
||||||
import dev.meloda.fast.datastore.UserSettings
|
import dev.meloda.fast.datastore.UserSettings
|
||||||
import dev.meloda.fast.domain.ConvoUseCase
|
import dev.meloda.fast.domain.ConvoUseCase
|
||||||
import dev.meloda.fast.domain.LoadConvosByIdUseCase
|
import dev.meloda.fast.domain.LoadConvosByIdUseCase
|
||||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||||
import dev.meloda.fast.domain.MessagesUseCase
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
import dev.meloda.fast.domain.util.asPresentation
|
import dev.meloda.fast.domain.util.asPresentation
|
||||||
import dev.meloda.fast.domain.util.extractAvatar
|
import dev.meloda.fast.domain.util.extractAvatar
|
||||||
import dev.meloda.fast.model.BaseError
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.model.ConvosFilter
|
import dev.meloda.fast.model.ConvosFilter
|
||||||
import dev.meloda.fast.model.InteractionType
|
import dev.meloda.fast.model.InteractionType
|
||||||
import dev.meloda.fast.model.LongPollParsedEvent
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
import dev.meloda.fast.model.api.domain.VkConvo
|
import dev.meloda.fast.model.api.domain.VkConvo
|
||||||
import dev.meloda.fast.ui.model.vk.ConvoOption
|
import dev.meloda.fast.ui.model.vk.ConvoOption
|
||||||
import dev.meloda.fast.ui.model.vk.UiConvo
|
import dev.meloda.fast.ui.model.vk.UiConvo
|
||||||
|
import dev.meloda.fast.ui.util.ImmutableList
|
||||||
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
||||||
|
import dev.meloda.fast.ui.util.buildImmutableList
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.launchIn
|
import kotlinx.coroutines.flow.launchIn
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import kotlinx.coroutines.flow.stateIn
|
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
|
|
||||||
|
@Immutable
|
||||||
class ConvosViewModel(
|
class ConvosViewModel(
|
||||||
updatesParser: LongPollUpdatesParser,
|
eventsHandler: LongPollEventsHandler,
|
||||||
private val filter: ConvosFilter,
|
val filter: ConvosFilter,
|
||||||
private val convoUseCase: ConvoUseCase,
|
private val convoUseCase: ConvoUseCase,
|
||||||
private val messagesUseCase: MessagesUseCase,
|
private val messagesUseCase: MessagesUseCase,
|
||||||
private val resources: Resources,
|
private val resources: Resources,
|
||||||
private val userSettings: UserSettings,
|
private val userSettings: UserSettings,
|
||||||
private val imageLoader: ImageLoader,
|
private val imageLoader: ImageLoader,
|
||||||
private val applicationContext: Context,
|
private val applicationContext: Context,
|
||||||
private val loadConvosByIdUseCase: LoadConvosByIdUseCase
|
private val loadConvosByIdUseCase: LoadConvosByIdUseCase,
|
||||||
|
private val networkStateListener: NetworkStateListener,
|
||||||
|
private val logger: FastLogger
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
private val _screenState = MutableStateFlow(ConvosScreenState.EMPTY)
|
|
||||||
val screenState = _screenState.asStateFlow()
|
|
||||||
|
|
||||||
private val _navigation = MutableStateFlow<ConvoNavigation?>(null)
|
private val screenState = MutableStateFlow(ConvosScreenState.EMPTY)
|
||||||
val navigation = _navigation.asStateFlow()
|
val screenStateFlow get() = screenState.asStateFlow()
|
||||||
|
|
||||||
private val _dialog = MutableStateFlow<ConvoDialog?>(null)
|
private val navigationIntent = MutableStateFlow<ConvoNavigationIntent?>(null)
|
||||||
val dialog = _dialog.asStateFlow()
|
val navigationIntentFlow get() = navigationIntent.asStateFlow()
|
||||||
|
|
||||||
private val _convos = MutableStateFlow<List<VkConvo>>(emptyList())
|
private val convos: MutableList<VkConvo> = mutableListOf()
|
||||||
val convos = _convos.asStateFlow()
|
|
||||||
|
|
||||||
private val _uiConvos = MutableStateFlow<List<UiConvo>>(emptyList())
|
private val pinnedConvosCount get() = convos.count(VkConvo::isPinned)
|
||||||
val uiConvos = _uiConvos.asStateFlow()
|
|
||||||
|
|
||||||
private val pinnedConvosCount = convos.map { convos ->
|
private var currentOffset = 0
|
||||||
convos.count(VkConvo::isPinned)
|
|
||||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, 0)
|
|
||||||
|
|
||||||
private val _baseError = MutableStateFlow<BaseError?>(null)
|
|
||||||
val baseError = _baseError.asStateFlow()
|
|
||||||
|
|
||||||
private val _currentOffset = MutableStateFlow(0)
|
|
||||||
val currentOffset = _currentOffset.asStateFlow()
|
|
||||||
|
|
||||||
private val _canPaginate = MutableStateFlow(false)
|
|
||||||
val canPaginate = _canPaginate.asStateFlow()
|
|
||||||
|
|
||||||
private val expandedConvoId = MutableStateFlow(0L)
|
|
||||||
|
|
||||||
private val useContactNames: Boolean get() = userSettings.useContactNames.value
|
|
||||||
|
|
||||||
private val interactionsTimers = hashMapOf<Long, InteractionJob?>()
|
private val interactionsTimers = hashMapOf<Long, InteractionJob?>()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
_screenState.updateValue { copy(isArchive = filter == ConvosFilter.ARCHIVE) }
|
|
||||||
|
|
||||||
loadConvos()
|
loadConvos()
|
||||||
|
|
||||||
updatesParser.onNewMessage(::handleNewMessage)
|
eventsHandler.onMessageNew(::handleNewMessage)
|
||||||
updatesParser.onMessageEdited(::handleEditedMessage)
|
eventsHandler.onMessageEdit(::handleEditedMessage)
|
||||||
updatesParser.onMessageIncomingRead(::handleReadIncomingMessage)
|
eventsHandler.onMessageIncomingRead(::handleReadIncomingMessage)
|
||||||
updatesParser.onMessageOutgoingRead(::handleReadOutgoingMessage)
|
eventsHandler.onMessageOutgoingRead(::handleReadOutgoingMessage)
|
||||||
updatesParser.onInteractions(::handleInteraction)
|
eventsHandler.onInteraction(::handleInteraction)
|
||||||
updatesParser.onChatMajorChanged(::handleChatMajorChanged)
|
eventsHandler.onChatMajorChange(::handleChatMajorChanged)
|
||||||
updatesParser.onChatMinorChanged(::handleChatMinorChanged)
|
eventsHandler.onChatMinorChange(::handleChatMinorChanged)
|
||||||
updatesParser.onChatCleared(::handleChatClearing)
|
eventsHandler.onChatClear(::handleChatClearing)
|
||||||
updatesParser.onChatArchived(::handleChatArchived)
|
eventsHandler.onChatArchive(::handleChatArchived)
|
||||||
|
|
||||||
userSettings.useContactNames.listenValue(viewModelScope) {
|
userSettings.useContactNames.listenValue(viewModelScope) {
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
networkStateListener.networkStateFlow.listenValue { state ->
|
||||||
|
logger.debug(this@ConvosViewModel::class, "network state changed: $state")
|
||||||
|
|
||||||
|
if (state == NetworkState.CONNECTED) {
|
||||||
|
if (screenState.value.error != null) {
|
||||||
|
onRefresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun handleIntent(intent: ConvoIntent) {
|
||||||
|
when (intent) {
|
||||||
|
ConvoIntent.ArchiveClick -> {
|
||||||
|
navigationIntent.setValue { ConvoNavigationIntent.Archive }
|
||||||
|
}
|
||||||
|
|
||||||
|
ConvoIntent.Back -> {
|
||||||
|
navigationIntent.setValue { ConvoNavigationIntent.Back }
|
||||||
|
}
|
||||||
|
|
||||||
|
ConvoIntent.ConsumeScrollToTop -> Unit
|
||||||
|
ConvoIntent.CreateChatClick -> {
|
||||||
|
navigationIntent.setValue { ConvoNavigationIntent.CreateChat }
|
||||||
|
}
|
||||||
|
|
||||||
|
ConvoIntent.ErrorActionButtonClick -> {
|
||||||
|
onRefresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
is ConvoIntent.ItemClick -> {
|
||||||
|
onConvoItemClick(intent.convoId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ConvoIntent.ItemLongClick -> {
|
||||||
|
onConvoItemLongClick(intent.convoId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ConvoIntent.OptionItemClick -> {
|
||||||
|
onOptionClicked(intent.option)
|
||||||
|
}
|
||||||
|
|
||||||
|
ConvoIntent.PaginationConditionsMet -> {
|
||||||
|
onPaginationConditionsMet()
|
||||||
|
}
|
||||||
|
|
||||||
|
ConvoIntent.Refresh -> {
|
||||||
|
onRefresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
is ConvoIntent.SetScrollIndex -> {
|
||||||
|
setScrollIndex(intent.index)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ConvoIntent.SetScrollOffset -> {
|
||||||
|
setScrollOffset(intent.offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ConvoIntent.Dialog -> {
|
||||||
|
when (intent) {
|
||||||
|
is ConvoIntent.Dialog.Cancel -> Unit
|
||||||
|
is ConvoIntent.Dialog.Confirm -> onDialogConfirmed(intent.bundle)
|
||||||
|
ConvoIntent.Dialog.Dismiss -> onDialogDismissed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onNavigationConsumed() {
|
fun onNavigationConsumed() {
|
||||||
_navigation.setValue { null }
|
navigationIntent.setValue { null }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDialogConfirmed(dialog: ConvoDialog, bundle: Bundle) {
|
private fun onDialogConfirmed(bundle: Bundle?) {
|
||||||
onDialogDismissed(dialog)
|
val dialog = screenState.value.dialog ?: return
|
||||||
|
onDialogDismissed()
|
||||||
|
|
||||||
|
val convo = with(screenState.value) {
|
||||||
|
convos.find { it.id == expandedConvoId }
|
||||||
|
} ?: return
|
||||||
|
|
||||||
when (dialog) {
|
when (dialog) {
|
||||||
is ConvoDialog.ConvoDelete -> {
|
is ConvoDialog.Delete -> {
|
||||||
deleteConvo(dialog.convoId)
|
deleteConvo(convo.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoPin -> {
|
is ConvoDialog.Pin -> {
|
||||||
pinConvo(dialog.convoId, true)
|
pinConvo(convo.id, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoUnpin -> {
|
is ConvoDialog.Unpin -> {
|
||||||
pinConvo(dialog.convoId, false)
|
pinConvo(convo.id, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoArchive -> {
|
is ConvoDialog.Archive -> {
|
||||||
archiveConvo(dialog.convoId, true)
|
archiveConvo(convo.id, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoUnarchive -> {
|
is ConvoDialog.Unarchive -> {
|
||||||
archiveConvo(dialog.convoId, false)
|
archiveConvo(convo.id, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
expandedConvoId.setValue { 0 }
|
collapseConvos(false)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDialogDismissed(dialog: ConvoDialog) {
|
private fun onDialogDismissed() {
|
||||||
_dialog.setValue { null }
|
screenState.updateValue { copy(dialog = null) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDialogItemPicked(dialog: ConvoDialog, bundle: Bundle) {
|
private fun onPaginationConditionsMet() {
|
||||||
when (dialog) {
|
currentOffset = convos.size
|
||||||
is ConvoDialog.ConvoDelete -> Unit
|
|
||||||
is ConvoDialog.ConvoPin -> Unit
|
|
||||||
is ConvoDialog.ConvoUnpin -> Unit
|
|
||||||
is ConvoDialog.ConvoArchive -> Unit
|
|
||||||
is ConvoDialog.ConvoUnarchive -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onErrorButtonClicked() {
|
|
||||||
when (baseError.value) {
|
|
||||||
null -> Unit
|
|
||||||
|
|
||||||
is BaseError.ConnectionError,
|
|
||||||
is BaseError.InternalError,
|
|
||||||
is BaseError.SimpleError,
|
|
||||||
is BaseError.UnknownError -> onRefresh()
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onPaginationConditionsMet() {
|
|
||||||
_currentOffset.update { convos.value.size }
|
|
||||||
loadConvos()
|
loadConvos()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onRefresh() {
|
private fun clearError() {
|
||||||
onErrorConsumed()
|
screenState.updateValue { copy(error = null) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onRefresh() {
|
||||||
|
clearError()
|
||||||
loadConvos(offset = 0)
|
loadConvos(offset = 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onConvoItemClick(convo: UiConvo) {
|
private fun onConvoItemClick(convoId: Long) {
|
||||||
collapseConvos()
|
collapseConvos()
|
||||||
_navigation.setValue { ConvoNavigation.MessagesHistory(peerId = convo.id) }
|
navigationIntent.setValue { ConvoNavigationIntent.MessagesHistory(convoId) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onConvoItemLongClick(convo: UiConvo) {
|
private fun onConvoItemLongClick(convoId: Long) {
|
||||||
expandedConvoId.setValue {
|
val isExpanded = screenState.value.convos.find { it.id == convoId }?.isExpanded == true
|
||||||
if (convo.isExpanded) 0
|
|
||||||
else convo.id
|
screenState.updateValue { copy(expandedConvoId = if (isExpanded) 0L else convoId) }
|
||||||
}
|
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onOptionClicked(
|
private fun onOptionClicked(option: ConvoOption) {
|
||||||
convo: UiConvo,
|
val convo =
|
||||||
option: ConvoOption
|
screenState.value.convos.find { it.id == screenState.value.expandedConvoId } ?: return
|
||||||
) {
|
|
||||||
when (option) {
|
when (option) {
|
||||||
ConvoOption.Delete -> {
|
ConvoOption.Delete -> setDialog(ConvoDialog.Delete)
|
||||||
_dialog.setValue { ConvoDialog.ConvoDelete(convo.id) }
|
|
||||||
}
|
|
||||||
|
|
||||||
ConvoOption.MarkAsRead -> {
|
ConvoOption.MarkAsRead -> {
|
||||||
convo.lastMessageId?.let { lastMessageId ->
|
val lastMessageId =
|
||||||
|
screenState.value.convos.find { it.id == screenState.value.expandedConvoId }?.lastMessageId
|
||||||
|
|
||||||
|
if (lastMessageId != null) {
|
||||||
readConvo(
|
readConvo(
|
||||||
peerId = convo.id,
|
peerId = convo.id,
|
||||||
startMessageId = lastMessageId
|
startMessageId = lastMessageId
|
||||||
@@ -211,48 +249,39 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ConvoOption.Pin -> {
|
ConvoOption.Pin -> setDialog(ConvoDialog.Pin)
|
||||||
_dialog.setValue { ConvoDialog.ConvoPin(convo.id) }
|
ConvoOption.Unpin -> setDialog(ConvoDialog.Unpin)
|
||||||
}
|
ConvoOption.Archive -> setDialog(ConvoDialog.Archive)
|
||||||
|
ConvoOption.Unarchive -> setDialog(ConvoDialog.Unarchive)
|
||||||
ConvoOption.Unpin -> {
|
|
||||||
_dialog.setValue { ConvoDialog.ConvoUnpin(convo.id) }
|
|
||||||
}
|
|
||||||
|
|
||||||
ConvoOption.Archive -> {
|
|
||||||
_dialog.setValue { ConvoDialog.ConvoArchive(convo.id) }
|
|
||||||
}
|
|
||||||
|
|
||||||
ConvoOption.Unarchive -> {
|
|
||||||
_dialog.setValue { ConvoDialog.ConvoUnarchive(convo.id) }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onErrorConsumed() {
|
private fun setScrollIndex(index: Int) {
|
||||||
_baseError.setValue { null }
|
screenState.setValue { old -> old.copy(scrollIndex = index) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setScrollIndex(index: Int) {
|
private fun setScrollOffset(offset: Int) {
|
||||||
_screenState.setValue { old -> old.copy(scrollIndex = index) }
|
screenState.setValue { old -> old.copy(scrollOffset = offset) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setScrollOffset(offset: Int) {
|
private fun setDialog(dialog: ConvoDialog?) {
|
||||||
_screenState.setValue { old -> old.copy(scrollOffset = offset) }
|
screenState.updateValue { copy(dialog = dialog) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onCreateChatButtonClicked() {
|
private fun replaceConvos(newConvos: List<VkConvo>) {
|
||||||
_navigation.setValue { ConvoNavigation.CreateChat }
|
convos.clear()
|
||||||
|
convos.addAll(newConvos)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun collapseConvos() {
|
private fun collapseConvos(sync: Boolean = true) {
|
||||||
expandedConvoId.setValue { 0 }
|
screenState.updateValue { copy(expandedConvoId = null) }
|
||||||
|
|
||||||
|
if (sync) {
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun loadConvos(
|
private fun loadConvos(offset: Int = currentOffset) {
|
||||||
offset: Int = currentOffset.value
|
|
||||||
) {
|
|
||||||
convoUseCase.getConvos(
|
convoUseCase.getConvos(
|
||||||
count = LOAD_COUNT,
|
count = LOAD_COUNT,
|
||||||
offset = offset,
|
offset = offset,
|
||||||
@@ -260,23 +289,20 @@ class ConvosViewModel(
|
|||||||
).listenValue(viewModelScope) { state ->
|
).listenValue(viewModelScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
val newBaseError = VkUtils.parseError(error)
|
screenState.updateValue { copy(error = VkUtils.parseError(error)) }
|
||||||
_baseError.update { newBaseError }
|
|
||||||
},
|
},
|
||||||
success = { response ->
|
success = { response ->
|
||||||
val convos = response
|
val newConvos = if (offset == 0) {
|
||||||
val fullConvos = if (offset == 0) {
|
response
|
||||||
convos
|
|
||||||
} else {
|
} else {
|
||||||
this.convos.value.plus(convos)
|
convos.plus(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
val itemsCountSufficient = response.size == LOAD_COUNT
|
val itemsCountSufficient = response.size == LOAD_COUNT
|
||||||
|
|
||||||
val paginationExhausted = !itemsCountSufficient &&
|
val paginationExhausted = !itemsCountSufficient && convos.isNotEmpty()
|
||||||
this.convos.value.isNotEmpty()
|
|
||||||
|
|
||||||
_screenState.updateValue {
|
screenState.updateValue {
|
||||||
copy(isPaginationExhausted = paginationExhausted)
|
copy(isPaginationExhausted = paginationExhausted)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,13 +319,14 @@ class ConvosViewModel(
|
|||||||
|
|
||||||
convoUseCase.storeConvos(response)
|
convoUseCase.storeConvos(response)
|
||||||
|
|
||||||
_convos.emit(fullConvos)
|
replaceConvos(newConvos)
|
||||||
|
|
||||||
|
screenState.updateValue { copy(canPaginate = itemsCountSufficient) }
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
_canPaginate.setValue { itemsCountSufficient }
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
_screenState.setValue { old ->
|
screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
isLoading = offset == 0 && state.isLoading(),
|
isLoading = offset == 0 && state.isLoading(),
|
||||||
isPaginating = offset > 0 && state.isLoading()
|
isPaginating = offset > 0 && state.isLoading()
|
||||||
@@ -313,17 +340,17 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == peerId }
|
newConvos.indexOfFirstOrNull { it.id == peerId }
|
||||||
?: return@processState
|
?: return@processState
|
||||||
|
|
||||||
newConvos.removeAt(convoIndex)
|
newConvos.removeAt(convoIndex)
|
||||||
_convos.update { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
_screenState.emit(screenState.value.copy(isLoading = state.isLoading()))
|
screenState.emit(screenStateFlow.value.copy(isLoading = state.isLoading()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,7 +364,7 @@ class ConvosViewModel(
|
|||||||
LongPollParsedEvent.ChatMajorChanged(
|
LongPollParsedEvent.ChatMajorChanged(
|
||||||
peerId = peerId,
|
peerId = peerId,
|
||||||
majorId = if (pin) {
|
majorId = if (pin) {
|
||||||
pinnedConvosCount.value.plus(1) * 16
|
pinnedConvosCount.plus(1) * 16
|
||||||
} else {
|
} else {
|
||||||
0
|
0
|
||||||
}
|
}
|
||||||
@@ -346,7 +373,7 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
_screenState.setValue { old -> old.copy(isLoading = state.isLoading()) }
|
screenState.setValue { old -> old.copy(isLoading = state.isLoading()) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -356,7 +383,7 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
convos.value.find { it.id == peerId }?.let { convo ->
|
convos.find { it.id == peerId }?.let { convo ->
|
||||||
handleChatArchived(
|
handleChatArchived(
|
||||||
LongPollParsedEvent.ChatArchived(
|
LongPollParsedEvent.ChatArchived(
|
||||||
convo = convo,
|
convo = convo,
|
||||||
@@ -370,10 +397,10 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: 03-Apr-25, Danil Nikolaev: handle business messages
|
// TODO: 03-Apr-25, Danil Nikolaev: handle business messages
|
||||||
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
|
private fun handleNewMessage(event: LongPollParsedEvent.MessageNew) {
|
||||||
val message = event.message
|
val message = event.message
|
||||||
|
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
||||||
|
|
||||||
@@ -391,8 +418,8 @@ class ConvosViewModel(
|
|||||||
val convo = (response.firstOrNull() ?: return@listenValue)
|
val convo = (response.firstOrNull() ?: return@listenValue)
|
||||||
.copy(lastMessage = message)
|
.copy(lastMessage = message)
|
||||||
|
|
||||||
newConvos.add(pinnedConvosCount.value, convo)
|
newConvos.add(pinnedConvosCount, convo)
|
||||||
_convos.update { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -428,19 +455,17 @@ class ConvosViewModel(
|
|||||||
newConvos[convoIndex] = newConvo
|
newConvos[convoIndex] = newConvo
|
||||||
} else {
|
} else {
|
||||||
newConvos.removeAt(convoIndex)
|
newConvos.removeAt(convoIndex)
|
||||||
|
newConvos.add(pinnedConvosCount, newConvo)
|
||||||
val toPosition = pinnedConvosCount.value
|
|
||||||
newConvos.add(toPosition, newConvo)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_convos.update { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) {
|
private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) {
|
||||||
val message = event.message
|
val message = event.message
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
|
|
||||||
val convoIndex = newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
val convoIndex = newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
if (convoIndex == null) { // диалога нет в списке
|
||||||
@@ -452,13 +477,14 @@ class ConvosViewModel(
|
|||||||
lastMessageId = message.id,
|
lastMessageId = message.id,
|
||||||
lastCmId = message.cmId
|
lastCmId = message.cmId
|
||||||
)
|
)
|
||||||
_convos.update { newConvos }
|
|
||||||
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) {
|
private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
|
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||||
@@ -472,13 +498,13 @@ class ConvosViewModel(
|
|||||||
unreadCount = event.unreadCount
|
unreadCount = event.unreadCount
|
||||||
)
|
)
|
||||||
|
|
||||||
_convos.update { newConvos }
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) {
|
private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
|
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||||
@@ -492,7 +518,7 @@ class ConvosViewModel(
|
|||||||
unreadCount = event.unreadCount
|
unreadCount = event.unreadCount
|
||||||
)
|
)
|
||||||
|
|
||||||
_convos.update { newConvos }
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -502,7 +528,7 @@ class ConvosViewModel(
|
|||||||
val peerId = event.peerId
|
val peerId = event.peerId
|
||||||
val userIds = event.userIds
|
val userIds = event.userIds
|
||||||
|
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoAndIndex =
|
val convoAndIndex =
|
||||||
newConvos.findWithIndex { it.id == peerId }
|
newConvos.findWithIndex { it.id == peerId }
|
||||||
|
|
||||||
@@ -513,7 +539,7 @@ class ConvosViewModel(
|
|||||||
interactionIds = userIds
|
interactionIds = userIds
|
||||||
)
|
)
|
||||||
|
|
||||||
_convos.update { newConvos }
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
|
|
||||||
interactionsTimers[peerId]?.let { interactionJob ->
|
interactionsTimers[peerId]?.let { interactionJob ->
|
||||||
@@ -545,7 +571,7 @@ class ConvosViewModel(
|
|||||||
private fun stopInteraction(peerId: Long, interactionJob: InteractionJob) {
|
private fun stopInteraction(peerId: Long, interactionJob: InteractionJob) {
|
||||||
interactionsTimers[peerId] ?: return
|
interactionsTimers[peerId] ?: return
|
||||||
|
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoAndIndex =
|
val convoAndIndex =
|
||||||
newConvos.findWithIndex { it.id == peerId } ?: return
|
newConvos.findWithIndex { it.id == peerId } ?: return
|
||||||
|
|
||||||
@@ -555,7 +581,7 @@ class ConvosViewModel(
|
|||||||
interactionIds = emptyList()
|
interactionIds = emptyList()
|
||||||
)
|
)
|
||||||
|
|
||||||
_convos.update { newConvos }
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
|
|
||||||
interactionJob.timerJob.cancel()
|
interactionJob.timerJob.cancel()
|
||||||
@@ -563,7 +589,7 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) {
|
private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||||
|
|
||||||
@@ -573,13 +599,13 @@ class ConvosViewModel(
|
|||||||
newConvos[convoIndex] =
|
newConvos[convoIndex] =
|
||||||
newConvos[convoIndex].copy(majorId = event.majorId)
|
newConvos[convoIndex].copy(majorId = event.majorId)
|
||||||
|
|
||||||
_convos.setValue { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) {
|
private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||||
|
|
||||||
@@ -589,22 +615,23 @@ class ConvosViewModel(
|
|||||||
newConvos[convoIndex] =
|
newConvos[convoIndex] =
|
||||||
newConvos[convoIndex].copy(minorId = event.minorId)
|
newConvos[convoIndex].copy(minorId = event.minorId)
|
||||||
|
|
||||||
_convos.setValue { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) {
|
private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
|
|
||||||
val convoIndex = newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
val convoIndex = newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||||
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
if (convoIndex == null) { // диалога нет в списке
|
||||||
// pizdets
|
// pizdets
|
||||||
} else {
|
} else {
|
||||||
|
// TODO: 30.05.2026, Danil Nikolaev: reimplement
|
||||||
newConvos.removeAt(convoIndex)
|
newConvos.removeAt(convoIndex)
|
||||||
|
|
||||||
_convos.setValue { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -612,7 +639,7 @@ class ConvosViewModel(
|
|||||||
private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) {
|
private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) {
|
||||||
val convo = event.convo
|
val convo = event.convo
|
||||||
|
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
|
|
||||||
when (filter) {
|
when (filter) {
|
||||||
ConvosFilter.BUSINESS_NOTIFY -> Unit
|
ConvosFilter.BUSINESS_NOTIFY -> Unit
|
||||||
@@ -627,7 +654,7 @@ class ConvosViewModel(
|
|||||||
newConvos.removeAt(index)
|
newConvos.removeAt(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
_convos.update { newConvos }
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,10 +665,10 @@ class ConvosViewModel(
|
|||||||
|
|
||||||
newConvos.removeAt(index)
|
newConvos.removeAt(index)
|
||||||
} else {
|
} else {
|
||||||
newConvos.add(pinnedConvosCount.value, convo)
|
newConvos.add(pinnedConvosCount, convo)
|
||||||
}
|
}
|
||||||
|
|
||||||
_convos.update { newConvos.sorted() }
|
replaceConvos(newConvos.sorted())
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -655,7 +682,7 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
val newConvos = convos.value.toMutableList()
|
val newConvos = convos.toMutableList()
|
||||||
val convoIndex =
|
val convoIndex =
|
||||||
newConvos.indexOfFirstOrNull { it.id == peerId }
|
newConvos.indexOfFirstOrNull { it.id == peerId }
|
||||||
?: return@listenValue
|
?: return@listenValue
|
||||||
@@ -663,7 +690,7 @@ class ConvosViewModel(
|
|||||||
newConvos[convoIndex] =
|
newConvos[convoIndex] =
|
||||||
newConvos[convoIndex].copy(inRead = startMessageId)
|
newConvos[convoIndex].copy(inRead = startMessageId)
|
||||||
|
|
||||||
_convos.update { newConvos }
|
replaceConvos(newConvos)
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -695,47 +722,44 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun syncUiConvos(): List<UiConvo> {
|
private fun syncUiConvos(): List<UiConvo> {
|
||||||
val convos = convos.value
|
|
||||||
|
|
||||||
val newUiConvos = convos.map { convo ->
|
val newUiConvos = convos.map { convo ->
|
||||||
val options = mutableListOf<ConvoOption>()
|
val options: ImmutableList<ConvoOption> = buildImmutableList {
|
||||||
convo.lastMessage?.run {
|
if (!convo.isRead() && convo.lastMessage != null && convo.lastMessage?.isOut == false) {
|
||||||
if (!convo.isRead() && !this.isOut) {
|
add(ConvoOption.MarkAsRead)
|
||||||
options += ConvoOption.MarkAsRead
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
val convosSize = this.convos.value.size
|
|
||||||
val pinnedCount = pinnedConvosCount.value
|
|
||||||
|
|
||||||
val canPinOneMoreDialog =
|
|
||||||
convosSize > 4 && pinnedCount < 5 && !convo.isPinned()
|
|
||||||
|
|
||||||
if (convo.isPinned()) {
|
if (convo.isPinned()) {
|
||||||
options += ConvoOption.Unpin
|
add(ConvoOption.Unpin)
|
||||||
} else if (canPinOneMoreDialog) {
|
}
|
||||||
options += ConvoOption.Pin
|
|
||||||
|
if (convos.size > 4 && pinnedConvosCount < 5 && !convo.isPinned()) {
|
||||||
|
add(ConvoOption.Pin)
|
||||||
}
|
}
|
||||||
|
|
||||||
when (filter) {
|
when (filter) {
|
||||||
ConvosFilter.ARCHIVE -> ConvoOption.Unarchive
|
ConvosFilter.BUSINESS_NOTIFY -> Unit
|
||||||
|
ConvosFilter.ARCHIVE -> add(ConvoOption.Unarchive)
|
||||||
|
|
||||||
ConvosFilter.UNREAD,
|
ConvosFilter.ALL,
|
||||||
ConvosFilter.ALL -> ConvoOption.Archive
|
ConvosFilter.UNREAD -> {
|
||||||
|
if (convo.id != UserConfig.userId) {
|
||||||
|
add(ConvoOption.Archive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
ConvosFilter.BUSINESS_NOTIFY -> null
|
add(ConvoOption.Delete)
|
||||||
}?.let(options::add)
|
}
|
||||||
|
|
||||||
options += ConvoOption.Delete
|
|
||||||
|
|
||||||
convo.asPresentation(
|
convo.asPresentation(
|
||||||
resources = resources,
|
resources = resources,
|
||||||
useContactName = useContactNames,
|
useContactName = userSettings.useContactNames.value,
|
||||||
isExpanded = expandedConvoId.value == convo.id,
|
isExpanded = screenState.value.expandedConvoId == convo.id,
|
||||||
options = options.toImmutableList()
|
options = options
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
_uiConvos.setValue { newUiConvos }
|
|
||||||
|
screenState.updateValue { copy(convos = newUiConvos.toImmutableList()) }
|
||||||
|
|
||||||
return newUiConvos
|
return newUiConvos
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,13 +25,15 @@ val convosModule = module {
|
|||||||
private fun Scope.createConvosViewModel(filter: ConvosFilter): ConvosViewModel {
|
private fun Scope.createConvosViewModel(filter: ConvosFilter): ConvosViewModel {
|
||||||
return ConvosViewModel(
|
return ConvosViewModel(
|
||||||
filter = filter,
|
filter = filter,
|
||||||
updatesParser = get(),
|
eventsHandler = get(),
|
||||||
convoUseCase = get(),
|
convoUseCase = get(),
|
||||||
messagesUseCase = get(),
|
messagesUseCase = get(),
|
||||||
resources = get(),
|
resources = get(),
|
||||||
userSettings = get(),
|
userSettings = get(),
|
||||||
imageLoader = get(),
|
imageLoader = get(),
|
||||||
applicationContext = get(),
|
applicationContext = get(),
|
||||||
loadConvosByIdUseCase = get()
|
loadConvosByIdUseCase = get(),
|
||||||
|
networkStateListener = get(),
|
||||||
|
logger = get()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import androidx.compose.runtime.Immutable
|
|||||||
|
|
||||||
@Immutable
|
@Immutable
|
||||||
sealed class ConvoDialog {
|
sealed class ConvoDialog {
|
||||||
data class ConvoPin(val convoId: Long) : ConvoDialog()
|
data object Pin : ConvoDialog()
|
||||||
data class ConvoUnpin(val convoId: Long) : ConvoDialog()
|
data object Unpin : ConvoDialog()
|
||||||
data class ConvoDelete(val convoId: Long) : ConvoDialog()
|
data object Delete : ConvoDialog()
|
||||||
data class ConvoArchive(val convoId: Long) : ConvoDialog()
|
data object Archive : ConvoDialog()
|
||||||
data class ConvoUnarchive(val convoId: Long) : ConvoDialog()
|
data object Unarchive : ConvoDialog()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package dev.meloda.fast.convos.model
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import dev.meloda.fast.ui.model.vk.ConvoOption
|
||||||
|
|
||||||
|
sealed class ConvoIntent {
|
||||||
|
data class ItemClick(val convoId: Long) : ConvoIntent()
|
||||||
|
data class ItemLongClick(val convoId: Long) : ConvoIntent()
|
||||||
|
data class OptionItemClick(val option: ConvoOption) : ConvoIntent()
|
||||||
|
data object PaginationConditionsMet : ConvoIntent()
|
||||||
|
|
||||||
|
data object Back : ConvoIntent()
|
||||||
|
data object Refresh : ConvoIntent()
|
||||||
|
data object CreateChatClick : ConvoIntent()
|
||||||
|
data object ArchiveClick : ConvoIntent()
|
||||||
|
|
||||||
|
data class SetScrollIndex(val index: Int) : ConvoIntent()
|
||||||
|
data class SetScrollOffset(val offset: Int) : ConvoIntent()
|
||||||
|
|
||||||
|
data object ErrorActionButtonClick : ConvoIntent()
|
||||||
|
|
||||||
|
data object ConsumeScrollToTop : ConvoIntent()
|
||||||
|
|
||||||
|
sealed class Dialog : ConvoIntent() {
|
||||||
|
data object Dismiss : Dialog()
|
||||||
|
data class Confirm(val bundle: Bundle? = null) : Dialog()
|
||||||
|
data class Cancel(val bundle: Bundle? = null) : Dialog()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package dev.meloda.fast.convos.model
|
|
||||||
|
|
||||||
import androidx.compose.runtime.Immutable
|
|
||||||
|
|
||||||
@Immutable
|
|
||||||
sealed class ConvoNavigation {
|
|
||||||
|
|
||||||
data class MessagesHistory(val peerId: Long) : ConvoNavigation()
|
|
||||||
|
|
||||||
data object CreateChat : ConvoNavigation()
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package dev.meloda.fast.convos.model
|
||||||
|
|
||||||
|
sealed class ConvoNavigationIntent {
|
||||||
|
|
||||||
|
data object Back : ConvoNavigationIntent()
|
||||||
|
data class MessagesHistory(val convoId: Long) : ConvoNavigationIntent()
|
||||||
|
data object CreateChat : ConvoNavigationIntent()
|
||||||
|
data object Archive : ConvoNavigationIntent()
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
package dev.meloda.fast.convos.model
|
package dev.meloda.fast.convos.model
|
||||||
|
|
||||||
import androidx.compose.runtime.Immutable
|
import androidx.compose.runtime.Immutable
|
||||||
|
import dev.meloda.fast.model.BaseError
|
||||||
|
import dev.meloda.fast.ui.model.vk.UiConvo
|
||||||
|
import dev.meloda.fast.ui.util.ImmutableList
|
||||||
|
import dev.meloda.fast.ui.util.emptyImmutableList
|
||||||
|
|
||||||
@Immutable
|
@Immutable
|
||||||
data class ConvosScreenState(
|
data class ConvosScreenState(
|
||||||
@@ -10,7 +14,13 @@ data class ConvosScreenState(
|
|||||||
val profileImageUrl: String?,
|
val profileImageUrl: String?,
|
||||||
val scrollIndex: Int,
|
val scrollIndex: Int,
|
||||||
val scrollOffset: Int,
|
val scrollOffset: Int,
|
||||||
val isArchive: Boolean
|
val canPaginate: Boolean,
|
||||||
|
val expandedConvoId: Long?,
|
||||||
|
val convos: ImmutableList<UiConvo>,
|
||||||
|
val dialog: ConvoDialog?,
|
||||||
|
|
||||||
|
// TODO: 30.05.2026, Danil Nikolaev: remove
|
||||||
|
val error: BaseError?
|
||||||
) {
|
) {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -21,7 +31,11 @@ data class ConvosScreenState(
|
|||||||
profileImageUrl = null,
|
profileImageUrl = null,
|
||||||
scrollIndex = 0,
|
scrollIndex = 0,
|
||||||
scrollOffset = 0,
|
scrollOffset = 0,
|
||||||
isArchive = false
|
canPaginate = false,
|
||||||
|
expandedConvoId = null,
|
||||||
|
convos = emptyImmutableList(),
|
||||||
|
dialog = null,
|
||||||
|
error = null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+44
-28
@@ -1,12 +1,16 @@
|
|||||||
package dev.meloda.fast.convos.navigation
|
package dev.meloda.fast.convos.navigation
|
||||||
|
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.navigation.NavGraphBuilder
|
import androidx.navigation.NavGraphBuilder
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import androidx.navigation.navigation
|
import androidx.navigation.navigation
|
||||||
import dev.meloda.fast.convos.ConvosViewModel
|
import dev.meloda.fast.convos.ConvosViewModel
|
||||||
|
import dev.meloda.fast.convos.model.ConvoNavigationIntent
|
||||||
import dev.meloda.fast.convos.presentation.ConvosRoute
|
import dev.meloda.fast.convos.presentation.ConvosRoute
|
||||||
import dev.meloda.fast.model.BaseError
|
|
||||||
import dev.meloda.fast.model.ConvosFilter
|
import dev.meloda.fast.model.ConvosFilter
|
||||||
import dev.meloda.fast.ui.extensions.getOrThrow
|
import dev.meloda.fast.ui.extensions.getOrThrow
|
||||||
import dev.meloda.fast.ui.theme.LocalNavController
|
import dev.meloda.fast.ui.theme.LocalNavController
|
||||||
@@ -24,44 +28,56 @@ object Convos
|
|||||||
object Archive
|
object Archive
|
||||||
|
|
||||||
fun NavGraphBuilder.convosGraph(
|
fun NavGraphBuilder.convosGraph(
|
||||||
|
handleNavigationIntent: (ConvoNavigationIntent) -> Unit,
|
||||||
activity: AppCompatActivity,
|
activity: AppCompatActivity,
|
||||||
onError: (BaseError) -> Unit,
|
|
||||||
onNavigateToMessagesHistory: (id: Long) -> Unit,
|
|
||||||
onNavigateToCreateChat: () -> Unit,
|
|
||||||
onScrolledToTop: () -> Unit
|
|
||||||
) {
|
) {
|
||||||
navigation<ConvoGraph>(
|
navigation<ConvoGraph>(
|
||||||
startDestination = Convos
|
startDestination = Convos
|
||||||
) {
|
) {
|
||||||
val convosViewModel: ConvosViewModel = with(activity) {
|
|
||||||
getViewModel(qualifier = named(ConvosFilter.ALL))
|
|
||||||
}
|
|
||||||
composable<Convos> {
|
composable<Convos> {
|
||||||
val navController = LocalNavController.getOrThrow()
|
ConvosRootRoute(
|
||||||
|
handleNavigationIntent = handleNavigationIntent,
|
||||||
ConvosRoute(
|
viewModel = with(activity) {
|
||||||
viewModel = convosViewModel,
|
getViewModel(named(ConvosFilter.ALL))
|
||||||
onError = onError,
|
}
|
||||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
|
||||||
onNavigateToCreateChat = onNavigateToCreateChat,
|
|
||||||
onNavigateToArchive = { navController.navigate(Archive) },
|
|
||||||
onScrolledToTop = onScrolledToTop
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
composable<Archive> {
|
composable<Archive> {
|
||||||
val navController = LocalNavController.getOrThrow()
|
ConvosRootRoute(
|
||||||
|
handleNavigationIntent = handleNavigationIntent,
|
||||||
ConvosRoute(
|
|
||||||
viewModel = with(activity) {
|
viewModel = with(activity) {
|
||||||
getViewModel<ConvosViewModel>(
|
getViewModel<ConvosViewModel>(named(ConvosFilter.ARCHIVE))
|
||||||
qualifier = named(ConvosFilter.ARCHIVE)
|
}
|
||||||
)
|
|
||||||
},
|
|
||||||
onBack = navController::navigateUp,
|
|
||||||
onError = onError,
|
|
||||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
|
||||||
onScrolledToTop = onScrolledToTop
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ConvosRootRoute(
|
||||||
|
handleNavigationIntent: (ConvoNavigationIntent) -> Unit,
|
||||||
|
viewModel: ConvosViewModel
|
||||||
|
) {
|
||||||
|
val navController = LocalNavController.getOrThrow()
|
||||||
|
|
||||||
|
val screenState by viewModel.screenStateFlow.collectAsStateWithLifecycle()
|
||||||
|
val navigationIntent by viewModel.navigationIntentFlow.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
LaunchedEffect(navigationIntent) {
|
||||||
|
navigationIntent?.let {
|
||||||
|
when (navigationIntent) {
|
||||||
|
ConvoNavigationIntent.Back -> navController.navigateUp()
|
||||||
|
ConvoNavigationIntent.Archive -> navController.navigate(Archive)
|
||||||
|
else -> handleNavigationIntent(it)
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModel.onNavigationConsumed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ConvosRoute(
|
||||||
|
handleIntent = viewModel::handleIntent,
|
||||||
|
screenState = screenState,
|
||||||
|
isArchive = viewModel.filter == ConvosFilter.ARCHIVE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
+18
-22
@@ -1,82 +1,78 @@
|
|||||||
package dev.meloda.fast.convos.presentation
|
package dev.meloda.fast.convos.presentation
|
||||||
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.res.vectorResource
|
import androidx.compose.ui.res.vectorResource
|
||||||
import androidx.core.os.bundleOf
|
|
||||||
import dev.meloda.fast.convos.model.ConvoDialog
|
import dev.meloda.fast.convos.model.ConvoDialog
|
||||||
|
import dev.meloda.fast.convos.model.ConvoIntent
|
||||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
import dev.meloda.fast.ui.components.MaterialDialog
|
import dev.meloda.fast.ui.components.MaterialDialog
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun HandleDialogs(
|
fun HandleDialogs(
|
||||||
|
handleIntent: (ConvoIntent) -> Unit,
|
||||||
screenState: ConvosScreenState,
|
screenState: ConvosScreenState,
|
||||||
dialog: ConvoDialog?,
|
|
||||||
onConfirmed: (ConvoDialog, Bundle) -> Unit = { _, _ -> },
|
|
||||||
onDismissed: (ConvoDialog) -> Unit = {},
|
|
||||||
onItemPicked: (ConvoDialog, Bundle) -> Unit = { _, _ -> }
|
|
||||||
) {
|
) {
|
||||||
when (dialog) {
|
when (screenState.dialog) {
|
||||||
null -> Unit
|
null -> Unit
|
||||||
|
|
||||||
is ConvoDialog.ConvoArchive -> {
|
is ConvoDialog.Archive -> {
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||||
title = stringResource(id = R.string.confirm_archive_convo),
|
title = stringResource(id = R.string.confirm_archive_convo),
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||||
confirmText = stringResource(id = R.string.action_archive),
|
confirmText = stringResource(id = R.string.action_archive),
|
||||||
cancelText = stringResource(id = R.string.cancel),
|
cancelText = stringResource(id = R.string.cancel),
|
||||||
icon = ImageVector.vectorResource(R.drawable.ic_archive_fill_round_24)
|
icon = ImageVector.vectorResource(R.drawable.ic_archive_fill_round_24)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoUnarchive -> {
|
is ConvoDialog.Unarchive -> {
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||||
title = stringResource(id = R.string.confirm_unarchive_convo),
|
title = stringResource(id = R.string.confirm_unarchive_convo),
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||||
confirmText = stringResource(id = R.string.action_unarchive),
|
confirmText = stringResource(id = R.string.action_unarchive),
|
||||||
cancelText = stringResource(id = R.string.cancel),
|
cancelText = stringResource(id = R.string.cancel),
|
||||||
icon = ImageVector.vectorResource(R.drawable.ic_unarchive_fill_round_24)
|
icon = ImageVector.vectorResource(R.drawable.ic_unarchive_fill_round_24)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoDelete -> {
|
is ConvoDialog.Delete -> {
|
||||||
val errorColor = MaterialTheme.colorScheme.error
|
val errorColor = MaterialTheme.colorScheme.error
|
||||||
|
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||||
icon = ImageVector.vectorResource(R.drawable.ic_delete_fill_round_24),
|
icon = ImageVector.vectorResource(R.drawable.ic_delete_fill_round_24),
|
||||||
iconTint = errorColor,
|
iconTint = errorColor,
|
||||||
title = stringResource(id = R.string.confirm_delete_convo),
|
title = stringResource(id = R.string.confirm_delete_convo),
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||||
confirmText = stringResource(id = R.string.action_delete),
|
confirmText = stringResource(id = R.string.action_delete),
|
||||||
confirmContainerColor = errorColor,
|
confirmContainerColor = errorColor,
|
||||||
cancelText = stringResource(id = R.string.cancel),
|
cancelText = stringResource(id = R.string.cancel),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoPin -> {
|
is ConvoDialog.Pin -> {
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||||
icon = ImageVector.vectorResource(R.drawable.ic_keep_fill_round_24),
|
icon = ImageVector.vectorResource(R.drawable.ic_keep_fill_round_24),
|
||||||
title = stringResource(id = R.string.confirm_pin_convo),
|
title = stringResource(id = R.string.confirm_pin_convo),
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||||
confirmText = stringResource(id = R.string.action_pin),
|
confirmText = stringResource(id = R.string.action_pin),
|
||||||
cancelText = stringResource(id = R.string.cancel),
|
cancelText = stringResource(id = R.string.cancel),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
is ConvoDialog.ConvoUnpin -> {
|
is ConvoDialog.Unpin -> {
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||||
icon = ImageVector.vectorResource(R.drawable.ic_keep_off_fill_round_24),
|
icon = ImageVector.vectorResource(R.drawable.ic_keep_off_fill_round_24),
|
||||||
title = stringResource(id = R.string.confirm_unpin_convo),
|
title = stringResource(id = R.string.confirm_unpin_convo),
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||||
confirmText = stringResource(id = R.string.action_unpin),
|
confirmText = stringResource(id = R.string.action_unpin),
|
||||||
cancelText = stringResource(id = R.string.cancel),
|
cancelText = stringResource(id = R.string.cancel),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -62,9 +62,9 @@ val BirthdayColor = Color(0xffb00b69)
|
|||||||
@OptIn(ExperimentalFoundationApi::class)
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun ConvoItem(
|
fun ConvoItem(
|
||||||
onItemClick: (UiConvo) -> Unit,
|
onItemClick: (convoId: Long) -> Unit,
|
||||||
onItemLongClick: (convo: UiConvo) -> Unit,
|
onItemLongClick: (convoId: Long) -> Unit,
|
||||||
onOptionClicked: (UiConvo, ConvoOption) -> Unit,
|
onOptionClicked: (ConvoOption) -> Unit,
|
||||||
maxLines: Int,
|
maxLines: Int,
|
||||||
isUserAccount: Boolean,
|
isUserAccount: Boolean,
|
||||||
convo: UiConvo,
|
convo: UiConvo,
|
||||||
@@ -81,9 +81,9 @@ fun ConvoItem(
|
|||||||
modifier = modifier
|
modifier = modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
onClick = { onItemClick(convo) },
|
onClick = { onItemClick(convo.id) },
|
||||||
onLongClick = {
|
onLongClick = {
|
||||||
onItemLongClick(convo)
|
onItemLongClick(convo.id)
|
||||||
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
|
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -281,7 +281,7 @@ fun ConvoItem(
|
|||||||
val builder =
|
val builder =
|
||||||
AnnotatedString.Builder(convo.message.text)
|
AnnotatedString.Builder(convo.message.text)
|
||||||
|
|
||||||
convo.message.spanStyles.map { spanStyleRange ->
|
convo.message.spanStyles.forEach { spanStyleRange ->
|
||||||
val updatedSpanStyle =
|
val updatedSpanStyle =
|
||||||
if (spanStyleRange.item.color == Color.Red) {
|
if (spanStyleRange.item.color == Color.Red) {
|
||||||
spanStyleRange.item.copy(color = MaterialTheme.colorScheme.primary)
|
spanStyleRange.item.copy(color = MaterialTheme.colorScheme.primary)
|
||||||
@@ -378,7 +378,7 @@ fun ConvoItem(
|
|||||||
}
|
}
|
||||||
|
|
||||||
ElevatedAssistChip(
|
ElevatedAssistChip(
|
||||||
onClick = { onOptionClicked(convo, option) },
|
onClick = { onOptionClicked(option) },
|
||||||
leadingIcon = {
|
leadingIcon = {
|
||||||
option.icon.getResourcePainter()?.let { painter ->
|
option.icon.getResourcePainter()?.let { painter ->
|
||||||
Icon(
|
Icon(
|
||||||
|
|||||||
@@ -36,12 +36,12 @@ import kotlinx.coroutines.launch
|
|||||||
fun ConvosList(
|
fun ConvosList(
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
convos: ImmutableList<UiConvo>,
|
convos: ImmutableList<UiConvo>,
|
||||||
onConvosClick: (UiConvo) -> Unit,
|
onConvosClick: (Long) -> Unit,
|
||||||
onConvosLongClick: (UiConvo) -> Unit,
|
onConvosLongClick: (Long) -> Unit,
|
||||||
screenState: ConvosScreenState,
|
screenState: ConvosScreenState,
|
||||||
state: LazyListState,
|
state: LazyListState,
|
||||||
maxLines: Int,
|
maxLines: Int,
|
||||||
onOptionClicked: (UiConvo, ConvoOption) -> Unit,
|
onOptionClicked: (ConvoOption) -> Unit,
|
||||||
padding: PaddingValues
|
padding: PaddingValues
|
||||||
) {
|
) {
|
||||||
val theme = LocalThemeConfig.current
|
val theme = LocalThemeConfig.current
|
||||||
|
|||||||
@@ -1,79 +1,23 @@
|
|||||||
package dev.meloda.fast.convos.presentation
|
package dev.meloda.fast.convos.presentation
|
||||||
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import dev.meloda.fast.convos.model.ConvoIntent
|
||||||
import androidx.compose.runtime.getValue
|
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|
||||||
import dev.meloda.fast.convos.ConvosViewModel
|
|
||||||
import dev.meloda.fast.convos.model.ConvoNavigation
|
|
||||||
import dev.meloda.fast.model.BaseError
|
|
||||||
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ConvosRoute(
|
fun ConvosRoute(
|
||||||
viewModel: ConvosViewModel,
|
handleIntent: (ConvoIntent) -> Unit,
|
||||||
onBack: (() -> Unit)? = null,
|
screenState: ConvosScreenState,
|
||||||
onError: (BaseError) -> Unit,
|
isArchive: Boolean,
|
||||||
onNavigateToMessagesHistory: (convoId: Long) -> Unit,
|
|
||||||
onNavigateToCreateChat: (() -> Unit)? = null,
|
|
||||||
onNavigateToArchive: (() -> Unit)? = null,
|
|
||||||
onScrolledToTop: () -> Unit,
|
|
||||||
) {
|
) {
|
||||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
|
||||||
val navigationEvent by viewModel.navigation.collectAsStateWithLifecycle()
|
|
||||||
val convos by viewModel.uiConvos.collectAsStateWithLifecycle()
|
|
||||||
val dialog by viewModel.dialog.collectAsStateWithLifecycle()
|
|
||||||
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
|
||||||
val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
LaunchedEffect(navigationEvent) {
|
|
||||||
val shouldBeConsumed: Boolean = when (val navigation = navigationEvent) {
|
|
||||||
null -> false
|
|
||||||
|
|
||||||
is ConvoNavigation.CreateChat -> {
|
|
||||||
onNavigateToCreateChat?.invoke()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
is ConvoNavigation.MessagesHistory -> {
|
|
||||||
onNavigateToMessagesHistory(navigation.peerId)
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shouldBeConsumed) viewModel.onNavigationConsumed()
|
|
||||||
}
|
|
||||||
|
|
||||||
ConvosScreen(
|
ConvosScreen(
|
||||||
onBack = { onBack?.invoke() },
|
handleIntent = handleIntent,
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
convos = convos.toImmutableList(),
|
isArchive = isArchive,
|
||||||
baseError = baseError,
|
|
||||||
canPaginate = canPaginate,
|
|
||||||
onConvoItemClicked = viewModel::onConvoItemClick,
|
|
||||||
onConvoItemLongClicked = viewModel::onConvoItemLongClick,
|
|
||||||
onOptionClicked = viewModel::onOptionClicked,
|
|
||||||
onPaginationConditionsMet = viewModel::onPaginationConditionsMet,
|
|
||||||
onRefresh = viewModel::onRefresh,
|
|
||||||
onCreateChatButtonClicked = viewModel::onCreateChatButtonClicked,
|
|
||||||
onArchiveActionClicked = { onNavigateToArchive?.invoke() },
|
|
||||||
setScrollIndex = viewModel::setScrollIndex,
|
|
||||||
setScrollOffset = viewModel::setScrollOffset,
|
|
||||||
onConsumeReselection = onScrolledToTop,
|
|
||||||
onErrorViewButtonClicked = {
|
|
||||||
if (baseError in listOf(BaseError.AccountBlocked, BaseError.SessionExpired)) {
|
|
||||||
onError(requireNotNull(baseError))
|
|
||||||
} else {
|
|
||||||
viewModel.onErrorButtonClicked()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
HandleDialogs(
|
HandleDialogs(
|
||||||
|
handleIntent = handleIntent,
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
dialog = dialog,
|
|
||||||
onConfirmed = viewModel::onDialogConfirmed,
|
|
||||||
onDismissed = viewModel::onDialogDismissed,
|
|
||||||
onItemPicked = viewModel::onDialogItemPicked
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+40
-50
@@ -56,25 +56,23 @@ import dev.chrisbanes.haze.hazeEffect
|
|||||||
import dev.chrisbanes.haze.hazeSource
|
import dev.chrisbanes.haze.hazeSource
|
||||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||||
import dev.chrisbanes.haze.materials.HazeMaterials
|
import dev.chrisbanes.haze.materials.HazeMaterials
|
||||||
|
import dev.meloda.fast.common.model.NetworkState
|
||||||
|
import dev.meloda.fast.convos.model.ConvoIntent
|
||||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||||
import dev.meloda.fast.convos.navigation.ConvoGraph
|
import dev.meloda.fast.convos.navigation.ConvoGraph
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
import dev.meloda.fast.model.BaseError
|
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
|
import dev.meloda.fast.ui.common.LocalNetworkState
|
||||||
import dev.meloda.fast.ui.components.FullScreenContainedLoader
|
import dev.meloda.fast.ui.components.FullScreenContainedLoader
|
||||||
import dev.meloda.fast.ui.components.NoItemsView
|
import dev.meloda.fast.ui.components.NoItemsView
|
||||||
import dev.meloda.fast.ui.components.SegmentedButtonItem
|
import dev.meloda.fast.ui.components.SegmentedButtonItem
|
||||||
import dev.meloda.fast.ui.components.SegmentedButtonsRow
|
import dev.meloda.fast.ui.components.SegmentedButtonsRow
|
||||||
import dev.meloda.fast.ui.components.VkErrorView
|
import dev.meloda.fast.ui.components.VkErrorView
|
||||||
import dev.meloda.fast.ui.model.vk.ConvoOption
|
|
||||||
import dev.meloda.fast.ui.model.vk.UiConvo
|
|
||||||
import dev.meloda.fast.ui.theme.LocalBottomPadding
|
import dev.meloda.fast.ui.theme.LocalBottomPadding
|
||||||
import dev.meloda.fast.ui.theme.LocalHazeState
|
import dev.meloda.fast.ui.theme.LocalHazeState
|
||||||
import dev.meloda.fast.ui.theme.LocalReselectedTab
|
import dev.meloda.fast.ui.theme.LocalReselectedTab
|
||||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||||
import dev.meloda.fast.ui.util.ImmutableList
|
|
||||||
import dev.meloda.fast.ui.util.buildImmutableList
|
import dev.meloda.fast.ui.util.buildImmutableList
|
||||||
import dev.meloda.fast.ui.util.emptyImmutableList
|
|
||||||
import dev.meloda.fast.ui.util.isScrollingUp
|
import dev.meloda.fast.ui.util.isScrollingUp
|
||||||
import kotlinx.coroutines.flow.collectLatest
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
import kotlinx.coroutines.flow.debounce
|
import kotlinx.coroutines.flow.debounce
|
||||||
@@ -82,26 +80,14 @@ import kotlin.time.Duration.Companion.milliseconds
|
|||||||
|
|
||||||
@OptIn(
|
@OptIn(
|
||||||
ExperimentalMaterial3Api::class,
|
ExperimentalMaterial3Api::class,
|
||||||
ExperimentalHazeMaterialsApi::class, ExperimentalMaterial3ExpressiveApi::class,
|
ExperimentalHazeMaterialsApi::class,
|
||||||
|
ExperimentalMaterial3ExpressiveApi::class,
|
||||||
)
|
)
|
||||||
@Composable
|
@Composable
|
||||||
fun ConvosScreen(
|
fun ConvosScreen(
|
||||||
screenState: ConvosScreenState = ConvosScreenState.EMPTY,
|
handleIntent: (ConvoIntent) -> Unit,
|
||||||
convos: ImmutableList<UiConvo> = emptyImmutableList(),
|
screenState: ConvosScreenState,
|
||||||
baseError: BaseError? = null,
|
isArchive: Boolean,
|
||||||
canPaginate: Boolean = false,
|
|
||||||
onBack: () -> Unit = {},
|
|
||||||
onConvoItemClicked: (convo: UiConvo) -> Unit = {},
|
|
||||||
onConvoItemLongClicked: (convo: UiConvo) -> Unit = {},
|
|
||||||
onOptionClicked: (UiConvo, ConvoOption) -> Unit = { _, _ -> },
|
|
||||||
onPaginationConditionsMet: () -> Unit = {},
|
|
||||||
onRefresh: () -> Unit = {},
|
|
||||||
onCreateChatButtonClicked: () -> Unit = {},
|
|
||||||
onArchiveActionClicked: () -> Unit = {},
|
|
||||||
setScrollIndex: (Int) -> Unit = {},
|
|
||||||
setScrollOffset: (Int) -> Unit = {},
|
|
||||||
onConsumeReselection: () -> Unit = {},
|
|
||||||
onErrorViewButtonClicked: () -> Unit = {}
|
|
||||||
) {
|
) {
|
||||||
val currentTheme = LocalThemeConfig.current
|
val currentTheme = LocalThemeConfig.current
|
||||||
val maxLines = if (currentTheme.enableMultiline) 2 else 1
|
val maxLines = if (currentTheme.enableMultiline) 2 else 1
|
||||||
@@ -114,14 +100,14 @@ fun ConvosScreen(
|
|||||||
val currentTabReselected = LocalReselectedTab.current[ConvoGraph] == true
|
val currentTabReselected = LocalReselectedTab.current[ConvoGraph] == true
|
||||||
LaunchedEffect(currentTabReselected) {
|
LaunchedEffect(currentTabReselected) {
|
||||||
if (currentTabReselected) {
|
if (currentTabReselected) {
|
||||||
if (screenState.isArchive) {
|
if (isArchive) {
|
||||||
onBack.invoke()
|
handleIntent(ConvoIntent.Back)
|
||||||
} else {
|
} else {
|
||||||
if (listState.firstVisibleItemIndex > 14) {
|
if (listState.firstVisibleItemIndex > 14) {
|
||||||
listState.scrollToItem(14)
|
listState.scrollToItem(14)
|
||||||
}
|
}
|
||||||
listState.animateScrollToItem(0)
|
listState.animateScrollToItem(0)
|
||||||
onConsumeReselection()
|
handleIntent(ConvoIntent.ConsumeScrollToTop)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,18 +115,18 @@ fun ConvosScreen(
|
|||||||
LaunchedEffect(listState) {
|
LaunchedEffect(listState) {
|
||||||
snapshotFlow { listState.firstVisibleItemIndex }
|
snapshotFlow { listState.firstVisibleItemIndex }
|
||||||
.debounce(500L.milliseconds)
|
.debounce(500L.milliseconds)
|
||||||
.collectLatest(setScrollIndex)
|
.collectLatest { handleIntent(ConvoIntent.SetScrollIndex(it)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(listState) {
|
LaunchedEffect(listState) {
|
||||||
snapshotFlow { listState.firstVisibleItemScrollOffset }
|
snapshotFlow { listState.firstVisibleItemScrollOffset }
|
||||||
.debounce(500L.milliseconds)
|
.debounce(500L.milliseconds)
|
||||||
.collectLatest(setScrollOffset)
|
.collectLatest { handleIntent(ConvoIntent.SetScrollOffset(it)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
val paginationConditionMet by remember(canPaginate, listState) {
|
val paginationConditionMet by remember(screenState.canPaginate, listState) {
|
||||||
derivedStateOf {
|
derivedStateOf {
|
||||||
canPaginate &&
|
screenState.canPaginate &&
|
||||||
(listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
|
(listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
|
||||||
?: -9) >= (listState.layoutInfo.totalItemsCount - 6)
|
?: -9) >= (listState.layoutInfo.totalItemsCount - 6)
|
||||||
}
|
}
|
||||||
@@ -148,7 +134,7 @@ fun ConvosScreen(
|
|||||||
|
|
||||||
LaunchedEffect(paginationConditionMet) {
|
LaunchedEffect(paginationConditionMet) {
|
||||||
if (paginationConditionMet && !screenState.isPaginating) {
|
if (paginationConditionMet && !screenState.isPaginating) {
|
||||||
onPaginationConditionsMet()
|
handleIntent(ConvoIntent.PaginationConditionsMet)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,6 +158,8 @@ fun ConvosScreen(
|
|||||||
animationSpec = tween(durationMillis = 50)
|
animationSpec = tween(durationMillis = 50)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val networkState = LocalNetworkState.current
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentWindowInsets = WindowInsets.statusBars,
|
contentWindowInsets = WindowInsets.statusBars,
|
||||||
@@ -182,8 +170,9 @@ fun ConvosScreen(
|
|||||||
Text(
|
Text(
|
||||||
text = stringResource(
|
text = stringResource(
|
||||||
id = when {
|
id = when {
|
||||||
|
networkState == NetworkState.DISCONNECTED -> R.string.title_no_network
|
||||||
screenState.isLoading -> R.string.title_loading
|
screenState.isLoading -> R.string.title_loading
|
||||||
screenState.isArchive -> R.string.title_archive
|
isArchive -> R.string.title_archive
|
||||||
else -> R.string.title_convos
|
else -> R.string.title_convos
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
@@ -193,8 +182,8 @@ fun ConvosScreen(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
if (screenState.isArchive) {
|
if (isArchive) {
|
||||||
IconButton(onClick = onBack) {
|
IconButton(onClick = { handleIntent(ConvoIntent.Back) }) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(R.drawable.ic_arrow_back_round_24),
|
painter = painterResource(R.drawable.ic_arrow_back_round_24),
|
||||||
contentDescription = null
|
contentDescription = null
|
||||||
@@ -206,7 +195,7 @@ fun ConvosScreen(
|
|||||||
val dropDownItems: List<@Composable () -> Unit> = buildList {}
|
val dropDownItems: List<@Composable () -> Unit> = buildList {}
|
||||||
|
|
||||||
val items = buildImmutableList {
|
val items = buildImmutableList {
|
||||||
if (!screenState.isArchive) {
|
if (!isArchive) {
|
||||||
add(SegmentedButtonItem("archive", R.drawable.ic_archive_round_24))
|
add(SegmentedButtonItem("archive", R.drawable.ic_archive_round_24))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,8 +214,8 @@ fun ConvosScreen(
|
|||||||
items = items,
|
items = items,
|
||||||
onClick = { index ->
|
onClick = { index ->
|
||||||
when (items[index].key) {
|
when (items[index].key) {
|
||||||
"archive" -> onArchiveActionClicked()
|
"archive" -> handleIntent(ConvoIntent.ArchiveClick)
|
||||||
"refresh" -> onRefresh()
|
"refresh" -> handleIntent(ConvoIntent.Refresh)
|
||||||
"more" -> dropDownMenuExpanded = true
|
"more" -> dropDownMenuExpanded = true
|
||||||
|
|
||||||
else -> Unit
|
else -> Unit
|
||||||
@@ -263,7 +252,7 @@ fun ConvosScreen(
|
|||||||
)
|
)
|
||||||
|
|
||||||
val showHorizontalProgressBar by remember(screenState) {
|
val showHorizontalProgressBar by remember(screenState) {
|
||||||
derivedStateOf { screenState.isLoading && convos.isNotEmpty() }
|
derivedStateOf { screenState.isLoading && screenState.convos.isNotEmpty() }
|
||||||
}
|
}
|
||||||
AnimatedVisibility(showHorizontalProgressBar) {
|
AnimatedVisibility(showHorizontalProgressBar) {
|
||||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||||
@@ -274,14 +263,14 @@ fun ConvosScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
if (!screenState.isArchive) {
|
if (!isArchive) {
|
||||||
val offsetY by animateIntAsState(
|
val offsetY by animateIntAsState(
|
||||||
targetValue = if (listState.isScrollingUp()) 0 else 600
|
targetValue = if (listState.isScrollingUp()) 0 else 600
|
||||||
)
|
)
|
||||||
|
|
||||||
Column {
|
Column {
|
||||||
FloatingActionButton(
|
FloatingActionButton(
|
||||||
onClick = onCreateChatButtonClicked,
|
onClick = { handleIntent(ConvoIntent.CreateChatClick) },
|
||||||
modifier = Modifier.offset {
|
modifier = Modifier.offset {
|
||||||
IntOffset(0, offsetY)
|
IntOffset(0, offsetY)
|
||||||
}
|
}
|
||||||
@@ -298,14 +287,15 @@ fun ConvosScreen(
|
|||||||
}
|
}
|
||||||
) { padding ->
|
) { padding ->
|
||||||
when {
|
when {
|
||||||
baseError != null -> {
|
// TODO: 30.05.2026, Danil Nikolaev: move to UI State
|
||||||
|
screenState.error != null -> {
|
||||||
VkErrorView(
|
VkErrorView(
|
||||||
baseError = baseError,
|
baseError = screenState.error,
|
||||||
onButtonClick = onErrorViewButtonClicked
|
onButtonClick = { handleIntent(ConvoIntent.ErrorActionButtonClick) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
screenState.isLoading && convos.isEmpty() -> FullScreenContainedLoader()
|
screenState.isLoading && screenState.convos.isEmpty() -> FullScreenContainedLoader()
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
val pullToRefreshState = rememberPullToRefreshState()
|
val pullToRefreshState = rememberPullToRefreshState()
|
||||||
@@ -318,7 +308,7 @@ fun ConvosScreen(
|
|||||||
.padding(bottom = padding.calculateBottomPadding()),
|
.padding(bottom = padding.calculateBottomPadding()),
|
||||||
state = pullToRefreshState,
|
state = pullToRefreshState,
|
||||||
isRefreshing = screenState.isLoading,
|
isRefreshing = screenState.isLoading,
|
||||||
onRefresh = onRefresh,
|
onRefresh = { handleIntent(ConvoIntent.Refresh) },
|
||||||
indicator = {
|
indicator = {
|
||||||
PullToRefreshDefaults.Indicator(
|
PullToRefreshDefaults.Indicator(
|
||||||
state = pullToRefreshState,
|
state = pullToRefreshState,
|
||||||
@@ -330,9 +320,9 @@ fun ConvosScreen(
|
|||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
ConvosList(
|
ConvosList(
|
||||||
convos = convos,
|
convos = screenState.convos,
|
||||||
onConvosClick = onConvoItemClicked,
|
onConvosClick = { handleIntent(ConvoIntent.ItemClick(it)) },
|
||||||
onConvosLongClick = onConvoItemLongClicked,
|
onConvosLongClick = { handleIntent(ConvoIntent.ItemLongClick(it)) },
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
state = listState,
|
state = listState,
|
||||||
maxLines = maxLines,
|
maxLines = maxLines,
|
||||||
@@ -341,14 +331,14 @@ fun ConvosScreen(
|
|||||||
} else {
|
} else {
|
||||||
Modifier
|
Modifier
|
||||||
}.fillMaxSize(),
|
}.fillMaxSize(),
|
||||||
onOptionClicked = onOptionClicked,
|
onOptionClicked = { handleIntent(ConvoIntent.OptionItemClick(it)) },
|
||||||
padding = padding
|
padding = padding
|
||||||
)
|
)
|
||||||
|
|
||||||
if (convos.isEmpty()) {
|
if (screenState.convos.isEmpty()) {
|
||||||
NoItemsView(
|
NoItemsView(
|
||||||
buttonText = stringResource(R.string.action_refresh),
|
buttonText = stringResource(R.string.action_refresh),
|
||||||
onButtonClick = onRefresh
|
onButtonClick = { handleIntent(ConvoIntent.Refresh) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -21,11 +21,11 @@ fun NavGraphBuilder.friendsScreen(
|
|||||||
onMessageClicked: (userId: Long) -> Unit,
|
onMessageClicked: (userId: Long) -> Unit,
|
||||||
onScrolledToTop: () -> Unit
|
onScrolledToTop: () -> Unit
|
||||||
) {
|
) {
|
||||||
|
composable<Friends> {
|
||||||
val friendsViewModel: FriendsViewModel = activity.getViewModel<FriendsViewModelImpl>()
|
val friendsViewModel: FriendsViewModel = activity.getViewModel<FriendsViewModelImpl>()
|
||||||
val onlineFriendsViewModel =
|
val onlineFriendsViewModel =
|
||||||
activity.getViewModel<OnlineFriendsViewModelImpl>()
|
activity.getViewModel<OnlineFriendsViewModelImpl>()
|
||||||
|
|
||||||
composable<Friends> {
|
|
||||||
FriendsRoute(
|
FriendsRoute(
|
||||||
friendsViewModel = friendsViewModel,
|
friendsViewModel = friendsViewModel,
|
||||||
onlineFriendsViewModel = onlineFriendsViewModel,
|
onlineFriendsViewModel = onlineFriendsViewModel,
|
||||||
|
|||||||
+13
-23
@@ -6,7 +6,6 @@ import android.content.Context
|
|||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.util.Log
|
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.compose.ui.text.AnnotatedString
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
import androidx.compose.ui.text.SpanStyle
|
import androidx.compose.ui.text.SpanStyle
|
||||||
@@ -40,7 +39,7 @@ import dev.meloda.fast.datastore.UserSettings
|
|||||||
import dev.meloda.fast.domain.ConvoUseCase
|
import dev.meloda.fast.domain.ConvoUseCase
|
||||||
import dev.meloda.fast.domain.GetMessageReadPeersUseCase
|
import dev.meloda.fast.domain.GetMessageReadPeersUseCase
|
||||||
import dev.meloda.fast.domain.LoadConvosByIdUseCase
|
import dev.meloda.fast.domain.LoadConvosByIdUseCase
|
||||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||||
import dev.meloda.fast.domain.MessagesUseCase
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
import dev.meloda.fast.domain.util.asPresentation
|
import dev.meloda.fast.domain.util.asPresentation
|
||||||
import dev.meloda.fast.domain.util.extractAvatar
|
import dev.meloda.fast.domain.util.extractAvatar
|
||||||
@@ -85,7 +84,7 @@ class MessagesHistoryViewModelImpl(
|
|||||||
private val userSettings: UserSettings,
|
private val userSettings: UserSettings,
|
||||||
private val loadConvosByIdUseCase: LoadConvosByIdUseCase,
|
private val loadConvosByIdUseCase: LoadConvosByIdUseCase,
|
||||||
private val getMessageReadPeersUseCase: GetMessageReadPeersUseCase,
|
private val getMessageReadPeersUseCase: GetMessageReadPeersUseCase,
|
||||||
updatesParser: LongPollUpdatesParser,
|
eventsHandler: LongPollEventsHandler,
|
||||||
savedStateHandle: SavedStateHandle
|
savedStateHandle: SavedStateHandle
|
||||||
) : MessagesHistoryViewModel, ViewModel() {
|
) : MessagesHistoryViewModel, ViewModel() {
|
||||||
|
|
||||||
@@ -125,15 +124,15 @@ class MessagesHistoryViewModelImpl(
|
|||||||
loadConvo()
|
loadConvo()
|
||||||
loadMessagesHistory()
|
loadMessagesHistory()
|
||||||
|
|
||||||
updatesParser.onNewMessage(::handleNewMessage)
|
eventsHandler.onMessageNew(::handleNewMessage)
|
||||||
updatesParser.onMessageEdited(::handleEditedMessage)
|
eventsHandler.onMessageEdit(::handleEditedMessage)
|
||||||
updatesParser.onMessageIncomingRead(::handleReadIncomingEvent)
|
eventsHandler.onMessageIncomingRead(::handleReadIncomingEvent)
|
||||||
updatesParser.onMessageOutgoingRead(::handleReadOutgoingEvent)
|
eventsHandler.onMessageOutgoingRead(::handleReadOutgoingEvent)
|
||||||
updatesParser.onMessageDeleted(::handleMessageDeleted)
|
eventsHandler.onMessageDelete(::handleMessageDeleted)
|
||||||
updatesParser.onMessageRestored(::handleMessageRestored)
|
eventsHandler.onMessageRestore(::handleMessageRestored)
|
||||||
updatesParser.onMessageMarkedAsImportant(::handleMessageMarkedAsImportant)
|
eventsHandler.onMessageMarkAsImportant(::handleMessageMarkedAsImportant)
|
||||||
updatesParser.onMessageMarkedAsSpam(::handleMessageMarkedAsSpam)
|
eventsHandler.onMessageMarkAsSpam(::handleMessageMarkedAsSpam)
|
||||||
updatesParser.onMessageMarkedAsNotSpam(::handleMessageMarkedAsNotSpam)
|
eventsHandler.onMessageMarkAsNotSpam(::handleMessageMarkedAsNotSpam)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNavigationConsumed() {
|
override fun onNavigationConsumed() {
|
||||||
@@ -682,11 +681,9 @@ class MessagesHistoryViewModelImpl(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
|
private fun handleNewMessage(event: LongPollParsedEvent.MessageNew) {
|
||||||
val message = event.message
|
val message = event.message
|
||||||
|
|
||||||
Log.d("MessagesHistoryViewModel", "handleNewMessage: $message")
|
|
||||||
|
|
||||||
if (message.peerId != screenState.value.convoId) return
|
if (message.peerId != screenState.value.convoId) return
|
||||||
if (messages.value.indexOfFirstOrNull { it.id == message.id } != null) return
|
if (messages.value.indexOfFirstOrNull { it.id == message.id } != null) return
|
||||||
|
|
||||||
@@ -835,8 +832,6 @@ class MessagesHistoryViewModelImpl(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun loadConvo() {
|
private fun loadConvo() {
|
||||||
Log.d("MessagesHistoryViewModelImpl", "loadConvo()")
|
|
||||||
|
|
||||||
loadConvosByIdUseCase(
|
loadConvosByIdUseCase(
|
||||||
peerIds = listOf(screenState.value.convoId),
|
peerIds = listOf(screenState.value.convoId),
|
||||||
extended = true,
|
extended = true,
|
||||||
@@ -904,8 +899,6 @@ class MessagesHistoryViewModelImpl(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun loadMessagesHistory(offset: Int = currentOffset.value) {
|
private fun loadMessagesHistory(offset: Int = currentOffset.value) {
|
||||||
Log.d("MessagesHistoryViewModel", "loadMessagesHistory: $offset")
|
|
||||||
|
|
||||||
messagesUseCase.getMessagesHistory(
|
messagesUseCase.getMessagesHistory(
|
||||||
convoId = screenState.value.convoId,
|
convoId = screenState.value.convoId,
|
||||||
count = MESSAGES_LOAD_COUNT,
|
count = MESSAGES_LOAD_COUNT,
|
||||||
@@ -1037,6 +1030,7 @@ class MessagesHistoryViewModelImpl(
|
|||||||
isSpam = false,
|
isSpam = false,
|
||||||
pinnedAt = null,
|
pinnedAt = null,
|
||||||
formatData = formatData,
|
formatData = formatData,
|
||||||
|
isDeleted = false
|
||||||
)
|
)
|
||||||
formatData = formatData.copy(items = emptyList())
|
formatData = formatData.copy(items = emptyList())
|
||||||
sendingMessages += newMessage
|
sendingMessages += newMessage
|
||||||
@@ -1078,8 +1072,6 @@ class MessagesHistoryViewModelImpl(
|
|||||||
state.processState(
|
state.processState(
|
||||||
any = { sendingMessages.remove(newMessage) },
|
any = { sendingMessages.remove(newMessage) },
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.d("MessagesHistoryViewModelImpl", "sendMessage: ERROR: $error")
|
|
||||||
|
|
||||||
val failedId = -500_000L - failedMessages.size
|
val failedId = -500_000L - failedMessages.size
|
||||||
val newFailedMessage = newMessage.copy(id = failedId)
|
val newFailedMessage = newMessage.copy(id = failedId)
|
||||||
failedMessages += newFailedMessage
|
failedMessages += newFailedMessage
|
||||||
@@ -1143,8 +1135,6 @@ class MessagesHistoryViewModelImpl(
|
|||||||
) ?: return
|
) ?: return
|
||||||
|
|
||||||
// TODO: 13/03/2026, Danil Nikolaev: check if message is exact same, then do not edit
|
// TODO: 13/03/2026, Danil Nikolaev: check if message is exact same, then do not edit
|
||||||
|
|
||||||
Log.d("MessagesHistoryViewModelImpl", "editMessage: $newMessage")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun markAsImportant(
|
private fun markAsImportant(
|
||||||
|
|||||||
-2
@@ -1,7 +1,6 @@
|
|||||||
package dev.meloda.fast.messageshistory.presentation
|
package dev.meloda.fast.messageshistory.presentation
|
||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.util.Log
|
|
||||||
import android.view.HapticFeedbackConstants
|
import android.view.HapticFeedbackConstants
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.animateColorAsState
|
import androidx.compose.animation.animateColorAsState
|
||||||
@@ -129,7 +128,6 @@ fun MessagesList(
|
|||||||
when (attachment) {
|
when (attachment) {
|
||||||
is VkPhotoDomain -> {
|
is VkPhotoDomain -> {
|
||||||
val maxSize = attachment.getMaxSize()
|
val maxSize = attachment.getMaxSize()
|
||||||
Log.d("MessagesList", "onPhotoLongClicked. Max size: ${maxSize?.url}")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-1
@@ -64,7 +64,6 @@ fun DynamicPreviewGrid(
|
|||||||
val spacingPx = with(LocalDensity.current) { spacing.toPx() }
|
val spacingPx = with(LocalDensity.current) { spacing.toPx() }
|
||||||
|
|
||||||
val rows = previews.chunked(3)
|
val rows = previews.chunked(3)
|
||||||
Log.d("ROWS", "DynamicPreviewGrid: ${rows.size}")
|
|
||||||
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(spacing)) {
|
Column(verticalArrangement = Arrangement.spacedBy(spacing)) {
|
||||||
rows.forEachIndexed { outerIndex, row ->
|
rows.forEachIndexed { outerIndex, row ->
|
||||||
|
|||||||
@@ -5,69 +5,60 @@ import androidx.lifecycle.viewModelScope
|
|||||||
import dev.meloda.fast.common.VkConstants
|
import dev.meloda.fast.common.VkConstants
|
||||||
import dev.meloda.fast.common.extensions.listenValue
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
import dev.meloda.fast.common.extensions.setValue
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
import dev.meloda.fast.data.State
|
|
||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.data.processState
|
import dev.meloda.fast.data.processState
|
||||||
import dev.meloda.fast.domain.GetLocalUserByIdUseCase
|
import dev.meloda.fast.domain.GetLocalUserByIdUseCase
|
||||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||||
import dev.meloda.fast.model.BaseError
|
import dev.meloda.fast.logger.FastLogger
|
||||||
import dev.meloda.fast.network.VkErrorCode
|
|
||||||
import dev.meloda.fast.profile.model.ProfileScreenState
|
import dev.meloda.fast.profile.model.ProfileScreenState
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
interface ProfileViewModel {
|
class ProfileViewModel(
|
||||||
val screenState: StateFlow<ProfileScreenState>
|
|
||||||
val baseError: StateFlow<BaseError?>
|
|
||||||
}
|
|
||||||
|
|
||||||
class ProfileViewModelImpl(
|
|
||||||
private val getLocalUserByIdUseCase: GetLocalUserByIdUseCase,
|
private val getLocalUserByIdUseCase: GetLocalUserByIdUseCase,
|
||||||
private val loadUserByIdUseCase: LoadUserByIdUseCase
|
private val loadUserByIdUseCase: LoadUserByIdUseCase,
|
||||||
) : ViewModel(), ProfileViewModel {
|
private val logger: FastLogger
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
override val screenState = MutableStateFlow(ProfileScreenState.EMPTY)
|
private val screenState = MutableStateFlow(ProfileScreenState.EMPTY)
|
||||||
override val baseError = MutableStateFlow<BaseError?>(null)
|
val screenStateFlow get() = screenState.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
getLocalAccountInfo()
|
getLocalAccountInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getLocalAccountInfo() {
|
private fun getLocalAccountInfo() {
|
||||||
getLocalUserByIdUseCase(UserConfig.userId)
|
logger.debug(this@ProfileViewModel::class, "START")
|
||||||
.listenValue(viewModelScope) { state ->
|
emit(screenState.value.copy(isLoading = true))
|
||||||
|
|
||||||
|
getLocalUserByIdUseCase(UserConfig.userId).listenValue { state ->
|
||||||
|
logger.debug(this@ProfileViewModel::class, "LOADED: $state")
|
||||||
|
|
||||||
|
emit(screenState.value.copy(isLoading = false))
|
||||||
|
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = {
|
||||||
if (error is State.Error.ApiError) {
|
logger.debug(this@ProfileViewModel::class, "ERROR")
|
||||||
when (error.errorCode) {
|
emit(screenState.value.copy(avatarUrl = null, fullName = null))
|
||||||
VkErrorCode.USER_AUTHORIZATION_FAILED -> {
|
|
||||||
baseError.setValue { BaseError.SessionExpired }
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
screenState.setValue { old ->
|
|
||||||
old.copy(
|
|
||||||
avatarUrl = null,
|
|
||||||
fullName = null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
success = { user ->
|
success = { user ->
|
||||||
screenState.setValue { old ->
|
logger.debug(this@ProfileViewModel::class, "SUCCESS")
|
||||||
old.copy(
|
emit(
|
||||||
|
screenState.value.copy(
|
||||||
avatarUrl = user?.photo200,
|
avatarUrl = user?.photo200,
|
||||||
fullName = user?.fullName
|
fullName = user?.fullName
|
||||||
)
|
)
|
||||||
}
|
)
|
||||||
},
|
},
|
||||||
any = ::loadAccountInfo
|
any = ::loadAccountInfo
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun emit(state: ProfileScreenState) {
|
||||||
|
screenState.setValue { state }
|
||||||
|
}
|
||||||
|
|
||||||
private fun loadAccountInfo() {
|
private fun loadAccountInfo() {
|
||||||
loadUserByIdUseCase(
|
loadUserByIdUseCase(
|
||||||
userId = null,
|
userId = null,
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package dev.meloda.fast.profile.di
|
package dev.meloda.fast.profile.di
|
||||||
|
|
||||||
import dev.meloda.fast.profile.ProfileViewModelImpl
|
import dev.meloda.fast.profile.ProfileViewModel
|
||||||
import org.koin.core.module.dsl.viewModelOf
|
import org.koin.core.module.dsl.viewModelOf
|
||||||
import org.koin.dsl.module
|
import org.koin.dsl.module
|
||||||
|
|
||||||
val profileModule = module {
|
val profileModule = module {
|
||||||
viewModelOf(::ProfileViewModelImpl)
|
viewModelOf(::ProfileViewModel)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
package dev.meloda.fast.profile.navigation
|
package dev.meloda.fast.profile.navigation
|
||||||
|
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.navigation.NavGraphBuilder
|
import androidx.navigation.NavGraphBuilder
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import dev.meloda.fast.model.BaseError
|
|
||||||
import dev.meloda.fast.profile.ProfileViewModel
|
import dev.meloda.fast.profile.ProfileViewModel
|
||||||
import dev.meloda.fast.profile.ProfileViewModelImpl
|
|
||||||
import dev.meloda.fast.profile.presentation.ProfileRoute
|
import dev.meloda.fast.profile.presentation.ProfileRoute
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import org.koin.androidx.viewmodel.ext.android.getViewModel
|
import org.koin.androidx.viewmodel.ext.android.getViewModel
|
||||||
@@ -15,19 +15,17 @@ object Profile
|
|||||||
|
|
||||||
fun NavGraphBuilder.profileScreen(
|
fun NavGraphBuilder.profileScreen(
|
||||||
activity: AppCompatActivity,
|
activity: AppCompatActivity,
|
||||||
onError: (BaseError) -> Unit,
|
|
||||||
onSettingsButtonClicked: () -> Unit,
|
onSettingsButtonClicked: () -> Unit,
|
||||||
onPhotoClicked: (url: String) -> Unit
|
onPhotoClicked: (url: String) -> Unit
|
||||||
) {
|
) {
|
||||||
val viewModel: ProfileViewModel = with(activity) {
|
|
||||||
getViewModel<ProfileViewModelImpl>()
|
|
||||||
}
|
|
||||||
composable<Profile> {
|
composable<Profile> {
|
||||||
|
val viewModel: ProfileViewModel = activity.getViewModel()
|
||||||
|
val screenState by viewModel.screenStateFlow.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
ProfileRoute(
|
ProfileRoute(
|
||||||
onError = onError,
|
screenState = screenState,
|
||||||
onSettingsButtonClicked = onSettingsButtonClicked,
|
onSettingsButtonClicked = onSettingsButtonClicked,
|
||||||
onPhotoClicked = onPhotoClicked,
|
onPhotoClicked = onPhotoClicked,
|
||||||
viewModel = viewModel
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-20
@@ -14,15 +14,12 @@ import androidx.compose.foundation.layout.statusBarsPadding
|
|||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.IconButton
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.material3.TopAppBarDefaults
|
import androidx.compose.material3.TopAppBarDefaults
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
@@ -31,28 +28,21 @@ import androidx.compose.ui.layout.ContentScale
|
|||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.unit.LayoutDirection
|
import androidx.compose.ui.unit.LayoutDirection
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import dev.meloda.fast.model.BaseError
|
|
||||||
import dev.meloda.fast.profile.ProfileViewModel
|
|
||||||
import dev.meloda.fast.profile.ProfileViewModelImpl
|
|
||||||
import dev.meloda.fast.profile.model.ProfileScreenState
|
import dev.meloda.fast.profile.model.ProfileScreenState
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
import org.koin.androidx.compose.koinViewModel
|
import dev.meloda.fast.ui.components.SegmentedButtonItem
|
||||||
|
import dev.meloda.fast.ui.components.SegmentedButtonsRow
|
||||||
|
import dev.meloda.fast.ui.util.buildImmutableList
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ProfileRoute(
|
fun ProfileRoute(
|
||||||
onError: (BaseError) -> Unit,
|
screenState: ProfileScreenState,
|
||||||
onSettingsButtonClicked: () -> Unit,
|
onSettingsButtonClicked: () -> Unit,
|
||||||
onPhotoClicked: (url: String) -> Unit,
|
onPhotoClicked: (url: String) -> Unit,
|
||||||
viewModel: ProfileViewModel = koinViewModel<ProfileViewModelImpl>()
|
|
||||||
) {
|
) {
|
||||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
|
||||||
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
ProfileScreen(
|
ProfileScreen(
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
baseError = baseError,
|
|
||||||
onSettingsButtonClicked = onSettingsButtonClicked,
|
onSettingsButtonClicked = onSettingsButtonClicked,
|
||||||
onPhotoClicked = onPhotoClicked
|
onPhotoClicked = onPhotoClicked
|
||||||
)
|
)
|
||||||
@@ -63,7 +53,6 @@ fun ProfileRoute(
|
|||||||
@Composable
|
@Composable
|
||||||
fun ProfileScreen(
|
fun ProfileScreen(
|
||||||
screenState: ProfileScreenState = ProfileScreenState.EMPTY,
|
screenState: ProfileScreenState = ProfileScreenState.EMPTY,
|
||||||
baseError: BaseError? = null,
|
|
||||||
onSettingsButtonClicked: () -> Unit = {},
|
onSettingsButtonClicked: () -> Unit = {},
|
||||||
onPhotoClicked: (url: String) -> Unit = {}
|
onPhotoClicked: (url: String) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
@@ -72,12 +61,19 @@ fun ProfileScreen(
|
|||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = {},
|
title = {},
|
||||||
actions = {
|
actions = {
|
||||||
IconButton(onClick = onSettingsButtonClicked) {
|
val items = buildImmutableList {
|
||||||
Icon(
|
add(SegmentedButtonItem("settings", R.drawable.ic_settings_round_24))
|
||||||
painter = painterResource(R.drawable.ic_settings_round_24),
|
|
||||||
contentDescription = null
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
SegmentedButtonsRow(
|
||||||
|
modifier = Modifier.padding(end = 8.dp),
|
||||||
|
items = items,
|
||||||
|
onClick = { index ->
|
||||||
|
when (items[index].key) {
|
||||||
|
"settings" -> onSettingsButtonClicked()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
},
|
},
|
||||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
|
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,9 +11,10 @@ import dev.meloda.fast.common.VkConstants
|
|||||||
import dev.meloda.fast.common.extensions.findWithIndex
|
import dev.meloda.fast.common.extensions.findWithIndex
|
||||||
import dev.meloda.fast.common.extensions.listenValue
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
import dev.meloda.fast.common.extensions.setValue
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.common.extensions.updateValue
|
||||||
import dev.meloda.fast.common.model.DarkMode
|
import dev.meloda.fast.common.model.DarkMode
|
||||||
import dev.meloda.fast.common.model.LogLevel
|
|
||||||
import dev.meloda.fast.common.model.LongPollState
|
import dev.meloda.fast.common.model.LongPollState
|
||||||
|
import dev.meloda.fast.common.model.NetworkLogLevel
|
||||||
import dev.meloda.fast.common.model.UiText
|
import dev.meloda.fast.common.model.UiText
|
||||||
import dev.meloda.fast.common.model.parseString
|
import dev.meloda.fast.common.model.parseString
|
||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
@@ -24,19 +25,23 @@ import dev.meloda.fast.datastore.SettingsKeys
|
|||||||
import dev.meloda.fast.datastore.UserSettings
|
import dev.meloda.fast.datastore.UserSettings
|
||||||
import dev.meloda.fast.domain.GetCurrentAccountUseCase
|
import dev.meloda.fast.domain.GetCurrentAccountUseCase
|
||||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||||
|
import dev.meloda.fast.logger.FastLogger
|
||||||
|
import dev.meloda.fast.model.AccountDto
|
||||||
import dev.meloda.fast.model.database.AccountEntity
|
import dev.meloda.fast.model.database.AccountEntity
|
||||||
import dev.meloda.fast.settings.model.HapticType
|
import dev.meloda.fast.settings.model.HapticType
|
||||||
import dev.meloda.fast.settings.model.SettingsDialog
|
import dev.meloda.fast.settings.model.SettingsDialog
|
||||||
|
import dev.meloda.fast.settings.model.SettingsEffect
|
||||||
|
import dev.meloda.fast.settings.model.SettingsIntent
|
||||||
import dev.meloda.fast.settings.model.SettingsItem
|
import dev.meloda.fast.settings.model.SettingsItem
|
||||||
|
import dev.meloda.fast.settings.model.SettingsNavigationIntent
|
||||||
import dev.meloda.fast.settings.model.SettingsScreenState
|
import dev.meloda.fast.settings.model.SettingsScreenState
|
||||||
import dev.meloda.fast.settings.model.TextProvider
|
import dev.meloda.fast.settings.model.TextProvider
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.async
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.awaitAll
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
class SettingsViewModel(
|
class SettingsViewModel(
|
||||||
@@ -45,35 +50,76 @@ class SettingsViewModel(
|
|||||||
private val getCurrentAccountUseCase: GetCurrentAccountUseCase,
|
private val getCurrentAccountUseCase: GetCurrentAccountUseCase,
|
||||||
private val userSettings: UserSettings,
|
private val userSettings: UserSettings,
|
||||||
private val resources: Resources,
|
private val resources: Resources,
|
||||||
private val longPollController: LongPollController
|
private val longPollController: LongPollController,
|
||||||
|
private val logger: FastLogger
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val _screenState = MutableStateFlow(SettingsScreenState.EMPTY)
|
private val screenState = MutableStateFlow(SettingsScreenState.EMPTY)
|
||||||
val screenState = _screenState.asStateFlow()
|
val screenStateFlow get() = screenState.asStateFlow()
|
||||||
|
|
||||||
private val _hapticType = MutableStateFlow<HapticType?>(null)
|
private val screenEffect = MutableSharedFlow<SettingsEffect>(extraBufferCapacity = 1)
|
||||||
val hapticType = _hapticType.asStateFlow()
|
val screenEffectFlow = screenEffect.asSharedFlow()
|
||||||
|
|
||||||
private val _dialog = MutableStateFlow<SettingsDialog?>(null)
|
private val settings = mutableListOf<SettingsItem<*>>()
|
||||||
val dialog = _dialog.asStateFlow()
|
private var showDebugCategory: Boolean = userSettings.showDebugCategory.value
|
||||||
|
|
||||||
private val _isNeedToRestart = MutableStateFlow(false)
|
|
||||||
val isNeedToRestart = _isNeedToRestart.asStateFlow()
|
|
||||||
|
|
||||||
private val settings = MutableStateFlow<List<SettingsItem<*>>>(emptyList())
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
createSettings()
|
createSettings()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDialogConfirmed(dialog: SettingsDialog, bundle: Bundle) {
|
fun handleIntent(intent: SettingsIntent) {
|
||||||
onDialogDismissed(dialog)
|
when (intent) {
|
||||||
|
SettingsIntent.BackClick -> {
|
||||||
|
screenEffect.tryEmit(SettingsEffect.Navigate(SettingsNavigationIntent.Back))
|
||||||
|
}
|
||||||
|
|
||||||
|
is SettingsIntent.ItemClick -> {
|
||||||
|
onSettingsItemClicked(intent.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
is SettingsIntent.ItemLongClick -> {
|
||||||
|
onSettingsItemLongClicked(intent.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
is SettingsIntent.ItemValueChanged -> {
|
||||||
|
onSettingsItemChanged(intent.key, intent.newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
is SettingsIntent.Dialog -> {
|
||||||
|
when (intent) {
|
||||||
|
SettingsIntent.Dialog.CancelClick -> Unit
|
||||||
|
|
||||||
|
is SettingsIntent.Dialog.ConfirmClick -> {
|
||||||
|
onDialogConfirmed(intent.bundle)
|
||||||
|
}
|
||||||
|
|
||||||
|
SettingsIntent.Dialog.Dismiss -> {
|
||||||
|
onDialogDismissed()
|
||||||
|
}
|
||||||
|
|
||||||
|
is SettingsIntent.Dialog.ItemPick -> {
|
||||||
|
onDialogItemPicked(intent.bundle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setDialog(dialog: SettingsDialog?) {
|
||||||
|
screenState.updateValue { copy(dialog = dialog) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onDialogConfirmed(bundle: Bundle?) {
|
||||||
|
val dialog = screenState.value.dialog ?: return
|
||||||
|
onDialogDismissed()
|
||||||
|
|
||||||
when (dialog) {
|
when (dialog) {
|
||||||
is SettingsDialog.LogOut -> onLogOutAlertPositiveClick()
|
is SettingsDialog.LogOut -> onLogOutAlertPositiveClick()
|
||||||
is SettingsDialog.PerformCrash -> onPerformCrashPositiveButtonClicked()
|
is SettingsDialog.PerformCrash -> onPerformCrashPositiveButtonClicked()
|
||||||
|
|
||||||
is SettingsDialog.ImportAuthData -> {
|
is SettingsDialog.ImportAuthData -> {
|
||||||
|
if (bundle == null) return
|
||||||
|
|
||||||
val accessToken = bundle.getString("ACCESS_TOKEN") ?: return
|
val accessToken = bundle.getString("ACCESS_TOKEN") ?: return
|
||||||
val exchangeToken = bundle.getString("EXCHANGE_TOKEN")
|
val exchangeToken = bundle.getString("EXCHANGE_TOKEN")
|
||||||
val trustedHash = bundle.getString("TRUSTED_HASH")
|
val trustedHash = bundle.getString("TRUSTED_HASH")
|
||||||
@@ -89,21 +135,29 @@ class SettingsViewModel(
|
|||||||
).listenValue(viewModelScope) { state ->
|
).listenValue(viewModelScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
|
logger.error(
|
||||||
|
this@SettingsViewModel::class,
|
||||||
|
"importAuthInfo(): loadUserById(): ERROR: $error"
|
||||||
|
)
|
||||||
UserConfig.accessToken = oldToken
|
UserConfig.accessToken = oldToken
|
||||||
},
|
},
|
||||||
success = { user ->
|
success = { user ->
|
||||||
if (user == null) return@listenValue
|
if (user == null) {
|
||||||
|
UserConfig.accessToken = oldToken
|
||||||
|
return@listenValue
|
||||||
|
}
|
||||||
|
|
||||||
UserConfig.currentUserId = user.id
|
UserConfig.currentUserId = user.id
|
||||||
|
|
||||||
val account = getCurrentAccountUseCase()
|
val account = getCurrentAccountUseCase()
|
||||||
|
?.mapToDto()
|
||||||
?.copy(
|
?.copy(
|
||||||
userId = user.id,
|
userId = user.id,
|
||||||
accessToken = accessToken,
|
accessToken = accessToken,
|
||||||
fastToken = null,
|
fastToken = null,
|
||||||
exchangeToken = exchangeToken,
|
exchangeToken = exchangeToken,
|
||||||
trustedHash = trustedHash
|
trustedHash = trustedHash
|
||||||
) ?: AccountEntity(
|
) ?: AccountDto(
|
||||||
userId = user.id,
|
userId = user.id,
|
||||||
accessToken = accessToken,
|
accessToken = accessToken,
|
||||||
fastToken = null,
|
fastToken = null,
|
||||||
@@ -111,9 +165,11 @@ class SettingsViewModel(
|
|||||||
exchangeToken = exchangeToken
|
exchangeToken = exchangeToken
|
||||||
)
|
)
|
||||||
|
|
||||||
accountsRepository.storeAccounts(listOf(account))
|
accountsRepository.storeAccounts(listOf(account.mapToEntity()))
|
||||||
|
|
||||||
_isNeedToRestart.setValue { true }
|
screenEffect.tryEmit(
|
||||||
|
SettingsEffect.Navigate(SettingsNavigationIntent.Restart)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -124,7 +180,8 @@ class SettingsViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDialogDismissed(dialog: SettingsDialog) {
|
private fun onDialogDismissed() {
|
||||||
|
val dialog = screenState.value.dialog ?: return
|
||||||
when (dialog) {
|
when (dialog) {
|
||||||
is SettingsDialog.LogOut -> Unit
|
is SettingsDialog.LogOut -> Unit
|
||||||
is SettingsDialog.PerformCrash -> Unit
|
is SettingsDialog.PerformCrash -> Unit
|
||||||
@@ -132,10 +189,11 @@ class SettingsViewModel(
|
|||||||
is SettingsDialog.ExportAuthData -> Unit
|
is SettingsDialog.ExportAuthData -> Unit
|
||||||
}
|
}
|
||||||
|
|
||||||
_dialog.setValue { null }
|
setDialog(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onDialogItemPicked(dialog: SettingsDialog, bundle: Bundle) {
|
private fun onDialogItemPicked(bundle: Bundle?) {
|
||||||
|
val dialog = screenState.value.dialog ?: return
|
||||||
when (dialog) {
|
when (dialog) {
|
||||||
is SettingsDialog.LogOut -> Unit
|
is SettingsDialog.LogOut -> Unit
|
||||||
is SettingsDialog.PerformCrash -> Unit
|
is SettingsDialog.PerformCrash -> Unit
|
||||||
@@ -144,10 +202,8 @@ class SettingsViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onLogOutAlertPositiveClick() {
|
private fun onLogOutAlertPositiveClick() {
|
||||||
viewModelScope.launch(Dispatchers.IO) {
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
val tasks = listOf(
|
|
||||||
async {
|
|
||||||
accountsRepository.storeAccounts(
|
accountsRepository.storeAccounts(
|
||||||
listOf(
|
listOf(
|
||||||
AccountEntity(
|
AccountEntity(
|
||||||
@@ -159,40 +215,39 @@ class SettingsViewModel(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
},
|
|
||||||
async { UserConfig.clear() }
|
|
||||||
)
|
|
||||||
|
|
||||||
tasks.awaitAll()
|
UserConfig.clear()
|
||||||
|
|
||||||
|
screenEffect.tryEmit(SettingsEffect.Navigate(SettingsNavigationIntent.LogOut))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onPerformCrashPositiveButtonClicked() {
|
private fun onPerformCrashPositiveButtonClicked() {
|
||||||
throw Exception("Test exception")
|
throw Exception("Test exception")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onSettingsItemClicked(key: String) {
|
private fun onSettingsItemClicked(key: String) {
|
||||||
when (key) {
|
when (key) {
|
||||||
SettingsKeys.KEY_ACCOUNT_LOGOUT -> {
|
SettingsKeys.KEY_ACCOUNT_LOGOUT -> {
|
||||||
_dialog.setValue { SettingsDialog.LogOut }
|
setDialog(SettingsDialog.LogOut)
|
||||||
}
|
}
|
||||||
|
|
||||||
SettingsKeys.KEY_DEBUG_PERFORM_CRASH -> {
|
SettingsKeys.KEY_DEBUG_PERFORM_CRASH -> {
|
||||||
_dialog.setValue { SettingsDialog.PerformCrash }
|
setDialog(SettingsDialog.PerformCrash)
|
||||||
}
|
}
|
||||||
|
|
||||||
SettingsKeys.KEY_DEBUG_IMPORT_AUTH_DATA -> {
|
SettingsKeys.KEY_DEBUG_IMPORT_AUTH_DATA -> {
|
||||||
_dialog.setValue { SettingsDialog.ImportAuthData }
|
setDialog(SettingsDialog.ImportAuthData)
|
||||||
}
|
}
|
||||||
|
|
||||||
SettingsKeys.KEY_DEBUG_EXPORT_AUTH_DATA -> {
|
SettingsKeys.KEY_DEBUG_EXPORT_AUTH_DATA -> {
|
||||||
_dialog.setValue {
|
setDialog(
|
||||||
SettingsDialog.ExportAuthData(
|
SettingsDialog.ExportAuthData(
|
||||||
accessToken = UserConfig.accessToken,
|
accessToken = UserConfig.accessToken,
|
||||||
exchangeToken = UserConfig.exchangeToken,
|
exchangeToken = UserConfig.exchangeToken,
|
||||||
trustedHash = UserConfig.trustedHash
|
trustedHash = UserConfig.trustedHash
|
||||||
)
|
)
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
SettingsKeys.KEY_DEBUG_HIDE_DEBUG_LIST -> {
|
SettingsKeys.KEY_DEBUG_HIDE_DEBUG_LIST -> {
|
||||||
@@ -203,13 +258,13 @@ class SettingsViewModel(
|
|||||||
|
|
||||||
createSettings()
|
createSettings()
|
||||||
|
|
||||||
_hapticType.update { HapticType.REJECT }
|
screenEffect.tryEmit(SettingsEffect.PerformHaptic(HapticType.REJECT))
|
||||||
_screenState.setValue { old -> old.copy(showDebugOptions = false) }
|
showDebugCategory = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onSettingsItemLongClicked(key: String) {
|
private fun onSettingsItemLongClicked(key: String) {
|
||||||
when (key) {
|
when (key) {
|
||||||
SettingsKeys.KEY_ACTIVITY_SEND_ONLINE_STATUS -> {
|
SettingsKeys.KEY_ACTIVITY_SEND_ONLINE_STATUS -> {
|
||||||
if (AppSettings.Debug.showDebugCategory) return
|
if (AppSettings.Debug.showDebugCategory) return
|
||||||
@@ -219,18 +274,18 @@ class SettingsViewModel(
|
|||||||
|
|
||||||
createSettings()
|
createSettings()
|
||||||
|
|
||||||
_hapticType.update { HapticType.LONG_PRESS }
|
screenEffect.tryEmit(SettingsEffect.PerformHaptic(HapticType.LONG_PRESS))
|
||||||
_screenState.setValue { old -> old.copy(showDebugOptions = true) }
|
showDebugCategory = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onSettingsItemChanged(key: String, newValue: Any?) {
|
private fun onSettingsItemChanged(key: String, newValue: Any?) {
|
||||||
settings.value.findWithIndex { it.key == key }?.let { (index, item) ->
|
settings.findWithIndex { it.key == key }?.let { (index, item) ->
|
||||||
item.updateValue(newValue)
|
item.updateValue(newValue)
|
||||||
item.updateText()
|
item.updateText()
|
||||||
|
|
||||||
_screenState.setValue { old ->
|
screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
settings = old.settings.toMutableList().apply {
|
settings = old.settings.toMutableList().apply {
|
||||||
this[index] = item.asPresentation(resources)
|
this[index] = item.asPresentation(resources)
|
||||||
@@ -311,10 +366,6 @@ class SettingsViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onHapticPerformed() {
|
|
||||||
_hapticType.update { null }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun createSettings() {
|
private fun createSettings() {
|
||||||
val accountVisible = UserConfig.isLoggedIn()
|
val accountVisible = UserConfig.isLoggedIn()
|
||||||
val accountTitle = SettingsItem.Title(
|
val accountTitle = SettingsItem.Title(
|
||||||
@@ -497,10 +548,10 @@ class SettingsViewModel(
|
|||||||
)
|
)
|
||||||
|
|
||||||
val logLevelValues = listOf(
|
val logLevelValues = listOf(
|
||||||
LogLevel.NONE to UiText.Simple("None"),
|
NetworkLogLevel.NONE to UiText.Simple("None"),
|
||||||
LogLevel.BASIC to UiText.Simple("Basic"),
|
NetworkLogLevel.BASIC to UiText.Simple("Basic"),
|
||||||
LogLevel.HEADERS to UiText.Simple("Headers"),
|
NetworkLogLevel.HEADERS to UiText.Simple("Headers"),
|
||||||
LogLevel.BODY to UiText.Simple("Body")
|
NetworkLogLevel.BODY to UiText.Simple("Body")
|
||||||
).toMap()
|
).toMap()
|
||||||
|
|
||||||
val debugNetworkLogLevel = SettingsItem.ListItem(
|
val debugNetworkLogLevel = SettingsItem.ListItem(
|
||||||
@@ -509,10 +560,11 @@ class SettingsViewModel(
|
|||||||
valueClass = Int::class,
|
valueClass = Int::class,
|
||||||
defaultValue = SettingsKeys.DEFAULT_NETWORK_LOG_LEVEL,
|
defaultValue = SettingsKeys.DEFAULT_NETWORK_LOG_LEVEL,
|
||||||
titles = logLevelValues.values.toList(),
|
titles = logLevelValues.values.toList(),
|
||||||
values = logLevelValues.keys.toList().map(LogLevel::value)
|
values = logLevelValues.keys.toList().map(NetworkLogLevel::value)
|
||||||
).apply {
|
).apply {
|
||||||
textProvider = TextProvider { item ->
|
textProvider = TextProvider { item ->
|
||||||
val textValue = logLevelValues[LogLevel.parse(item.value)].parseString(resources)
|
val textValue =
|
||||||
|
logLevelValues[NetworkLogLevel.parse(item.value)].parseString(resources)
|
||||||
|
|
||||||
UiText.Simple("Current value: $textValue")
|
UiText.Simple("Current value: $textValue")
|
||||||
}
|
}
|
||||||
@@ -602,12 +654,10 @@ class SettingsViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun emitSettings(newSettings: List<SettingsItem<*>>) {
|
private fun emitSettings(newSettings: List<SettingsItem<*>>) {
|
||||||
settings.update { newSettings }
|
settings.clear()
|
||||||
|
settings.addAll(newSettings)
|
||||||
|
|
||||||
val uiSettings = newSettings.map { item ->
|
val uiSettings = newSettings.map { it.asPresentation(resources) }
|
||||||
item.asPresentation(resources)
|
screenState.setValue { old -> old.copy(settings = uiSettings) }
|
||||||
}
|
|
||||||
|
|
||||||
_screenState.setValue { old -> old.copy(settings = uiSettings) }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package dev.meloda.fast.settings.model
|
||||||
|
|
||||||
|
sealed interface SettingsEffect {
|
||||||
|
data class Navigate(val intent: SettingsNavigationIntent) : SettingsEffect
|
||||||
|
data class PerformHaptic(val type: HapticType) : SettingsEffect
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package dev.meloda.fast.settings.model
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
|
||||||
|
sealed class SettingsIntent {
|
||||||
|
data object BackClick : SettingsIntent()
|
||||||
|
|
||||||
|
data class ItemClick(val key: String) : SettingsIntent()
|
||||||
|
data class ItemLongClick(val key: String) : SettingsIntent()
|
||||||
|
data class ItemValueChanged(val key: String, val newValue: Any?) : SettingsIntent()
|
||||||
|
|
||||||
|
sealed class Dialog : SettingsIntent() {
|
||||||
|
data object Dismiss : Dialog()
|
||||||
|
data class ConfirmClick(val bundle: Bundle? = null) : Dialog()
|
||||||
|
data object CancelClick : Dialog()
|
||||||
|
data class ItemPick(val bundle: Bundle? = null) : Dialog()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
package dev.meloda.fast.settings.model
|
package dev.meloda.fast.settings.model
|
||||||
|
|
||||||
import android.content.res.Resources
|
import android.content.res.Resources
|
||||||
import androidx.compose.runtime.Immutable
|
import androidx.compose.runtime.Stable
|
||||||
import dev.meloda.fast.common.model.UiText
|
import dev.meloda.fast.common.model.UiText
|
||||||
import dev.meloda.fast.common.model.parseString
|
import dev.meloda.fast.common.model.parseString
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
@Immutable
|
@Stable
|
||||||
sealed class SettingsItem<T>(
|
sealed class SettingsItem<T>(
|
||||||
val key: String,
|
val key: String,
|
||||||
value: T,
|
value: T,
|
||||||
|
|||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package dev.meloda.fast.settings.model
|
||||||
|
|
||||||
|
sealed class SettingsNavigationIntent {
|
||||||
|
data object Back : SettingsNavigationIntent()
|
||||||
|
data object Language : SettingsNavigationIntent()
|
||||||
|
data object Restart : SettingsNavigationIntent()
|
||||||
|
data object LogOut : SettingsNavigationIntent()
|
||||||
|
}
|
||||||
+2
-2
@@ -6,13 +6,13 @@ import dev.meloda.fast.datastore.AppSettings
|
|||||||
@Immutable
|
@Immutable
|
||||||
data class SettingsScreenState(
|
data class SettingsScreenState(
|
||||||
val settings: List<UiItem>,
|
val settings: List<UiItem>,
|
||||||
val showDebugOptions: Boolean
|
val dialog: SettingsDialog?
|
||||||
) {
|
) {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val EMPTY: SettingsScreenState = SettingsScreenState(
|
val EMPTY: SettingsScreenState = SettingsScreenState(
|
||||||
settings = emptyList(),
|
settings = emptyList(),
|
||||||
showDebugOptions = AppSettings.Debug.showDebugCategory
|
dialog = null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-8
@@ -1,26 +1,49 @@
|
|||||||
package dev.meloda.fast.settings.navigation
|
package dev.meloda.fast.settings.navigation
|
||||||
|
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.platform.LocalView
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import androidx.navigation.NavGraphBuilder
|
import androidx.navigation.NavGraphBuilder
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.settings.SettingsViewModel
|
||||||
|
import dev.meloda.fast.settings.model.SettingsEffect
|
||||||
|
import dev.meloda.fast.settings.model.SettingsNavigationIntent
|
||||||
import dev.meloda.fast.settings.presentation.SettingsRoute
|
import dev.meloda.fast.settings.presentation.SettingsRoute
|
||||||
|
import kotlinx.coroutines.flow.collect
|
||||||
|
import kotlinx.coroutines.flow.onEach
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
import org.koin.androidx.compose.koinViewModel
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
object Settings
|
object Settings
|
||||||
|
|
||||||
fun NavGraphBuilder.settingsScreen(
|
fun NavGraphBuilder.settingsScreen(
|
||||||
onBack: () -> Unit,
|
handleNavigationIntent: (SettingsNavigationIntent) -> Unit
|
||||||
onLogOutButtonClicked: () -> Unit,
|
|
||||||
onLanguageItemClicked: () -> Unit,
|
|
||||||
onRestartRequired: () -> Unit,
|
|
||||||
) {
|
) {
|
||||||
composable<Settings> {
|
composable<Settings> {
|
||||||
|
val view = LocalView.current
|
||||||
|
val viewModel: SettingsViewModel = koinViewModel()
|
||||||
|
val screenState by viewModel.screenStateFlow.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
viewModel.screenEffectFlow.onEach { effect ->
|
||||||
|
when (effect) {
|
||||||
|
is SettingsEffect.Navigate -> handleNavigationIntent(effect.intent)
|
||||||
|
is SettingsEffect.PerformHaptic -> {
|
||||||
|
if (AppSettings.General.enableHaptic) {
|
||||||
|
view.performHapticFeedback(effect.type.getHaptic())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.collect()
|
||||||
|
}
|
||||||
|
|
||||||
SettingsRoute(
|
SettingsRoute(
|
||||||
onBack = onBack,
|
handleIntent = viewModel::handleIntent,
|
||||||
onLogOutButtonClicked = onLogOutButtonClicked,
|
screenState = screenState,
|
||||||
onLanguageItemClicked = onLanguageItemClicked,
|
|
||||||
onRestartRequired = onRestartRequired
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-18
@@ -3,7 +3,6 @@ package dev.meloda.fast.settings.presentation
|
|||||||
import android.content.ClipData
|
import android.content.ClipData
|
||||||
import android.content.ClipboardManager
|
import android.content.ClipboardManager
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Bundle
|
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
@@ -26,20 +25,18 @@ import androidx.core.os.bundleOf
|
|||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.datastore.SettingsKeys
|
import dev.meloda.fast.datastore.SettingsKeys
|
||||||
import dev.meloda.fast.settings.model.SettingsDialog
|
import dev.meloda.fast.settings.model.SettingsDialog
|
||||||
|
import dev.meloda.fast.settings.model.SettingsIntent
|
||||||
import dev.meloda.fast.settings.model.SettingsScreenState
|
import dev.meloda.fast.settings.model.SettingsScreenState
|
||||||
|
import dev.meloda.fast.ui.R
|
||||||
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
||||||
import dev.meloda.fast.ui.components.MaterialDialog
|
import dev.meloda.fast.ui.components.MaterialDialog
|
||||||
import dev.meloda.fast.ui.R
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun HandleDialogs(
|
fun HandleDialogs(
|
||||||
|
handleIntent: (SettingsIntent.Dialog) -> Unit,
|
||||||
screenState: SettingsScreenState,
|
screenState: SettingsScreenState,
|
||||||
dialog: SettingsDialog?,
|
|
||||||
onConfirmed: (SettingsDialog, Bundle) -> Unit = { _, _ -> },
|
|
||||||
onDismissed: (SettingsDialog) -> Unit = {},
|
|
||||||
onItemPicked: (SettingsDialog, Bundle) -> Unit = { _, _ -> }
|
|
||||||
) {
|
) {
|
||||||
if (dialog == null) return
|
val dialog = screenState.dialog ?: return
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
||||||
@@ -48,13 +45,13 @@ fun HandleDialogs(
|
|||||||
val isEasterEgg = UserConfig.userId == SettingsKeys.ID_DMITRY
|
val isEasterEgg = UserConfig.userId == SettingsKeys.ID_DMITRY
|
||||||
|
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(SettingsIntent.Dialog.Dismiss) },
|
||||||
title = stringResource(
|
title = stringResource(
|
||||||
id = if (isEasterEgg) R.string.easter_egg_log_out_dmitry
|
id = if (isEasterEgg) R.string.easter_egg_log_out_dmitry
|
||||||
else R.string.sign_out_confirm_title
|
else R.string.sign_out_confirm_title
|
||||||
),
|
),
|
||||||
text = stringResource(id = R.string.sign_out_confirm),
|
text = stringResource(id = R.string.sign_out_confirm),
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(SettingsIntent.Dialog.ConfirmClick()) },
|
||||||
confirmText = stringResource(
|
confirmText = stringResource(
|
||||||
id = if (isEasterEgg) R.string.easter_egg_log_out_dmitry
|
id = if (isEasterEgg) R.string.easter_egg_log_out_dmitry
|
||||||
else R.string.action_sign_out
|
else R.string.action_sign_out
|
||||||
@@ -66,10 +63,10 @@ fun HandleDialogs(
|
|||||||
|
|
||||||
is SettingsDialog.PerformCrash -> {
|
is SettingsDialog.PerformCrash -> {
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(SettingsIntent.Dialog.Dismiss) },
|
||||||
title = "Perform crash",
|
title = "Perform crash",
|
||||||
text = "App will be crashed. Are you sure?",
|
text = "App will be crashed. Are you sure?",
|
||||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
confirmAction = { handleIntent(SettingsIntent.Dialog.ConfirmClick()) },
|
||||||
confirmText = stringResource(id = R.string.yes),
|
confirmText = stringResource(id = R.string.yes),
|
||||||
cancelText = stringResource(id = R.string.cancel),
|
cancelText = stringResource(id = R.string.cancel),
|
||||||
actionInvokeDismiss = ActionInvokeDismiss.Always
|
actionInvokeDismiss = ActionInvokeDismiss.Always
|
||||||
@@ -88,17 +85,18 @@ fun HandleDialogs(
|
|||||||
}
|
}
|
||||||
|
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(SettingsIntent.Dialog.Dismiss) },
|
||||||
title = "Import auth data",
|
title = "Import auth data",
|
||||||
confirmAction = {
|
confirmAction = {
|
||||||
onConfirmed(
|
handleIntent(
|
||||||
dialog,
|
SettingsIntent.Dialog.ConfirmClick(
|
||||||
bundleOf(
|
bundleOf(
|
||||||
"ACCESS_TOKEN" to accessToken,
|
"ACCESS_TOKEN" to accessToken,
|
||||||
"EXCHANGE_TOKEN" to exchangeToken.ifEmpty { null },
|
"EXCHANGE_TOKEN" to exchangeToken.ifEmpty { null },
|
||||||
"TRUSTED_HASH" to trustedHash.ifEmpty { null }
|
"TRUSTED_HASH" to trustedHash.ifEmpty { null }
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
)
|
||||||
},
|
},
|
||||||
confirmText = "Import",
|
confirmText = "Import",
|
||||||
cancelText = stringResource(R.string.cancel)
|
cancelText = stringResource(R.string.cancel)
|
||||||
@@ -198,17 +196,18 @@ fun HandleDialogs(
|
|||||||
}
|
}
|
||||||
|
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { onDismissed(dialog) },
|
onDismissRequest = { handleIntent(SettingsIntent.Dialog.Dismiss) },
|
||||||
title = "Export auth data",
|
title = "Export auth data",
|
||||||
confirmAction = {
|
confirmAction = {
|
||||||
onConfirmed(
|
handleIntent(
|
||||||
dialog,
|
SettingsIntent.Dialog.ConfirmClick(
|
||||||
bundleOf(
|
bundleOf(
|
||||||
"ACCESS_TOKEN" to accessToken,
|
"ACCESS_TOKEN" to accessToken,
|
||||||
"EXCHANGE_TOKEN" to exchangeToken.ifEmpty { null },
|
"EXCHANGE_TOKEN" to exchangeToken.ifEmpty { null },
|
||||||
"TRUSTED_HASH" to trustedHash.ifEmpty { null }
|
"TRUSTED_HASH" to trustedHash.ifEmpty { null }
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
)
|
||||||
},
|
},
|
||||||
confirmText = stringResource(R.string.ok),
|
confirmText = stringResource(R.string.ok),
|
||||||
) {
|
) {
|
||||||
@@ -269,7 +268,8 @@ fun HandleDialogs(
|
|||||||
"Auth data copied to clipboard. Be careful with this data. If another person gets it, your account will be at risk",
|
"Auth data copied to clipboard. Be careful with this data. If another person gets it, your account will be at risk",
|
||||||
Toast.LENGTH_LONG
|
Toast.LENGTH_LONG
|
||||||
).show()
|
).show()
|
||||||
onDismissed(dialog)
|
|
||||||
|
handleIntent(SettingsIntent.Dialog.Dismiss)
|
||||||
},
|
},
|
||||||
modifier = Modifier.align(Alignment.CenterHorizontally)
|
modifier = Modifier.align(Alignment.CenterHorizontally)
|
||||||
) {
|
) {
|
||||||
|
|||||||
+6
-50
@@ -1,65 +1,21 @@
|
|||||||
package dev.meloda.fast.settings.presentation
|
package dev.meloda.fast.settings.presentation
|
||||||
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import dev.meloda.fast.settings.model.SettingsIntent
|
||||||
import androidx.compose.runtime.getValue
|
import dev.meloda.fast.settings.model.SettingsScreenState
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|
||||||
import dev.meloda.fast.datastore.SettingsKeys
|
|
||||||
import dev.meloda.fast.settings.SettingsViewModel
|
|
||||||
import dev.meloda.fast.settings.model.SettingsDialog
|
|
||||||
import org.koin.compose.viewmodel.koinViewModel
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun SettingsRoute(
|
fun SettingsRoute(
|
||||||
onBack: () -> Unit,
|
handleIntent: (SettingsIntent) -> Unit,
|
||||||
onLogOutButtonClicked: () -> Unit,
|
screenState: SettingsScreenState,
|
||||||
onLanguageItemClicked: () -> Unit,
|
|
||||||
onRestartRequired: () -> Unit,
|
|
||||||
viewModel: SettingsViewModel = koinViewModel()
|
|
||||||
) {
|
) {
|
||||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
|
||||||
val hapticType by viewModel.hapticType.collectAsStateWithLifecycle()
|
|
||||||
val dialog by viewModel.dialog.collectAsStateWithLifecycle()
|
|
||||||
val isNeedToRestart by viewModel.isNeedToRestart.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
LaunchedEffect(isNeedToRestart) {
|
|
||||||
if (isNeedToRestart) {
|
|
||||||
onRestartRequired()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SettingsScreen(
|
SettingsScreen(
|
||||||
|
handleIntent = handleIntent,
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
hapticType = hapticType,
|
|
||||||
onBack = onBack,
|
|
||||||
onHapticPerformed = viewModel::onHapticPerformed,
|
|
||||||
onSettingsItemClicked = { key ->
|
|
||||||
when (key) {
|
|
||||||
SettingsKeys.KEY_APPEARANCE_LANGUAGE -> {
|
|
||||||
onLanguageItemClicked()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> viewModel.onSettingsItemClicked(key)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onSettingsItemLongClicked = viewModel::onSettingsItemLongClicked,
|
|
||||||
onSettingsItemValueChanged = viewModel::onSettingsItemChanged
|
|
||||||
)
|
)
|
||||||
|
|
||||||
HandleDialogs(
|
HandleDialogs(
|
||||||
|
handleIntent = handleIntent,
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
dialog = dialog,
|
|
||||||
onConfirmed = { dialog, bundle ->
|
|
||||||
when (dialog) {
|
|
||||||
is SettingsDialog.LogOut -> {
|
|
||||||
onLogOutButtonClicked()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
viewModel.onDialogConfirmed(dialog, bundle)
|
|
||||||
},
|
|
||||||
onDismissed = viewModel::onDialogDismissed,
|
|
||||||
onItemPicked = viewModel::onDialogItemPicked
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-19
@@ -21,10 +21,10 @@ import androidx.compose.material3.Text
|
|||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.material3.TopAppBarDefaults
|
import androidx.compose.material3.TopAppBarDefaults
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalView
|
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -34,8 +34,7 @@ import dev.chrisbanes.haze.hazeEffect
|
|||||||
import dev.chrisbanes.haze.hazeSource
|
import dev.chrisbanes.haze.hazeSource
|
||||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||||
import dev.chrisbanes.haze.materials.HazeMaterials
|
import dev.chrisbanes.haze.materials.HazeMaterials
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.settings.model.SettingsIntent
|
||||||
import dev.meloda.fast.settings.model.HapticType
|
|
||||||
import dev.meloda.fast.settings.model.SettingsScreenState
|
import dev.meloda.fast.settings.model.SettingsScreenState
|
||||||
import dev.meloda.fast.settings.model.UiItem
|
import dev.meloda.fast.settings.model.UiItem
|
||||||
import dev.meloda.fast.settings.presentation.item.ListItem
|
import dev.meloda.fast.settings.presentation.item.ListItem
|
||||||
@@ -43,8 +42,8 @@ import dev.meloda.fast.settings.presentation.item.SwitchItem
|
|||||||
import dev.meloda.fast.settings.presentation.item.TextFieldItem
|
import dev.meloda.fast.settings.presentation.item.TextFieldItem
|
||||||
import dev.meloda.fast.settings.presentation.item.TitleItem
|
import dev.meloda.fast.settings.presentation.item.TitleItem
|
||||||
import dev.meloda.fast.settings.presentation.item.TitleTextItem
|
import dev.meloda.fast.settings.presentation.item.TitleTextItem
|
||||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
|
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||||
|
|
||||||
|
|
||||||
@OptIn(
|
@OptIn(
|
||||||
@@ -53,23 +52,19 @@ import dev.meloda.fast.ui.R
|
|||||||
)
|
)
|
||||||
@Composable
|
@Composable
|
||||||
fun SettingsScreen(
|
fun SettingsScreen(
|
||||||
|
handleIntent: (SettingsIntent) -> Unit,
|
||||||
screenState: SettingsScreenState = SettingsScreenState.EMPTY,
|
screenState: SettingsScreenState = SettingsScreenState.EMPTY,
|
||||||
hapticType: HapticType? = null,
|
|
||||||
onBack: () -> Unit = {},
|
|
||||||
onHapticPerformed: () -> Unit = {},
|
|
||||||
onSettingsItemClicked: (key: String) -> Unit = {},
|
|
||||||
onSettingsItemLongClicked: (key: String) -> Unit = {},
|
|
||||||
onSettingsItemValueChanged: (key: String, newValue: Any?) -> Unit = { _, _ -> }
|
|
||||||
) {
|
) {
|
||||||
val view = LocalView.current
|
val onSettingsItemClicked by rememberUpdatedState { key: String ->
|
||||||
|
handleIntent(SettingsIntent.ItemClick(key))
|
||||||
|
}
|
||||||
|
|
||||||
LaunchedEffect(hapticType) {
|
val onSettingsItemLongClicked by rememberUpdatedState { key: String ->
|
||||||
if (hapticType != null) {
|
handleIntent(SettingsIntent.ItemLongClick(key))
|
||||||
if (AppSettings.General.enableHaptic) {
|
|
||||||
view.performHapticFeedback(hapticType.getHaptic())
|
|
||||||
}
|
|
||||||
onHapticPerformed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val onSettingsItemValueChanged by rememberUpdatedState { key: String, newValue: Any? ->
|
||||||
|
handleIntent(SettingsIntent.ItemValueChanged(key, newValue))
|
||||||
}
|
}
|
||||||
|
|
||||||
val themeConfig = LocalThemeConfig.current
|
val themeConfig = LocalThemeConfig.current
|
||||||
@@ -90,7 +85,7 @@ fun SettingsScreen(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
IconButton(onClick = onBack) {
|
IconButton(onClick = { handleIntent(SettingsIntent.BackClick) }) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(id = R.drawable.ic_arrow_back_round_24),
|
painter = painterResource(id = R.drawable.ic_arrow_back_round_24),
|
||||||
contentDescription = "Back button"
|
contentDescription = "Back button"
|
||||||
|
|||||||
@@ -55,3 +55,4 @@ include(":feature:friends")
|
|||||||
include(":feature:profile")
|
include(":feature:profile")
|
||||||
include(":feature:createchat")
|
include(":feature:createchat")
|
||||||
include(":core:presentation")
|
include(":core:presentation")
|
||||||
|
include(":core:logger")
|
||||||
|
|||||||
Reference in New Issue
Block a user