forked from melod1n/fast-messenger
Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff8e2fdd49 | |||
| 514b8859c7 | |||
| c18a7963bf | |||
| 255a194c25 | |||
| 6b7f8f2397 | |||
| 0ffd92b875 | |||
| 68fff3ebee | |||
| f6c6ed59f3 | |||
| f24eae8209 | |||
| 96f45aef6a | |||
| 5dc000341b | |||
| 6961ac7240 | |||
| c380c1a73d | |||
| 2bf81c60d6 | |||
| 2e472733d9 | |||
| d91b726b9d | |||
| 3bb4de24a7 | |||
| 22d13fcbe5 | |||
| cb653eddc2 | |||
| df2c61d8d7 |
@@ -0,0 +1,131 @@
|
|||||||
|
# Fast Messenger Tech Debt Audit
|
||||||
|
|
||||||
|
## Critical
|
||||||
|
|
||||||
|
### `core/network/src/main/kotlin/dev/meloda/fast/network/interceptor/Error14HandlingInterceptor.kt`
|
||||||
|
- captcha flow is built around `wait/notify`, a raw executor, and shared mutable state.
|
||||||
|
- risk: deadlocks, leaked jobs, hard-to-reproduce auth hangs.
|
||||||
|
- fix: rewrite as suspend-based flow with timeout and explicit cancellation.
|
||||||
|
|
||||||
|
### `core/domain/src/main/kotlin/dev/meloda/fast/domain/LongPollEventParser.kt`
|
||||||
|
- file mixes parsing, dispatching, IO loading, and concurrency orchestration.
|
||||||
|
- risk: regressions when VK event format changes.
|
||||||
|
- fix: split by event family and add parser tests.
|
||||||
|
|
||||||
|
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/MessagesHistoryViewModelImpl.kt`
|
||||||
|
- view model is doing too much: loaders, navigation, selection, long poll hooks, read peers, dialog flow.
|
||||||
|
- risk: brittle state transitions and untestable branching.
|
||||||
|
- fix: extract coordinators/handlers per concern.
|
||||||
|
|
||||||
|
### `app/src/main/kotlin/dev/meloda/fast/MainViewModel.kt`
|
||||||
|
- root bootstrap handles auth, locale, long poll, permissions, profile, and start destination in one class.
|
||||||
|
- risk: startup bugs and hidden coupling between flows.
|
||||||
|
- fix: move startup/permission orchestration into dedicated controllers.
|
||||||
|
|
||||||
|
### `app/src/main/kotlin/dev/meloda/fast/presentation/RootScreen.kt`
|
||||||
|
- root composable owns too many top-level flows and dialogs.
|
||||||
|
- risk: UI orchestration drift and hard-to-read navigation logic.
|
||||||
|
- fix: split dialogs, bootstrap, and navigation concern into smaller composables.
|
||||||
|
|
||||||
|
## High
|
||||||
|
|
||||||
|
### `core/domain/src/main/kotlin/dev/meloda/fast/domain/LongPollEventParser.kt`
|
||||||
|
- uses many `Log.d` calls and large `when` branches.
|
||||||
|
- fix: reduce logging noise and add structured tracing only where needed.
|
||||||
|
|
||||||
|
### `core/network/src/main/kotlin/dev/meloda/fast/network/ResponseConverterFactory.kt`
|
||||||
|
- double-parsing response bodies and only logging malformed payloads.
|
||||||
|
- risk: opaque failures and harder debugging.
|
||||||
|
- fix: normalize error conversion and surface typed failures.
|
||||||
|
|
||||||
|
### `feature/profile/src/main/kotlin/dev/meloda/fast/profile/ProfileViewModel.kt`
|
||||||
|
- `loadAccountInfo()` has an empty error branch.
|
||||||
|
- risk: profile can fail silently.
|
||||||
|
- fix: set `baseError` and show fallback UI.
|
||||||
|
|
||||||
|
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/attachments/Attachments.kt`
|
||||||
|
- attachment preview logic still sits in UI layer and mixes fallback behavior.
|
||||||
|
- risk: silent drops of unsupported attachments.
|
||||||
|
- fix: move preview mapping to domain/ui-model layer.
|
||||||
|
|
||||||
|
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/Link.kt`
|
||||||
|
- title handling is nullable and duplicated with preview logic.
|
||||||
|
- fix: create a small UI model for link rendering.
|
||||||
|
|
||||||
|
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/File.kt`
|
||||||
|
- preview extraction is inline and branches on raw model internals.
|
||||||
|
- fix: extract to mapper/UI model.
|
||||||
|
|
||||||
|
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/MessagesList.kt`
|
||||||
|
- message-item interaction is dense and repeated.
|
||||||
|
- fix: normalize scroll/reply handlers and reduce nested callbacks.
|
||||||
|
|
||||||
|
## Medium
|
||||||
|
|
||||||
|
### `core/data/src/main/kotlin/dev/meloda/fast/data/VkUsersMap.kt`
|
||||||
|
- lookup helpers were using unsafe assumptions on external data.
|
||||||
|
- status: already improved, but should stay covered by tests.
|
||||||
|
|
||||||
|
### `core/data/src/main/kotlin/dev/meloda/fast/data/VkGroupsMap.kt`
|
||||||
|
- same risk profile as users map.
|
||||||
|
- status: already improved, still needs tests.
|
||||||
|
|
||||||
|
### `core/domain/src/main/kotlin/dev/meloda/fast/domain/OAuthUseCaseImpl.kt`
|
||||||
|
- auth success mapping used forced unwraps on server data.
|
||||||
|
- status: already improved, but auth contract should be validated.
|
||||||
|
|
||||||
|
### `app/src/main/kotlin/dev/meloda/fast/presentation/MainActivity.kt`
|
||||||
|
- service lifecycle now respects config changes, but app exit semantics should be documented.
|
||||||
|
- fix: keep explicit separation of app-close vs config-change behavior.
|
||||||
|
|
||||||
|
### `build-logic/convention/src/main/kotlin/dev/meloda/fast/KotlinAndroid.kt`
|
||||||
|
- build-tools are pinned to the local environment.
|
||||||
|
- risk: portable builds may drift between machines.
|
||||||
|
- fix: prefer SDK-managed consistency or document required SDK version.
|
||||||
|
|
||||||
|
### `app/src/main/kotlin/dev/meloda/fast/presentation/RootErrorDialog.kt`
|
||||||
|
- currently hardcodes English strings for some errors.
|
||||||
|
- fix: localize all texts through resources.
|
||||||
|
|
||||||
|
### `app/src/main/kotlin/dev/meloda/fast/presentation/RootScreen.kt`
|
||||||
|
- root-level error dialog is better, but some orchestration still remains in the root composable.
|
||||||
|
- fix: split into smaller root flows over time.
|
||||||
|
|
||||||
|
## Low
|
||||||
|
|
||||||
|
### `core/ui/src/main/kotlin/dev/meloda/fast/ui/components/AnimatedDots.kt`
|
||||||
|
- marked TODO rewrite.
|
||||||
|
- fix when touching related loading UI.
|
||||||
|
|
||||||
|
### `core/ui/src/main/kotlin/dev/meloda/fast/ui/theme/AppTheme.kt`
|
||||||
|
- color picker TODO suggests unfinished theme customization.
|
||||||
|
|
||||||
|
### `core/model/src/main/kotlin/dev/meloda/fast/model/api/data/LongPollUpdates.kt`
|
||||||
|
- `List<List<Any>>` is a weakly typed API boundary.
|
||||||
|
- fix: introduce explicit event DTOs.
|
||||||
|
|
||||||
|
### `core/model/src/main/kotlin/dev/meloda/fast/model/api/domain/VkMessage.kt`
|
||||||
|
- attachment persistence is still a TODO area.
|
||||||
|
|
||||||
|
### `core/model/src/main/kotlin/dev/meloda/fast/model/database/VkMessageEntity.kt`
|
||||||
|
- attachment storage/restoration is unresolved.
|
||||||
|
|
||||||
|
### `core/common/src/main/kotlin/dev/meloda/fast/common/model/LongPollState.kt`
|
||||||
|
- Android 15 support TODO.
|
||||||
|
|
||||||
|
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/MessagesHistoryViewModelImpl.kt`
|
||||||
|
- large commented-out legacy block should be removed once upload flow is reimplemented.
|
||||||
|
|
||||||
|
### `feature/auth/src/main/kotlin/dev/meloda/fast/auth/login/LoginViewModel.kt`
|
||||||
|
- debug/auth token acquisition TODO indicates unfinished auth path.
|
||||||
|
|
||||||
|
## What To Do First
|
||||||
|
1. Rewrite captcha interceptor.
|
||||||
|
2. Split `LongPollEventParser`.
|
||||||
|
3. Extract `MessagesHistoryViewModelImpl` orchestration.
|
||||||
|
4. Localize `RootErrorDialog` strings.
|
||||||
|
5. Add tests for auth, long poll parsing, and attachment mapping.
|
||||||
|
|
||||||
|
## Note
|
||||||
|
- Current code is already better on crash-prone nullable handling and service lifecycle.
|
||||||
|
- Remaining work is mostly structural and testability-focused.
|
||||||
@@ -79,6 +79,9 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
implementation(libs.acra.email)
|
||||||
|
implementation(libs.acra.dialog)
|
||||||
|
|
||||||
implementation(projects.feature.auth)
|
implementation(projects.feature.auth)
|
||||||
|
|
||||||
implementation(projects.feature.chatmaterials)
|
implementation(projects.feature.chatmaterials)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -38,6 +37,7 @@ interface MainViewModel {
|
|||||||
val startDestination: StateFlow<Any?>
|
val startDestination: StateFlow<Any?>
|
||||||
val isNeedToReplaceWithAuth: StateFlow<Boolean>
|
val isNeedToReplaceWithAuth: StateFlow<Boolean>
|
||||||
val currentUser: StateFlow<VkUser?>
|
val currentUser: StateFlow<VkUser?>
|
||||||
|
val baseError: StateFlow<BaseError?>
|
||||||
|
|
||||||
val isNeedToShowNotificationsDeniedDialog: StateFlow<Boolean>
|
val isNeedToShowNotificationsDeniedDialog: StateFlow<Boolean>
|
||||||
val isNeedToShowNotificationsRationaleDialog: StateFlow<Boolean>
|
val isNeedToShowNotificationsRationaleDialog: StateFlow<Boolean>
|
||||||
@@ -45,6 +45,7 @@ interface MainViewModel {
|
|||||||
val isNeedToRequestNotifications: StateFlow<Boolean>
|
val isNeedToRequestNotifications: StateFlow<Boolean>
|
||||||
|
|
||||||
fun onError(error: BaseError)
|
fun onError(error: BaseError)
|
||||||
|
fun onErrorConsumed()
|
||||||
|
|
||||||
fun onNavigatedToAuth()
|
fun onNavigatedToAuth()
|
||||||
|
|
||||||
@@ -73,6 +74,7 @@ class MainViewModelImpl(
|
|||||||
override val startDestination = MutableStateFlow<Any?>(null)
|
override val startDestination = MutableStateFlow<Any?>(null)
|
||||||
override val isNeedToReplaceWithAuth = MutableStateFlow(false)
|
override val isNeedToReplaceWithAuth = MutableStateFlow(false)
|
||||||
override val currentUser = MutableStateFlow<VkUser?>(null)
|
override val currentUser = MutableStateFlow<VkUser?>(null)
|
||||||
|
override val baseError = MutableStateFlow<BaseError?>(null)
|
||||||
|
|
||||||
override val isNeedToShowNotificationsDeniedDialog = MutableStateFlow(false)
|
override val isNeedToShowNotificationsDeniedDialog = MutableStateFlow(false)
|
||||||
override val isNeedToShowNotificationsRationaleDialog = MutableStateFlow(false)
|
override val isNeedToShowNotificationsRationaleDialog = MutableStateFlow(false)
|
||||||
@@ -82,6 +84,10 @@ class MainViewModelImpl(
|
|||||||
private var openNotificationsSettings = false
|
private var openNotificationsSettings = false
|
||||||
private var openAppSettings = false
|
private var openAppSettings = false
|
||||||
|
|
||||||
|
init {
|
||||||
|
listenLongPollState()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onError(error: BaseError) {
|
override fun onError(error: BaseError) {
|
||||||
when (error) {
|
when (error) {
|
||||||
BaseError.SessionExpired,
|
BaseError.SessionExpired,
|
||||||
@@ -89,9 +95,15 @@ class MainViewModelImpl(
|
|||||||
isNeedToReplaceWithAuth.update { true }
|
isNeedToReplaceWithAuth.update { true }
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> Unit // TODO: 21-Mar-25, Danil Nikolaev: show error in ui
|
else -> {
|
||||||
|
baseError.update { error }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onErrorConsumed() {
|
||||||
|
baseError.update { null }
|
||||||
|
}
|
||||||
|
|
||||||
override fun onNavigatedToAuth() {
|
override fun onNavigatedToAuth() {
|
||||||
isNeedToReplaceWithAuth.update { false }
|
isNeedToReplaceWithAuth.update { false }
|
||||||
@@ -203,10 +215,6 @@ class MainViewModelImpl(
|
|||||||
viewModelScope.launch(Dispatchers.IO) {
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
val currentAccount = getCurrentAccountUseCase()
|
val currentAccount = getCurrentAccountUseCase()
|
||||||
|
|
||||||
Log.d("MainViewModel", "currentAccount: $currentAccount")
|
|
||||||
|
|
||||||
listenLongPollState()
|
|
||||||
|
|
||||||
if (currentAccount != null) {
|
if (currentAccount != null) {
|
||||||
UserConfig.apply {
|
UserConfig.apply {
|
||||||
this.userId = currentAccount.userId
|
this.userId = currentAccount.userId
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ 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 org.acra.config.dialog
|
||||||
|
import org.acra.config.mailSender
|
||||||
|
import org.acra.data.StringFormat
|
||||||
|
import org.acra.ktx.initAcra
|
||||||
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
|
||||||
import org.koin.android.ext.koin.androidLogger
|
import org.koin.android.ext.koin.androidLogger
|
||||||
@@ -20,12 +24,14 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
|||||||
|
|
||||||
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
|
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
|
||||||
AppSettings.init(preferences)
|
AppSettings.init(preferences)
|
||||||
|
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
|
||||||
|
|
||||||
initKoin()
|
initKoin()
|
||||||
|
initAcra()
|
||||||
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun newImageLoader(): ImageLoader = get()
|
||||||
|
|
||||||
private fun initKoin() {
|
private fun initKoin() {
|
||||||
startKoin {
|
startKoin {
|
||||||
androidLogger()
|
androidLogger()
|
||||||
@@ -34,5 +40,21 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun newImageLoader(): ImageLoader = get()
|
private fun initAcra() {
|
||||||
|
initAcra {
|
||||||
|
buildConfigClass = BuildConfig::class.java
|
||||||
|
reportFormat = StringFormat.JSON
|
||||||
|
|
||||||
|
mailSender {
|
||||||
|
mailTo = "lischenkodev@gmail.com"
|
||||||
|
reportAsFile = true
|
||||||
|
reportFileName = "Crash.txt"
|
||||||
|
}
|
||||||
|
|
||||||
|
dialog {
|
||||||
|
text = "App crashed"
|
||||||
|
enabled = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,9 +7,7 @@ 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.MainViewModelImpl
|
||||||
import dev.meloda.fast.auth.captcha.di.captchaModule
|
import dev.meloda.fast.auth.authModule
|
||||||
import dev.meloda.fast.auth.login.di.loginModule
|
|
||||||
import dev.meloda.fast.auth.validation.di.validationModule
|
|
||||||
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
|
||||||
@@ -38,9 +36,7 @@ import org.koin.dsl.module
|
|||||||
val applicationModule = module {
|
val applicationModule = module {
|
||||||
includes(domainModule)
|
includes(domainModule)
|
||||||
includes(
|
includes(
|
||||||
loginModule,
|
authModule,
|
||||||
validationModule,
|
|
||||||
captchaModule,
|
|
||||||
convosModule,
|
convosModule,
|
||||||
settingsModule,
|
settingsModule,
|
||||||
messagesHistoryModule,
|
messagesHistoryModule,
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import dev.meloda.fast.model.BaseError
|
|||||||
import dev.meloda.fast.model.BottomNavigationItem
|
import dev.meloda.fast.model.BottomNavigationItem
|
||||||
import dev.meloda.fast.presentation.MainScreen
|
import dev.meloda.fast.presentation.MainScreen
|
||||||
import dev.meloda.fast.profile.navigation.Profile
|
import dev.meloda.fast.profile.navigation.Profile
|
||||||
|
import dev.meloda.fast.ui.R
|
||||||
import dev.meloda.fast.ui.util.ImmutableList
|
import dev.meloda.fast.ui.util.ImmutableList
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import dev.meloda.fast.ui.R
|
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
object MainGraph
|
object MainGraph
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ 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
|
||||||
@@ -65,9 +64,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||||
LaunchedEffect(viewModel) {
|
|
||||||
Log.d("VM_CREATE", "onCreate: viewModel: $viewModel")
|
|
||||||
}
|
|
||||||
|
|
||||||
LifecycleResumeEffect(true) {
|
LifecycleResumeEffect(true) {
|
||||||
viewModel.onAppResumed(intent)
|
viewModel.onAppResumed(intent)
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ import dev.meloda.fast.friends.navigation.friendsScreen
|
|||||||
import dev.meloda.fast.model.BaseError
|
import dev.meloda.fast.model.BaseError
|
||||||
import dev.meloda.fast.model.BottomNavigationItem
|
import dev.meloda.fast.model.BottomNavigationItem
|
||||||
import dev.meloda.fast.navigation.MainGraph
|
import dev.meloda.fast.navigation.MainGraph
|
||||||
|
import dev.meloda.fast.profile.navigation.Profile
|
||||||
import dev.meloda.fast.profile.navigation.profileScreen
|
import dev.meloda.fast.profile.navigation.profileScreen
|
||||||
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
|
||||||
@@ -69,15 +70,18 @@ fun MainScreen(
|
|||||||
val theme = LocalThemeConfig.current
|
val theme = LocalThemeConfig.current
|
||||||
val hazeState = remember { HazeState(true) }
|
val hazeState = remember { HazeState(true) }
|
||||||
val navController = rememberNavController()
|
val navController = rememberNavController()
|
||||||
|
val defaultTabIndex = remember(navigationItems) {
|
||||||
var selectedItemIndex by rememberSaveable {
|
navigationItems.indexOfFirst { it.route == ConvoGraph }.takeIf { it >= 0 } ?: 0
|
||||||
mutableIntStateOf(1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
BackHandler(enabled = selectedItemIndex != 1) {
|
var selectedItemIndex by rememberSaveable {
|
||||||
|
mutableIntStateOf(defaultTabIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
BackHandler(enabled = selectedItemIndex != defaultTabIndex) {
|
||||||
val currentRoute = navigationItems[selectedItemIndex].route
|
val currentRoute = navigationItems[selectedItemIndex].route
|
||||||
|
|
||||||
selectedItemIndex = 1
|
selectedItemIndex = defaultTabIndex
|
||||||
navController.navigate(navigationItems[selectedItemIndex].route) {
|
navController.navigate(navigationItems[selectedItemIndex].route) {
|
||||||
popUpTo(route = currentRoute) {
|
popUpTo(route = currentRoute) {
|
||||||
inclusive = true
|
inclusive = true
|
||||||
@@ -127,7 +131,7 @@ fun MainScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
icon = {
|
icon = {
|
||||||
if (index == navigationItems.size - 1) {
|
if (item.route == Profile) {
|
||||||
var isLoading by remember {
|
var isLoading by remember {
|
||||||
mutableStateOf(true)
|
mutableStateOf(true)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package dev.meloda.fast.presentation
|
||||||
|
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import dev.meloda.fast.model.BaseError
|
||||||
|
import dev.meloda.fast.ui.R
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun RootErrorDialog(
|
||||||
|
baseError: BaseError?,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onConfirm: () -> Unit,
|
||||||
|
) {
|
||||||
|
if (baseError == null) return
|
||||||
|
|
||||||
|
val errorText = when (baseError) {
|
||||||
|
BaseError.ConnectionError -> "Connection error"
|
||||||
|
BaseError.InternalError -> "Internal error"
|
||||||
|
BaseError.UnknownError -> "Unknown error"
|
||||||
|
is BaseError.SimpleError -> baseError.message
|
||||||
|
BaseError.SessionExpired -> "Session expired"
|
||||||
|
BaseError.AccountBlocked -> "Account blocked"
|
||||||
|
}
|
||||||
|
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(text = stringResource(id = R.string.warning)) },
|
||||||
|
text = { Text(text = errorText) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = onConfirm) {
|
||||||
|
Text(text = stringResource(id = R.string.try_again))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -4,16 +4,12 @@ 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
|
||||||
import androidx.compose.animation.fadeOut
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.material3.TextButton
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.CompositionLocalProvider
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
@@ -41,6 +37,7 @@ 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.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.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
|
||||||
@@ -48,6 +45,8 @@ import dev.meloda.fast.common.LongPollController
|
|||||||
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
|
||||||
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.datastore.CaptchaTokenResult
|
||||||
import dev.meloda.fast.datastore.UserSettings
|
import dev.meloda.fast.datastore.UserSettings
|
||||||
import dev.meloda.fast.languagepicker.navigation.languagePickerScreen
|
import dev.meloda.fast.languagepicker.navigation.languagePickerScreen
|
||||||
import dev.meloda.fast.languagepicker.navigation.navigateToLanguagePicker
|
import dev.meloda.fast.languagepicker.navigation.navigateToLanguagePicker
|
||||||
@@ -89,9 +88,6 @@ fun RootScreen(
|
|||||||
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||||
LaunchedEffect(viewModel) {
|
|
||||||
Log.d("VM_CREATE", "RootScreen(): viewModel: $viewModel")
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentUser: VkUser? by viewModel.currentUser.collectAsStateWithLifecycle()
|
val currentUser: VkUser? by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
@@ -123,13 +119,11 @@ fun RootScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
LifecycleResumeEffect(longPollStateToApply) {
|
LifecycleResumeEffect(longPollStateToApply) {
|
||||||
Log.d("LongPollMainActivity", "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(
|
||||||
@@ -238,6 +232,7 @@ fun RootScreen(
|
|||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val startDestination by viewModel.startDestination.collectAsStateWithLifecycle()
|
val startDestination by viewModel.startDestination.collectAsStateWithLifecycle()
|
||||||
val isNeedToOpenAuth by viewModel.isNeedToReplaceWithAuth.collectAsStateWithLifecycle()
|
val isNeedToOpenAuth by viewModel.isNeedToReplaceWithAuth.collectAsStateWithLifecycle()
|
||||||
|
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
||||||
val isNeedToShowDeniedDialog by viewModel.isNeedToShowNotificationsDeniedDialog.collectAsStateWithLifecycle()
|
val isNeedToShowDeniedDialog by viewModel.isNeedToShowNotificationsDeniedDialog.collectAsStateWithLifecycle()
|
||||||
val isNeedToShowRationaleDialog by viewModel.isNeedToShowNotificationsRationaleDialog.collectAsStateWithLifecycle()
|
val isNeedToShowRationaleDialog by viewModel.isNeedToShowNotificationsRationaleDialog.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
@@ -301,6 +296,12 @@ fun RootScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
RootErrorDialog(
|
||||||
|
baseError = baseError,
|
||||||
|
onDismiss = viewModel::onErrorConsumed,
|
||||||
|
onConfirm = viewModel::onErrorConsumed
|
||||||
|
)
|
||||||
|
|
||||||
if (startDestination != null) {
|
if (startDestination != null) {
|
||||||
CompositionLocalProvider(
|
CompositionLocalProvider(
|
||||||
LocalNavRootController provides navController,
|
LocalNavRootController provides navController,
|
||||||
@@ -310,6 +311,9 @@ fun RootScreen(
|
|||||||
mutableStateOf<Pair<List<String>, Int?>?>(null)
|
mutableStateOf<Pair<List<String>, Int?>?>(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val captchaRedirectUri by AppSettings.getCaptchaRedirectUriFlow()
|
||||||
|
.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
NavHost(
|
NavHost(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
@@ -334,7 +338,7 @@ fun RootScreen(
|
|||||||
photoViewerInfo = listOf(url) to null
|
photoViewerInfo = listOf(url) to null
|
||||||
},
|
},
|
||||||
onMessageClicked = navController::navigateToMessagesHistory,
|
onMessageClicked = navController::navigateToMessagesHistory,
|
||||||
onNavigateToCreateChat = navController::navigateToCreateChat
|
onNavigateToCreateChat = navController::navigateToCreateChat,
|
||||||
)
|
)
|
||||||
|
|
||||||
messagesHistoryScreen(
|
messagesHistoryScreen(
|
||||||
@@ -381,6 +385,18 @@ fun RootScreen(
|
|||||||
},
|
},
|
||||||
onDismiss = { photoViewerInfo = null }
|
onDismiss = { photoViewerInfo = null }
|
||||||
)
|
)
|
||||||
|
|
||||||
|
CaptchaScreen(
|
||||||
|
captchaRedirectUri = captchaRedirectUri,
|
||||||
|
onBack = {
|
||||||
|
AppSettings.setCaptchaResult(CaptchaTokenResult.Cancelled)
|
||||||
|
},
|
||||||
|
onResult = { result ->
|
||||||
|
AppSettings.setCaptchaResult(
|
||||||
|
CaptchaTokenResult.Success(result)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,11 +16,17 @@ import dev.meloda.fast.common.LongPollController
|
|||||||
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.model.LongPollState
|
import dev.meloda.fast.common.model.LongPollState
|
||||||
|
import dev.meloda.fast.data.VkMemoryCache
|
||||||
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.LongPollUpdatesParser
|
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||||
import dev.meloda.fast.domain.LongPollUseCase
|
import dev.meloda.fast.domain.LongPollUseCase
|
||||||
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
|
import dev.meloda.fast.domain.StoreUsersUseCase
|
||||||
|
import dev.meloda.fast.model.api.data.VkGroupData
|
||||||
|
import dev.meloda.fast.model.api.data.VkUserData
|
||||||
|
import dev.meloda.fast.model.api.data.asDomain
|
||||||
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
|
||||||
@@ -32,10 +38,11 @@ import kotlinx.coroutines.Job
|
|||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlinx.coroutines.flow.last
|
||||||
import org.koin.android.ext.android.inject
|
import org.koin.android.ext.android.inject
|
||||||
import kotlin.coroutines.CoroutineContext
|
import kotlin.coroutines.CoroutineContext
|
||||||
import kotlin.coroutines.resume
|
import kotlin.coroutines.resume
|
||||||
import kotlin.coroutines.suspendCoroutine
|
|
||||||
import kotlin.time.Duration.Companion.seconds
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
|
||||||
class LongPollingService : Service() {
|
class LongPollingService : Service() {
|
||||||
@@ -55,6 +62,8 @@ class LongPollingService : Service() {
|
|||||||
private val coroutineScope = CoroutineScope(coroutineContext)
|
private val coroutineScope = CoroutineScope(coroutineContext)
|
||||||
|
|
||||||
private val longPollUseCase: LongPollUseCase by inject()
|
private val longPollUseCase: LongPollUseCase by inject()
|
||||||
|
private val messagesUseCase: MessagesUseCase by inject()
|
||||||
|
private val storeUsersUseCase: StoreUsersUseCase by inject()
|
||||||
private val updatesParser: LongPollUpdatesParser by inject()
|
private val updatesParser: LongPollUpdatesParser by inject()
|
||||||
|
|
||||||
private var currentJob: Job? = null
|
private var currentJob: Job? = null
|
||||||
@@ -150,6 +159,8 @@ class LongPollingService : Service() {
|
|||||||
var serverInfo = getServerInfo()
|
var serverInfo = getServerInfo()
|
||||||
?: throw LongPollException(message = "bad VK response (server info)")
|
?: throw LongPollException(message = "bad VK response (server info)")
|
||||||
|
|
||||||
|
syncLongPollHistory(serverInfo)
|
||||||
|
|
||||||
var lastUpdatesResponse: LongPollUpdates? = getUpdatesResponse(serverInfo)
|
var lastUpdatesResponse: LongPollUpdates? = getUpdatesResponse(serverInfo)
|
||||||
?: throw LongPollException(message = "initiation error: bad VK response (last updates)")
|
?: throw LongPollException(message = "initiation error: bad VK response (last updates)")
|
||||||
|
|
||||||
@@ -160,6 +171,7 @@ class LongPollingService : Service() {
|
|||||||
failCount++
|
failCount++
|
||||||
serverInfo = getServerInfo()
|
serverInfo = getServerInfo()
|
||||||
?: throw LongPollException(message = "failed retrieving server info after error: bad VK response (server info #2)")
|
?: throw LongPollException(message = "failed retrieving server info after error: bad VK response (server info #2)")
|
||||||
|
syncLongPollHistory(serverInfo)
|
||||||
lastUpdatesResponse = getUpdatesResponse(serverInfo)
|
lastUpdatesResponse = getUpdatesResponse(serverInfo)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -179,6 +191,7 @@ class LongPollingService : Service() {
|
|||||||
?: throw LongPollException(
|
?: throw LongPollException(
|
||||||
message = "failed retrieving server info after error: bad VK response (server info #3)"
|
message = "failed retrieving server info after error: bad VK response (server info #3)"
|
||||||
)
|
)
|
||||||
|
syncLongPollHistory(serverInfo)
|
||||||
lastUpdatesResponse = getUpdatesResponse(serverInfo)
|
lastUpdatesResponse = getUpdatesResponse(serverInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,6 +209,9 @@ class LongPollingService : Service() {
|
|||||||
updates.forEach(updatesParser::parseNextUpdate)
|
updates.forEach(updatesParser::parseNextUpdate)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
AppSettings.LongPoll.ts = lastUpdatesResponse.ts ?: serverInfo.ts
|
||||||
|
AppSettings.LongPoll.pts = lastUpdatesResponse.pts ?: AppSettings.LongPoll.pts
|
||||||
|
|
||||||
lastUpdatesResponse = getUpdatesResponse(serverInfo.copy(ts = newTs))
|
lastUpdatesResponse = getUpdatesResponse(serverInfo.copy(ts = newTs))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -204,7 +220,7 @@ class LongPollingService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getServerInfo(): VkLongPollData? = suspendCoroutine {
|
private suspend fun getServerInfo(): VkLongPollData? = suspendCancellableCoroutine {
|
||||||
longPollUseCase.getLongPollServer(
|
longPollUseCase.getLongPollServer(
|
||||||
needPts = true,
|
needPts = true,
|
||||||
version = VkConstants.LP_VERSION
|
version = VkConstants.LP_VERSION
|
||||||
@@ -224,7 +240,7 @@ class LongPollingService : Service() {
|
|||||||
|
|
||||||
private suspend fun getUpdatesResponse(
|
private suspend fun getUpdatesResponse(
|
||||||
server: VkLongPollData
|
server: VkLongPollData
|
||||||
): LongPollUpdates? = suspendCoroutine {
|
): LongPollUpdates? = suspendCancellableCoroutine {
|
||||||
longPollUseCase.getLongPollUpdates(
|
longPollUseCase.getLongPollUpdates(
|
||||||
serverUrl = "https://${server.server}",
|
serverUrl = "https://${server.server}",
|
||||||
key = server.key,
|
key = server.key,
|
||||||
@@ -246,6 +262,73 @@ class LongPollingService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun syncLongPollHistory(serverInfo: VkLongPollData) {
|
||||||
|
val cursorTs = AppSettings.LongPoll.ts ?: serverInfo.ts
|
||||||
|
val cursorPts = AppSettings.LongPoll.pts ?: serverInfo.pts
|
||||||
|
val maxMsgId = messagesUseCase.getLocalMaxMessageId()
|
||||||
|
|
||||||
|
var currentTs = cursorTs
|
||||||
|
var currentPts = cursorPts
|
||||||
|
var more: Int?
|
||||||
|
|
||||||
|
do {
|
||||||
|
val historyResponse = getLongPollHistory(
|
||||||
|
ts = currentTs,
|
||||||
|
pts = currentPts,
|
||||||
|
maxMsgId = maxMsgId
|
||||||
|
) ?: return
|
||||||
|
|
||||||
|
historyResponse.history.orEmpty().forEach(updatesParser::parseNextUpdate)
|
||||||
|
|
||||||
|
historyResponse.messages?.items.orEmpty().takeIf { it.isNotEmpty() }?.let { rawMessages ->
|
||||||
|
val messages = rawMessages.map { it.asDomain() }
|
||||||
|
messagesUseCase.storeMessages(messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
historyResponse.profiles.orEmpty().takeIf { it.isNotEmpty() }?.let { profiles ->
|
||||||
|
val users = profiles.map(VkUserData::mapToDomain)
|
||||||
|
VkMemoryCache.appendUsers(users)
|
||||||
|
storeUsersUseCase(users).last()
|
||||||
|
}
|
||||||
|
|
||||||
|
historyResponse.groups.orEmpty().takeIf { it.isNotEmpty() }?.let { groups ->
|
||||||
|
VkMemoryCache.appendGroups(groups.map(VkGroupData::mapToDomain))
|
||||||
|
}
|
||||||
|
|
||||||
|
currentTs = historyResponse.ts ?: historyResponse.fromPts ?: currentTs
|
||||||
|
currentPts = historyResponse.newPts ?: historyResponse.pts ?: currentPts
|
||||||
|
more = historyResponse.more
|
||||||
|
|
||||||
|
AppSettings.LongPoll.ts = currentTs
|
||||||
|
AppSettings.LongPoll.pts = currentPts
|
||||||
|
} while (more == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun getLongPollHistory(
|
||||||
|
ts: Int,
|
||||||
|
pts: Int,
|
||||||
|
maxMsgId: Long?
|
||||||
|
): dev.meloda.fast.model.api.data.LongPollHistoryResponse? = suspendCancellableCoroutine {
|
||||||
|
longPollUseCase.getLongPollHistory(
|
||||||
|
ts = ts,
|
||||||
|
pts = pts,
|
||||||
|
lpVersion = VkConstants.LP_VERSION,
|
||||||
|
maxMsgId = maxMsgId,
|
||||||
|
eventsLimit = 1000,
|
||||||
|
msgsLimit = 200
|
||||||
|
).listenValue(coroutineScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
success = { response ->
|
||||||
|
it.resume(response)
|
||||||
|
},
|
||||||
|
error = { error ->
|
||||||
|
Log.e(TAG, "getLongPollHistory: error: $error")
|
||||||
|
it.resume(null)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun handleError(throwable: Throwable) {
|
private fun handleError(throwable: Throwable) {
|
||||||
Log.e(TAG, "error: $throwable")
|
Log.e(TAG, "error: $throwable")
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package dev.meloda.fast.service.longpolling.di
|
package dev.meloda.fast.service.longpolling.di
|
||||||
|
|
||||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||||
|
import dev.meloda.fast.domain.LongPollUpdatesReducer
|
||||||
import dev.meloda.fast.domain.LongPollUseCase
|
import dev.meloda.fast.domain.LongPollUseCase
|
||||||
import dev.meloda.fast.domain.LongPollUseCaseImpl
|
import dev.meloda.fast.domain.LongPollUseCaseImpl
|
||||||
import org.koin.core.module.dsl.singleOf
|
import org.koin.core.module.dsl.singleOf
|
||||||
@@ -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(::LongPollUpdatesReducer)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import com.android.build.api.dsl.ApplicationExtension
|
import com.android.build.api.dsl.ApplicationExtension
|
||||||
import dev.meloda.fast.configureKotlinAndroid
|
import dev.meloda.fast.configureKotlinAndroid
|
||||||
|
import dev.meloda.fast.getVersionInt
|
||||||
import org.gradle.api.Plugin
|
import org.gradle.api.Plugin
|
||||||
import org.gradle.api.Project
|
import org.gradle.api.Project
|
||||||
import org.gradle.kotlin.dsl.configure
|
import org.gradle.kotlin.dsl.configure
|
||||||
@@ -14,9 +15,9 @@ class AndroidApplicationConventionPlugin : Plugin<Project> {
|
|||||||
extensions.configure<ApplicationExtension> {
|
extensions.configure<ApplicationExtension> {
|
||||||
configureKotlinAndroid(this)
|
configureKotlinAndroid(this)
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
targetSdk = 36
|
minSdk = getVersionInt("minSdk")
|
||||||
compileSdk = 36
|
compileSdk = getVersionInt("compileSdk")
|
||||||
minSdk = 23
|
targetSdk = getVersionInt("targetSdk")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import com.android.build.api.dsl.LibraryExtension
|
import com.android.build.api.dsl.LibraryExtension
|
||||||
import dev.meloda.fast.configureAndroidCompose
|
import dev.meloda.fast.configureAndroidCompose
|
||||||
|
import dev.meloda.fast.getVersionInt
|
||||||
import org.gradle.api.Plugin
|
import org.gradle.api.Plugin
|
||||||
import org.gradle.api.Project
|
import org.gradle.api.Project
|
||||||
import org.gradle.kotlin.dsl.apply
|
import org.gradle.kotlin.dsl.apply
|
||||||
import org.gradle.kotlin.dsl.getByType
|
import org.gradle.kotlin.dsl.configure
|
||||||
|
|
||||||
class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
|
class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
|
||||||
override fun apply(target: Project) {
|
override fun apply(target: Project) {
|
||||||
@@ -12,9 +13,14 @@ class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
|
|||||||
apply(plugin = "org.jetbrains.kotlin.plugin.compose")
|
apply(plugin = "org.jetbrains.kotlin.plugin.compose")
|
||||||
apply(plugin = "com.github.skydoves.compose.stability.analyzer")
|
apply(plugin = "com.github.skydoves.compose.stability.analyzer")
|
||||||
|
|
||||||
val extension = extensions.getByType<LibraryExtension>()
|
extensions.configure<LibraryExtension> {
|
||||||
extension.androidResources.enable = false
|
configureAndroidCompose(this)
|
||||||
configureAndroidCompose(extension)
|
androidResources.enable = false
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = getVersionInt("minSdk")
|
||||||
|
compileSdk = getVersionInt("compileSdk")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import com.android.build.api.dsl.TestExtension
|
import com.android.build.api.dsl.TestExtension
|
||||||
import dev.meloda.fast.configureKotlinAndroid
|
import dev.meloda.fast.configureKotlinAndroid
|
||||||
|
import dev.meloda.fast.getVersionInt
|
||||||
import org.gradle.api.Plugin
|
import org.gradle.api.Plugin
|
||||||
import org.gradle.api.Project
|
import org.gradle.api.Project
|
||||||
import org.gradle.kotlin.dsl.configure
|
import org.gradle.kotlin.dsl.configure
|
||||||
@@ -13,7 +14,11 @@ class AndroidTestConventionPlugin : Plugin<Project> {
|
|||||||
|
|
||||||
extensions.configure<TestExtension> {
|
extensions.configure<TestExtension> {
|
||||||
configureKotlinAndroid(this)
|
configureKotlinAndroid(this)
|
||||||
defaultConfig.targetSdk = 36
|
defaultConfig {
|
||||||
|
minSdk = getVersionInt("minSdk")
|
||||||
|
compileSdk = getVersionInt("compileSdk")
|
||||||
|
targetSdk = getVersionInt("targetSdk")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,8 @@ internal fun Project.configureKotlinAndroid(
|
|||||||
}
|
}
|
||||||
|
|
||||||
commonExtension.apply {
|
commonExtension.apply {
|
||||||
compileSdk = 36
|
compileSdk = getVersionInt("compileSdk")
|
||||||
|
buildToolsVersion = "36.1.0"
|
||||||
}
|
}
|
||||||
|
|
||||||
configureKotlin<KotlinAndroidProjectExtension>()
|
configureKotlin<KotlinAndroidProjectExtension>()
|
||||||
@@ -61,6 +62,7 @@ private inline fun <reified T : KotlinBaseExtension> Project.configureKotlin() =
|
|||||||
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
|
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
|
||||||
"-opt-in=kotlinx.coroutines.FlowPreview",
|
"-opt-in=kotlinx.coroutines.FlowPreview",
|
||||||
"-Xannotation-default-target=param-property",
|
"-Xannotation-default-target=param-property",
|
||||||
|
"-Xcontext-parameters"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,3 +7,8 @@ import org.gradle.kotlin.dsl.getByType
|
|||||||
|
|
||||||
val Project.libs
|
val Project.libs
|
||||||
get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
|
get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
|
||||||
|
|
||||||
|
|
||||||
|
fun Project.getVersionInt(alias: String): Int {
|
||||||
|
return libs.findVersion(alias).get().requiredVersion.toInt()
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,6 +13,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
|
||||||
@@ -45,6 +46,14 @@ fun <T> Flow<T>.listenValue(
|
|||||||
action: suspend (T) -> Unit
|
action: suspend (T) -> Unit
|
||||||
): Job = onEach(action::invoke).launchIn(coroutineScope)
|
): Job = onEach(action::invoke).launchIn(coroutineScope)
|
||||||
|
|
||||||
|
fun CoroutineScope.launchDbRefresh(
|
||||||
|
load: suspend () -> Unit,
|
||||||
|
after: suspend () -> Unit
|
||||||
|
): Job = launch {
|
||||||
|
load()
|
||||||
|
after()
|
||||||
|
}
|
||||||
|
|
||||||
fun createTimerFlow(
|
fun createTimerFlow(
|
||||||
time: Int,
|
time: Int,
|
||||||
onStartAction: (suspend () -> Unit)? = null,
|
onStartAction: (suspend () -> Unit)? = null,
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package dev.meloda.fast.common.paging
|
||||||
|
|
||||||
|
fun canPaginate(pageSize: Int, loadedCount: Int): Boolean = loadedCount == pageSize
|
||||||
|
|
||||||
|
fun isPaginationExhausted(
|
||||||
|
pageSize: Int,
|
||||||
|
loadedCount: Int,
|
||||||
|
hasExistingItems: Boolean
|
||||||
|
): Boolean = loadedCount != pageSize && hasExistingItems
|
||||||
|
|
||||||
|
fun <T> mergePage(
|
||||||
|
existing: List<T>,
|
||||||
|
page: List<T>,
|
||||||
|
offset: Int
|
||||||
|
): List<T> = if (offset == 0) page else existing + page
|
||||||
|
|
||||||
|
data class LoadingFlags(
|
||||||
|
val isLoading: Boolean,
|
||||||
|
val isPaginating: Boolean
|
||||||
|
)
|
||||||
|
|
||||||
|
fun loadingFlags(offset: Int, isLoading: Boolean): LoadingFlags = LoadingFlags(
|
||||||
|
isLoading = offset == 0 && isLoading,
|
||||||
|
isPaginating = offset > 0 && isLoading
|
||||||
|
)
|
||||||
@@ -1,24 +1,18 @@
|
|||||||
package dev.meloda.fast.data
|
package dev.meloda.fast.data
|
||||||
|
|
||||||
import androidx.core.net.toUri
|
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
import java.net.URLEncoder
|
|
||||||
|
|
||||||
class AccessTokenInterceptor : Interceptor {
|
class AccessTokenInterceptor : Interceptor {
|
||||||
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val builder = chain.request().url.newBuilder()
|
val request = chain.request()
|
||||||
|
val urlBuilder = request.url.newBuilder()
|
||||||
|
|
||||||
val uri = builder.build().toUri().toString().toUri()
|
if (request.url.queryParameter("access_token") == null) {
|
||||||
|
urlBuilder.addQueryParameter("access_token", UserConfig.accessToken)
|
||||||
if (uri.getQueryParameter("access_token") == null) {
|
|
||||||
builder.addQueryParameter(
|
|
||||||
"access_token",
|
|
||||||
URLEncoder.encode(UserConfig.accessToken, "utf-8")
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return chain.proceed(chain.request().newBuilder().apply { url(builder.build()) }.build())
|
return chain.proceed(request.newBuilder().url(urlBuilder.build()).build())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,9 @@ object UserConfig {
|
|||||||
accessToken = ""
|
accessToken = ""
|
||||||
fastToken = ""
|
fastToken = ""
|
||||||
userId = -1
|
userId = -1
|
||||||
|
trustedHash = null
|
||||||
|
exchangeToken = null
|
||||||
|
AppSettings.LongPoll.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isLoggedIn(): Boolean {
|
fun isLoggedIn(): Boolean {
|
||||||
|
|||||||
@@ -21,12 +21,10 @@ class VkGroupsMap(
|
|||||||
else map[abs(convo.id)]
|
else map[abs(convo.id)]
|
||||||
|
|
||||||
fun messageActionGroup(message: VkMessage): VkGroupDomain? =
|
fun messageActionGroup(message: VkMessage): VkGroupDomain? =
|
||||||
if (message.actionMemberId == null || message.actionMemberId!! >= 0) null
|
message.actionMemberId?.takeIf { it < 0 }?.let { map[abs(it)] }
|
||||||
else map[abs(message.actionMemberId!!)]
|
|
||||||
|
|
||||||
fun messageActionGroup(message: VkMessageData): VkGroupDomain? =
|
fun messageActionGroup(message: VkMessageData): VkGroupDomain? =
|
||||||
if (message.action?.memberId == null || message.action!!.memberId!! >= 0) null
|
message.action?.memberId?.takeIf { it < 0 }?.let { map[abs(it)] }
|
||||||
else map[abs(message.action!!.memberId!!)]
|
|
||||||
|
|
||||||
fun messageGroup(message: VkMessage): VkGroupDomain? =
|
fun messageGroup(message: VkMessage): VkGroupDomain? =
|
||||||
if (!message.isGroup()) null
|
if (!message.isGroup()) null
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package dev.meloda.fast.data
|
package dev.meloda.fast.data
|
||||||
|
|
||||||
import dev.meloda.fast.data.UserConfig.userId
|
|
||||||
import dev.meloda.fast.model.api.domain.VkContactDomain
|
import dev.meloda.fast.model.api.domain.VkContactDomain
|
||||||
import dev.meloda.fast.model.api.domain.VkConvo
|
import dev.meloda.fast.model.api.domain.VkConvo
|
||||||
import dev.meloda.fast.model.api.domain.VkGroupDomain
|
import dev.meloda.fast.model.api.domain.VkGroupDomain
|
||||||
@@ -38,7 +37,15 @@ object VkMemoryCache {
|
|||||||
contacts.forEach { contact -> VkMemoryCache.contacts[contact.userId] = contact }
|
contacts.forEach { contact -> VkMemoryCache.contacts[contact.userId] = contact }
|
||||||
}
|
}
|
||||||
|
|
||||||
operator fun set(userid: Long, user: VkUser) {
|
fun clear() {
|
||||||
|
users.clear()
|
||||||
|
groups.clear()
|
||||||
|
messages.clear()
|
||||||
|
convos.clear()
|
||||||
|
contacts.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun set(userId: Long, user: VkUser) {
|
||||||
users[userId] = user
|
users[userId] = user
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,12 +20,10 @@ class VkUsersMap(
|
|||||||
else map[convo.id]
|
else map[convo.id]
|
||||||
|
|
||||||
fun messageActionUser(message: VkMessage): VkUser? =
|
fun messageActionUser(message: VkMessage): VkUser? =
|
||||||
if (message.actionMemberId == null || message.actionMemberId!! <= 0) null
|
message.actionMemberId?.takeIf { it > 0 }?.let(map::get)
|
||||||
else map[message.actionMemberId]
|
|
||||||
|
|
||||||
fun messageActionUser(message: VkMessageData): VkUser? =
|
fun messageActionUser(message: VkMessageData): VkUser? =
|
||||||
if (message.action?.memberId == null || message.action!!.memberId!! <= 0) null
|
message.action?.memberId?.takeIf { it > 0 }?.let(map::get)
|
||||||
else map[message.action!!.memberId]
|
|
||||||
|
|
||||||
fun messageUser(message: VkMessage): VkUser? =
|
fun messageUser(message: VkMessage): VkUser? =
|
||||||
if (!message.isUser()) null
|
if (!message.isUser()) null
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import dev.meloda.fast.network.RestApiErrorDomain
|
|||||||
interface ConvosRepository {
|
interface ConvosRepository {
|
||||||
|
|
||||||
suspend fun storeConvos(convos: List<VkConvo>)
|
suspend fun storeConvos(convos: List<VkConvo>)
|
||||||
|
suspend fun getLocalConvos(): List<VkConvo>
|
||||||
|
suspend fun getLocalConvoById(peerId: Long): VkConvo?
|
||||||
|
suspend fun deleteLocalConvo(peerId: Long)
|
||||||
|
|
||||||
suspend fun getConvos(
|
suspend fun getConvos(
|
||||||
count: Int?,
|
count: Int?,
|
||||||
|
|||||||
@@ -19,11 +19,13 @@ import dev.meloda.fast.model.api.domain.VkGroupDomain
|
|||||||
import dev.meloda.fast.model.api.domain.VkMessage
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
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
|
||||||
|
import dev.meloda.fast.model.database.VkConvoEntity
|
||||||
import dev.meloda.fast.model.api.requests.ConvosGetRequest
|
import dev.meloda.fast.model.api.requests.ConvosGetRequest
|
||||||
import dev.meloda.fast.network.RestApiErrorDomain
|
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.convos.ConvosService
|
import dev.meloda.fast.network.service.convos.ConvosService
|
||||||
|
import dev.meloda.fast.model.database.asExternalModel
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -40,6 +42,28 @@ class ConvosRepositoryImpl(
|
|||||||
convoDao.insertAll(convos.map(VkConvo::asEntity))
|
convoDao.insertAll(convos.map(VkConvo::asEntity))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalConvos(): List<VkConvo> = withContext(Dispatchers.IO) {
|
||||||
|
convoDao.getAllWithMessage().map { convoWithMessage ->
|
||||||
|
convoWithMessage.convo.asExternalModel().copy(
|
||||||
|
lastMessage = convoWithMessage.message?.asExternalModel()
|
||||||
|
)
|
||||||
|
}.sorted()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalConvoById(peerId: Long): VkConvo? = withContext(Dispatchers.IO) {
|
||||||
|
convoDao.getByIdWithMessage(peerId)?.let { convoWithMessage ->
|
||||||
|
convoWithMessage.convo.asExternalModel().copy(
|
||||||
|
lastMessage = convoWithMessage.message?.asExternalModel()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deleteLocalConvo(peerId: Long) {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
convoDao.deleteById(peerId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun getConvos(
|
override suspend fun getConvos(
|
||||||
count: Int?,
|
count: Int?,
|
||||||
offset: Int?,
|
offset: Int?,
|
||||||
@@ -198,4 +222,28 @@ class ConvosRepositoryImpl(
|
|||||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||||
convosService.unarchive(mapOf("peer_id" to peerId.toString())).mapApiDefault()
|
convosService.unarchive(mapOf("peer_id" to peerId.toString())).mapApiDefault()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun List<VkConvo>.sorted(): List<VkConvo> {
|
||||||
|
val newConvos = toMutableList()
|
||||||
|
|
||||||
|
val pinnedConvos = newConvos
|
||||||
|
.filter(VkConvo::isPinned)
|
||||||
|
.sortedWith { c1, c2 ->
|
||||||
|
val diff = c2.majorId - c1.majorId
|
||||||
|
|
||||||
|
if (diff == 0) {
|
||||||
|
c2.minorId - c1.minorId
|
||||||
|
} else {
|
||||||
|
diff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
newConvos.removeAll(pinnedConvos)
|
||||||
|
newConvos.sortWith { c1, c2 ->
|
||||||
|
(c2.lastMessage?.date ?: 0) - (c1.lastMessage?.date ?: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
newConvos.addAll(0, pinnedConvos)
|
||||||
|
return newConvos
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package dev.meloda.fast.data.api.longpoll
|
package dev.meloda.fast.data.api.longpoll
|
||||||
|
|
||||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||||
|
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||||
import dev.meloda.fast.network.RestApiErrorDomain
|
import dev.meloda.fast.network.RestApiErrorDomain
|
||||||
import com.slack.eithernet.ApiResult
|
import com.slack.eithernet.ApiResult
|
||||||
@@ -21,4 +22,14 @@ interface LongPollRepository {
|
|||||||
mode: Int,
|
mode: Int,
|
||||||
version: Int
|
version: Int
|
||||||
): ApiResult<LongPollUpdates, RestApiErrorDomain>
|
): ApiResult<LongPollUpdates, RestApiErrorDomain>
|
||||||
|
|
||||||
|
suspend fun getLongPollHistory(
|
||||||
|
ts: Int,
|
||||||
|
pts: Int,
|
||||||
|
lpVersion: Int,
|
||||||
|
lastN: Int? = null,
|
||||||
|
maxMsgId: Long? = null,
|
||||||
|
eventsLimit: Int? = null,
|
||||||
|
msgsLimit: Int? = null
|
||||||
|
): ApiResult<LongPollHistoryResponse, RestApiErrorDomain>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package dev.meloda.fast.data.api.longpoll
|
package dev.meloda.fast.data.api.longpoll
|
||||||
|
|
||||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||||
|
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||||
|
import dev.meloda.fast.model.api.requests.LongPollGetHistoryRequest
|
||||||
import dev.meloda.fast.model.api.requests.LongPollGetUpdatesRequest
|
import dev.meloda.fast.model.api.requests.LongPollGetUpdatesRequest
|
||||||
import dev.meloda.fast.model.api.requests.MessagesGetLongPollServerRequest
|
import dev.meloda.fast.model.api.requests.MessagesGetLongPollServerRequest
|
||||||
import dev.meloda.fast.network.RestApiErrorDomain
|
import dev.meloda.fast.network.RestApiErrorDomain
|
||||||
@@ -52,4 +54,29 @@ class LongPollRepositoryImpl(
|
|||||||
|
|
||||||
longPollService.getResponse(serverUrl, requestModel.map).mapDefault()
|
longPollService.getResponse(serverUrl, requestModel.map).mapDefault()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun getLongPollHistory(
|
||||||
|
ts: Int,
|
||||||
|
pts: Int,
|
||||||
|
lpVersion: Int,
|
||||||
|
lastN: Int?,
|
||||||
|
maxMsgId: Long?,
|
||||||
|
eventsLimit: Int?,
|
||||||
|
msgsLimit: Int?
|
||||||
|
): ApiResult<LongPollHistoryResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||||
|
val requestModel = LongPollGetHistoryRequest(
|
||||||
|
ts = ts,
|
||||||
|
pts = pts,
|
||||||
|
lpVersion = lpVersion,
|
||||||
|
lastN = lastN,
|
||||||
|
maxMsgId = maxMsgId,
|
||||||
|
eventsLimit = eventsLimit,
|
||||||
|
msgsLimit = msgsLimit
|
||||||
|
)
|
||||||
|
|
||||||
|
messagesService.getLongPollHistory(requestModel.map).mapApiResult(
|
||||||
|
successMapper = { response -> response.requireResponse() },
|
||||||
|
errorMapper = { error -> error?.toDomain() }
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,12 @@ interface MessagesRepository {
|
|||||||
|
|
||||||
suspend fun storeMessages(messages: List<VkMessage>)
|
suspend fun storeMessages(messages: List<VkMessage>)
|
||||||
|
|
||||||
|
suspend fun getLocalMessages(convoId: Long): List<VkMessage>
|
||||||
|
suspend fun getLocalMessageById(messageId: Long): VkMessage?
|
||||||
|
suspend fun getLocalMessageByConvoMessageId(convoId: Long, cmId: Long): VkMessage?
|
||||||
|
suspend fun getLocalMaxMessageId(): Long?
|
||||||
|
suspend fun deleteLocalMessages(messageIds: List<Long>)
|
||||||
|
|
||||||
suspend fun getHistory(
|
suspend fun getHistory(
|
||||||
convoId: Long,
|
convoId: Long,
|
||||||
offset: Int?,
|
offset: Int?,
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import dev.meloda.fast.model.api.domain.VkGroupDomain
|
|||||||
import dev.meloda.fast.model.api.domain.VkMessage
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
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
|
||||||
|
import dev.meloda.fast.model.database.VkMessageEntity
|
||||||
import dev.meloda.fast.model.api.requests.MessagesCreateChatRequest
|
import dev.meloda.fast.model.api.requests.MessagesCreateChatRequest
|
||||||
import dev.meloda.fast.model.api.requests.MessagesDeleteRequest
|
import dev.meloda.fast.model.api.requests.MessagesDeleteRequest
|
||||||
import dev.meloda.fast.model.api.requests.MessagesEditRequest
|
import dev.meloda.fast.model.api.requests.MessagesEditRequest
|
||||||
@@ -39,6 +40,7 @@ import dev.meloda.fast.model.api.requests.MessagesUnpinMessageRequest
|
|||||||
import dev.meloda.fast.model.api.responses.MessagesGetConvoMembersResponse
|
import dev.meloda.fast.model.api.responses.MessagesGetConvoMembersResponse
|
||||||
import dev.meloda.fast.model.api.responses.MessagesGetReadPeersResponse
|
import dev.meloda.fast.model.api.responses.MessagesGetReadPeersResponse
|
||||||
import dev.meloda.fast.model.api.responses.MessagesSendResponse
|
import dev.meloda.fast.model.api.responses.MessagesSendResponse
|
||||||
|
import dev.meloda.fast.model.database.asExternalModel
|
||||||
import dev.meloda.fast.network.RestApiErrorDomain
|
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
|
||||||
@@ -354,6 +356,28 @@ class MessagesRepositoryImpl(
|
|||||||
messageDao.insertAll(messages.map(VkMessage::asEntity))
|
messageDao.insertAll(messages.map(VkMessage::asEntity))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMessages(convoId: Long): List<VkMessage> = withContext(Dispatchers.IO) {
|
||||||
|
messageDao.getAll(convoId).map(VkMessageEntity::asExternalModel)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMessageById(messageId: Long): VkMessage? = withContext(Dispatchers.IO) {
|
||||||
|
messageDao.getById(messageId)?.asExternalModel()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMessageByConvoMessageId(convoId: Long, cmId: Long): VkMessage? = withContext(Dispatchers.IO) {
|
||||||
|
messageDao.getByConvoMessageId(convoId, cmId)?.asExternalModel()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMaxMessageId(): Long? = withContext(Dispatchers.IO) {
|
||||||
|
messageDao.getMaxId()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deleteLocalMessages(messageIds: List<Long>) {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
messageDao.deleteByIds(messageIds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun edit(
|
override suspend fun edit(
|
||||||
peerId: Long,
|
peerId: Long,
|
||||||
messageId: Long?,
|
messageId: Long?,
|
||||||
|
|||||||
@@ -23,5 +23,6 @@ interface OAuthRepository {
|
|||||||
validationCode: String?,
|
validationCode: String?,
|
||||||
captchaSid: String?,
|
captchaSid: String?,
|
||||||
captchaKey: String?,
|
captchaKey: String?,
|
||||||
|
successToken: String?
|
||||||
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain>
|
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,8 @@ class OAuthRepositoryImpl(
|
|||||||
VkOAuthError.NEED_CAPTCHA -> {
|
VkOAuthError.NEED_CAPTCHA -> {
|
||||||
OAuthErrorDomain.CaptchaRequiredError(
|
OAuthErrorDomain.CaptchaRequiredError(
|
||||||
captchaSid = response.captchaSid.orEmpty(),
|
captchaSid = response.captchaSid.orEmpty(),
|
||||||
captchaImageUrl = response.captchaImage.orEmpty()
|
captchaImageUrl = response.captchaImage.orEmpty(),
|
||||||
|
redirectUri = response.redirectUri
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,6 +123,7 @@ class OAuthRepositoryImpl(
|
|||||||
validationCode: String?,
|
validationCode: String?,
|
||||||
captchaSid: String?,
|
captchaSid: String?,
|
||||||
captchaKey: String?,
|
captchaKey: String?,
|
||||||
|
successToken: String?
|
||||||
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> =
|
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> =
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
val requestModel = AuthDirectRequest(
|
val requestModel = AuthDirectRequest(
|
||||||
@@ -135,6 +137,7 @@ class OAuthRepositoryImpl(
|
|||||||
validationCode = validationCode,
|
validationCode = validationCode,
|
||||||
captchaSid = captchaSid,
|
captchaSid = captchaSid,
|
||||||
captchaKey = captchaKey,
|
captchaKey = captchaKey,
|
||||||
|
successToken = successToken
|
||||||
)
|
)
|
||||||
|
|
||||||
oAuthService.getSilentToken(requestModel.map).mapResult(
|
oAuthService.getSilentToken(requestModel.map).mapResult(
|
||||||
@@ -175,7 +178,8 @@ class OAuthRepositoryImpl(
|
|||||||
VkOAuthError.NEED_CAPTCHA -> {
|
VkOAuthError.NEED_CAPTCHA -> {
|
||||||
OAuthErrorDomain.CaptchaRequiredError(
|
OAuthErrorDomain.CaptchaRequiredError(
|
||||||
captchaSid = response.captchaSid.orEmpty(),
|
captchaSid = response.captchaSid.orEmpty(),
|
||||||
captchaImageUrl = response.captchaImage.orEmpty()
|
captchaImageUrl = response.captchaImage.orEmpty(),
|
||||||
|
redirectUri = response.redirectUri
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,13 @@ import dev.meloda.fast.model.database.VkConvoEntity
|
|||||||
@Dao
|
@Dao
|
||||||
abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
||||||
|
|
||||||
@Query("SELECT * FROM convos")
|
@Query("SELECT * FROM convos ORDER BY majorId DESC, minorId DESC")
|
||||||
abstract suspend fun getAll(): List<VkConvoEntity>
|
abstract suspend fun getAll(): List<VkConvoEntity>
|
||||||
|
|
||||||
|
@Transaction
|
||||||
|
@Query("SELECT * FROM convos ORDER BY majorId DESC, minorId DESC")
|
||||||
|
abstract suspend fun getAllWithMessage(): List<ConvoWithMessage>
|
||||||
|
|
||||||
@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<Int>): List<VkConvoEntity>
|
||||||
|
|
||||||
@@ -22,6 +26,9 @@ abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
|||||||
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
||||||
abstract suspend fun getByIdWithMessage(id: Long): ConvoWithMessage?
|
abstract suspend fun getByIdWithMessage(id: Long): ConvoWithMessage?
|
||||||
|
|
||||||
|
@Query("DELETE FROM convos WHERE id IS (:id)")
|
||||||
|
abstract suspend fun deleteById(id: Long): Int
|
||||||
|
|
||||||
@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<Int>): Int
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,15 +10,21 @@ abstract class MessageDao : EntityDao<VkMessageEntity> {
|
|||||||
@Query("SELECT * FROM messages")
|
@Query("SELECT * FROM messages")
|
||||||
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) ORDER BY date DESC, id DESC")
|
||||||
abstract suspend fun getAll(convoId: Long): List<VkMessageEntity>
|
abstract suspend fun getAll(convoId: Long): List<VkMessageEntity>
|
||||||
|
|
||||||
@Query("SELECT * FROM messages WHERE id IN (:ids)")
|
@Query("SELECT * FROM messages WHERE id IN (:ids)")
|
||||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkMessageEntity>
|
abstract suspend fun getAllByIds(ids: List<Long>): List<VkMessageEntity>
|
||||||
|
|
||||||
@Query("SELECT * FROM messages WHERE id IS (:messageId)")
|
@Query("SELECT * FROM messages WHERE id IS (:messageId)")
|
||||||
abstract suspend fun getById(messageId: Long): VkMessageEntity?
|
abstract suspend fun getById(messageId: Long): VkMessageEntity?
|
||||||
|
|
||||||
|
@Query("SELECT * FROM messages WHERE peerId IS (:convoId) AND cmId IS (:cmId)")
|
||||||
|
abstract suspend fun getByConvoMessageId(convoId: Long, cmId: Long): VkMessageEntity?
|
||||||
|
|
||||||
|
@Query("SELECT MAX(id) FROM messages")
|
||||||
|
abstract suspend fun getMaxId(): Long?
|
||||||
|
|
||||||
@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<Long>): Int
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,13 +4,32 @@ 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.LogLevel
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlin.properties.Delegates
|
import kotlin.properties.Delegates
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
sealed class CaptchaTokenResult {
|
||||||
|
data object Initial : CaptchaTokenResult()
|
||||||
|
data object Null : CaptchaTokenResult()
|
||||||
|
data object Cancelled : CaptchaTokenResult()
|
||||||
|
data class Success(val token: String) : CaptchaTokenResult()
|
||||||
|
}
|
||||||
|
|
||||||
object AppSettings {
|
object AppSettings {
|
||||||
|
|
||||||
private var preferences: SharedPreferences by Delegates.notNull()
|
private var preferences: SharedPreferences by Delegates.notNull()
|
||||||
|
|
||||||
|
private val captchaResult = MutableStateFlow<CaptchaTokenResult>(CaptchaTokenResult.Initial)
|
||||||
|
fun getCaptchaResultFlow(): StateFlow<CaptchaTokenResult> = captchaResult.asStateFlow()
|
||||||
|
fun setCaptchaResult(result: CaptchaTokenResult) = captchaResult.update { result }
|
||||||
|
|
||||||
|
private val captchaRedirectUri = MutableStateFlow<String?>(null)
|
||||||
|
fun getCaptchaRedirectUriFlow() = captchaRedirectUri.asStateFlow()
|
||||||
|
fun setCaptchaRedirectUri(redirectUri: String?) = captchaRedirectUri.update { redirectUri }
|
||||||
|
|
||||||
fun init(preferences: SharedPreferences) {
|
fun init(preferences: SharedPreferences) {
|
||||||
this.preferences = preferences
|
this.preferences = preferences
|
||||||
}
|
}
|
||||||
@@ -211,6 +230,21 @@ object AppSettings {
|
|||||||
set(value) = put(SettingsKeys.KEY_MORE_ANIMATIONS, value)
|
set(value) = put(SettingsKeys.KEY_MORE_ANIMATIONS, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
object LongPoll {
|
||||||
|
var ts: Int?
|
||||||
|
get() = get(SettingsKeys.KEY_LONG_POLL_TS, 0).takeIf { it > 0 }
|
||||||
|
set(value) = put(SettingsKeys.KEY_LONG_POLL_TS, value ?: 0)
|
||||||
|
|
||||||
|
var pts: Int?
|
||||||
|
get() = get(SettingsKeys.KEY_LONG_POLL_PTS, 0).takeIf { it > 0 }
|
||||||
|
set(value) = put(SettingsKeys.KEY_LONG_POLL_PTS, value ?: 0)
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
ts = null
|
||||||
|
pts = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
object Debug {
|
object Debug {
|
||||||
var showAlertAfterCrash: Boolean
|
var showAlertAfterCrash: Boolean
|
||||||
get() = get(
|
get() = get(
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ object SettingsKeys {
|
|||||||
const val DEFAULT_VALUE_FEATURES_FAST_TEXT = "¯\\_(ツ)_/¯"
|
const val DEFAULT_VALUE_FEATURES_FAST_TEXT = "¯\\_(ツ)_/¯"
|
||||||
const val KEY_LONG_POLL_IN_BACKGROUND = "lp_background"
|
const val KEY_LONG_POLL_IN_BACKGROUND = "lp_background"
|
||||||
const val DEFAULT_LONG_POLL_IN_BACKGROUND = false
|
const val DEFAULT_LONG_POLL_IN_BACKGROUND = false
|
||||||
|
const val KEY_LONG_POLL_TS = "lp_ts"
|
||||||
|
const val KEY_LONG_POLL_PTS = "lp_pts"
|
||||||
|
|
||||||
const val KEY_ACTIVITY_SEND_ONLINE_STATUS = "activity_send_online_status"
|
const val KEY_ACTIVITY_SEND_ONLINE_STATUS = "activity_send_online_status"
|
||||||
const val DEFAULT_VALUE_KEY_ACTIVITY_SEND_ONLINE_STATUS = false
|
const val DEFAULT_VALUE_KEY_ACTIVITY_SEND_ONLINE_STATUS = false
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
interface ConvoUseCase : BaseUseCase {
|
interface ConvoUseCase : BaseUseCase {
|
||||||
|
|
||||||
suspend fun storeConvos(convos: List<VkConvo>)
|
suspend fun storeConvos(convos: List<VkConvo>)
|
||||||
|
suspend fun getLocalConvos(): List<VkConvo>
|
||||||
|
suspend fun getLocalConvoById(peerId: Long): VkConvo?
|
||||||
|
suspend fun deleteLocalConvo(peerId: Long)
|
||||||
|
|
||||||
fun getConvos(
|
fun getConvos(
|
||||||
count: Int? = null,
|
count: Int? = null,
|
||||||
|
|||||||
@@ -19,6 +19,18 @@ class ConvoUseCaseImpl(
|
|||||||
repository.storeConvos(convos)
|
repository.storeConvos(convos)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalConvos(): List<VkConvo> = withContext(Dispatchers.IO) {
|
||||||
|
repository.getLocalConvos()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalConvoById(peerId: Long): VkConvo? = withContext(Dispatchers.IO) {
|
||||||
|
repository.getLocalConvoById(peerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deleteLocalConvo(peerId: Long) = withContext(Dispatchers.IO) {
|
||||||
|
repository.deleteLocalConvo(peerId)
|
||||||
|
}
|
||||||
|
|
||||||
override fun getConvos(
|
override fun getConvos(
|
||||||
count: Int?,
|
count: Int?,
|
||||||
offset: Int?,
|
offset: Int?,
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
|
import dev.meloda.fast.model.LongPollEvent
|
||||||
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
|
|
||||||
|
internal class LongPollEventDispatcher {
|
||||||
|
private val listenersMap: MutableMap<LongPollEvent, MutableList<VkEventCallback<LongPollParsedEvent>>> =
|
||||||
|
mutableMapOf()
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
fun <T : LongPollParsedEvent> dispatch(eventType: LongPollEvent, event: T) {
|
||||||
|
listenersMap[eventType]?.forEach { callback ->
|
||||||
|
(callback as? VkEventCallback<T>)?.onEvent(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dispatchAll(eventType: LongPollEvent, events: List<LongPollParsedEvent>) {
|
||||||
|
events.forEach { event -> dispatch(eventType, event) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
fun <T : LongPollParsedEvent> registerListener(
|
||||||
|
eventType: LongPollEvent,
|
||||||
|
listener: VkEventCallback<T>
|
||||||
|
) {
|
||||||
|
listenersMap[eventType] = (listenersMap[eventType] ?: mutableListOf())
|
||||||
|
.also { it.add(listener as VkEventCallback<LongPollParsedEvent>) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T : LongPollParsedEvent> registerListeners(
|
||||||
|
eventTypes: List<LongPollEvent>,
|
||||||
|
listener: VkEventCallback<T>
|
||||||
|
) {
|
||||||
|
eventTypes.forEach { eventType -> registerListener(eventType, listener) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,537 @@
|
|||||||
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import dev.meloda.fast.common.VkConstants
|
||||||
|
import dev.meloda.fast.common.extensions.asInt
|
||||||
|
import dev.meloda.fast.common.extensions.asLong
|
||||||
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
|
import dev.meloda.fast.common.extensions.toList
|
||||||
|
import dev.meloda.fast.data.UserConfig
|
||||||
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.model.ApiEvent
|
||||||
|
import dev.meloda.fast.model.ConvoFlags
|
||||||
|
import dev.meloda.fast.model.InteractionType
|
||||||
|
import dev.meloda.fast.model.LongPollEvent
|
||||||
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
|
import dev.meloda.fast.model.MessageFlags
|
||||||
|
import dev.meloda.fast.model.api.domain.VkConvo
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
internal class LongPollEventParser(
|
||||||
|
private val coroutineScope: CoroutineScope,
|
||||||
|
private val convoUseCase: ConvoUseCase,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val dispatch: (LongPollEvent, LongPollParsedEvent) -> Unit,
|
||||||
|
private val dispatchAll: (LongPollEvent, List<LongPollParsedEvent>) -> Unit
|
||||||
|
) {
|
||||||
|
fun parseNextUpdate(event: List<Any>) {
|
||||||
|
val eventId = event.first().asInt()
|
||||||
|
|
||||||
|
when (val eventType = ApiEvent.parseOrNull(eventId)) {
|
||||||
|
null -> Unit
|
||||||
|
|
||||||
|
ApiEvent.MESSAGE_SET_FLAGS -> parseMessageSetFlags(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_CLEAR_FLAGS -> parseMessageClearFlags(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_NEW -> parseMessageNew(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_EDIT -> parseMessageEdit(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_READ_INCOMING -> parseMessageReadIncoming(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_READ_OUTGOING -> parseMessageReadOutgoing(eventType, event)
|
||||||
|
ApiEvent.CHAT_CLEAR_FLAGS -> parseChatClearFlags(eventType, event)
|
||||||
|
ApiEvent.CHAT_SET_FLAGS -> parseChatSetFlags(eventType, event)
|
||||||
|
ApiEvent.MESSAGES_DELETED -> parseMessagesDeleted(eventType, event)
|
||||||
|
ApiEvent.CHAT_MAJOR_CHANGED -> parseChatMajorChanged(eventType, event)
|
||||||
|
ApiEvent.CHAT_MINOR_CHANGED -> parseChatMinorChanged(eventType, event)
|
||||||
|
|
||||||
|
ApiEvent.TYPING,
|
||||||
|
ApiEvent.AUDIO_MESSAGE_RECORDING,
|
||||||
|
ApiEvent.PHOTO_UPLOADING,
|
||||||
|
ApiEvent.VIDEO_UPLOADING,
|
||||||
|
ApiEvent.FILE_UPLOADING -> parseInteraction(eventType, event)
|
||||||
|
|
||||||
|
ApiEvent.UNREAD_COUNT_UPDATE -> parseUnreadCounterUpdate(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_UPDATED -> parseMessageUpdated(eventType, event)
|
||||||
|
ApiEvent.MESSAGE_CACHE_CLEAR -> parseMessageCacheClear(eventType, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageSetFlags(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val cmId = event[1].asLong()
|
||||||
|
val flags = event[2].asInt()
|
||||||
|
val peerId = event[3].asLong()
|
||||||
|
|
||||||
|
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
||||||
|
|
||||||
|
val parsedFlags = MessageFlags.parse(flags)
|
||||||
|
parsedFlags.forEach { flag ->
|
||||||
|
when (flag) {
|
||||||
|
MessageFlags.IMPORTANT -> {
|
||||||
|
val eventToSend = LongPollParsedEvent.MessageMarkedAsImportant(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId,
|
||||||
|
marked = true
|
||||||
|
)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.MARKED_AS_IMPORTANT, eventToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageFlags.SPAM -> {
|
||||||
|
val eventToSend = LongPollParsedEvent.MessageMarkedAsSpam(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId
|
||||||
|
)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.MARKED_AS_SPAM, eventToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageFlags.DELETED -> {
|
||||||
|
val eventToSend =
|
||||||
|
if (parsedFlags.contains(MessageFlags.DELETED_FOR_ALL)) {
|
||||||
|
LongPollParsedEvent.MessageDeleted(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId,
|
||||||
|
forAll = true
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
LongPollParsedEvent.MessageDeleted(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId,
|
||||||
|
forAll = false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.MESSAGE_DELETED, eventToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageFlags.AUDIO_LISTENED -> {
|
||||||
|
val eventToSend = LongPollParsedEvent.AudioMessageListened(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId
|
||||||
|
)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.AUDIO_MESSAGE_LISTENED, eventToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatchAll(LongPollEvent.MESSAGE_SET_FLAGS, eventsToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageClearFlags(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val cmId = event[1].asLong()
|
||||||
|
val flags = event[2].asInt()
|
||||||
|
val peerId = event[3].asLong()
|
||||||
|
|
||||||
|
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
||||||
|
|
||||||
|
val parsedFlags = MessageFlags.parse(flags)
|
||||||
|
|
||||||
|
coroutineScope.launch {
|
||||||
|
parsedFlags.forEach { flag ->
|
||||||
|
when (flag) {
|
||||||
|
MessageFlags.IMPORTANT -> {
|
||||||
|
val eventToSend = LongPollParsedEvent.MessageMarkedAsImportant(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId,
|
||||||
|
marked = false
|
||||||
|
)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.MARKED_AS_IMPORTANT, eventToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageFlags.SPAM -> {
|
||||||
|
if (parsedFlags.contains(MessageFlags.CANCEL_SPAM)) {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val message = loadMessage(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId
|
||||||
|
)
|
||||||
|
message?.let {
|
||||||
|
val eventToSend =
|
||||||
|
LongPollParsedEvent.MessageMarkedAsNotSpam(message = message)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.MARKED_AS_NOT_SPAM, eventToSend)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageFlags.DELETED -> {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val message = loadMessage(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId
|
||||||
|
)
|
||||||
|
message?.let {
|
||||||
|
val eventToSend =
|
||||||
|
LongPollParsedEvent.MessageRestored(message = message)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.MESSAGE_RESTORED, eventToSend)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatchAll(LongPollEvent.MESSAGE_CLEAR_FLAGS, eventsToSend)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageNew(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val cmId = event[1].asLong()
|
||||||
|
val peerId = event[4].asLong()
|
||||||
|
|
||||||
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
val message =
|
||||||
|
async { loadMessage(peerId = peerId, cmId = cmId) }.await()
|
||||||
|
|
||||||
|
val convo =
|
||||||
|
async {
|
||||||
|
loadConvo(
|
||||||
|
peerId = peerId,
|
||||||
|
extended = true,
|
||||||
|
fields = VkConstants.ALL_FIELDS
|
||||||
|
)
|
||||||
|
}.await()
|
||||||
|
|
||||||
|
message?.let {
|
||||||
|
dispatch(
|
||||||
|
LongPollEvent.MESSAGE_NEW,
|
||||||
|
LongPollParsedEvent.NewMessage(
|
||||||
|
message = message,
|
||||||
|
inArchive = convo?.isArchived == true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageEdit(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val cmId = event[1].asLong()
|
||||||
|
val peerId = event[3].asLong()
|
||||||
|
|
||||||
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
loadMessage(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId
|
||||||
|
)?.let { message ->
|
||||||
|
dispatch(LongPollEvent.MESSAGE_EDITED, LongPollParsedEvent.MessageEdited(message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageReadIncoming(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
dispatchMessageRead(
|
||||||
|
longPollEvent = LongPollEvent.INCOMING_MESSAGE_READ,
|
||||||
|
parsedEvent = LongPollParsedEvent.IncomingMessageRead(
|
||||||
|
peerId = event[1].asLong(),
|
||||||
|
cmId = event[2].asLong(),
|
||||||
|
unreadCount = event[3].asInt()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageReadOutgoing(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
dispatchMessageRead(
|
||||||
|
longPollEvent = LongPollEvent.OUTGOING_MESSAGE_READ,
|
||||||
|
parsedEvent = LongPollParsedEvent.OutgoingMessageRead(
|
||||||
|
peerId = event[1].asLong(),
|
||||||
|
cmId = event[2].asLong(),
|
||||||
|
unreadCount = event[3].asInt()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseChatClearFlags(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val peerId = event[1].asLong()
|
||||||
|
val flags = event[2].asInt()
|
||||||
|
|
||||||
|
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
||||||
|
|
||||||
|
val parsedFlags = ConvoFlags.parse(flags)
|
||||||
|
|
||||||
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
parsedFlags.forEach { flag ->
|
||||||
|
when (flag) {
|
||||||
|
ConvoFlags.ARCHIVED -> {
|
||||||
|
handleArchivedChat(
|
||||||
|
peerId = peerId,
|
||||||
|
archived = false,
|
||||||
|
eventsToSend = eventsToSend
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatchAll(LongPollEvent.CHAT_CLEAR_FLAGS, eventsToSend)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseChatSetFlags(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val peerId = event[1].asLong()
|
||||||
|
val flags = event[2].asInt()
|
||||||
|
|
||||||
|
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
||||||
|
|
||||||
|
val parsedFlags = ConvoFlags.parse(flags)
|
||||||
|
|
||||||
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
parsedFlags.forEach { flag ->
|
||||||
|
when (flag) {
|
||||||
|
ConvoFlags.ARCHIVED -> {
|
||||||
|
handleArchivedChat(
|
||||||
|
peerId = peerId,
|
||||||
|
archived = true,
|
||||||
|
eventsToSend = eventsToSend
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatchAll(LongPollEvent.CHAT_SET_FLAGS, eventsToSend)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessagesDeleted(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val peerId = event[1].asLong()
|
||||||
|
val cmId = event[2].asLong()
|
||||||
|
|
||||||
|
dispatch(
|
||||||
|
LongPollEvent.CHAT_CLEARED,
|
||||||
|
LongPollParsedEvent.ChatCleared(
|
||||||
|
peerId = peerId,
|
||||||
|
toCmId = cmId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseChatMajorChanged(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val peerId = event[1].asLong()
|
||||||
|
val majorId = event[2].asInt()
|
||||||
|
|
||||||
|
dispatch(
|
||||||
|
LongPollEvent.CHAT_MAJOR_CHANGED,
|
||||||
|
LongPollParsedEvent.ChatMajorChanged(
|
||||||
|
peerId = peerId,
|
||||||
|
majorId = majorId,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseChatMinorChanged(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val peerId = event[1].asLong()
|
||||||
|
val minorId = event[2].asInt()
|
||||||
|
|
||||||
|
dispatch(
|
||||||
|
LongPollEvent.CHAT_MINOR_CHANGED,
|
||||||
|
LongPollParsedEvent.ChatMinorChanged(
|
||||||
|
peerId = peerId,
|
||||||
|
minorId = minorId,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseInteraction(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val interactionType = when (eventType) {
|
||||||
|
ApiEvent.TYPING -> InteractionType.Typing
|
||||||
|
ApiEvent.AUDIO_MESSAGE_RECORDING -> InteractionType.VoiceMessage
|
||||||
|
ApiEvent.PHOTO_UPLOADING -> InteractionType.Photo
|
||||||
|
ApiEvent.VIDEO_UPLOADING -> InteractionType.Video
|
||||||
|
ApiEvent.FILE_UPLOADING -> InteractionType.File
|
||||||
|
else -> return
|
||||||
|
}
|
||||||
|
|
||||||
|
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 userIds = event[2].toList(Any::asLong).filter { it != UserConfig.userId }
|
||||||
|
val totalCount = event[3].asInt()
|
||||||
|
val timestamp = event[4].asInt()
|
||||||
|
|
||||||
|
if (userIds.isEmpty()) return
|
||||||
|
|
||||||
|
dispatch(
|
||||||
|
longPollEvent,
|
||||||
|
LongPollParsedEvent.Interaction(
|
||||||
|
interactionType = interactionType,
|
||||||
|
peerId = peerId,
|
||||||
|
userIds = userIds,
|
||||||
|
totalCount = totalCount,
|
||||||
|
timestamp = timestamp
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseUnreadCounterUpdate(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val unreadCount = event[1].asInt()
|
||||||
|
val unreadUnmutedCount = event[2].asInt()
|
||||||
|
val showOnlyMuted = event[3].asInt() == 1
|
||||||
|
val businessNotifyUnreadCount = event[4].asInt()
|
||||||
|
val archiveUnreadCount = event[7].asInt()
|
||||||
|
val archiveUnreadUnmutedCount = event[8].asInt()
|
||||||
|
val archiveMentionsCount = event[9].asInt()
|
||||||
|
|
||||||
|
dispatch(
|
||||||
|
LongPollEvent.UNREAD_COUNTER_UPDATE,
|
||||||
|
LongPollParsedEvent.UnreadCounter(
|
||||||
|
unread = unreadCount,
|
||||||
|
unreadUnmuted = unreadUnmutedCount,
|
||||||
|
showOnlyMuted = showOnlyMuted,
|
||||||
|
business = businessNotifyUnreadCount,
|
||||||
|
archive = archiveUnreadCount,
|
||||||
|
archiveUnmuted = archiveUnreadUnmutedCount,
|
||||||
|
archiveMentions = archiveMentionsCount
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageUpdated(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val cmId = event[1].asLong()
|
||||||
|
val peerId = event[4].asLong()
|
||||||
|
|
||||||
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
loadMessage(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = cmId
|
||||||
|
)?.let { message ->
|
||||||
|
dispatch(LongPollEvent.MESSAGE_UPDATED, LongPollParsedEvent.MessageUpdated(message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseMessageCacheClear(eventType: ApiEvent, event: List<Any>) {
|
||||||
|
val messageId = event[1].asLong()
|
||||||
|
|
||||||
|
coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
loadMessage(messageId = messageId)?.let { message ->
|
||||||
|
dispatch(
|
||||||
|
LongPollEvent.MESSAGE_CACHE_CLEAR,
|
||||||
|
LongPollParsedEvent.MessageCacheClear(message)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun loadMessage(
|
||||||
|
peerId: Long? = null,
|
||||||
|
cmId: Long? = null,
|
||||||
|
messageId: Long? = null
|
||||||
|
): VkMessage? = suspendCancellableCoroutine { continuation ->
|
||||||
|
require((peerId != null && cmId != null) || messageId != null)
|
||||||
|
|
||||||
|
val job = coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
messagesUseCase.getById(
|
||||||
|
peerCmIds = null,
|
||||||
|
peerId = peerId,
|
||||||
|
messageIds = messageId?.let(::listOf),
|
||||||
|
cmIds = cmId?.let(::listOf),
|
||||||
|
extended = true,
|
||||||
|
fields = VkConstants.ALL_FIELDS
|
||||||
|
).listenValue(this) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = { error ->
|
||||||
|
Log.e("LongPollEventParser", "loadMessage: error: $error")
|
||||||
|
continuation.resume(null)
|
||||||
|
},
|
||||||
|
success = { response ->
|
||||||
|
val message = response.singleOrNull() ?: run {
|
||||||
|
continuation.resume(null)
|
||||||
|
return@listenValue
|
||||||
|
}
|
||||||
|
|
||||||
|
continuation.resume(message)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
continuation.invokeOnCancellation {
|
||||||
|
job.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun loadConvo(
|
||||||
|
peerId: Long,
|
||||||
|
extended: Boolean = false,
|
||||||
|
fields: String? = null
|
||||||
|
): VkConvo? = suspendCancellableCoroutine { continuation ->
|
||||||
|
val job = coroutineScope.launch(Dispatchers.IO) {
|
||||||
|
convoUseCase.getById(
|
||||||
|
peerIds = listOf(peerId),
|
||||||
|
extended = extended,
|
||||||
|
fields = fields
|
||||||
|
).listenValue(coroutineScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = { error ->
|
||||||
|
Log.e("LongPollEventParser", "loadConvo: error: $error")
|
||||||
|
continuation.resume(null)
|
||||||
|
},
|
||||||
|
success = { response ->
|
||||||
|
val convo = response.singleOrNull() ?: run {
|
||||||
|
continuation.resume(null)
|
||||||
|
return@listenValue
|
||||||
|
}
|
||||||
|
|
||||||
|
continuation.resume(convo)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
continuation.invokeOnCancellation {
|
||||||
|
job.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun handleArchivedChat(
|
||||||
|
peerId: Long,
|
||||||
|
archived: Boolean,
|
||||||
|
eventsToSend: MutableList<LongPollParsedEvent>
|
||||||
|
) {
|
||||||
|
val convo = loadConvo(
|
||||||
|
peerId = peerId,
|
||||||
|
extended = true,
|
||||||
|
fields = VkConstants.ALL_FIELDS
|
||||||
|
) ?: return
|
||||||
|
|
||||||
|
val message = loadMessage(
|
||||||
|
peerId = peerId,
|
||||||
|
cmId = convo.lastCmId
|
||||||
|
)
|
||||||
|
|
||||||
|
val eventToSend = LongPollParsedEvent.ChatArchived(
|
||||||
|
convo = convo.copy(lastMessage = message),
|
||||||
|
archived = archived
|
||||||
|
)
|
||||||
|
eventsToSend += eventToSend
|
||||||
|
dispatch(LongPollEvent.CHAT_ARCHIVED, eventToSend)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dispatchMessageRead(
|
||||||
|
longPollEvent: LongPollEvent,
|
||||||
|
parsedEvent: LongPollParsedEvent
|
||||||
|
) {
|
||||||
|
dispatch(longPollEvent, parsedEvent)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,35 +1,17 @@
|
|||||||
package dev.meloda.fast.domain
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import dev.meloda.fast.common.VkConstants
|
|
||||||
import dev.meloda.fast.common.extensions.asInt
|
|
||||||
import dev.meloda.fast.common.extensions.asLong
|
|
||||||
import dev.meloda.fast.common.extensions.listenValue
|
|
||||||
import dev.meloda.fast.common.extensions.toList
|
|
||||||
import dev.meloda.fast.data.UserConfig
|
|
||||||
import dev.meloda.fast.data.processState
|
|
||||||
import dev.meloda.fast.model.ApiEvent
|
|
||||||
import dev.meloda.fast.model.ConvoFlags
|
|
||||||
import dev.meloda.fast.model.InteractionType
|
|
||||||
import dev.meloda.fast.model.LongPollEvent
|
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.api.domain.VkConvo
|
|
||||||
import dev.meloda.fast.model.api.domain.VkMessage
|
|
||||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.async
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import kotlin.coroutines.CoroutineContext
|
import kotlin.coroutines.CoroutineContext
|
||||||
import kotlin.coroutines.resume
|
|
||||||
import kotlin.coroutines.suspendCoroutine
|
|
||||||
|
|
||||||
class LongPollUpdatesParser(
|
class LongPollUpdatesParser(
|
||||||
private val convoUseCase: ConvoUseCase,
|
convoUseCase: ConvoUseCase,
|
||||||
private val messagesUseCase: MessagesUseCase
|
messagesUseCase: MessagesUseCase
|
||||||
) {
|
) {
|
||||||
private val job = SupervisorJob()
|
private val job = SupervisorJob()
|
||||||
|
|
||||||
@@ -43,747 +25,89 @@ class LongPollUpdatesParser(
|
|||||||
get() = Dispatchers.Default + job + exceptionHandler
|
get() = Dispatchers.Default + job + exceptionHandler
|
||||||
|
|
||||||
private val coroutineScope = CoroutineScope(coroutineContext)
|
private val coroutineScope = CoroutineScope(coroutineContext)
|
||||||
|
private val eventDispatcher = LongPollEventDispatcher()
|
||||||
private val listenersMap: MutableMap<LongPollEvent, MutableList<VkEventCallback<LongPollParsedEvent>>> =
|
private val eventParser = LongPollEventParser(
|
||||||
mutableMapOf()
|
coroutineScope = coroutineScope,
|
||||||
|
convoUseCase = convoUseCase,
|
||||||
|
messagesUseCase = messagesUseCase,
|
||||||
|
dispatch = eventDispatcher::dispatch,
|
||||||
|
dispatchAll = eventDispatcher::dispatchAll
|
||||||
|
)
|
||||||
|
|
||||||
fun parseNextUpdate(event: List<Any>) {
|
fun parseNextUpdate(event: List<Any>) {
|
||||||
val eventId = event.first().asInt()
|
eventParser.parseNextUpdate(event)
|
||||||
|
|
||||||
when (val eventType = ApiEvent.parseOrNull(eventId)) {
|
|
||||||
null -> Log.d("LongPollUpdatesParser", "parseNextUpdate: unknownEvent: $event")
|
|
||||||
|
|
||||||
ApiEvent.MESSAGE_SET_FLAGS -> parseMessageSetFlags(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_CLEAR_FLAGS -> parseMessageClearFlags(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_NEW -> parseMessageNew(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_EDIT -> parseMessageEdit(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_READ_INCOMING -> parseMessageReadIncoming(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_READ_OUTGOING -> parseMessageReadOutgoing(eventType, event)
|
|
||||||
ApiEvent.CHAT_CLEAR_FLAGS -> parseChatClearFlags(eventType, event)
|
|
||||||
ApiEvent.CHAT_SET_FLAGS -> parseChatSetFlags(eventType, event)
|
|
||||||
ApiEvent.MESSAGES_DELETED -> parseMessagesDeleted(eventType, event)
|
|
||||||
ApiEvent.CHAT_MAJOR_CHANGED -> parseChatMajorChanged(eventType, event)
|
|
||||||
ApiEvent.CHAT_MINOR_CHANGED -> parseChatMinorChanged(eventType, event)
|
|
||||||
|
|
||||||
ApiEvent.TYPING,
|
|
||||||
ApiEvent.AUDIO_MESSAGE_RECORDING,
|
|
||||||
ApiEvent.PHOTO_UPLOADING,
|
|
||||||
ApiEvent.VIDEO_UPLOADING,
|
|
||||||
ApiEvent.FILE_UPLOADING -> parseInteraction(eventType, event)
|
|
||||||
|
|
||||||
ApiEvent.UNREAD_COUNT_UPDATE -> parseUnreadCounterUpdate(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_UPDATED -> parseMessageUpdated(eventType, event)
|
|
||||||
ApiEvent.MESSAGE_CACHE_CLEAR -> parseMessageCacheClear(eventType, event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageSetFlags(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
|
||||||
val flags = event[2].asInt()
|
|
||||||
val peerId = event[3].asLong()
|
|
||||||
|
|
||||||
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
|
||||||
|
|
||||||
val parsedFlags = MessageFlags.parse(flags)
|
|
||||||
parsedFlags.forEach { flag ->
|
|
||||||
when (flag) {
|
|
||||||
MessageFlags.IMPORTANT -> {
|
|
||||||
val eventToSend = LongPollParsedEvent.MessageMarkedAsImportant(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId,
|
|
||||||
marked = true
|
|
||||||
)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsImportant>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
MessageFlags.SPAM -> {
|
|
||||||
val eventToSend = LongPollParsedEvent.MessageMarkedAsSpam(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_SPAM]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsSpam>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
MessageFlags.DELETED -> {
|
|
||||||
val eventToSend =
|
|
||||||
if (parsedFlags.contains(MessageFlags.DELETED_FOR_ALL)) {
|
|
||||||
LongPollParsedEvent.MessageDeleted(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId,
|
|
||||||
forAll = true
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
LongPollParsedEvent.MessageDeleted(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId,
|
|
||||||
forAll = false
|
|
||||||
)
|
|
||||||
}
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_DELETED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageDeleted>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
MessageFlags.AUDIO_LISTENED -> {
|
|
||||||
val eventToSend = LongPollParsedEvent.AudioMessageListened(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.AUDIO_MESSAGE_LISTENED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.AudioMessageListened>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_SET_FLAGS]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageClearFlags(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
|
||||||
val flags = event[2].asInt()
|
|
||||||
val peerId = event[3].asLong()
|
|
||||||
|
|
||||||
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
|
||||||
|
|
||||||
val parsedFlags = MessageFlags.parse(flags)
|
|
||||||
|
|
||||||
coroutineScope.launch {
|
|
||||||
parsedFlags.forEach { flag ->
|
|
||||||
when (flag) {
|
|
||||||
MessageFlags.IMPORTANT -> {
|
|
||||||
val eventToSend = LongPollParsedEvent.MessageMarkedAsImportant(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId,
|
|
||||||
marked = false
|
|
||||||
)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsImportant>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
MessageFlags.SPAM -> {
|
|
||||||
if (parsedFlags.contains(MessageFlags.CANCEL_SPAM)) {
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
val message = loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)
|
|
||||||
message?.let {
|
|
||||||
val eventToSend =
|
|
||||||
LongPollParsedEvent.MessageMarkedAsNotSpam(message = message)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MARKED_AS_NOT_SPAM]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsNotSpam>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
MessageFlags.DELETED -> {
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
val message = loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)
|
|
||||||
message?.let {
|
|
||||||
val eventToSend =
|
|
||||||
LongPollParsedEvent.MessageRestored(message = message)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_RESTORED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageRestored>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_CLEAR_FLAGS]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
vkEventCallback.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageNew(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
|
||||||
val peerId = event[4].asLong()
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
val message =
|
|
||||||
async { loadMessage(peerId = peerId, cmId = cmId) }.await()
|
|
||||||
|
|
||||||
val convo =
|
|
||||||
async {
|
|
||||||
loadConvo(
|
|
||||||
peerId = peerId,
|
|
||||||
extended = true,
|
|
||||||
fields = VkConstants.ALL_FIELDS
|
|
||||||
)
|
|
||||||
}.await()
|
|
||||||
|
|
||||||
message?.let {
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_NEW]?.let {
|
|
||||||
it.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.NewMessage>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.NewMessage(
|
|
||||||
message = message,
|
|
||||||
inArchive = convo?.isArchived == true
|
|
||||||
// TODO: 03-Apr-25, Danil Nikolaev:
|
|
||||||
// load user settings about restoring chats with
|
|
||||||
// enabled notifications from archive
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageEdit(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
|
||||||
val peerId = event[3].asLong()
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)?.let { message ->
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_EDITED]?.let {
|
|
||||||
it.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.MessageEdited>)
|
|
||||||
.onEvent(LongPollParsedEvent.MessageEdited(message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageReadIncoming(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val cmId = event[2].asLong()
|
|
||||||
val unreadCount = event[3].asInt()
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.INCOMING_MESSAGE_READ]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.IncomingMessageRead>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.IncomingMessageRead(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId,
|
|
||||||
unreadCount = unreadCount
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageReadOutgoing(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val cmId = event[2].asLong()
|
|
||||||
val unreadCount = event[3].asInt()
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.OUTGOING_MESSAGE_READ]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.OutgoingMessageRead>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.OutgoingMessageRead(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId,
|
|
||||||
unreadCount = unreadCount
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseChatClearFlags(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val flags = event[2].asInt()
|
|
||||||
|
|
||||||
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
|
||||||
|
|
||||||
val parsedFlags = ConvoFlags.parse(flags)
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
parsedFlags.forEach { flag ->
|
|
||||||
when (flag) {
|
|
||||||
ConvoFlags.ARCHIVED -> {
|
|
||||||
val convo = loadConvo(
|
|
||||||
peerId = peerId,
|
|
||||||
extended = true,
|
|
||||||
fields = VkConstants.ALL_FIELDS
|
|
||||||
) ?: return@forEach
|
|
||||||
|
|
||||||
val message = loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = convo.lastCmId
|
|
||||||
)
|
|
||||||
|
|
||||||
val eventToSend = LongPollParsedEvent.ChatArchived(
|
|
||||||
convo = convo.copy(lastMessage = message),
|
|
||||||
archived = false
|
|
||||||
)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.ChatArchived>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
|
||||||
listenersMap[LongPollEvent.CHAT_CLEAR_FLAGS]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(
|
|
||||||
eventToSend
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseChatSetFlags(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val flags = event[2].asInt()
|
|
||||||
|
|
||||||
val eventsToSend = mutableListOf<LongPollParsedEvent>()
|
|
||||||
|
|
||||||
val parsedFlags = ConvoFlags.parse(flags)
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
parsedFlags.forEach { flag ->
|
|
||||||
when (flag) {
|
|
||||||
ConvoFlags.ARCHIVED -> {
|
|
||||||
val convo = loadConvo(
|
|
||||||
peerId = peerId,
|
|
||||||
extended = true,
|
|
||||||
fields = VkConstants.ALL_FIELDS
|
|
||||||
) ?: return@forEach
|
|
||||||
|
|
||||||
val message = loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = convo.lastCmId
|
|
||||||
)
|
|
||||||
|
|
||||||
val eventToSend = LongPollParsedEvent.ChatArchived(
|
|
||||||
convo = convo.copy(lastMessage = message),
|
|
||||||
archived = true
|
|
||||||
)
|
|
||||||
eventsToSend += eventToSend
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.ChatArchived>)
|
|
||||||
?.onEvent(eventToSend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eventsToSend.forEach { eventToSend ->
|
|
||||||
listenersMap[LongPollEvent.CHAT_SET_FLAGS]?.let { listeners ->
|
|
||||||
listeners.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(
|
|
||||||
eventToSend
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessagesDeleted(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val cmId = event[2].asLong()
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_CLEARED]?.let { listeners ->
|
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.ChatCleared>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.ChatCleared(
|
|
||||||
peerId = peerId,
|
|
||||||
toCmId = cmId
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseChatMajorChanged(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val majorId = event[2].asInt()
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_MAJOR_CHANGED]?.let { listeners ->
|
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.ChatMajorChanged>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.ChatMajorChanged(
|
|
||||||
peerId = peerId,
|
|
||||||
majorId = majorId,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseChatMinorChanged(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val peerId = event[1].asLong()
|
|
||||||
val minorId = event[2].asInt()
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.CHAT_MINOR_CHANGED]?.let { listeners ->
|
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.ChatMinorChanged>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.ChatMinorChanged(
|
|
||||||
peerId = peerId,
|
|
||||||
minorId = minorId,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseInteraction(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
|
||||||
|
|
||||||
val interactionType = when (eventType) {
|
|
||||||
ApiEvent.TYPING -> InteractionType.Typing
|
|
||||||
ApiEvent.AUDIO_MESSAGE_RECORDING -> InteractionType.VoiceMessage
|
|
||||||
ApiEvent.PHOTO_UPLOADING -> InteractionType.Photo
|
|
||||||
ApiEvent.VIDEO_UPLOADING -> InteractionType.Video
|
|
||||||
ApiEvent.FILE_UPLOADING -> InteractionType.File
|
|
||||||
else -> return
|
|
||||||
}
|
|
||||||
|
|
||||||
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 userIds = event[2].toList(Any::asLong).filter { it != UserConfig.userId }
|
|
||||||
val totalCount = event[3].asInt()
|
|
||||||
val timestamp = event[4].asInt()
|
|
||||||
|
|
||||||
// if userIds contains only account's id, then we don't need to show our status
|
|
||||||
if (userIds.isEmpty()) return
|
|
||||||
|
|
||||||
listenersMap[longPollEvent]?.let { listeners ->
|
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.Interaction>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.Interaction(
|
|
||||||
interactionType = interactionType,
|
|
||||||
peerId = peerId,
|
|
||||||
userIds = userIds,
|
|
||||||
totalCount = totalCount,
|
|
||||||
timestamp = timestamp
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseUnreadCounterUpdate(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
|
||||||
|
|
||||||
val unreadCount = event[1].asInt()
|
|
||||||
val unreadUnmutedCount = event[2].asInt()
|
|
||||||
val showOnlyMuted = event[3].asInt() == 1
|
|
||||||
val businessNotifyUnreadCount = event[4].asInt()
|
|
||||||
val archiveUnreadCount = event[7].asInt()
|
|
||||||
val archiveUnreadUnmutedCount = event[8].asInt()
|
|
||||||
val archiveMentionsCount = event[9].asInt()
|
|
||||||
|
|
||||||
listenersMap[LongPollEvent.UNREAD_COUNTER_UPDATE]?.let { listeners ->
|
|
||||||
listeners.forEach { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.UnreadCounter>)
|
|
||||||
.onEvent(
|
|
||||||
LongPollParsedEvent.UnreadCounter(
|
|
||||||
unread = unreadCount,
|
|
||||||
unreadUnmuted = unreadUnmutedCount,
|
|
||||||
showOnlyMuted = showOnlyMuted,
|
|
||||||
business = businessNotifyUnreadCount,
|
|
||||||
archive = archiveUnreadCount,
|
|
||||||
archiveUnmuted = archiveUnreadUnmutedCount,
|
|
||||||
archiveMentions = archiveMentionsCount
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageUpdated(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
|
||||||
|
|
||||||
val cmId = event[1].asLong()
|
|
||||||
val peerId = event[4].asLong()
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
loadMessage(
|
|
||||||
peerId = peerId,
|
|
||||||
cmId = cmId
|
|
||||||
)?.let { message ->
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_UPDATED]?.let {
|
|
||||||
it.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.MessageUpdated>)
|
|
||||||
.onEvent(LongPollParsedEvent.MessageUpdated(message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseMessageCacheClear(eventType: ApiEvent, event: List<Any>) {
|
|
||||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
|
||||||
|
|
||||||
val messageId = event[1].asLong()
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
loadMessage(messageId = messageId)?.let { message ->
|
|
||||||
listenersMap[LongPollEvent.MESSAGE_CACHE_CLEAR]?.let {
|
|
||||||
it.map { vkEventCallback ->
|
|
||||||
(vkEventCallback as VkEventCallback<LongPollParsedEvent.MessageCacheClear>)
|
|
||||||
.onEvent(LongPollParsedEvent.MessageCacheClear(message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun loadMessage(
|
|
||||||
peerId: Long? = null,
|
|
||||||
cmId: Long? = null,
|
|
||||||
messageId: Long? = null
|
|
||||||
): VkMessage? = suspendCoroutine { continuation ->
|
|
||||||
require((peerId != null && cmId != null) || messageId != null)
|
|
||||||
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
messagesUseCase.getById(
|
|
||||||
peerCmIds = null,
|
|
||||||
peerId = peerId,
|
|
||||||
messageIds = messageId?.let(::listOf),
|
|
||||||
cmIds = cmId?.let(::listOf),
|
|
||||||
extended = true,
|
|
||||||
fields = VkConstants.ALL_FIELDS
|
|
||||||
).listenValue(this) { state ->
|
|
||||||
state.processState(
|
|
||||||
error = { error ->
|
|
||||||
Log.e("LongPollUpdatesParser", "loadMessage: error: $error")
|
|
||||||
continuation.resume(null)
|
|
||||||
},
|
|
||||||
success = { response ->
|
|
||||||
val message = response.singleOrNull() ?: run {
|
|
||||||
continuation.resume(null)
|
|
||||||
return@listenValue
|
|
||||||
}
|
|
||||||
|
|
||||||
continuation.resume(message)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun loadConvo(
|
|
||||||
peerId: Long,
|
|
||||||
extended: Boolean = false,
|
|
||||||
fields: String? = null
|
|
||||||
): VkConvo? = suspendCoroutine { continuation ->
|
|
||||||
coroutineScope.launch(Dispatchers.IO) {
|
|
||||||
convoUseCase.getById(
|
|
||||||
peerIds = listOf(peerId),
|
|
||||||
extended = extended,
|
|
||||||
fields = fields
|
|
||||||
).listenValue(coroutineScope) { state ->
|
|
||||||
state.processState(
|
|
||||||
error = { error ->
|
|
||||||
Log.e("LongPollUpdatesParser", "loadConvo: error: $error")
|
|
||||||
continuation.resume(null)
|
|
||||||
},
|
|
||||||
success = { response ->
|
|
||||||
val convo = response.singleOrNull() ?: run {
|
|
||||||
continuation.resume(null)
|
|
||||||
return@listenValue
|
|
||||||
}
|
|
||||||
|
|
||||||
continuation.resume(convo)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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) {
|
fun onMessageSetFlags(block: (LongPollParsedEvent) -> Unit) {
|
||||||
registerListener(LongPollEvent.MESSAGE_SET_FLAGS, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_SET_FLAGS, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageMarkedAsImportant(block: (LongPollParsedEvent.MessageMarkedAsImportant) -> Unit) {
|
fun onMessageMarkedAsImportant(block: (LongPollParsedEvent.MessageMarkedAsImportant) -> Unit) {
|
||||||
registerListener(LongPollEvent.MARKED_AS_IMPORTANT, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MARKED_AS_IMPORTANT, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageMarkedAsSpam(block: (LongPollParsedEvent.MessageMarkedAsSpam) -> Unit) {
|
fun onMessageMarkedAsSpam(block: (LongPollParsedEvent.MessageMarkedAsSpam) -> Unit) {
|
||||||
registerListener(LongPollEvent.MARKED_AS_SPAM, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MARKED_AS_SPAM, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageDeleted(block: (LongPollParsedEvent.MessageDeleted) -> Unit) {
|
fun onMessageDeleted(block: (LongPollParsedEvent.MessageDeleted) -> Unit) {
|
||||||
registerListener(LongPollEvent.MESSAGE_DELETED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_DELETED, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageClearFlags(block: (LongPollParsedEvent) -> Unit) {
|
fun onMessageClearFlags(block: (LongPollParsedEvent) -> Unit) {
|
||||||
registerListener(LongPollEvent.MESSAGE_CLEAR_FLAGS, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_CLEAR_FLAGS, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageMarkedAsNotSpam(block: (LongPollParsedEvent.MessageMarkedAsNotSpam) -> Unit) {
|
fun onMessageMarkedAsNotSpam(block: (LongPollParsedEvent.MessageMarkedAsNotSpam) -> Unit) {
|
||||||
registerListener(LongPollEvent.MARKED_AS_NOT_SPAM, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MARKED_AS_NOT_SPAM, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageRestored(block: (LongPollParsedEvent.MessageRestored) -> Unit) {
|
fun onMessageRestored(block: (LongPollParsedEvent.MessageRestored) -> Unit) {
|
||||||
registerListener(LongPollEvent.MESSAGE_RESTORED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_RESTORED, assembleEventCallback(block))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageUpdated(block: (LongPollParsedEvent.MessageUpdated) -> Unit) {
|
||||||
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_UPDATED, assembleEventCallback(block))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageCacheClear(block: (LongPollParsedEvent.MessageCacheClear) -> Unit) {
|
||||||
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_CACHE_CLEAR, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onNewMessage(block: (LongPollParsedEvent.NewMessage) -> Unit) {
|
fun onNewMessage(block: (LongPollParsedEvent.NewMessage) -> Unit) {
|
||||||
registerListener(LongPollEvent.MESSAGE_NEW, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_NEW, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageEdited(block: (LongPollParsedEvent.MessageEdited) -> Unit) {
|
fun onMessageEdited(block: (LongPollParsedEvent.MessageEdited) -> Unit) {
|
||||||
registerListener(LongPollEvent.MESSAGE_EDITED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.MESSAGE_EDITED, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageIncomingRead(block: (LongPollParsedEvent.IncomingMessageRead) -> Unit) {
|
fun onMessageIncomingRead(block: (LongPollParsedEvent.IncomingMessageRead) -> Unit) {
|
||||||
registerListener(LongPollEvent.INCOMING_MESSAGE_READ, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.INCOMING_MESSAGE_READ, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onMessageOutgoingRead(block: (LongPollParsedEvent.OutgoingMessageRead) -> Unit) {
|
fun onMessageOutgoingRead(block: (LongPollParsedEvent.OutgoingMessageRead) -> Unit) {
|
||||||
registerListener(LongPollEvent.OUTGOING_MESSAGE_READ, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.OUTGOING_MESSAGE_READ, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onChatCleared(block: (LongPollParsedEvent.ChatCleared) -> Unit) {
|
fun onChatCleared(block: (LongPollParsedEvent.ChatCleared) -> Unit) {
|
||||||
registerListener(LongPollEvent.CHAT_CLEARED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.CHAT_CLEARED, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onChatMajorChanged(block: (LongPollParsedEvent.ChatMajorChanged) -> Unit) {
|
fun onChatMajorChanged(block: (LongPollParsedEvent.ChatMajorChanged) -> Unit) {
|
||||||
registerListener(LongPollEvent.CHAT_MAJOR_CHANGED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.CHAT_MAJOR_CHANGED, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onChatMinorChanged(block: (LongPollParsedEvent.ChatMinorChanged) -> Unit) {
|
fun onChatMinorChanged(block: (LongPollParsedEvent.ChatMinorChanged) -> Unit) {
|
||||||
registerListener(LongPollEvent.CHAT_MINOR_CHANGED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.CHAT_MINOR_CHANGED, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onChatArchived(block: (LongPollParsedEvent.ChatArchived) -> Unit) {
|
fun onChatArchived(block: (LongPollParsedEvent.ChatArchived) -> Unit) {
|
||||||
registerListener(LongPollEvent.CHAT_ARCHIVED, assembleEventCallback(block))
|
eventDispatcher.registerListener(LongPollEvent.CHAT_ARCHIVED, assembleEventCallback(block))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onInteractions(block: (LongPollParsedEvent.Interaction) -> Unit) {
|
fun onInteractions(block: (LongPollParsedEvent.Interaction) -> Unit) {
|
||||||
registerListeners(
|
eventDispatcher.registerListeners(
|
||||||
eventTypes = listOf(
|
eventTypes = listOf(
|
||||||
LongPollEvent.TYPING,
|
LongPollEvent.TYPING,
|
||||||
LongPollEvent.AUDIO_MESSAGE_RECORDING,
|
LongPollEvent.AUDIO_MESSAGE_RECORDING,
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.SharedFlow
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.filterIsInstance
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class LongPollUpdatesReducer(
|
||||||
|
updatesParser: LongPollUpdatesParser,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val convoUseCase: ConvoUseCase
|
||||||
|
) {
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
|
||||||
|
private val _events = MutableSharedFlow<LongPollParsedEvent>(extraBufferCapacity = 256)
|
||||||
|
val events: SharedFlow<LongPollParsedEvent> = _events.asSharedFlow()
|
||||||
|
|
||||||
|
val newMessages = events.filterIsInstance<LongPollParsedEvent.NewMessage>()
|
||||||
|
val messageEdited = events.filterIsInstance<LongPollParsedEvent.MessageEdited>()
|
||||||
|
val messageIncomingRead = events.filterIsInstance<LongPollParsedEvent.IncomingMessageRead>()
|
||||||
|
val messageOutgoingRead = events.filterIsInstance<LongPollParsedEvent.OutgoingMessageRead>()
|
||||||
|
val messageDeleted = events.filterIsInstance<LongPollParsedEvent.MessageDeleted>()
|
||||||
|
val messageRestored = events.filterIsInstance<LongPollParsedEvent.MessageRestored>()
|
||||||
|
val messageMarkedAsImportant = events.filterIsInstance<LongPollParsedEvent.MessageMarkedAsImportant>()
|
||||||
|
val messageMarkedAsSpam = events.filterIsInstance<LongPollParsedEvent.MessageMarkedAsSpam>()
|
||||||
|
val messageMarkedAsNotSpam = events.filterIsInstance<LongPollParsedEvent.MessageMarkedAsNotSpam>()
|
||||||
|
val interactions = events.filterIsInstance<LongPollParsedEvent.Interaction>()
|
||||||
|
val chatMajorChanged = events.filterIsInstance<LongPollParsedEvent.ChatMajorChanged>()
|
||||||
|
val chatMinorChanged = events.filterIsInstance<LongPollParsedEvent.ChatMinorChanged>()
|
||||||
|
val chatCleared = events.filterIsInstance<LongPollParsedEvent.ChatCleared>()
|
||||||
|
val chatArchived = events.filterIsInstance<LongPollParsedEvent.ChatArchived>()
|
||||||
|
val messageUpdated = events.filterIsInstance<LongPollParsedEvent.MessageUpdated>()
|
||||||
|
val messageCacheClear = events.filterIsInstance<LongPollParsedEvent.MessageCacheClear>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
updatesParser.onNewMessage { publish(it) }
|
||||||
|
updatesParser.onMessageEdited { publish(it) }
|
||||||
|
updatesParser.onMessageIncomingRead { publish(it) }
|
||||||
|
updatesParser.onMessageOutgoingRead { publish(it) }
|
||||||
|
updatesParser.onMessageDeleted { publish(it) }
|
||||||
|
updatesParser.onMessageRestored { publish(it) }
|
||||||
|
updatesParser.onMessageUpdated { publish(it) }
|
||||||
|
updatesParser.onMessageCacheClear { publish(it) }
|
||||||
|
updatesParser.onMessageMarkedAsImportant { publish(it) }
|
||||||
|
updatesParser.onMessageMarkedAsSpam { publish(it) }
|
||||||
|
updatesParser.onMessageMarkedAsNotSpam { publish(it) }
|
||||||
|
updatesParser.onInteractions { publish(it) }
|
||||||
|
updatesParser.onChatMajorChanged { publish(it) }
|
||||||
|
updatesParser.onChatMinorChanged { publish(it) }
|
||||||
|
updatesParser.onChatCleared { publish(it) }
|
||||||
|
updatesParser.onChatArchived { publish(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publish(event: LongPollParsedEvent) {
|
||||||
|
scope.launch {
|
||||||
|
runCatching { applyCommon(event) }
|
||||||
|
.onFailure { throwable ->
|
||||||
|
Log.e("LongPollUpdatesReducer", "applyCommon failed: $event", throwable)
|
||||||
|
}
|
||||||
|
_events.emit(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun applyCommon(event: LongPollParsedEvent) {
|
||||||
|
when (event) {
|
||||||
|
is LongPollParsedEvent.NewMessage -> {
|
||||||
|
messagesUseCase.storeMessages(listOf(event.message))
|
||||||
|
updateConvoForMessage(event.message, unreadIncrement = if (event.message.isOut) 0 else 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageEdited -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageUpdated -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageCacheClear -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.IncomingMessageRead -> {
|
||||||
|
updateConvoReadState(
|
||||||
|
peerId = event.peerId,
|
||||||
|
inReadCmId = event.cmId,
|
||||||
|
unreadCount = event.unreadCount
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.OutgoingMessageRead -> {
|
||||||
|
updateConvoReadState(
|
||||||
|
peerId = event.peerId,
|
||||||
|
outReadCmId = event.cmId,
|
||||||
|
unreadCount = event.unreadCount
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageDeleted -> {
|
||||||
|
val message = messagesUseCase.getLocalMessageByConvoMessageId(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId
|
||||||
|
)
|
||||||
|
if (message != null) {
|
||||||
|
messagesUseCase.deleteLocalMessages(listOf(message.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageRestored -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageMarkedAsImportant -> {
|
||||||
|
val message = messagesUseCase.getLocalMessageByConvoMessageId(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId
|
||||||
|
) ?: return
|
||||||
|
|
||||||
|
messagesUseCase.storeMessage(message.copy(isImportant = event.marked))
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageMarkedAsSpam -> {
|
||||||
|
val message = messagesUseCase.getLocalMessageByConvoMessageId(
|
||||||
|
convoId = event.peerId,
|
||||||
|
cmId = event.cmId
|
||||||
|
)
|
||||||
|
if (message != null) {
|
||||||
|
messagesUseCase.deleteLocalMessages(listOf(message.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.MessageMarkedAsNotSpam -> {
|
||||||
|
messagesUseCase.storeMessage(event.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatMajorChanged -> {
|
||||||
|
updateConvoSortState(event.peerId, majorId = event.majorId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatMinorChanged -> {
|
||||||
|
updateConvoSortState(event.peerId, minorId = event.minorId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatCleared -> {
|
||||||
|
convoUseCase.deleteLocalConvo(event.peerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.ChatArchived -> {
|
||||||
|
event.convo.lastMessage?.let(messagesUseCase::storeMessage)
|
||||||
|
convoUseCase.storeConvos(listOf(event.convo.copy(isArchived = event.archived)))
|
||||||
|
}
|
||||||
|
|
||||||
|
is LongPollParsedEvent.Interaction -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun updateConvoReadState(
|
||||||
|
peerId: Long,
|
||||||
|
inReadCmId: Long? = null,
|
||||||
|
outReadCmId: Long? = null,
|
||||||
|
unreadCount: Int
|
||||||
|
) {
|
||||||
|
val convo = convoUseCase.getLocalConvoById(peerId) ?: return
|
||||||
|
convoUseCase.storeConvos(
|
||||||
|
listOf(
|
||||||
|
convo.copy(
|
||||||
|
inReadCmId = inReadCmId ?: convo.inReadCmId,
|
||||||
|
outReadCmId = outReadCmId ?: convo.outReadCmId,
|
||||||
|
unreadCount = unreadCount
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun updateConvoSortState(
|
||||||
|
peerId: Long,
|
||||||
|
majorId: Int? = null,
|
||||||
|
minorId: Int? = null
|
||||||
|
) {
|
||||||
|
val convo = convoUseCase.getLocalConvoById(peerId) ?: return
|
||||||
|
convoUseCase.storeConvos(
|
||||||
|
listOf(
|
||||||
|
convo.copy(
|
||||||
|
majorId = majorId ?: convo.majorId,
|
||||||
|
minorId = minorId ?: convo.minorId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun updateConvoForMessage(
|
||||||
|
message: VkMessage,
|
||||||
|
unreadIncrement: Int
|
||||||
|
) {
|
||||||
|
val convo = convoUseCase.getLocalConvoById(message.peerId) ?: return
|
||||||
|
convoUseCase.storeConvos(
|
||||||
|
listOf(
|
||||||
|
convo.copy(
|
||||||
|
lastMessageId = message.id,
|
||||||
|
lastCmId = message.cmId,
|
||||||
|
unreadCount = convo.unreadCount + unreadIncrement
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package dev.meloda.fast.domain
|
package dev.meloda.fast.domain
|
||||||
|
|
||||||
import dev.meloda.fast.data.State
|
import dev.meloda.fast.data.State
|
||||||
|
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||||
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 kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -21,4 +22,14 @@ interface LongPollUseCase {
|
|||||||
mode: Int,
|
mode: Int,
|
||||||
version: Int
|
version: Int
|
||||||
): Flow<State<LongPollUpdates>>
|
): Flow<State<LongPollUpdates>>
|
||||||
|
|
||||||
|
fun getLongPollHistory(
|
||||||
|
ts: Int,
|
||||||
|
pts: Int,
|
||||||
|
lpVersion: Int,
|
||||||
|
lastN: Int? = null,
|
||||||
|
maxMsgId: Long? = null,
|
||||||
|
eventsLimit: Int? = null,
|
||||||
|
msgsLimit: Int? = null
|
||||||
|
): Flow<State<LongPollHistoryResponse>>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package dev.meloda.fast.domain
|
|||||||
import dev.meloda.fast.data.State
|
import dev.meloda.fast.data.State
|
||||||
import dev.meloda.fast.data.api.longpoll.LongPollRepository
|
import dev.meloda.fast.data.api.longpoll.LongPollRepository
|
||||||
import dev.meloda.fast.data.mapToState
|
import dev.meloda.fast.data.mapToState
|
||||||
|
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||||
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 kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -48,4 +49,27 @@ class LongPollUseCaseImpl(
|
|||||||
).mapToState()
|
).mapToState()
|
||||||
emit(newState)
|
emit(newState)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun getLongPollHistory(
|
||||||
|
ts: Int,
|
||||||
|
pts: Int,
|
||||||
|
lpVersion: Int,
|
||||||
|
lastN: Int?,
|
||||||
|
maxMsgId: Long?,
|
||||||
|
eventsLimit: Int?,
|
||||||
|
msgsLimit: Int?
|
||||||
|
): Flow<State<LongPollHistoryResponse>> = flow {
|
||||||
|
emit(State.Loading)
|
||||||
|
|
||||||
|
val newState = repository.getLongPollHistory(
|
||||||
|
ts = ts,
|
||||||
|
pts = pts,
|
||||||
|
lpVersion = lpVersion,
|
||||||
|
lastN = lastN,
|
||||||
|
maxMsgId = maxMsgId,
|
||||||
|
eventsLimit = eventsLimit,
|
||||||
|
msgsLimit = msgsLimit
|
||||||
|
).mapToState()
|
||||||
|
emit(newState)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ interface MessagesUseCase : BaseUseCase {
|
|||||||
|
|
||||||
suspend fun storeMessage(message: VkMessage)
|
suspend fun storeMessage(message: VkMessage)
|
||||||
suspend fun storeMessages(messages: List<VkMessage>)
|
suspend fun storeMessages(messages: List<VkMessage>)
|
||||||
|
suspend fun getLocalMessages(convoId: Long): List<VkMessage>
|
||||||
|
suspend fun getLocalMessageById(messageId: Long): VkMessage?
|
||||||
|
suspend fun getLocalMessageByConvoMessageId(convoId: Long, cmId: Long): VkMessage?
|
||||||
|
suspend fun getLocalMaxMessageId(): Long?
|
||||||
|
suspend fun deleteLocalMessages(messageIds: List<Long>)
|
||||||
|
|
||||||
fun getMessagesHistory(
|
fun getMessagesHistory(
|
||||||
convoId: Long,
|
convoId: Long,
|
||||||
|
|||||||
@@ -22,6 +22,26 @@ class MessagesUseCaseImpl(
|
|||||||
repository.storeMessages(messages)
|
repository.storeMessages(messages)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMessages(convoId: Long): List<VkMessage> {
|
||||||
|
return repository.getLocalMessages(convoId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMessageById(messageId: Long): VkMessage? {
|
||||||
|
return repository.getLocalMessageById(messageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMessageByConvoMessageId(convoId: Long, cmId: Long): VkMessage? {
|
||||||
|
return repository.getLocalMessageByConvoMessageId(convoId, cmId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalMaxMessageId(): Long? {
|
||||||
|
return repository.getLocalMaxMessageId()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deleteLocalMessages(messageIds: List<Long>) {
|
||||||
|
repository.deleteLocalMessages(messageIds)
|
||||||
|
}
|
||||||
|
|
||||||
override fun getMessagesHistory(
|
override fun getMessagesHistory(
|
||||||
convoId: Long,
|
convoId: Long,
|
||||||
count: Int?,
|
count: Int?,
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ interface OAuthUseCase {
|
|||||||
password: String,
|
password: String,
|
||||||
forceSms: Boolean,
|
forceSms: Boolean,
|
||||||
validationCode: String?,
|
validationCode: String?,
|
||||||
captchaSid: String?,
|
captchaSid: String? = null,
|
||||||
captchaKey: String?
|
captchaKey: String? = null,
|
||||||
|
successToken: String? = null
|
||||||
): Flow<State<GetSilentTokenResponse>>
|
): Flow<State<GetSilentTokenResponse>>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,22 +22,35 @@ class OAuthUseCaseImpl(
|
|||||||
): Flow<State<AuthInfo>> = flow {
|
): Flow<State<AuthInfo>> = flow {
|
||||||
emit(State.Loading)
|
emit(State.Loading)
|
||||||
|
|
||||||
val newState = oAuthRepository.auth(
|
val newState = when (val authResult = oAuthRepository.auth(
|
||||||
login = login,
|
login = login,
|
||||||
password = password,
|
password = password,
|
||||||
forceSms = forceSms,
|
forceSms = forceSms,
|
||||||
validationCode = validationCode,
|
validationCode = validationCode,
|
||||||
captchaSid = captchaSid,
|
captchaSid = captchaSid,
|
||||||
captchaKey = captchaKey
|
captchaKey = captchaKey
|
||||||
).asState(
|
)) {
|
||||||
successMapper = {
|
is com.slack.eithernet.ApiResult.Success -> {
|
||||||
|
val value = authResult.value
|
||||||
|
val userId = value.userId
|
||||||
|
val accessToken = value.accessToken
|
||||||
|
val validationHash = value.validationHash
|
||||||
|
|
||||||
|
if (userId == null || accessToken == null || validationHash == null) {
|
||||||
|
State.Error.InternalError
|
||||||
|
} else {
|
||||||
|
State.Success(
|
||||||
AuthInfo(
|
AuthInfo(
|
||||||
userId = it.userId!!,
|
userId = userId,
|
||||||
accessToken = it.accessToken!!,
|
accessToken = accessToken,
|
||||||
validationHash = it.validationHash!!
|
validationHash = validationHash
|
||||||
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
)
|
}
|
||||||
|
|
||||||
|
else -> authResult.asState()
|
||||||
|
}
|
||||||
|
|
||||||
emit(newState)
|
emit(newState)
|
||||||
}
|
}
|
||||||
@@ -48,7 +61,8 @@ class OAuthUseCaseImpl(
|
|||||||
forceSms: Boolean,
|
forceSms: Boolean,
|
||||||
validationCode: String?,
|
validationCode: String?,
|
||||||
captchaSid: String?,
|
captchaSid: String?,
|
||||||
captchaKey: String?
|
captchaKey: String?,
|
||||||
|
successToken: String?
|
||||||
): Flow<State<GetSilentTokenResponse>> = flow {
|
): Flow<State<GetSilentTokenResponse>> = flow {
|
||||||
emit(State.Loading)
|
emit(State.Loading)
|
||||||
|
|
||||||
@@ -58,7 +72,8 @@ class OAuthUseCaseImpl(
|
|||||||
forceSms = forceSms,
|
forceSms = forceSms,
|
||||||
validationCode = validationCode,
|
validationCode = validationCode,
|
||||||
captchaSid = captchaSid,
|
captchaSid = captchaSid,
|
||||||
captchaKey = captchaKey
|
captchaKey = captchaKey,
|
||||||
|
successToken = successToken
|
||||||
).asState()
|
).asState()
|
||||||
|
|
||||||
emit(newState)
|
emit(newState)
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package dev.meloda.fast.model.api.data
|
||||||
|
|
||||||
|
import com.squareup.moshi.Json
|
||||||
|
import com.squareup.moshi.JsonClass
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class LongPollHistoryResponse(
|
||||||
|
@Json(name = "history") val history: List<List<Any>>? = null,
|
||||||
|
@Json(name = "messages") val messages: Messages? = null,
|
||||||
|
@Json(name = "profiles") val profiles: List<VkUserData>? = null,
|
||||||
|
@Json(name = "groups") val groups: List<VkGroupData>? = null,
|
||||||
|
@Json(name = "new_pts") val newPts: Int? = null,
|
||||||
|
@Json(name = "from_pts") val fromPts: Int? = null,
|
||||||
|
@Json(name = "ts") val ts: Int? = null,
|
||||||
|
@Json(name = "pts") val pts: Int? = null,
|
||||||
|
@Json(name = "more") val more: Int? = null,
|
||||||
|
@Json(name = "conversations") val conversations: List<VkConvoData>? = null
|
||||||
|
) {
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class Messages(
|
||||||
|
@Json(name = "count") val count: Int? = null,
|
||||||
|
@Json(name = "items") val items: List<VkMessageData>? = null
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import com.squareup.moshi.JsonClass
|
|||||||
|
|
||||||
@JsonClass(generateAdapter = true)
|
@JsonClass(generateAdapter = true)
|
||||||
data class VkWidgetData(
|
data class VkWidgetData(
|
||||||
val id: Long
|
val id: Long?
|
||||||
) : VkAttachmentData {
|
) : VkAttachmentData {
|
||||||
|
|
||||||
fun toDomain() = VkWidgetDomain(id)
|
fun toDomain() = VkWidgetDomain(id)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package dev.meloda.fast.model.api.domain
|
|||||||
import dev.meloda.fast.model.api.data.AttachmentType
|
import dev.meloda.fast.model.api.data.AttachmentType
|
||||||
|
|
||||||
data class VkWidgetDomain(
|
data class VkWidgetDomain(
|
||||||
val id: Long
|
val id: Long?
|
||||||
) : VkAttachment {
|
) : VkAttachment {
|
||||||
|
|
||||||
override val type: AttachmentType = AttachmentType.WIDGET
|
override val type: AttachmentType = AttachmentType.WIDGET
|
||||||
|
|||||||
@@ -19,3 +19,27 @@ data class LongPollGetUpdatesRequest(
|
|||||||
"version" to version.toString()
|
"version" to version.toString()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
data class LongPollGetHistoryRequest(
|
||||||
|
val ts: Int,
|
||||||
|
val pts: Int,
|
||||||
|
val lpVersion: Int,
|
||||||
|
val lastN: Int? = null,
|
||||||
|
val maxMsgId: Long? = null,
|
||||||
|
val eventsLimit: Int? = null,
|
||||||
|
val msgsLimit: Int? = null,
|
||||||
|
val extended: Boolean = true,
|
||||||
|
) {
|
||||||
|
val map: Map<String, String>
|
||||||
|
get() = mutableMapOf(
|
||||||
|
"ts" to ts.toString(),
|
||||||
|
"pts" to pts.toString(),
|
||||||
|
"lp_version" to lpVersion.toString(),
|
||||||
|
"extended" to if (extended) "1" else "0",
|
||||||
|
).apply {
|
||||||
|
lastN?.let { this["last_n"] = it.toString() }
|
||||||
|
maxMsgId?.let { this["max_msg_id"] = it.toString() }
|
||||||
|
eventsLimit?.let { this["events_limit"] = it.toString() }
|
||||||
|
msgsLimit?.let { this["msgs_limit"] = it.toString() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ data class AuthDirectRequest(
|
|||||||
val validationCode: String? = null,
|
val validationCode: String? = null,
|
||||||
val captchaSid: String? = null,
|
val captchaSid: String? = null,
|
||||||
val captchaKey: String? = null,
|
val captchaKey: String? = null,
|
||||||
val trustedHash: String? = null
|
val trustedHash: String? = null,
|
||||||
|
val successToken: String? = null
|
||||||
) {
|
) {
|
||||||
|
|
||||||
val map
|
val map
|
||||||
@@ -31,6 +32,7 @@ data class AuthDirectRequest(
|
|||||||
captchaSid?.let { this["captcha_sid"] = it }
|
captchaSid?.let { this["captcha_sid"] = it }
|
||||||
captchaKey?.let { this["captcha_key"] = it }
|
captchaKey?.let { this["captcha_key"] = it }
|
||||||
trustedHash?.let { this["trusted_hash"] = it }
|
trustedHash?.let { this["trusted_hash"] = it }
|
||||||
|
successToken?.let { this["success_token"] = it }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ sealed class OAuthErrorDomain {
|
|||||||
|
|
||||||
data class CaptchaRequiredError(
|
data class CaptchaRequiredError(
|
||||||
val captchaSid: String,
|
val captchaSid: String,
|
||||||
val captchaImageUrl: String
|
val captchaImageUrl: String,
|
||||||
|
val redirectUri: String?
|
||||||
) : OAuthErrorDomain()
|
) : OAuthErrorDomain()
|
||||||
|
|
||||||
data class UserBannedError(
|
data class UserBannedError(
|
||||||
|
|||||||
@@ -53,6 +53,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")
|
||||||
throw ApiException(
|
throw ApiException(
|
||||||
RestApiError(
|
RestApiError(
|
||||||
errorCode = -1,
|
errorCode = -1,
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ package dev.meloda.fast.network
|
|||||||
|
|
||||||
enum class ValidationType(val value: String) {
|
enum class ValidationType(val value: String) {
|
||||||
APP("2fa_app"),
|
APP("2fa_app"),
|
||||||
SMS("2fa_sms");
|
SMS("sms"),
|
||||||
|
SMS2("2fa_sms");
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun parse(value: String): ValidationType =
|
fun parse(value: String): ValidationType =
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ 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
|
||||||
import dev.meloda.fast.network.ResponseConverterFactory
|
import dev.meloda.fast.network.ResponseConverterFactory
|
||||||
|
import dev.meloda.fast.network.interceptor.Error14HandlingInterceptor
|
||||||
import dev.meloda.fast.network.interceptor.LanguageInterceptor
|
import dev.meloda.fast.network.interceptor.LanguageInterceptor
|
||||||
import dev.meloda.fast.network.interceptor.VersionInterceptor
|
import dev.meloda.fast.network.interceptor.VersionInterceptor
|
||||||
import dev.meloda.fast.network.service.account.AccountService
|
import dev.meloda.fast.network.service.account.AccountService
|
||||||
@@ -45,6 +46,7 @@ val networkModule = module {
|
|||||||
single { ChuckerInterceptor.Builder(get()).collector(get()).build() }
|
single { ChuckerInterceptor.Builder(get()).collector(get()).build() }
|
||||||
singleOf(::VersionInterceptor)
|
singleOf(::VersionInterceptor)
|
||||||
singleOf(::LanguageInterceptor)
|
singleOf(::LanguageInterceptor)
|
||||||
|
singleOf(::Error14HandlingInterceptor)
|
||||||
|
|
||||||
single<OkHttpClient>(named("auth")) {
|
single<OkHttpClient>(named("auth")) {
|
||||||
buildHttpClient(true)
|
buildHttpClient(true)
|
||||||
@@ -101,6 +103,7 @@ private fun Scope.buildHttpClient(forAuth: Boolean): OkHttpClient {
|
|||||||
addInterceptor(get(named("token_interceptor")) as Interceptor)
|
addInterceptor(get(named("token_interceptor")) as Interceptor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.addInterceptor(get<Error14HandlingInterceptor>())
|
||||||
.addInterceptor(get<VersionInterceptor>())
|
.addInterceptor(get<VersionInterceptor>())
|
||||||
.addInterceptor(get<LanguageInterceptor>())
|
.addInterceptor(get<LanguageInterceptor>())
|
||||||
.addInterceptor(get<ChuckerInterceptor>())
|
.addInterceptor(get<ChuckerInterceptor>())
|
||||||
|
|||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
package dev.meloda.fast.network.interceptor
|
||||||
|
|
||||||
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.datastore.CaptchaTokenResult
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.Response
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
|
import kotlin.time.Duration.Companion.minutes
|
||||||
|
|
||||||
|
class Error14HandlingInterceptor : Interceptor {
|
||||||
|
|
||||||
|
private val cookie = AtomicReference<String?>(null)
|
||||||
|
private val captchaMutex = Mutex()
|
||||||
|
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val request = chain.request().withCookie()
|
||||||
|
val response = chain.proceed(request)
|
||||||
|
response.parseCookie()
|
||||||
|
|
||||||
|
if (request.shouldSkipCaptcha()) return response
|
||||||
|
|
||||||
|
val redirectUri = response.getRedirectUri() ?: return response
|
||||||
|
val token = awaitCaptchaToken(redirectUri)
|
||||||
|
|
||||||
|
return chain.proceed(chain.request().withCookie().withSuccessToken(token))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitCaptchaToken(redirectUri: String): String = runBlocking(Dispatchers.IO) {
|
||||||
|
captchaMutex.withLock {
|
||||||
|
AppSettings.setCaptchaResult(CaptchaTokenResult.Initial)
|
||||||
|
AppSettings.setCaptchaRedirectUri(redirectUri)
|
||||||
|
|
||||||
|
try {
|
||||||
|
withTimeout(CAPTCHA_TIMEOUT) {
|
||||||
|
AppSettings.getCaptchaResultFlow()
|
||||||
|
.first { it != CaptchaTokenResult.Initial }
|
||||||
|
.toToken()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
AppSettings.setCaptchaResult(CaptchaTokenResult.Initial)
|
||||||
|
AppSettings.setCaptchaRedirectUri(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun CaptchaTokenResult.toToken(): String = when (this) {
|
||||||
|
is CaptchaTokenResult.Success -> token
|
||||||
|
CaptchaTokenResult.Cancelled -> throw IOException("Captcha cancelled")
|
||||||
|
CaptchaTokenResult.Null -> throw IOException("Captcha result is empty")
|
||||||
|
CaptchaTokenResult.Initial -> throw IllegalStateException("Captcha result not ready")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Request.withSuccessToken(token: String): Request {
|
||||||
|
return newBuilder()
|
||||||
|
.url(url.newBuilder().addQueryParameter("success_token", token).build())
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Response.getRedirectUri(): String? {
|
||||||
|
val responseBody = JSONObject(peekBody(Long.MAX_VALUE).string())
|
||||||
|
return if (responseBody.has("error")) {
|
||||||
|
val stringError = try {
|
||||||
|
responseBody.getString("error")
|
||||||
|
} catch (ignored: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stringError != null) {
|
||||||
|
if (stringError == CAPTCHA_ERROR_KIND && responseBody.has("redirect_uri")) {
|
||||||
|
responseBody.getString("redirect_uri")
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val error = responseBody.getJSONObject("error")
|
||||||
|
if (error.getInt("error_code") == CAPTCHA_ERROR_CODE) {
|
||||||
|
error.getString("redirect_uri")
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Request.shouldSkipCaptcha(): Boolean {
|
||||||
|
return false
|
||||||
|
// return !domains.contains(url.toUrl().host) && domains.isNotEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Response.parseCookie() {
|
||||||
|
headers("Set-Cookie").firstOrNull { it.contains("remixstlid") }?.let(cookie::set)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Request.withCookie(): Request {
|
||||||
|
return newBuilder().apply { cookie.get()?.let { addHeader("Cookie", it) } }.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
private const val CAPTCHA_ERROR_CODE = 14
|
||||||
|
private const val CAPTCHA_ERROR_KIND = "need_captcha"
|
||||||
|
private val CAPTCHA_TIMEOUT = 10.minutes
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
@@ -2,6 +2,7 @@ package dev.meloda.fast.network.service.messages
|
|||||||
|
|
||||||
import com.slack.eithernet.ApiResult
|
import com.slack.eithernet.ApiResult
|
||||||
import dev.meloda.fast.model.api.data.VkChatData
|
import dev.meloda.fast.model.api.data.VkChatData
|
||||||
|
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||||
import dev.meloda.fast.model.api.data.VkMessageData
|
import dev.meloda.fast.model.api.data.VkMessageData
|
||||||
import dev.meloda.fast.model.api.responses.MessagesCreateChatResponse
|
import dev.meloda.fast.model.api.responses.MessagesCreateChatResponse
|
||||||
@@ -44,6 +45,12 @@ interface MessagesService {
|
|||||||
@FieldMap params: Map<String, String>
|
@FieldMap params: Map<String, String>
|
||||||
): ApiResult<ApiResponse<VkLongPollData>, RestApiError>
|
): ApiResult<ApiResponse<VkLongPollData>, RestApiError>
|
||||||
|
|
||||||
|
@FormUrlEncoded
|
||||||
|
@POST(MessagesUrls.GET_LONG_POLL_HISTORY)
|
||||||
|
suspend fun getLongPollHistory(
|
||||||
|
@FieldMap params: Map<String, String>
|
||||||
|
): ApiResult<ApiResponse<LongPollHistoryResponse>, RestApiError>
|
||||||
|
|
||||||
@FormUrlEncoded
|
@FormUrlEncoded
|
||||||
@POST(MessagesUrls.MARK_AS_READ)
|
@POST(MessagesUrls.MARK_AS_READ)
|
||||||
suspend fun markAsRead(
|
suspend fun markAsRead(
|
||||||
|
|||||||
@@ -303,4 +303,6 @@
|
|||||||
|
|
||||||
<string name="confirm_chat_create_with_title">Are you sure you want to create chat «%s»?</string>
|
<string name="confirm_chat_create_with_title">Are you sure you want to create chat «%s»?</string>
|
||||||
<string name="confirm_chat_create_empty_with_title">Are you sure you want to create chat «%s» only with yourself?</string>
|
<string name="confirm_chat_create_empty_with_title">Are you sure you want to create chat «%s» only with yourself?</string>
|
||||||
|
|
||||||
|
<string name="title_edit_message">Edit message</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package dev.meloda.fast.auth.login
|
|||||||
import androidx.compose.ui.test.assertHasClickAction
|
import androidx.compose.ui.test.assertHasClickAction
|
||||||
import androidx.compose.ui.test.junit4.createComposeRule
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
import androidx.compose.ui.test.onNodeWithTag
|
import androidx.compose.ui.test.onNodeWithTag
|
||||||
import dev.meloda.fast.auth.login.presentation.LogoScreen
|
|
||||||
import org.junit.Rule
|
import org.junit.Rule
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
|
||||||
@@ -15,7 +14,7 @@ class LogoScreenTest {
|
|||||||
@Test
|
@Test
|
||||||
fun goNextButton_isClickable() {
|
fun goNextButton_isClickable() {
|
||||||
composeTestRule.setContent {
|
composeTestRule.setContent {
|
||||||
LogoScreen()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
composeTestRule.onNodeWithTag(testTag = "go_next_fab").assertHasClickAction()
|
composeTestRule.onNodeWithTag(testTag = "go_next_fab").assertHasClickAction()
|
||||||
|
|||||||
@@ -3,9 +3,6 @@ package dev.meloda.fast.auth
|
|||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import androidx.navigation.NavGraphBuilder
|
import androidx.navigation.NavGraphBuilder
|
||||||
import androidx.navigation.navigation
|
import androidx.navigation.navigation
|
||||||
import dev.meloda.fast.auth.captcha.navigation.captchaScreen
|
|
||||||
import dev.meloda.fast.auth.captcha.navigation.navigateToCaptcha
|
|
||||||
import dev.meloda.fast.auth.captcha.navigation.setCaptchaResult
|
|
||||||
import dev.meloda.fast.auth.login.navigation.Login
|
import dev.meloda.fast.auth.login.navigation.Login
|
||||||
import dev.meloda.fast.auth.login.navigation.loginScreen
|
import dev.meloda.fast.auth.login.navigation.loginScreen
|
||||||
import dev.meloda.fast.auth.userbanned.model.UserBannedArguments
|
import dev.meloda.fast.auth.userbanned.model.UserBannedArguments
|
||||||
@@ -28,11 +25,6 @@ fun NavGraphBuilder.authNavGraph(
|
|||||||
) {
|
) {
|
||||||
navigation<AuthGraph>(startDestination = Login) {
|
navigation<AuthGraph>(startDestination = Login) {
|
||||||
loginScreen(
|
loginScreen(
|
||||||
onNavigateToCaptcha = { arguments ->
|
|
||||||
navController.navigateToCaptcha(
|
|
||||||
captchaImageUrl = URLEncoder.encode(arguments.captchaImageUrl, "utf-8")
|
|
||||||
)
|
|
||||||
},
|
|
||||||
onNavigateToValidation = { arguments ->
|
onNavigateToValidation = { arguments ->
|
||||||
navController.navigateToValidation(
|
navController.navigateToValidation(
|
||||||
ValidationArguments(
|
ValidationArguments(
|
||||||
@@ -70,17 +62,6 @@ fun NavGraphBuilder.authNavGraph(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
captchaScreen(
|
|
||||||
onBack = {
|
|
||||||
navController.setCaptchaResult(null)
|
|
||||||
navController.navigateUp()
|
|
||||||
},
|
|
||||||
onResult = { code ->
|
|
||||||
navController.setCaptchaResult(code)
|
|
||||||
navController.popBackStack()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
userBannedRoute(onBack = navController::navigateUp)
|
userBannedRoute(onBack = navController::navigateUp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package dev.meloda.fast.auth
|
package dev.meloda.fast.auth
|
||||||
|
|
||||||
import dev.meloda.fast.auth.captcha.di.captchaModule
|
|
||||||
import dev.meloda.fast.auth.validation.di.validationModule
|
import dev.meloda.fast.auth.validation.di.validationModule
|
||||||
import dev.meloda.fast.auth.login.di.loginModule
|
import dev.meloda.fast.auth.login.di.loginModule
|
||||||
import org.koin.dsl.module
|
import org.koin.dsl.module
|
||||||
@@ -9,6 +8,5 @@ val authModule = module {
|
|||||||
includes(
|
includes(
|
||||||
loginModule,
|
loginModule,
|
||||||
validationModule,
|
validationModule,
|
||||||
captchaModule,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.captcha
|
|
||||||
|
|
||||||
import androidx.lifecycle.SavedStateHandle
|
|
||||||
import androidx.lifecycle.ViewModel
|
|
||||||
import dev.meloda.fast.auth.captcha.model.CaptchaScreenState
|
|
||||||
import dev.meloda.fast.auth.captcha.navigation.Captcha
|
|
||||||
import dev.meloda.fast.auth.captcha.validation.CaptchaValidator
|
|
||||||
import dev.meloda.fast.common.extensions.setValue
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
import java.net.URLDecoder
|
|
||||||
|
|
||||||
interface CaptchaViewModel {
|
|
||||||
val screenState: StateFlow<CaptchaScreenState>
|
|
||||||
val isNeedToOpenLogin: StateFlow<Boolean>
|
|
||||||
|
|
||||||
fun onCodeInputChanged(newCode: String)
|
|
||||||
|
|
||||||
fun onTextFieldDoneAction()
|
|
||||||
fun onDoneButtonClicked()
|
|
||||||
|
|
||||||
fun onNavigatedToLogin()
|
|
||||||
}
|
|
||||||
|
|
||||||
class CaptchaViewModelImpl(
|
|
||||||
private val validator: CaptchaValidator,
|
|
||||||
savedStateHandle: SavedStateHandle
|
|
||||||
) : CaptchaViewModel, ViewModel() {
|
|
||||||
|
|
||||||
override val screenState = MutableStateFlow(CaptchaScreenState.EMPTY)
|
|
||||||
override val isNeedToOpenLogin = MutableStateFlow(false)
|
|
||||||
|
|
||||||
|
|
||||||
init {
|
|
||||||
val captchaImage = Captcha.from(savedStateHandle).captchaImageUrl
|
|
||||||
|
|
||||||
screenState.setValue { old ->
|
|
||||||
old.copy(captchaImageUrl = URLDecoder.decode(captchaImage, "utf-8"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCodeInputChanged(newCode: String) {
|
|
||||||
val newState = screenState.value.copy(code = newCode.trim())
|
|
||||||
screenState.update { newState }
|
|
||||||
processValidation()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onTextFieldDoneAction() {
|
|
||||||
onDoneButtonClicked()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDoneButtonClicked() {
|
|
||||||
if (!processValidation()) return
|
|
||||||
|
|
||||||
isNeedToOpenLogin.update { true }
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onNavigatedToLogin() {
|
|
||||||
screenState.update { CaptchaScreenState.EMPTY }
|
|
||||||
isNeedToOpenLogin.update { false }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun processValidation(): Boolean {
|
|
||||||
val isValid = validator.validate(screenState.value).isValid()
|
|
||||||
screenState.setValue { old -> old.copy(codeError = !isValid) }
|
|
||||||
return isValid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.captcha.di
|
|
||||||
|
|
||||||
import dev.meloda.fast.auth.captcha.CaptchaViewModel
|
|
||||||
import dev.meloda.fast.auth.captcha.CaptchaViewModelImpl
|
|
||||||
import dev.meloda.fast.auth.captcha.validation.CaptchaValidator
|
|
||||||
import org.koin.core.module.dsl.singleOf
|
|
||||||
import org.koin.core.module.dsl.viewModelOf
|
|
||||||
import org.koin.dsl.bind
|
|
||||||
import org.koin.dsl.module
|
|
||||||
|
|
||||||
val captchaModule = module {
|
|
||||||
singleOf(::CaptchaValidator)
|
|
||||||
viewModelOf(::CaptchaViewModelImpl) bind CaptchaViewModel::class
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.captcha.model
|
|
||||||
|
|
||||||
data class CaptchaScreenState(
|
|
||||||
val captchaImageUrl: String,
|
|
||||||
val code: String,
|
|
||||||
val codeError: Boolean
|
|
||||||
) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
val EMPTY = CaptchaScreenState(
|
|
||||||
captchaImageUrl = "",
|
|
||||||
code = "",
|
|
||||||
codeError = false
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-8
@@ -1,8 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.captcha.model
|
|
||||||
|
|
||||||
sealed class CaptchaValidationResult {
|
|
||||||
data object Empty : CaptchaValidationResult()
|
|
||||||
data object Valid : CaptchaValidationResult()
|
|
||||||
|
|
||||||
fun isValid() = this == Valid
|
|
||||||
}
|
|
||||||
-40
@@ -1,40 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.captcha.navigation
|
|
||||||
|
|
||||||
import androidx.lifecycle.SavedStateHandle
|
|
||||||
import androidx.navigation.NavController
|
|
||||||
import androidx.navigation.NavGraphBuilder
|
|
||||||
import androidx.navigation.compose.composable
|
|
||||||
import androidx.navigation.toRoute
|
|
||||||
import dev.meloda.fast.auth.captcha.presentation.CaptchaRoute
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Captcha(val captchaImageUrl: String) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
fun from(savedStateHandle: SavedStateHandle) = savedStateHandle.toRoute<Captcha>()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fun NavGraphBuilder.captchaScreen(
|
|
||||||
onBack: () -> Unit,
|
|
||||||
onResult: (String) -> Unit
|
|
||||||
) {
|
|
||||||
composable<Captcha> {
|
|
||||||
CaptchaRoute(
|
|
||||||
onBack = onBack,
|
|
||||||
onResult = onResult
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun NavController.navigateToCaptcha(captchaImageUrl: String) {
|
|
||||||
this.navigate(Captcha(captchaImageUrl))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun NavController.setCaptchaResult(code: String?) {
|
|
||||||
this.previousBackStackEntry
|
|
||||||
?.savedStateHandle
|
|
||||||
?.set("captcha_code", code)
|
|
||||||
}
|
|
||||||
+121
-200
@@ -1,33 +1,22 @@
|
|||||||
package dev.meloda.fast.auth.captcha.presentation
|
package dev.meloda.fast.auth.captcha.presentation
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.util.Log
|
||||||
|
import android.webkit.JavascriptInterface
|
||||||
|
import android.webkit.WebResourceRequest
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.animation.fadeIn
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.foundation.isSystemInDarkTheme
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.WindowInsets
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.ime
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.union
|
|
||||||
import androidx.compose.foundation.layout.width
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.text.KeyboardActions
|
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
|
||||||
import androidx.compose.material3.FloatingActionButton
|
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Scaffold
|
|
||||||
import androidx.compose.material3.ScaffoldDefaults
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.material3.TextField
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -37,63 +26,34 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
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.graphics.Color
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.platform.LocalFocusManager
|
import androidx.compose.ui.platform.LocalFocusManager
|
||||||
import androidx.compose.ui.platform.LocalView
|
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
|
||||||
import androidx.compose.ui.text.input.TextFieldValue
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
|
|
||||||
import coil.compose.AsyncImage
|
|
||||||
import dev.meloda.fast.auth.captcha.CaptchaViewModel
|
|
||||||
import dev.meloda.fast.auth.captcha.CaptchaViewModelImpl
|
|
||||||
import dev.meloda.fast.auth.captcha.model.CaptchaScreenState
|
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
import dev.meloda.fast.ui.common.FastPreview
|
|
||||||
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.MaterialDialog
|
import dev.meloda.fast.ui.components.MaterialDialog
|
||||||
import dev.meloda.fast.ui.components.TextFieldErrorText
|
import org.json.JSONObject
|
||||||
import dev.meloda.fast.ui.theme.AppTheme
|
|
||||||
import org.koin.androidx.compose.koinViewModel
|
|
||||||
|
|
||||||
@Composable
|
private const val TAG = "CaptchaScreen"
|
||||||
fun CaptchaRoute(
|
|
||||||
onBack: () -> Unit,
|
|
||||||
onResult: (String) -> Unit,
|
|
||||||
viewModel: CaptchaViewModel = koinViewModel<CaptchaViewModelImpl>()
|
|
||||||
) {
|
|
||||||
LocalViewModelStoreOwner.current
|
|
||||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
|
||||||
val isNeedToOpenLogin by viewModel.isNeedToOpenLogin.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
LaunchedEffect(isNeedToOpenLogin) {
|
|
||||||
if (isNeedToOpenLogin) {
|
|
||||||
viewModel.onNavigatedToLogin()
|
|
||||||
onResult(screenState.code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CaptchaScreen(
|
|
||||||
screenState = screenState,
|
|
||||||
onBack = onBack,
|
|
||||||
onCodeInputChanged = viewModel::onCodeInputChanged,
|
|
||||||
onTextFieldDoneAction = viewModel::onTextFieldDoneAction,
|
|
||||||
onDoneButtonClicked = viewModel::onDoneButtonClicked
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun CaptchaScreen(
|
fun CaptchaScreen(
|
||||||
screenState: CaptchaScreenState = CaptchaScreenState.EMPTY,
|
captchaRedirectUri: String?,
|
||||||
onBack: () -> Unit = {},
|
onBack: () -> Unit = {},
|
||||||
onCodeInputChanged: (String) -> Unit = {},
|
onResult: (String) -> Unit = {}
|
||||||
onTextFieldDoneAction: () -> Unit = {},
|
|
||||||
onDoneButtonClicked: () -> Unit = {}
|
|
||||||
) {
|
) {
|
||||||
|
if (captchaRedirectUri != null) {
|
||||||
|
val focusManager = LocalFocusManager.current
|
||||||
|
val keyboardController = LocalSoftwareKeyboardController.current
|
||||||
|
LaunchedEffect(true) {
|
||||||
|
focusManager.clearFocus(true)
|
||||||
|
keyboardController?.hide()
|
||||||
|
}
|
||||||
|
|
||||||
var confirmedExit by remember {
|
var confirmedExit by remember {
|
||||||
mutableStateOf(false)
|
mutableStateOf(false)
|
||||||
}
|
}
|
||||||
@@ -102,6 +62,10 @@ fun CaptchaScreen(
|
|||||||
mutableStateOf(false)
|
mutableStateOf(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var isWebViewLoading by remember {
|
||||||
|
mutableStateOf(true)
|
||||||
|
}
|
||||||
|
|
||||||
LaunchedEffect(confirmedExit) {
|
LaunchedEffect(confirmedExit) {
|
||||||
if (confirmedExit) {
|
if (confirmedExit) {
|
||||||
onBack()
|
onBack()
|
||||||
@@ -114,6 +78,7 @@ fun CaptchaScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FullScreenDialog(onDismiss = { showExitAlert = true }) {
|
||||||
if (showExitAlert) {
|
if (showExitAlert) {
|
||||||
MaterialDialog(
|
MaterialDialog(
|
||||||
onDismissRequest = { showExitAlert = false },
|
onDismissRequest = { showExitAlert = false },
|
||||||
@@ -126,148 +91,104 @@ fun CaptchaScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
val focusManager = LocalFocusManager.current
|
Box(
|
||||||
|
|
||||||
Scaffold(
|
|
||||||
contentWindowInsets = ScaffoldDefaults.contentWindowInsets.union(WindowInsets.ime)
|
|
||||||
) { padding ->
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.navigationBarsPadding()
|
||||||
.padding(30.dp),
|
.clickable(
|
||||||
verticalArrangement = Arrangement.SpaceBetween
|
interactionSource = remember { MutableInteractionSource() },
|
||||||
|
indication = null,
|
||||||
|
onClick = { showExitAlert = true }
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
ExtendedFloatingActionButton(
|
AndroidView(
|
||||||
onClick = onBack,
|
|
||||||
text = {
|
|
||||||
Text(
|
|
||||||
text = "Cancel",
|
|
||||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
|
||||||
)
|
|
||||||
},
|
|
||||||
icon = {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.ic_close_round_24),
|
|
||||||
contentDescription = "Close icon",
|
|
||||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
Column(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "Captcha",
|
|
||||||
style = MaterialTheme.typography.displayMedium,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground
|
|
||||||
)
|
|
||||||
Spacer(modifier = Modifier.height(38.dp))
|
|
||||||
Row(
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
modifier = Modifier.fillMaxWidth()
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "To proceed with your action, enter a code from the picture",
|
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
modifier = Modifier.weight(0.5f)
|
|
||||||
)
|
|
||||||
Spacer(modifier = Modifier.width(24.dp))
|
|
||||||
|
|
||||||
val imageModifier = Modifier
|
|
||||||
.border(
|
|
||||||
2.dp,
|
|
||||||
MaterialTheme.colorScheme.primary,
|
|
||||||
shape = RoundedCornerShape(10.dp)
|
|
||||||
)
|
|
||||||
.clip(RoundedCornerShape(10.dp))
|
|
||||||
.height(48.dp)
|
|
||||||
.width(130.dp)
|
|
||||||
|
|
||||||
if (LocalView.current.isInEditMode) {
|
|
||||||
Image(
|
|
||||||
painter = painterResource(id = R.drawable.img_test_captcha),
|
|
||||||
contentDescription = "Captcha image",
|
|
||||||
modifier = imageModifier
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
AsyncImage(
|
|
||||||
model = screenState.captchaImageUrl,
|
|
||||||
contentDescription = "Captcha image",
|
|
||||||
contentScale = ContentScale.FillBounds,
|
|
||||||
modifier = imageModifier
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(30.dp))
|
|
||||||
|
|
||||||
var code by remember { mutableStateOf(TextFieldValue(screenState.code)) }
|
|
||||||
val showError = screenState.codeError
|
|
||||||
|
|
||||||
TextField(
|
|
||||||
value = code,
|
|
||||||
onValueChange = { newText ->
|
|
||||||
code = newText
|
|
||||||
onCodeInputChanged(newText.text)
|
|
||||||
},
|
|
||||||
label = { Text(text = "Code") },
|
|
||||||
placeholder = { Text(text = "Code") },
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxSize()
|
||||||
.clip(RoundedCornerShape(10.dp)),
|
.align(Alignment.BottomCenter),
|
||||||
leadingIcon = {
|
factory = { context ->
|
||||||
Icon(
|
val webview = WebView(context)
|
||||||
painter = painterResource(id = R.drawable.ic_qr_code_round_24),
|
webview.setBackgroundColor(0)
|
||||||
contentDescription = "QR code icon",
|
webview.settings.javaScriptEnabled = true
|
||||||
tint = if (showError) {
|
webview.webViewClient = object : WebViewClient() {
|
||||||
MaterialTheme.colorScheme.error
|
override fun shouldOverrideUrlLoading(
|
||||||
} else {
|
view: WebView?,
|
||||||
MaterialTheme.colorScheme.primary
|
request: WebResourceRequest?
|
||||||
}
|
): Boolean {
|
||||||
)
|
Log.i(TAG, "shouldOverrideUrlLoading: $request")
|
||||||
},
|
return false
|
||||||
shape = RoundedCornerShape(10.dp),
|
|
||||||
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
|
|
||||||
keyboardActions = KeyboardActions(
|
|
||||||
onDone = {
|
|
||||||
focusManager.clearFocus()
|
|
||||||
onTextFieldDoneAction()
|
|
||||||
}
|
|
||||||
),
|
|
||||||
isError = showError
|
|
||||||
)
|
|
||||||
|
|
||||||
AnimatedVisibility(visible = showError) {
|
|
||||||
TextFieldErrorText(text = "Field must not be empty")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
FloatingActionButton(
|
override fun onPageStarted(
|
||||||
onClick = onDoneButtonClicked,
|
view: WebView?,
|
||||||
containerColor = MaterialTheme.colorScheme.secondaryContainer,
|
url: String?,
|
||||||
modifier = Modifier.align(Alignment.CenterHorizontally)
|
favicon: Bitmap?
|
||||||
) {
|
) {
|
||||||
Icon(
|
super.onPageStarted(view, url, favicon)
|
||||||
painter = painterResource(R.drawable.ic_check_round_24),
|
isWebViewLoading = true
|
||||||
contentDescription = "Done icon",
|
}
|
||||||
tint = MaterialTheme.colorScheme.onSecondaryContainer
|
|
||||||
|
override fun onPageFinished(view: WebView?, url: String?) {
|
||||||
|
super.onPageFinished(view, url)
|
||||||
|
isWebViewLoading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
webview.addJavascriptInterface(
|
||||||
|
WebCaptchaListener(
|
||||||
|
onSuccessTokenReceived = {
|
||||||
|
val response: String? = try {
|
||||||
|
JSONObject(it).getString("token")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response != null) {
|
||||||
|
onResult(response)
|
||||||
|
} else {
|
||||||
|
// TODO: 03/05/2026, Danil Nikolaev: show error
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onCloseRequested = { showExitAlert = true }
|
||||||
|
),
|
||||||
|
"AndroidBridge"
|
||||||
)
|
)
|
||||||
|
// webview.loadUrl("https://id.vk.ru/not_robot_captcha?variant=block&session_token=test&domain=test.com")
|
||||||
|
webview.loadUrl(captchaRedirectUri)
|
||||||
|
webview
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = isWebViewLoading,
|
||||||
|
enter = fadeIn(),
|
||||||
|
exit = fadeOut(),
|
||||||
|
modifier = Modifier.align(Alignment.Center)
|
||||||
|
) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(50.dp),
|
||||||
|
color = Color.White.copy(alpha = 0.85f)
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@FastPreview
|
class WebCaptchaListener(
|
||||||
@Composable
|
private val onSuccessTokenReceived: (String) -> Unit,
|
||||||
private fun CaptchaScreenPreview() {
|
private val onCloseRequested: (String) -> Unit
|
||||||
AppTheme(useDarkTheme = isSystemInDarkTheme(), useDynamicColors = true) {
|
) {
|
||||||
CaptchaScreen(
|
private val tag = "WebCaptchaListener"
|
||||||
screenState = CaptchaScreenState.EMPTY.copy(
|
|
||||||
code = "zcuecz"
|
@JavascriptInterface
|
||||||
)
|
fun VKCaptchaGetResult(arg: String) {
|
||||||
)
|
onSuccessTokenReceived(arg)
|
||||||
|
Log.i(tag, "VKCaptchaGetResult($arg)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun VKCaptchaCloseCaptcha(arg: String) {
|
||||||
|
onCloseRequested(arg)
|
||||||
|
Log.i(tag, "VKCaptchaCloseCaptcha($arg)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-14
@@ -1,14 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.captcha.validation
|
|
||||||
|
|
||||||
import dev.meloda.fast.auth.captcha.model.CaptchaScreenState
|
|
||||||
import dev.meloda.fast.auth.captcha.model.CaptchaValidationResult
|
|
||||||
|
|
||||||
class CaptchaValidator {
|
|
||||||
|
|
||||||
fun validate(screenState: CaptchaScreenState): CaptchaValidationResult {
|
|
||||||
return when {
|
|
||||||
screenState.code.trim().isEmpty() -> CaptchaValidationResult.Empty
|
|
||||||
else -> CaptchaValidationResult.Valid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -59,18 +59,12 @@ class LoginViewModel(
|
|||||||
private val _validationArguments = MutableStateFlow<LoginValidationArguments?>(null)
|
private val _validationArguments = MutableStateFlow<LoginValidationArguments?>(null)
|
||||||
val validationArguments = _validationArguments.asStateFlow()
|
val validationArguments = _validationArguments.asStateFlow()
|
||||||
|
|
||||||
private val _captchaArguments = MutableStateFlow<CaptchaArguments?>(null)
|
|
||||||
val captchaArguments = _captchaArguments.asStateFlow()
|
|
||||||
|
|
||||||
private val _userBannedArguments = MutableStateFlow<LoginUserBannedArguments?>(null)
|
private val _userBannedArguments = MutableStateFlow<LoginUserBannedArguments?>(null)
|
||||||
val userBannedArguments = _userBannedArguments.asStateFlow()
|
val userBannedArguments = _userBannedArguments.asStateFlow()
|
||||||
|
|
||||||
private val _isNeedToOpenMain = MutableStateFlow(false)
|
private val _isNeedToOpenMain = MutableStateFlow(false)
|
||||||
val isNeedToOpenMain = _isNeedToOpenMain.asStateFlow()
|
val isNeedToOpenMain = _isNeedToOpenMain.asStateFlow()
|
||||||
|
|
||||||
private val _isNeedToClearCaptchaCode = MutableStateFlow(false)
|
|
||||||
val isNeedToClearCaptchaCode = _isNeedToClearCaptchaCode.asStateFlow()
|
|
||||||
|
|
||||||
private val _isNeedToClearValidationCode = MutableStateFlow(false)
|
private val _isNeedToClearValidationCode = MutableStateFlow(false)
|
||||||
val isNeedToClearValidationCode = _isNeedToClearValidationCode.asStateFlow()
|
val isNeedToClearValidationCode = _isNeedToClearValidationCode.asStateFlow()
|
||||||
|
|
||||||
@@ -78,17 +72,10 @@ class LoginViewModel(
|
|||||||
screenState.map(loginValidator::validate)
|
screenState.map(loginValidator::validate)
|
||||||
.stateIn(viewModelScope, SharingStarted.Eagerly, listOf(LoginValidationResult.Empty))
|
.stateIn(viewModelScope, SharingStarted.Eagerly, listOf(LoginValidationResult.Empty))
|
||||||
|
|
||||||
private val captchaSid = MutableStateFlow<String?>(null)
|
|
||||||
private val captchaCode = MutableStateFlow<String?>(null)
|
|
||||||
private val validationSid = MutableStateFlow<String?>(null)
|
private val validationSid = MutableStateFlow<String?>(null)
|
||||||
private val validationCode = MutableStateFlow<String?>(null)
|
private val validationCode = MutableStateFlow<String?>(null)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
captchaCode.listenValue(viewModelScope) {
|
|
||||||
if (it != null) {
|
|
||||||
login()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
validationCode.listenValue(viewModelScope) {
|
validationCode.listenValue(viewModelScope) {
|
||||||
if (it != null) {
|
if (it != null) {
|
||||||
login()
|
login()
|
||||||
@@ -165,10 +152,6 @@ class LoginViewModel(
|
|||||||
_userBannedArguments.update { null }
|
_userBannedArguments.update { null }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onNavigatedToCaptcha() {
|
|
||||||
_captchaArguments.update { null }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onNavigatedToValidation() {
|
fun onNavigatedToValidation() {
|
||||||
_validationArguments.update { null }
|
_validationArguments.update { null }
|
||||||
}
|
}
|
||||||
@@ -181,25 +164,9 @@ class LoginViewModel(
|
|||||||
_isNeedToClearValidationCode.update { false }
|
_isNeedToClearValidationCode.update { false }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onCaptchaCodeReceived(code: String?) {
|
|
||||||
captchaCode.update { code }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onCaptchaCodeCleared() {
|
|
||||||
_isNeedToClearCaptchaCode.update { false }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun login(forceSms: Boolean = false) {
|
private fun login(forceSms: Boolean = false) {
|
||||||
val currentState = screenState.value.copy()
|
val currentState = screenState.value.copy()
|
||||||
|
|
||||||
Log.d(
|
|
||||||
"LoginViewModel",
|
|
||||||
"auth: login: ${currentState.login}; " +
|
|
||||||
"password: ${currentState.password}; " +
|
|
||||||
"2fa code: ${validationCode.value}; " +
|
|
||||||
"captcha code: ${captchaCode.value}"
|
|
||||||
)
|
|
||||||
|
|
||||||
processValidation()
|
processValidation()
|
||||||
if (!validationState.value.contains(LoginValidationResult.Valid)) return
|
if (!validationState.value.contains(LoginValidationResult.Valid)) return
|
||||||
|
|
||||||
@@ -207,23 +174,18 @@ class LoginViewModel(
|
|||||||
|
|
||||||
val currentValidationSid = validationSid.value
|
val currentValidationSid = validationSid.value
|
||||||
val currentValidationCode = validationCode.value?.takeIf { currentValidationSid != null }
|
val currentValidationCode = validationCode.value?.takeIf { currentValidationSid != null }
|
||||||
val currentCaptchaSid = captchaSid.value
|
|
||||||
val currentCaptchaCode = captchaCode.value?.takeIf { currentCaptchaSid != null }
|
|
||||||
|
|
||||||
oAuthUseCase.getSilentToken(
|
oAuthUseCase.getSilentToken(
|
||||||
login = currentState.login,
|
login = currentState.login,
|
||||||
password = currentState.password,
|
password = currentState.password,
|
||||||
forceSms = forceSms,
|
forceSms = forceSms,
|
||||||
validationCode = currentValidationCode,
|
validationCode = currentValidationCode,
|
||||||
captchaSid = currentCaptchaSid,
|
|
||||||
captchaKey = currentCaptchaCode
|
|
||||||
).listenValue(viewModelScope) { state ->
|
).listenValue(viewModelScope) { state ->
|
||||||
state.processState(
|
state.processState(
|
||||||
error = { error ->
|
error = { error ->
|
||||||
Log.d("LoginViewModelImpl", "login: error: $error")
|
Log.d("LoginViewModelImpl", "login: error: $error")
|
||||||
|
|
||||||
_screenState.updateValue { copy(isLoading = false) }
|
_screenState.updateValue { copy(isLoading = false) }
|
||||||
captchaSid.setValue { null }
|
|
||||||
|
|
||||||
parseError(error)
|
parseError(error)
|
||||||
},
|
},
|
||||||
@@ -286,7 +248,6 @@ class LoginViewModel(
|
|||||||
|
|
||||||
startLongPoll()
|
startLongPoll()
|
||||||
|
|
||||||
captchaSid.update { null }
|
|
||||||
validationSid.update { null }
|
validationSid.update { null }
|
||||||
|
|
||||||
loadUserByIdUseCase(
|
loadUserByIdUseCase(
|
||||||
@@ -333,11 +294,8 @@ class LoginViewModel(
|
|||||||
|
|
||||||
is OAuthErrorDomain.CaptchaRequiredError -> {
|
is OAuthErrorDomain.CaptchaRequiredError -> {
|
||||||
val arguments = CaptchaArguments(
|
val arguments = CaptchaArguments(
|
||||||
captchaSid = error.captchaSid,
|
redirectUri = error.redirectUri
|
||||||
captchaImageUrl = error.captchaImageUrl
|
|
||||||
)
|
)
|
||||||
_captchaArguments.update { arguments }
|
|
||||||
captchaSid.update { error.captchaSid }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
OAuthErrorDomain.InvalidCredentialsError -> {
|
OAuthErrorDomain.InvalidCredentialsError -> {
|
||||||
|
|||||||
@@ -7,6 +7,5 @@ import kotlinx.serialization.Serializable
|
|||||||
@Serializable
|
@Serializable
|
||||||
@Parcelize
|
@Parcelize
|
||||||
data class CaptchaArguments(
|
data class CaptchaArguments(
|
||||||
val captchaSid: String,
|
val redirectUri: String?
|
||||||
val captchaImageUrl: String
|
|
||||||
) : Parcelable
|
) : Parcelable
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ 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.auth.login.LoginViewModel
|
import dev.meloda.fast.auth.login.LoginViewModel
|
||||||
import dev.meloda.fast.auth.login.model.CaptchaArguments
|
|
||||||
import dev.meloda.fast.auth.login.model.LoginUserBannedArguments
|
import dev.meloda.fast.auth.login.model.LoginUserBannedArguments
|
||||||
import dev.meloda.fast.auth.login.model.LoginValidationArguments
|
import dev.meloda.fast.auth.login.model.LoginValidationArguments
|
||||||
import dev.meloda.fast.auth.login.presentation.LoginRoute
|
import dev.meloda.fast.auth.login.presentation.LoginRoute
|
||||||
@@ -19,7 +18,6 @@ import kotlinx.serialization.Serializable
|
|||||||
object Login
|
object Login
|
||||||
|
|
||||||
fun NavGraphBuilder.loginScreen(
|
fun NavGraphBuilder.loginScreen(
|
||||||
onNavigateToCaptcha: (CaptchaArguments) -> Unit,
|
|
||||||
onNavigateToValidation: (LoginValidationArguments) -> Unit,
|
onNavigateToValidation: (LoginValidationArguments) -> Unit,
|
||||||
onNavigateToMain: () -> Unit,
|
onNavigateToMain: () -> Unit,
|
||||||
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
|
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
|
||||||
@@ -31,7 +29,6 @@ fun NavGraphBuilder.loginScreen(
|
|||||||
backStackEntry.sharedViewModel<LoginViewModel>(navController = navController)
|
backStackEntry.sharedViewModel<LoginViewModel>(navController = navController)
|
||||||
|
|
||||||
val clearValidationCode by viewModel.isNeedToClearValidationCode.collectAsStateWithLifecycle()
|
val clearValidationCode by viewModel.isNeedToClearValidationCode.collectAsStateWithLifecycle()
|
||||||
val clearCaptchaCode by viewModel.isNeedToClearCaptchaCode.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
LaunchedEffect(clearValidationCode) {
|
LaunchedEffect(clearValidationCode) {
|
||||||
if (clearValidationCode) {
|
if (clearValidationCode) {
|
||||||
@@ -40,24 +37,14 @@ fun NavGraphBuilder.loginScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(clearCaptchaCode) {
|
|
||||||
if (clearCaptchaCode) {
|
|
||||||
backStackEntry.savedStateHandle["captcha_code"] = null
|
|
||||||
viewModel.onCaptchaCodeCleared()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val validationCode = backStackEntry.getValidationResult()
|
val validationCode = backStackEntry.getValidationResult()
|
||||||
val captchaCode = backStackEntry.getCaptchaResult()
|
|
||||||
|
|
||||||
LoginRoute(
|
LoginRoute(
|
||||||
onNavigateToUserBanned = onNavigateToUserBanned,
|
onNavigateToUserBanned = onNavigateToUserBanned,
|
||||||
onNavigateToMain = onNavigateToMain,
|
onNavigateToMain = onNavigateToMain,
|
||||||
onNavigateToCaptcha = onNavigateToCaptcha,
|
|
||||||
onNavigateToValidation = onNavigateToValidation,
|
onNavigateToValidation = onNavigateToValidation,
|
||||||
onNavigateToSettings = onNavigateToSettings,
|
onNavigateToSettings = onNavigateToSettings,
|
||||||
validationCode = validationCode,
|
validationCode = validationCode,
|
||||||
captchaCode = captchaCode,
|
|
||||||
viewModel = viewModel
|
viewModel = viewModel
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -66,7 +53,3 @@ fun NavGraphBuilder.loginScreen(
|
|||||||
fun NavBackStackEntry.getValidationResult(): String? {
|
fun NavBackStackEntry.getValidationResult(): String? {
|
||||||
return savedStateHandle["validation_code"]
|
return savedStateHandle["validation_code"]
|
||||||
}
|
}
|
||||||
|
|
||||||
fun NavBackStackEntry.getCaptchaResult(): String? {
|
|
||||||
return savedStateHandle["captcha_code"]
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -75,17 +75,14 @@ import org.koin.androidx.compose.koinViewModel
|
|||||||
fun LoginRoute(
|
fun LoginRoute(
|
||||||
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
|
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
|
||||||
onNavigateToMain: () -> Unit,
|
onNavigateToMain: () -> Unit,
|
||||||
onNavigateToCaptcha: (CaptchaArguments) -> Unit,
|
|
||||||
onNavigateToValidation: (LoginValidationArguments) -> Unit,
|
onNavigateToValidation: (LoginValidationArguments) -> Unit,
|
||||||
onNavigateToSettings: () -> Unit,
|
onNavigateToSettings: () -> Unit,
|
||||||
validationCode: String?,
|
validationCode: String?,
|
||||||
captchaCode: String?,
|
|
||||||
viewModel: LoginViewModel = koinViewModel()
|
viewModel: LoginViewModel = koinViewModel()
|
||||||
) {
|
) {
|
||||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
||||||
val isNeedToOpenMain by viewModel.isNeedToOpenMain.collectAsStateWithLifecycle()
|
val isNeedToOpenMain by viewModel.isNeedToOpenMain.collectAsStateWithLifecycle()
|
||||||
val userBannedArguments by viewModel.userBannedArguments.collectAsStateWithLifecycle()
|
val userBannedArguments by viewModel.userBannedArguments.collectAsStateWithLifecycle()
|
||||||
val captchaArguments by viewModel.captchaArguments.collectAsStateWithLifecycle()
|
|
||||||
val validationArguments by viewModel.validationArguments.collectAsStateWithLifecycle()
|
val validationArguments by viewModel.validationArguments.collectAsStateWithLifecycle()
|
||||||
val loginDialog by viewModel.loginDialog.collectAsStateWithLifecycle()
|
val loginDialog by viewModel.loginDialog.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
@@ -107,12 +104,6 @@ fun LoginRoute(
|
|||||||
onNavigateToUserBanned(arguments)
|
onNavigateToUserBanned(arguments)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LaunchedEffect(captchaArguments) {
|
|
||||||
captchaArguments?.let { arguments ->
|
|
||||||
viewModel.onNavigatedToCaptcha()
|
|
||||||
onNavigateToCaptcha(arguments)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LaunchedEffect(validationArguments) {
|
LaunchedEffect(validationArguments) {
|
||||||
validationArguments?.let { arguments ->
|
validationArguments?.let { arguments ->
|
||||||
viewModel.onNavigatedToValidation()
|
viewModel.onNavigatedToValidation()
|
||||||
@@ -122,9 +113,6 @@ fun LoginRoute(
|
|||||||
LaunchedEffect(validationCode) {
|
LaunchedEffect(validationCode) {
|
||||||
viewModel.onValidationCodeReceived(validationCode)
|
viewModel.onValidationCodeReceived(validationCode)
|
||||||
}
|
}
|
||||||
LaunchedEffect(captchaCode) {
|
|
||||||
viewModel.onCaptchaCodeReceived(captchaCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
LoginScreen(
|
LoginScreen(
|
||||||
screenState = screenState,
|
screenState = screenState,
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import androidx.lifecycle.SavedStateHandle
|
|||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import dev.meloda.fast.auth.validation.model.ValidationScreenState
|
import dev.meloda.fast.auth.validation.model.ValidationScreenState
|
||||||
import dev.meloda.fast.auth.validation.model.ValidationType
|
|
||||||
import dev.meloda.fast.auth.validation.navigation.Validation
|
import dev.meloda.fast.auth.validation.navigation.Validation
|
||||||
import dev.meloda.fast.auth.validation.validation.ValidationValidator
|
import dev.meloda.fast.auth.validation.validation.ValidationValidator
|
||||||
import dev.meloda.fast.common.extensions.createTimerFlow
|
import dev.meloda.fast.common.extensions.createTimerFlow
|
||||||
@@ -12,6 +11,7 @@ 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.processState
|
import dev.meloda.fast.data.processState
|
||||||
import dev.meloda.fast.domain.AuthUseCase
|
import dev.meloda.fast.domain.AuthUseCase
|
||||||
|
import dev.meloda.fast.network.ValidationType
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
package dev.meloda.fast.auth.validation.model
|
|
||||||
|
|
||||||
enum class ValidationType(val value: String) {
|
|
||||||
SMS("sms"), APP("2fa_app");
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
fun parse(value: String): ValidationType = entries.firstOrNull { it.value == value }
|
|
||||||
?: throw IllegalArgumentException("Unknown validation type with value: $value")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+2
-3
@@ -47,13 +47,12 @@ import androidx.compose.ui.semantics.semantics
|
|||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.text.input.TextFieldValue
|
import androidx.compose.ui.text.input.TextFieldValue
|
||||||
import androidx.compose.ui.tooling.preview.Preview
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import dev.meloda.fast.auth.validation.ValidationViewModel
|
import dev.meloda.fast.auth.validation.ValidationViewModel
|
||||||
import dev.meloda.fast.auth.validation.ValidationViewModelImpl
|
import dev.meloda.fast.auth.validation.ValidationViewModelImpl
|
||||||
import dev.meloda.fast.auth.validation.model.ValidationScreenState
|
import dev.meloda.fast.auth.validation.model.ValidationScreenState
|
||||||
import dev.meloda.fast.auth.validation.model.ValidationType
|
import dev.meloda.fast.network.ValidationType
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
import dev.meloda.fast.ui.common.FastPreview
|
import dev.meloda.fast.ui.common.FastPreview
|
||||||
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
||||||
@@ -119,7 +118,7 @@ fun ValidationScreen(
|
|||||||
val validationText by remember(validationType) {
|
val validationText by remember(validationType) {
|
||||||
mutableStateOf(
|
mutableStateOf(
|
||||||
when (validationType) {
|
when (validationType) {
|
||||||
ValidationType.SMS -> "SMS with the code is sent to ${screenState.phoneMask}"
|
ValidationType.SMS, ValidationType.SMS2 -> "SMS with the code is sent to ${screenState.phoneMask}"
|
||||||
ValidationType.APP -> "Enter the code from the code generator application"
|
ValidationType.APP -> "Enter the code from the code generator application"
|
||||||
|
|
||||||
null -> ""
|
null -> ""
|
||||||
|
|||||||
+17
-47
@@ -9,12 +9,16 @@ import dev.meloda.fast.chatmaterials.navigation.ChatMaterials
|
|||||||
import dev.meloda.fast.chatmaterials.util.asPresentation
|
import dev.meloda.fast.chatmaterials.util.asPresentation
|
||||||
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.paging.canPaginate as canPaginatePage
|
||||||
|
import dev.meloda.fast.common.paging.isPaginationExhausted as isPaginationExhaustedPage
|
||||||
|
import dev.meloda.fast.common.paging.loadingFlags
|
||||||
|
import dev.meloda.fast.common.paging.mergePage
|
||||||
import dev.meloda.fast.data.State
|
import dev.meloda.fast.data.State
|
||||||
|
import dev.meloda.fast.data.VkUtils
|
||||||
import dev.meloda.fast.data.processState
|
import dev.meloda.fast.data.processState
|
||||||
import dev.meloda.fast.domain.MessagesUseCase
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
import dev.meloda.fast.model.BaseError
|
import dev.meloda.fast.model.BaseError
|
||||||
import dev.meloda.fast.model.api.domain.VkAttachmentHistoryMessage
|
import dev.meloda.fast.model.api.domain.VkAttachmentHistoryMessage
|
||||||
import dev.meloda.fast.network.VkErrorCode
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
@@ -89,11 +93,14 @@ class ChatMaterialsViewModelImpl(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = ::handleError,
|
error = ::handleError,
|
||||||
success = { response ->
|
success = { response ->
|
||||||
val itemsCountSufficient = response.size == LOAD_COUNT
|
val itemsCountSufficient = canPaginatePage(LOAD_COUNT, response.size)
|
||||||
canPaginate.setValue { itemsCountSufficient }
|
canPaginate.setValue { itemsCountSufficient }
|
||||||
|
|
||||||
val paginationExhausted = !itemsCountSufficient
|
val paginationExhausted = isPaginationExhaustedPage(
|
||||||
&& screenState.value.materials.isNotEmpty()
|
pageSize = LOAD_COUNT,
|
||||||
|
loadedCount = response.size,
|
||||||
|
hasExistingItems = screenState.value.materials.isNotEmpty()
|
||||||
|
)
|
||||||
|
|
||||||
val loadedMaterials = response.mapNotNull(VkAttachmentHistoryMessage::asPresentation)
|
val loadedMaterials = response.mapNotNull(VkAttachmentHistoryMessage::asPresentation)
|
||||||
|
|
||||||
@@ -107,64 +114,27 @@ class ChatMaterialsViewModelImpl(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
if (offset == 0) {
|
|
||||||
screenState.setValue {
|
|
||||||
newState.copy(materials = loadedMaterials)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
screenState.setValue {
|
screenState.setValue {
|
||||||
newState.copy(
|
newState.copy(
|
||||||
materials = newState.materials.plus(loadedMaterials)
|
materials = mergePage(newState.materials, loadedMaterials, offset)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val flags = loadingFlags(offset, state.isLoading())
|
||||||
screenState.setValue { old ->
|
screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
isLoading = offset == 0 && state.isLoading(),
|
isLoading = flags.isLoading,
|
||||||
isPaginating = offset > 0 && state.isLoading()
|
isPaginating = flags.isPaginating
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleError(error: State.Error) {
|
private fun handleError(error: State.Error) {
|
||||||
when (error) {
|
VkUtils.parseError(error)?.let { newBaseError ->
|
||||||
is State.Error.ApiError -> {
|
baseError.setValue { newBaseError }
|
||||||
when (error.errorCode) {
|
|
||||||
VkErrorCode.USER_AUTHORIZATION_FAILED -> {
|
|
||||||
baseError.setValue { BaseError.SessionExpired }
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = error.errorMessage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.ConnectionError -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Connection error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.InternalError -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Internal error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.UnknownError -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Unknown error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,12 +8,16 @@ 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.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.launchDbRefresh
|
||||||
import dev.meloda.fast.common.extensions.updateValue
|
import dev.meloda.fast.common.extensions.updateValue
|
||||||
|
import dev.meloda.fast.common.paging.canPaginate as canPaginatePage
|
||||||
|
import dev.meloda.fast.common.paging.isPaginationExhausted as isPaginationExhaustedPage
|
||||||
|
import dev.meloda.fast.common.paging.loadingFlags
|
||||||
|
import dev.meloda.fast.common.paging.mergePage
|
||||||
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.ConvoNavigation
|
||||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||||
@@ -23,8 +27,7 @@ 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.LongPollUpdatesReducer
|
||||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
|
||||||
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
|
||||||
@@ -40,20 +43,21 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
|||||||
import kotlinx.coroutines.flow.SharingStarted
|
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.onEach
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
class ConvosViewModel(
|
class ConvosViewModel(
|
||||||
updatesParser: LongPollUpdatesParser,
|
updatesReducer: LongPollUpdatesReducer,
|
||||||
private val filter: ConvosFilter,
|
private 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
|
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
private val _screenState = MutableStateFlow(ConvosScreenState.EMPTY)
|
private val _screenState = MutableStateFlow(ConvosScreenState.EMPTY)
|
||||||
val screenState = _screenState.asStateFlow()
|
val screenState = _screenState.asStateFlow()
|
||||||
@@ -94,15 +98,15 @@ class ConvosViewModel(
|
|||||||
|
|
||||||
loadConvos()
|
loadConvos()
|
||||||
|
|
||||||
updatesParser.onNewMessage(::handleNewMessage)
|
updatesReducer.newMessages.onEach(::handleNewMessage).launchIn(viewModelScope)
|
||||||
updatesParser.onMessageEdited(::handleEditedMessage)
|
updatesReducer.messageEdited.onEach(::handleEditedMessage).launchIn(viewModelScope)
|
||||||
updatesParser.onMessageIncomingRead(::handleReadIncomingMessage)
|
updatesReducer.messageIncomingRead.onEach(::handleReadIncomingMessage).launchIn(viewModelScope)
|
||||||
updatesParser.onMessageOutgoingRead(::handleReadOutgoingMessage)
|
updatesReducer.messageOutgoingRead.onEach(::handleReadOutgoingMessage).launchIn(viewModelScope)
|
||||||
updatesParser.onInteractions(::handleInteraction)
|
updatesReducer.interactions.onEach(::handleInteraction).launchIn(viewModelScope)
|
||||||
updatesParser.onChatMajorChanged(::handleChatMajorChanged)
|
updatesReducer.chatMajorChanged.onEach(::handleChatMajorChanged).launchIn(viewModelScope)
|
||||||
updatesParser.onChatMinorChanged(::handleChatMinorChanged)
|
updatesReducer.chatMinorChanged.onEach(::handleChatMinorChanged).launchIn(viewModelScope)
|
||||||
updatesParser.onChatCleared(::handleChatClearing)
|
updatesReducer.chatCleared.onEach(::handleChatClearing).launchIn(viewModelScope)
|
||||||
updatesParser.onChatArchived(::handleChatArchived)
|
updatesReducer.chatArchived.onEach(::handleChatArchived).launchIn(viewModelScope)
|
||||||
|
|
||||||
userSettings.useContactNames.listenValue(viewModelScope) {
|
userSettings.useContactNames.listenValue(viewModelScope) {
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
@@ -253,6 +257,10 @@ class ConvosViewModel(
|
|||||||
private fun loadConvos(
|
private fun loadConvos(
|
||||||
offset: Int = currentOffset.value
|
offset: Int = currentOffset.value
|
||||||
) {
|
) {
|
||||||
|
if (offset == 0) {
|
||||||
|
refreshConvosFromDb()
|
||||||
|
}
|
||||||
|
|
||||||
convoUseCase.getConvos(
|
convoUseCase.getConvos(
|
||||||
count = LOAD_COUNT,
|
count = LOAD_COUNT,
|
||||||
offset = offset,
|
offset = offset,
|
||||||
@@ -264,17 +272,12 @@ class ConvosViewModel(
|
|||||||
_baseError.update { newBaseError }
|
_baseError.update { newBaseError }
|
||||||
},
|
},
|
||||||
success = { response ->
|
success = { response ->
|
||||||
val convos = response
|
val itemsCountSufficient = canPaginatePage(LOAD_COUNT, response.size)
|
||||||
val fullConvos = if (offset == 0) {
|
val paginationExhausted = isPaginationExhaustedPage(
|
||||||
convos
|
pageSize = LOAD_COUNT,
|
||||||
} else {
|
loadedCount = response.size,
|
||||||
this.convos.value.plus(convos)
|
hasExistingItems = this.convos.value.isNotEmpty()
|
||||||
}
|
)
|
||||||
|
|
||||||
val itemsCountSufficient = response.size == LOAD_COUNT
|
|
||||||
|
|
||||||
val paginationExhausted = !itemsCountSufficient &&
|
|
||||||
this.convos.value.isNotEmpty()
|
|
||||||
|
|
||||||
_screenState.updateValue {
|
_screenState.updateValue {
|
||||||
copy(isPaginationExhausted = paginationExhausted)
|
copy(isPaginationExhausted = paginationExhausted)
|
||||||
@@ -293,16 +296,17 @@ class ConvosViewModel(
|
|||||||
|
|
||||||
convoUseCase.storeConvos(response)
|
convoUseCase.storeConvos(response)
|
||||||
|
|
||||||
_convos.emit(fullConvos)
|
_convos.emit(mergePage(this.convos.value, response, offset))
|
||||||
syncUiConvos()
|
syncUiConvos()
|
||||||
_canPaginate.setValue { itemsCountSufficient }
|
_canPaginate.setValue { itemsCountSufficient }
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val flags = loadingFlags(offset, state.isLoading())
|
||||||
_screenState.setValue { old ->
|
_screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
isLoading = offset == 0 && state.isLoading(),
|
isLoading = flags.isLoading,
|
||||||
isPaginating = offset > 0 && state.isLoading()
|
isPaginating = flags.isPaginating
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -313,14 +317,10 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
val newConvos = convos.value.toMutableList()
|
viewModelScope.launch {
|
||||||
val convoIndex =
|
convoUseCase.deleteLocalConvo(peerId)
|
||||||
newConvos.indexOfFirstOrNull { it.id == peerId }
|
refreshConvosFromDb()
|
||||||
?: return@processState
|
}
|
||||||
|
|
||||||
newConvos.removeAt(convoIndex)
|
|
||||||
_convos.update { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
_screenState.emit(screenState.value.copy(isLoading = state.isLoading()))
|
_screenState.emit(screenState.value.copy(isLoading = state.isLoading()))
|
||||||
@@ -333,9 +333,11 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
handleChatMajorChanged(
|
viewModelScope.launch {
|
||||||
LongPollParsedEvent.ChatMajorChanged(
|
convoUseCase.getLocalConvoById(peerId)?.let { convo ->
|
||||||
peerId = peerId,
|
convoUseCase.storeConvos(
|
||||||
|
listOf(
|
||||||
|
convo.copy(
|
||||||
majorId = if (pin) {
|
majorId = if (pin) {
|
||||||
pinnedConvosCount.value.plus(1) * 16
|
pinnedConvosCount.value.plus(1) * 16
|
||||||
} else {
|
} else {
|
||||||
@@ -343,6 +345,10 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
refreshConvosFromDb()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -356,145 +362,35 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
convos.value.find { it.id == peerId }?.let { convo ->
|
viewModelScope.launch {
|
||||||
handleChatArchived(
|
convoUseCase.getLocalConvoById(peerId)?.let { convo ->
|
||||||
LongPollParsedEvent.ChatArchived(
|
convoUseCase.storeConvos(
|
||||||
convo = convo,
|
listOf(
|
||||||
archived = archive
|
convo.copy(isArchived = archive)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
refreshConvosFromDb()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: 03-Apr-25, Danil Nikolaev: handle business messages
|
|
||||||
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
|
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
|
||||||
val message = event.message
|
refreshConvosFromDb()
|
||||||
|
|
||||||
val newConvos = convos.value.toMutableList()
|
|
||||||
val convoIndex =
|
|
||||||
newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
|
||||||
|
|
||||||
if (convoIndex == null) {
|
|
||||||
if (event.inArchive != (filter == ConvosFilter.ARCHIVE)) return
|
|
||||||
|
|
||||||
loadConvosByIdUseCase(
|
|
||||||
peerIds = listOf(message.peerId),
|
|
||||||
extended = true,
|
|
||||||
fields = VkConstants.ALL_FIELDS
|
|
||||||
).listenValue(viewModelScope) { state ->
|
|
||||||
state.processState(
|
|
||||||
error = {},
|
|
||||||
success = { response ->
|
|
||||||
val convo = (response.firstOrNull() ?: return@listenValue)
|
|
||||||
.copy(lastMessage = message)
|
|
||||||
|
|
||||||
newConvos.add(pinnedConvosCount.value, convo)
|
|
||||||
_convos.update { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
val convo = newConvos[convoIndex]
|
|
||||||
var newConvo = convo.copy(
|
|
||||||
lastMessage = message,
|
|
||||||
lastMessageId = message.id,
|
|
||||||
lastCmId = message.cmId,
|
|
||||||
unreadCount = if (message.isOut) convo.unreadCount
|
|
||||||
else convo.unreadCount + 1
|
|
||||||
)
|
|
||||||
|
|
||||||
interactionsTimers[convo.id]?.let { job ->
|
|
||||||
if (job.interactionType == InteractionType.Typing
|
|
||||||
&& message.fromId in convo.interactionIds
|
|
||||||
) {
|
|
||||||
val newInteractionIds = newConvo.interactionIds.filter { id ->
|
|
||||||
id != message.fromId
|
|
||||||
}
|
|
||||||
|
|
||||||
newConvo = newConvo.copy(
|
|
||||||
interactionType = if (newInteractionIds.isEmpty()) -1 else {
|
|
||||||
newConvo.interactionType
|
|
||||||
},
|
|
||||||
interactionIds = newInteractionIds
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (convo.isPinned()) {
|
|
||||||
newConvos[convoIndex] = newConvo
|
|
||||||
} else {
|
|
||||||
newConvos.removeAt(convoIndex)
|
|
||||||
|
|
||||||
val toPosition = pinnedConvosCount.value
|
|
||||||
newConvos.add(toPosition, newConvo)
|
|
||||||
}
|
|
||||||
|
|
||||||
_convos.update { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) {
|
private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) {
|
||||||
val message = event.message
|
refreshConvosFromDb()
|
||||||
val newConvos = convos.value.toMutableList()
|
|
||||||
|
|
||||||
val convoIndex = newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
|
||||||
// pizdets
|
|
||||||
} else {
|
|
||||||
val convo = newConvos[convoIndex]
|
|
||||||
newConvos[convoIndex] = convo.copy(
|
|
||||||
lastMessage = message,
|
|
||||||
lastMessageId = message.id,
|
|
||||||
lastCmId = message.cmId
|
|
||||||
)
|
|
||||||
_convos.update { newConvos }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) {
|
private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) {
|
||||||
val newConvos = convos.value.toMutableList()
|
refreshConvosFromDb()
|
||||||
|
|
||||||
val convoIndex =
|
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
|
||||||
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
|
||||||
// pizdets
|
|
||||||
} else {
|
|
||||||
newConvos[convoIndex] =
|
|
||||||
newConvos[convoIndex].copy(
|
|
||||||
inReadCmId = event.cmId,
|
|
||||||
unreadCount = event.unreadCount
|
|
||||||
)
|
|
||||||
|
|
||||||
_convos.update { newConvos }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) {
|
private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) {
|
||||||
val newConvos = convos.value.toMutableList()
|
refreshConvosFromDb()
|
||||||
|
|
||||||
val convoIndex =
|
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
|
||||||
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
|
||||||
// pizdets
|
|
||||||
} else {
|
|
||||||
newConvos[convoIndex] =
|
|
||||||
newConvos[convoIndex].copy(
|
|
||||||
outReadCmId = event.cmId,
|
|
||||||
unreadCount = event.unreadCount
|
|
||||||
)
|
|
||||||
|
|
||||||
_convos.update { newConvos }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleInteraction(event: LongPollParsedEvent.Interaction) {
|
private fun handleInteraction(event: LongPollParsedEvent.Interaction) {
|
||||||
@@ -563,88 +459,19 @@ class ConvosViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) {
|
private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) {
|
||||||
val newConvos = convos.value.toMutableList()
|
refreshConvosFromDb()
|
||||||
val convoIndex =
|
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
|
||||||
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
|
||||||
// pizdets
|
|
||||||
} else {
|
|
||||||
newConvos[convoIndex] =
|
|
||||||
newConvos[convoIndex].copy(majorId = event.majorId)
|
|
||||||
|
|
||||||
_convos.setValue { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) {
|
private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) {
|
||||||
val newConvos = convos.value.toMutableList()
|
refreshConvosFromDb()
|
||||||
val convoIndex =
|
|
||||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
|
||||||
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
|
||||||
// pizdets
|
|
||||||
} else {
|
|
||||||
newConvos[convoIndex] =
|
|
||||||
newConvos[convoIndex].copy(minorId = event.minorId)
|
|
||||||
|
|
||||||
_convos.setValue { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) {
|
private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) {
|
||||||
val newConvos = convos.value.toMutableList()
|
refreshConvosFromDb()
|
||||||
|
|
||||||
val convoIndex = newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
|
||||||
|
|
||||||
if (convoIndex == null) { // диалога нет в списке
|
|
||||||
// pizdets
|
|
||||||
} else {
|
|
||||||
newConvos.removeAt(convoIndex)
|
|
||||||
|
|
||||||
_convos.setValue { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) {
|
private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) {
|
||||||
val convo = event.convo
|
refreshConvosFromDb()
|
||||||
|
|
||||||
val newConvos = convos.value.toMutableList()
|
|
||||||
|
|
||||||
when (filter) {
|
|
||||||
ConvosFilter.BUSINESS_NOTIFY -> Unit
|
|
||||||
|
|
||||||
ConvosFilter.ARCHIVE -> {
|
|
||||||
if (event.archived) {
|
|
||||||
newConvos.add(0, convo)
|
|
||||||
} else {
|
|
||||||
val index = newConvos.indexOfFirstOrNull { it.id == convo.id }
|
|
||||||
if (index == null) return
|
|
||||||
|
|
||||||
newConvos.removeAt(index)
|
|
||||||
}
|
|
||||||
|
|
||||||
_convos.update { newConvos }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
if (event.archived) {
|
|
||||||
val index = newConvos.indexOfFirstOrNull { it.id == convo.id }
|
|
||||||
if (index == null) return
|
|
||||||
|
|
||||||
newConvos.removeAt(index)
|
|
||||||
} else {
|
|
||||||
newConvos.add(pinnedConvosCount.value, convo)
|
|
||||||
}
|
|
||||||
|
|
||||||
_convos.update { newConvos.sorted() }
|
|
||||||
syncUiConvos()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun readConvo(peerId: Long, startMessageId: Long) {
|
private fun readConvo(peerId: Long, startMessageId: Long) {
|
||||||
@@ -655,21 +482,42 @@ class ConvosViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = {},
|
error = {},
|
||||||
success = {
|
success = {
|
||||||
val newConvos = convos.value.toMutableList()
|
viewModelScope.launch {
|
||||||
val convoIndex =
|
convoUseCase.getLocalConvoById(peerId)?.let { convo ->
|
||||||
newConvos.indexOfFirstOrNull { it.id == peerId }
|
convoUseCase.storeConvos(
|
||||||
?: return@listenValue
|
listOf(
|
||||||
|
convo.copy(
|
||||||
newConvos[convoIndex] =
|
inRead = startMessageId,
|
||||||
newConvos[convoIndex].copy(inRead = startMessageId)
|
unreadCount = 0
|
||||||
|
)
|
||||||
_convos.update { newConvos }
|
)
|
||||||
syncUiConvos()
|
)
|
||||||
|
}
|
||||||
|
refreshConvosFromDb()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun refreshConvosFromDb() {
|
||||||
|
viewModelScope.launchDbRefresh(
|
||||||
|
load = {
|
||||||
|
val localConvos = convoUseCase.getLocalConvos()
|
||||||
|
|
||||||
|
val filteredConvos = when (filter) {
|
||||||
|
ConvosFilter.ARCHIVE -> localConvos.filter(VkConvo::isArchived)
|
||||||
|
ConvosFilter.UNREAD -> localConvos.filter { !it.isArchived && it.unreadCount > 0 }
|
||||||
|
ConvosFilter.ALL -> localConvos.filterNot(VkConvo::isArchived)
|
||||||
|
ConvosFilter.BUSINESS_NOTIFY -> localConvos
|
||||||
|
}
|
||||||
|
|
||||||
|
_convos.emit(filteredConvos)
|
||||||
|
},
|
||||||
|
after = ::syncUiConvos
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
private fun List<VkConvo>.sorted(): List<VkConvo> {
|
private fun List<VkConvo>.sorted(): List<VkConvo> {
|
||||||
val newConvos = toMutableList()
|
val newConvos = toMutableList()
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ private fun Scope.createConvosViewModel(filter: ConvosFilter): ConvosViewModel {
|
|||||||
resources = get(),
|
resources = get(),
|
||||||
userSettings = get(),
|
userSettings = get(),
|
||||||
imageLoader = get(),
|
imageLoader = get(),
|
||||||
applicationContext = get(),
|
applicationContext = get()
|
||||||
loadConvosByIdUseCase = get()
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,9 +7,14 @@ import coil.ImageLoader
|
|||||||
import coil.request.ImageRequest
|
import coil.request.ImageRequest
|
||||||
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.paging.canPaginate as canPaginatePage
|
||||||
|
import dev.meloda.fast.common.paging.isPaginationExhausted as isPaginationExhaustedPage
|
||||||
|
import dev.meloda.fast.common.paging.loadingFlags
|
||||||
|
import dev.meloda.fast.common.paging.mergePage
|
||||||
import dev.meloda.fast.convos.model.CreateChatScreenState
|
import dev.meloda.fast.convos.model.CreateChatScreenState
|
||||||
import dev.meloda.fast.data.State
|
import dev.meloda.fast.data.State
|
||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
|
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.FriendsUseCase
|
import dev.meloda.fast.domain.FriendsUseCase
|
||||||
@@ -18,7 +23,6 @@ import dev.meloda.fast.domain.MessagesUseCase
|
|||||||
import dev.meloda.fast.domain.util.asPresentation
|
import dev.meloda.fast.domain.util.asPresentation
|
||||||
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.network.VkErrorCode
|
|
||||||
import dev.meloda.fast.ui.model.vk.UiFriend
|
import dev.meloda.fast.ui.model.vk.UiFriend
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -156,11 +160,14 @@ class CreateChatViewModel(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = ::handleError,
|
error = ::handleError,
|
||||||
success = { response ->
|
success = { response ->
|
||||||
val itemsCountSufficient = response.size == LOAD_COUNT
|
val itemsCountSufficient = canPaginatePage(LOAD_COUNT, response.size)
|
||||||
_canPaginate.setValue { itemsCountSufficient }
|
_canPaginate.setValue { itemsCountSufficient }
|
||||||
|
|
||||||
val paginationExhausted = !itemsCountSufficient &&
|
val paginationExhausted = isPaginationExhaustedPage(
|
||||||
screenState.value.friends.isNotEmpty()
|
pageSize = LOAD_COUNT,
|
||||||
|
loadedCount = response.size,
|
||||||
|
hasExistingItems = screenState.value.friends.isNotEmpty()
|
||||||
|
)
|
||||||
|
|
||||||
val imagesToPreload =
|
val imagesToPreload =
|
||||||
response.mapNotNull { it.photo100.takeIf { p -> !p.isNullOrEmpty() } }
|
response.mapNotNull { it.photo100.takeIf { p -> !p.isNullOrEmpty() } }
|
||||||
@@ -182,24 +189,19 @@ class CreateChatViewModel(
|
|||||||
val newState = screenState.value.copy(
|
val newState = screenState.value.copy(
|
||||||
isPaginationExhausted = paginationExhausted
|
isPaginationExhausted = paginationExhausted
|
||||||
)
|
)
|
||||||
if (offset == 0) {
|
|
||||||
_screenState.setValue {
|
|
||||||
newState.copy(friends = loadedFriends)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
_screenState.setValue {
|
_screenState.setValue {
|
||||||
newState.copy(
|
newState.copy(
|
||||||
friends = newState.friends.plus(loadedFriends)
|
friends = mergePage(newState.friends, loadedFriends, offset)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val flags = loadingFlags(offset, state.isLoading())
|
||||||
_screenState.setValue { old ->
|
_screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
isLoading = offset == 0 && state.isLoading(),
|
isLoading = flags.isLoading,
|
||||||
isPaginating = offset > 0 && state.isLoading()
|
isPaginating = flags.isPaginating
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,40 +230,8 @@ class CreateChatViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun handleError(error: State.Error) {
|
private fun handleError(error: State.Error) {
|
||||||
when (error) {
|
VkUtils.parseError(error)?.let { newBaseError ->
|
||||||
is State.Error.ApiError -> {
|
_baseError.setValue { newBaseError }
|
||||||
when (error.errorCode) {
|
|
||||||
VkErrorCode.USER_AUTHORIZATION_FAILED -> {
|
|
||||||
_baseError.setValue { BaseError.SessionExpired }
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
_baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = error.errorMessage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.ConnectionError -> {
|
|
||||||
_baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Connection error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.InternalError -> {
|
|
||||||
_baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Internal error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.UnknownError -> {
|
|
||||||
_baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Unknown error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,12 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
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.paging.canPaginate as canPaginatePage
|
||||||
|
import dev.meloda.fast.common.paging.isPaginationExhausted as isPaginationExhaustedPage
|
||||||
|
import dev.meloda.fast.common.paging.loadingFlags
|
||||||
|
import dev.meloda.fast.common.paging.mergePage
|
||||||
import dev.meloda.fast.data.State
|
import dev.meloda.fast.data.State
|
||||||
|
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.FriendsUseCase
|
import dev.meloda.fast.domain.FriendsUseCase
|
||||||
@@ -13,7 +18,6 @@ import dev.meloda.fast.domain.util.asPresentation
|
|||||||
import dev.meloda.fast.friends.model.FriendsScreenState
|
import dev.meloda.fast.friends.model.FriendsScreenState
|
||||||
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.network.VkErrorCode
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
@@ -80,40 +84,8 @@ abstract class BaseFriendsViewModelImpl : ViewModel(), FriendsViewModel {
|
|||||||
abstract fun loadFriends(offset: Int = currentOffset.value)
|
abstract fun loadFriends(offset: Int = currentOffset.value)
|
||||||
|
|
||||||
protected fun handleError(error: State.Error) {
|
protected fun handleError(error: State.Error) {
|
||||||
when (error) {
|
VkUtils.parseError(error)?.let { newBaseError ->
|
||||||
is State.Error.ApiError -> {
|
baseError.setValue { newBaseError }
|
||||||
when (error.errorCode) {
|
|
||||||
VkErrorCode.USER_AUTHORIZATION_FAILED -> {
|
|
||||||
baseError.setValue { BaseError.SessionExpired }
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = error.errorMessage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.ConnectionError -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Connection error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.InternalError -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Internal error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
State.Error.UnknownError -> {
|
|
||||||
baseError.setValue {
|
|
||||||
BaseError.SimpleError(message = "Unknown error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> Unit
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,11 +126,14 @@ class FriendsViewModelImpl(
|
|||||||
state.processState(
|
state.processState(
|
||||||
error = ::handleError,
|
error = ::handleError,
|
||||||
success = { response ->
|
success = { response ->
|
||||||
val itemsCountSufficient = response.size == LOAD_COUNT
|
val itemsCountSufficient = canPaginatePage(LOAD_COUNT, response.size)
|
||||||
canPaginate.setValue { itemsCountSufficient }
|
canPaginate.setValue { itemsCountSufficient }
|
||||||
|
|
||||||
val paginationExhausted = !itemsCountSufficient
|
val paginationExhausted = isPaginationExhaustedPage(
|
||||||
&& screenState.value.friends.isNotEmpty()
|
pageSize = LOAD_COUNT,
|
||||||
|
loadedCount = response.size,
|
||||||
|
hasExistingItems = screenState.value.friends.isNotEmpty()
|
||||||
|
)
|
||||||
|
|
||||||
imagesToPreload.setValue {
|
imagesToPreload.setValue {
|
||||||
response.mapNotNull(VkUser::photo100)
|
response.mapNotNull(VkUser::photo100)
|
||||||
@@ -174,24 +149,20 @@ class FriendsViewModelImpl(
|
|||||||
isPaginationExhausted = paginationExhausted
|
isPaginationExhausted = paginationExhausted
|
||||||
)
|
)
|
||||||
|
|
||||||
if (offset == 0) {
|
friends.emit(mergePage(friends.value, response, offset))
|
||||||
friends.emit(response)
|
|
||||||
screenState.setValue {
|
screenState.setValue {
|
||||||
newState.copy(friends = loadedFriends)
|
newState.copy(
|
||||||
}
|
friends = mergePage(newState.friends, loadedFriends, offset)
|
||||||
} else {
|
)
|
||||||
friends.emit(friends.value.plus(response))
|
|
||||||
screenState.setValue {
|
|
||||||
newState.copy(friends = newState.friends.plus(loadedFriends))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val flags = loadingFlags(offset, state.isLoading())
|
||||||
screenState.setValue { old ->
|
screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
isLoading = offset == 0 && state.isLoading(),
|
isLoading = flags.isLoading,
|
||||||
isPaginating = offset > 0 && state.isLoading()
|
isPaginating = flags.isPaginating
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,10 +200,14 @@ class OnlineFriendsViewModelImpl(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val flags = loadingFlags(
|
||||||
|
offset = offset,
|
||||||
|
isLoading = onlineState.isLoading() || state.isLoading()
|
||||||
|
)
|
||||||
screenState.setValue { old ->
|
screenState.setValue { old ->
|
||||||
old.copy(
|
old.copy(
|
||||||
isLoading = offset == 0 && (onlineState.isLoading() || state.isLoading()),
|
isLoading = flags.isLoading,
|
||||||
isPaginating = offset > 0 && (onlineState.isLoading() || state.isLoading())
|
isPaginating = flags.isPaginating
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+267
@@ -0,0 +1,267 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import com.conena.nanokt.collections.indexOfFirstOrNull
|
||||||
|
import dev.meloda.fast.common.extensions.getParcelableCompat
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessageDialog
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessageOption
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import dev.meloda.fast.ui.model.vk.MessageUiItem
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
||||||
|
internal class MessagesHistoryInteractionHandler(
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>,
|
||||||
|
private val messages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val dialog: MutableStateFlow<MessageDialog?>,
|
||||||
|
private val selectedMessages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val uiMessages: MutableStateFlow<List<MessageUiItem>>,
|
||||||
|
private val isNeedToScrollToIndex: MutableStateFlow<Int?>,
|
||||||
|
private val messageActions: MessagesHistoryMessageActions,
|
||||||
|
private val messageTransportActions: MessagesHistoryMessageTransportActions,
|
||||||
|
private val syncUiMessages: () -> Unit
|
||||||
|
) {
|
||||||
|
fun onDialogConfirmed(dialog: MessageDialog, bundle: Bundle) {
|
||||||
|
onDialogDismissed(dialog)
|
||||||
|
|
||||||
|
when (dialog) {
|
||||||
|
is MessageDialog.MessageOptions -> Unit
|
||||||
|
|
||||||
|
is MessageDialog.MessageDelete -> {
|
||||||
|
val deleteForEveryone = bundle.getBoolean("everyone")
|
||||||
|
|
||||||
|
if (dialog.message.id <= 0) {
|
||||||
|
val newMessages = messages.value.toMutableList()
|
||||||
|
newMessages.remove(dialog.message)
|
||||||
|
messages.setValue { newMessages }
|
||||||
|
syncUiMessages()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
messageTransportActions.deleteMessage(
|
||||||
|
messageIds = listOf(dialog.message.id),
|
||||||
|
deleteForAll = deleteForEveryone
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is MessageDialog.MessagesDelete -> {
|
||||||
|
val deleteForEveryone = bundle.getBoolean("everyone")
|
||||||
|
|
||||||
|
val failedMessages = dialog.messages.filter { it.id <= 0 }
|
||||||
|
val messageIdsToDelete =
|
||||||
|
dialog.messages
|
||||||
|
.filter { it.id > 0 }
|
||||||
|
.map(VkMessage::id)
|
||||||
|
|
||||||
|
messageTransportActions.deleteMessage(
|
||||||
|
messageIds = messageIdsToDelete,
|
||||||
|
deleteForAll = deleteForEveryone,
|
||||||
|
onSuccess = {
|
||||||
|
val newMessages = messages.value.toMutableList()
|
||||||
|
newMessages.removeAll(failedMessages)
|
||||||
|
messages.setValue { newMessages }
|
||||||
|
selectedMessages.setValue { emptyList() }
|
||||||
|
syncUiMessages()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is MessageDialog.MessagePin -> {
|
||||||
|
messageTransportActions.pinMessage(dialog.messageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is MessageDialog.MessageUnpin -> {
|
||||||
|
messageTransportActions.unpinMessage(dialog.messageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
is MessageDialog.MessageMarkImportance -> {
|
||||||
|
messageTransportActions.markAsImportant(
|
||||||
|
messageIds = listOf(dialog.message.id),
|
||||||
|
important = dialog.isImportant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is MessageDialog.MessageSpam -> {
|
||||||
|
if (dialog.isSpam) {
|
||||||
|
messageTransportActions.deleteMessage(
|
||||||
|
messageIds = listOf(dialog.message.id),
|
||||||
|
spam = true
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// TODO: 29-Mar-25, Danil Nikolaev: report as not spam
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onDialogDismissed(dialog: MessageDialog) {
|
||||||
|
this.dialog.setValue { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onDialogItemPicked(dialog: MessageDialog, bundle: Bundle) {
|
||||||
|
when (dialog) {
|
||||||
|
is MessageDialog.MessageOptions -> {
|
||||||
|
val cmId = bundle.getLong("cmId")
|
||||||
|
|
||||||
|
when (val option = bundle.getParcelableCompat("option", MessageOption::class)) {
|
||||||
|
null -> Unit
|
||||||
|
|
||||||
|
MessageOption.Retry -> {
|
||||||
|
// TODO: 28-Mar-25, Danil Nikolaev: retry sending
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Reply -> messageActions.replyToMessage(cmId)
|
||||||
|
|
||||||
|
MessageOption.ForwardHere -> {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Forward -> {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Pin -> {
|
||||||
|
this.dialog.setValue {
|
||||||
|
MessageDialog.MessagePin(dialog.message.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Unpin -> {
|
||||||
|
this.dialog.setValue {
|
||||||
|
MessageDialog.MessageUnpin(dialog.message.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Read -> {
|
||||||
|
messageTransportActions.readMessage(dialog.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Copy -> {
|
||||||
|
messageTransportActions.copyMessage(dialog.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.MarkAsImportant,
|
||||||
|
MessageOption.UnmarkAsImportant -> {
|
||||||
|
this.dialog.setValue {
|
||||||
|
MessageDialog.MessageMarkImportance(
|
||||||
|
message = dialog.message,
|
||||||
|
isImportant = option is MessageOption.MarkAsImportant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.MarkAsSpam,
|
||||||
|
MessageOption.UnmarkAsSpam -> {
|
||||||
|
this.dialog.setValue {
|
||||||
|
MessageDialog.MessageSpam(
|
||||||
|
message = dialog.message,
|
||||||
|
isSpam = option is MessageOption.MarkAsSpam
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Edit -> {
|
||||||
|
messageActions.editMessage(cmId)
|
||||||
|
syncUiMessages()
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageOption.Delete -> {
|
||||||
|
this.dialog.setValue {
|
||||||
|
MessageDialog.MessageDelete(dialog.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is MessageDialog.MessageDelete -> Unit
|
||||||
|
is MessageDialog.MessageUnpin -> Unit
|
||||||
|
is MessageDialog.MessageMarkImportance -> Unit
|
||||||
|
is MessageDialog.MessageSpam -> Unit
|
||||||
|
is MessageDialog.MessagePin -> Unit
|
||||||
|
is MessageDialog.MessagesDelete -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onCloseButtonClicked() {
|
||||||
|
if (selectedMessages.value.isNotEmpty()) {
|
||||||
|
selectedMessages.setValue { emptyList() }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (screenState.value.editCmId != null) {
|
||||||
|
messageActions.stopEditMessage()
|
||||||
|
}
|
||||||
|
|
||||||
|
syncUiMessages()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageClicked(messageId: Long) {
|
||||||
|
val currentMessage = messages.value.firstOrNull { it.id == messageId } ?: return
|
||||||
|
|
||||||
|
if (selectedMessages.value.isNotEmpty()) {
|
||||||
|
val isSelected = selectedMessages.value.contains(currentMessage)
|
||||||
|
|
||||||
|
selectedMessages.setValue { old ->
|
||||||
|
old.toMutableList().also {
|
||||||
|
if (isSelected) {
|
||||||
|
it.remove(currentMessage)
|
||||||
|
} else {
|
||||||
|
it.add(currentMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
syncUiMessages()
|
||||||
|
} else {
|
||||||
|
dialog.setValue {
|
||||||
|
MessageDialog.MessageOptions(currentMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageLongClicked(messageId: Long) {
|
||||||
|
val currentMessage = messages.value.firstOrNull { it.id == messageId } ?: return
|
||||||
|
|
||||||
|
val isSelected = selectedMessages.value.contains(currentMessage)
|
||||||
|
if (isSelected) return
|
||||||
|
|
||||||
|
selectedMessages.setValue { old ->
|
||||||
|
old.toMutableList().also {
|
||||||
|
it.add(currentMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
syncUiMessages()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onEditSelectedMessageClicked() {
|
||||||
|
val cmId = selectedMessages.value.firstOrNull()?.cmId ?: return
|
||||||
|
|
||||||
|
selectedMessages.setValue { emptyList() }
|
||||||
|
|
||||||
|
messageActions.editMessage(cmId)
|
||||||
|
|
||||||
|
syncUiMessages()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onDeleteSelectedMessagesClicked() {
|
||||||
|
dialog.setValue {
|
||||||
|
MessageDialog.MessagesDelete(selectedMessages.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onPinnedMessageClicked(messageId: Long) {
|
||||||
|
val messageIndex = uiMessages.value.indexOfFirstOrNull {
|
||||||
|
it is MessageUiItem.Message && it.id == messageId
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageIndex != null) {
|
||||||
|
isNeedToScrollToIndex.setValue { messageIndex }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onUnpinMessageClicked() {
|
||||||
|
val pinnedMessageId = screenState.value.pinnedMessage?.id ?: return
|
||||||
|
dialog.setValue {
|
||||||
|
MessageDialog.MessageUnpin(pinnedMessageId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import dev.meloda.fast.common.VkConstants
|
||||||
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
|
import dev.meloda.fast.common.extensions.launchDbRefresh
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.common.paging.canPaginate as canPaginatePage
|
||||||
|
import dev.meloda.fast.common.paging.isPaginationExhausted as isPaginationExhaustedPage
|
||||||
|
import dev.meloda.fast.common.paging.loadingFlags
|
||||||
|
import dev.meloda.fast.common.paging.mergePage
|
||||||
|
import dev.meloda.fast.common.provider.ResourceProvider
|
||||||
|
import dev.meloda.fast.data.State
|
||||||
|
import dev.meloda.fast.data.VkUtils
|
||||||
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.domain.ConvoUseCase
|
||||||
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
|
import dev.meloda.fast.domain.util.extractAvatar
|
||||||
|
import dev.meloda.fast.domain.util.extractTitle
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.BaseError
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
||||||
|
internal class MessagesHistoryLoaders(
|
||||||
|
private val convoUseCase: ConvoUseCase,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val resourceProvider: ResourceProvider,
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>,
|
||||||
|
private val messages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val imagesToPreload: MutableStateFlow<List<String>>,
|
||||||
|
private val canPaginate: MutableStateFlow<Boolean>,
|
||||||
|
private val baseError: MutableStateFlow<BaseError?>,
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val syncUiMessages: () -> Unit,
|
||||||
|
private val onPinnedMessage: (VkMessage?) -> Unit,
|
||||||
|
) {
|
||||||
|
fun loadConvo() {
|
||||||
|
Log.d("MessagesHistoryViewModelImpl", "loadConvo()")
|
||||||
|
|
||||||
|
scope.launchDbRefresh(
|
||||||
|
load = {
|
||||||
|
convoUseCase.getLocalConvoById(screenState.value.convoId)?.let { convo ->
|
||||||
|
val title = convo.extractTitle(
|
||||||
|
useContactName = AppSettings.General.useContactNames,
|
||||||
|
resources = resourceProvider.resources
|
||||||
|
)
|
||||||
|
val avatar = convo.extractAvatar()
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
convo = convo,
|
||||||
|
title = title,
|
||||||
|
avatar = avatar
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
onPinnedMessage(convo.pinnedMessage)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
after = {}
|
||||||
|
)
|
||||||
|
|
||||||
|
convoUseCase.getById(
|
||||||
|
peerIds = listOf(screenState.value.convoId),
|
||||||
|
extended = true,
|
||||||
|
fields = VkConstants.ALL_FIELDS
|
||||||
|
).listenValue(scope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = { response ->
|
||||||
|
val convo = response.firstOrNull() ?: return@listenValue
|
||||||
|
val title = convo.extractTitle(
|
||||||
|
useContactName = AppSettings.General.useContactNames,
|
||||||
|
resources = resourceProvider.resources
|
||||||
|
)
|
||||||
|
val avatar = convo.extractAvatar()
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
convo = convo,
|
||||||
|
title = title,
|
||||||
|
avatar = avatar
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
onPinnedMessage(convo.pinnedMessage)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadMessagesHistory(offset: Int) {
|
||||||
|
Log.d("MessagesHistoryViewModel", "loadMessagesHistory: $offset")
|
||||||
|
|
||||||
|
if (offset == 0) {
|
||||||
|
scope.launchDbRefresh(
|
||||||
|
load = {
|
||||||
|
val cachedMessages = messagesUseCase.getLocalMessages(screenState.value.convoId)
|
||||||
|
if (cachedMessages.isNotEmpty()) {
|
||||||
|
messages.emit(cachedMessages.sorted())
|
||||||
|
}
|
||||||
|
},
|
||||||
|
after = {
|
||||||
|
if (messages.value.isNotEmpty()) {
|
||||||
|
syncUiMessages()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
messagesUseCase.getMessagesHistory(
|
||||||
|
convoId = screenState.value.convoId,
|
||||||
|
count = MessagesHistoryViewModelImpl.MESSAGES_LOAD_COUNT,
|
||||||
|
offset = offset,
|
||||||
|
).listenValue(scope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = { response ->
|
||||||
|
val messages = response.messages
|
||||||
|
val fullMessages = mergePage(this.messages.value, messages, offset)
|
||||||
|
.sorted()
|
||||||
|
|
||||||
|
imagesToPreload.setValue {
|
||||||
|
messages.mapNotNull { it.extractAvatar().extractUrl() }
|
||||||
|
}
|
||||||
|
|
||||||
|
messagesUseCase.storeMessages(messages)
|
||||||
|
convoUseCase.storeConvos(response.convos)
|
||||||
|
|
||||||
|
val itemsCountSufficient = canPaginatePage(
|
||||||
|
MessagesHistoryViewModelImpl.MESSAGES_LOAD_COUNT,
|
||||||
|
messages.size
|
||||||
|
)
|
||||||
|
val paginationExhausted = isPaginationExhaustedPage(
|
||||||
|
pageSize = MessagesHistoryViewModelImpl.MESSAGES_LOAD_COUNT,
|
||||||
|
loadedCount = messages.size,
|
||||||
|
hasExistingItems = this.messages.value.isNotEmpty()
|
||||||
|
)
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(isPaginationExhausted = paginationExhausted)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.messages.emit(fullMessages)
|
||||||
|
syncUiMessages()
|
||||||
|
canPaginate.setValue { itemsCountSufficient }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
val flags = loadingFlags(offset, state.isLoading())
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
isLoading = flags.isLoading,
|
||||||
|
isPaginating = flags.isPaginating
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleError(error: State.Error) {
|
||||||
|
VkUtils.parseError(error)?.let { newBaseError ->
|
||||||
|
baseError.setValue { newBaseError }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun List<VkMessage>.sorted(): List<VkMessage> {
|
||||||
|
return sortedWith { m1, m2 ->
|
||||||
|
val dateDiff = m2.date - m1.date
|
||||||
|
if (dateDiff != 0) {
|
||||||
|
dateDiff
|
||||||
|
} else {
|
||||||
|
val idDiff = m2.id - m1.id
|
||||||
|
idDiff.toInt()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import dev.meloda.fast.common.extensions.launchDbRefresh
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.domain.ConvoUseCase
|
||||||
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.LongPollParsedEvent
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
||||||
|
internal class MessagesHistoryLongPollEventHandler(
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val convoUseCase: ConvoUseCase,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>,
|
||||||
|
private val messages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val syncUiMessages: () -> Unit,
|
||||||
|
private val onPinnedMessageChanged: (VkMessage?) -> Unit
|
||||||
|
) {
|
||||||
|
fun onNewMessage(event: LongPollParsedEvent.NewMessage) {
|
||||||
|
val message = event.message
|
||||||
|
|
||||||
|
Log.d("MessagesHistoryViewModel", "handleNewMessage: $message")
|
||||||
|
|
||||||
|
if (message.peerId != screenState.value.convoId) return
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageEdited(event: LongPollParsedEvent.MessageEdited) {
|
||||||
|
val message = event.message
|
||||||
|
if (message.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onReadIncoming(event: LongPollParsedEvent.IncomingMessageRead) {
|
||||||
|
if (event.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onReadOutgoing(event: LongPollParsedEvent.OutgoingMessageRead) {
|
||||||
|
if (event.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageDeleted(event: LongPollParsedEvent.MessageDeleted) {
|
||||||
|
if (event.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageRestored(event: LongPollParsedEvent.MessageRestored) {
|
||||||
|
if (event.message.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageMarkedAsImportant(event: LongPollParsedEvent.MessageMarkedAsImportant) {
|
||||||
|
if (event.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageMarkedAsSpam(event: LongPollParsedEvent.MessageMarkedAsSpam) {
|
||||||
|
if (event.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageMarkedAsNotSpam(event: LongPollParsedEvent.MessageMarkedAsNotSpam) {
|
||||||
|
if (event.message.peerId != screenState.value.convoId) return
|
||||||
|
|
||||||
|
refreshFromDb(refreshMessages = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refreshFromDb(refreshMessages: Boolean) {
|
||||||
|
scope.launchDbRefresh(
|
||||||
|
load = {
|
||||||
|
convoUseCase.getLocalConvoById(screenState.value.convoId)?.let { convo ->
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(convo = convo)
|
||||||
|
}
|
||||||
|
onPinnedMessageChanged(convo.pinnedMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (refreshMessages) {
|
||||||
|
val localMessages = messagesUseCase.getLocalMessages(screenState.value.convoId)
|
||||||
|
messages.setValue { localMessages }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
after = ::syncUiMessages
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import androidx.compose.ui.text.input.TextFieldValue
|
||||||
|
|
||||||
|
internal class MessagesHistoryMessageActions(
|
||||||
|
private val sendEditActions: MessagesHistoryMessageSendEditActions
|
||||||
|
) {
|
||||||
|
fun replyToMessage(cmId: Long) = sendEditActions.replyToMessage(cmId)
|
||||||
|
fun onMessageInputChanged(newText: TextFieldValue) = sendEditActions.onMessageInputChanged(newText)
|
||||||
|
fun onEmojiButtonLongClicked() = sendEditActions.onEmojiButtonLongClicked()
|
||||||
|
fun editMessage(cmId: Long) = sendEditActions.editMessage(cmId)
|
||||||
|
fun stopEditMessage() = sendEditActions.stopEditMessage()
|
||||||
|
fun onBoldClicked() = sendEditActions.onBoldClicked()
|
||||||
|
fun onItalicClicked() = sendEditActions.onItalicClicked()
|
||||||
|
fun onUnderlineClicked() = sendEditActions.onUnderlineClicked()
|
||||||
|
fun onRegularClicked() = sendEditActions.onRegularClicked()
|
||||||
|
fun onActionButtonClicked() = sendEditActions.onActionButtonClicked()
|
||||||
|
fun onReplyCloseClicked() = sendEditActions.onReplyCloseClicked()
|
||||||
|
fun onKeyboardShown() = sendEditActions.onKeyboardShown()
|
||||||
|
fun sendMessage() = sendEditActions.sendMessage()
|
||||||
|
fun confirmDeleteCurrentEditMessage() = sendEditActions.confirmDeleteCurrentEditMessage()
|
||||||
|
fun editCurrentEditMessage() = sendEditActions.editCurrentEditMessage()
|
||||||
|
}
|
||||||
+400
@@ -0,0 +1,400 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.TextRange
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import androidx.compose.ui.text.font.FontStyle
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.TextFieldValue
|
||||||
|
import androidx.compose.ui.text.style.TextDecoration
|
||||||
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
|
import dev.meloda.fast.common.extensions.launchDbRefresh
|
||||||
|
import dev.meloda.fast.common.extensions.removeIfCompat
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.common.provider.ResourceProvider
|
||||||
|
import dev.meloda.fast.data.UserConfig
|
||||||
|
import dev.meloda.fast.data.VkMemoryCache
|
||||||
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
|
import dev.meloda.fast.domain.util.extractReplySummary
|
||||||
|
import dev.meloda.fast.domain.util.extractReplyTitle
|
||||||
|
import dev.meloda.fast.domain.util.extractTitle
|
||||||
|
import dev.meloda.fast.messageshistory.model.ActionMode
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessageDialog
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.api.domain.FormatDataType
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.serialization.json.add
|
||||||
|
import kotlinx.serialization.json.buildJsonArray
|
||||||
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
|
import kotlinx.serialization.json.put
|
||||||
|
import kotlin.random.Random
|
||||||
|
|
||||||
|
internal class MessagesHistoryMessageSendEditActions(
|
||||||
|
private val viewModelScope: CoroutineScope,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val resourceProvider: ResourceProvider,
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>,
|
||||||
|
private val messages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val showKeyboard: MutableStateFlow<Boolean>,
|
||||||
|
private val dialog: MutableStateFlow<MessageDialog?>,
|
||||||
|
private val syncUiMessages: () -> Unit
|
||||||
|
) {
|
||||||
|
private var lastMessageText: String? = null
|
||||||
|
private val sendingMessages: MutableList<VkMessage> = mutableListOf()
|
||||||
|
private val failedMessages: MutableList<VkMessage> = mutableListOf()
|
||||||
|
private var replyToCmId: Long? = null
|
||||||
|
private var editMessage: VkMessage? = null
|
||||||
|
private var formatData = VkMessage.FormatData("1", emptyList())
|
||||||
|
|
||||||
|
fun replyToMessage(cmId: Long) {
|
||||||
|
val messageToReply = messages.value.find { it.cmId == cmId } ?: return
|
||||||
|
|
||||||
|
showKeyboard.setValue { true }
|
||||||
|
replyToCmId = cmId
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
replyTitle = messageToReply.extractTitle(),
|
||||||
|
replyText = messageToReply.extractReplySummary(resourceProvider.resources)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMessageInputChanged(newText: TextFieldValue) {
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
message = newText,
|
||||||
|
actionMode =
|
||||||
|
when {
|
||||||
|
screenState.value.editCmId != null -> {
|
||||||
|
// TODO: 13/03/2026, Danil Nikolaev: also check if attachments is empty
|
||||||
|
if (newText.text.trim().isEmpty()) {
|
||||||
|
ActionMode.DELETE
|
||||||
|
} else {
|
||||||
|
ActionMode.EDIT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
newText.text.trim().isEmpty() -> ActionMode.RECORD_AUDIO
|
||||||
|
else -> ActionMode.SEND
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
updateStyles()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onEmojiButtonLongClicked() {
|
||||||
|
AppSettings.Features.fastText.takeIf { it.isNotBlank() }?.let { text ->
|
||||||
|
val newText = "${screenState.value.message.text}$text"
|
||||||
|
onMessageInputChanged(
|
||||||
|
TextFieldValue(text = newText, selection = TextRange(newText.length))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun editMessage(cmId: Long) {
|
||||||
|
screenState.setValue { old -> old.copy(editCmId = cmId) }
|
||||||
|
|
||||||
|
val messageToEdit = messages.value.firstOrNull { it.cmId == cmId } ?: return
|
||||||
|
editMessage = messageToEdit
|
||||||
|
|
||||||
|
lastMessageText = screenState.value.message.text
|
||||||
|
|
||||||
|
var newState = screenState.value.copy(
|
||||||
|
message = TextFieldValue(
|
||||||
|
text = messageToEdit.text.orEmpty(),
|
||||||
|
selection = TextRange(messageToEdit.text.orEmpty().length)
|
||||||
|
),
|
||||||
|
actionMode = ActionMode.EDIT
|
||||||
|
)
|
||||||
|
|
||||||
|
messageToEdit.replyMessage?.let { reply ->
|
||||||
|
replyToCmId = reply.cmId
|
||||||
|
newState = newState.copy(
|
||||||
|
replyTitle = reply.extractReplyTitle(),
|
||||||
|
replyText = reply.extractReplySummary(resourceProvider.resources)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
showKeyboard.setValue { true }
|
||||||
|
screenState.setValue { newState }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopEditMessage() {
|
||||||
|
val lastText = lastMessageText.orEmpty().trim()
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
editCmId = null,
|
||||||
|
message = TextFieldValue(
|
||||||
|
text = lastText,
|
||||||
|
selection = TextRange(lastText.length)
|
||||||
|
),
|
||||||
|
actionMode = if (lastText.isBlank()) ActionMode.RECORD_AUDIO else ActionMode.SEND,
|
||||||
|
replyTitle = null,
|
||||||
|
replyText = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onBoldClicked() = updateFormatting(FormatDataType.BOLD)
|
||||||
|
fun onItalicClicked() = updateFormatting(FormatDataType.ITALIC)
|
||||||
|
fun onUnderlineClicked() = updateFormatting(FormatDataType.UNDERLINE)
|
||||||
|
|
||||||
|
fun onRegularClicked() {
|
||||||
|
formatData = formatData.copy(items = emptyList())
|
||||||
|
updateStyles()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onActionButtonClicked() {
|
||||||
|
when (screenState.value.actionMode) {
|
||||||
|
ActionMode.DELETE -> confirmDeleteCurrentEditMessage()
|
||||||
|
ActionMode.EDIT -> editCurrentEditMessage()
|
||||||
|
ActionMode.RECORD_AUDIO -> {
|
||||||
|
screenState.setValue { it.copy(actionMode = ActionMode.RECORD_VIDEO) }
|
||||||
|
}
|
||||||
|
ActionMode.RECORD_VIDEO -> {
|
||||||
|
screenState.setValue { it.copy(actionMode = ActionMode.RECORD_AUDIO) }
|
||||||
|
}
|
||||||
|
ActionMode.SEND -> sendMessage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onReplyCloseClicked() {
|
||||||
|
replyToCmId = null
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
replyTitle = null,
|
||||||
|
replyText = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onKeyboardShown() {
|
||||||
|
showKeyboard.setValue { false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendMessage() {
|
||||||
|
lastMessageText = screenState.value.message.text
|
||||||
|
|
||||||
|
val newMessage = VkMessage(
|
||||||
|
id = -1L - sendingMessages.size,
|
||||||
|
cmId = -1L - sendingMessages.size,
|
||||||
|
text = lastMessageText,
|
||||||
|
isOut = true,
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
fromId = UserConfig.userId,
|
||||||
|
date = (System.currentTimeMillis() / 1000).toInt(),
|
||||||
|
randomId = Random.nextInt().toLong(),
|
||||||
|
action = null,
|
||||||
|
actionMemberId = null,
|
||||||
|
actionText = null,
|
||||||
|
actionCmId = null,
|
||||||
|
actionMessage = null,
|
||||||
|
updateTime = null,
|
||||||
|
isImportant = false,
|
||||||
|
forwards = null,
|
||||||
|
attachments = null,
|
||||||
|
replyMessage = when {
|
||||||
|
replyToCmId != null -> messages.value.find { it.cmId == replyToCmId }
|
||||||
|
else -> null
|
||||||
|
},
|
||||||
|
geoType = null,
|
||||||
|
user = VkMemoryCache.getUser(UserConfig.userId),
|
||||||
|
group = null,
|
||||||
|
actionUser = null,
|
||||||
|
actionGroup = null,
|
||||||
|
isPinned = false,
|
||||||
|
isSpam = false,
|
||||||
|
pinnedAt = null,
|
||||||
|
formatData = formatData,
|
||||||
|
)
|
||||||
|
formatData = formatData.copy(items = emptyList())
|
||||||
|
sendingMessages += newMessage
|
||||||
|
messages.setValue { old -> listOf(newMessage).plus(old) }
|
||||||
|
syncUiMessages()
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
message = TextFieldValue(),
|
||||||
|
actionMode = ActionMode.RECORD_AUDIO,
|
||||||
|
replyTitle = null,
|
||||||
|
replyText = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val replyCmId = replyToCmId
|
||||||
|
replyToCmId = null
|
||||||
|
|
||||||
|
val forward = when {
|
||||||
|
replyCmId != null -> {
|
||||||
|
buildJsonObject {
|
||||||
|
put("peer_id", screenState.value.convoId)
|
||||||
|
put("conversation_message_ids", buildJsonArray { add(replyCmId) })
|
||||||
|
put("is_reply", true)
|
||||||
|
}.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
messagesUseCase.sendMessage(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
randomId = newMessage.randomId,
|
||||||
|
message = newMessage.text,
|
||||||
|
forward = forward,
|
||||||
|
attachments = null,
|
||||||
|
formatData = newMessage.formatData,
|
||||||
|
).listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
any = { sendingMessages.remove(newMessage) },
|
||||||
|
error = { error ->
|
||||||
|
Log.d("MessagesHistoryViewModelImpl", "sendMessage: ERROR: $error")
|
||||||
|
|
||||||
|
val failedId = -500_000L - failedMessages.size
|
||||||
|
val newFailedMessage = newMessage.copy(id = failedId)
|
||||||
|
failedMessages += newFailedMessage
|
||||||
|
|
||||||
|
val newMessages = messages.value.toMutableList()
|
||||||
|
newMessages[newMessages.indexOf(newMessage)] = newFailedMessage
|
||||||
|
messages.setValue { newMessages }
|
||||||
|
syncUiMessages()
|
||||||
|
},
|
||||||
|
success = { response ->
|
||||||
|
viewModelScope.launch {
|
||||||
|
messagesUseCase.storeMessage(
|
||||||
|
newMessage.copy(
|
||||||
|
id = response.messageId,
|
||||||
|
cmId = response.cmId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun confirmDeleteCurrentEditMessage() {
|
||||||
|
val currentMessage = editMessage ?: return
|
||||||
|
dialog.setValue { MessageDialog.MessageDelete(currentMessage) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun editCurrentEditMessage() {
|
||||||
|
val newText = screenState.value.message.text
|
||||||
|
val lastText = lastMessageText.orEmpty().trim()
|
||||||
|
val currentReplyToCmId = replyToCmId
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
editCmId = null,
|
||||||
|
message = TextFieldValue(
|
||||||
|
text = lastText,
|
||||||
|
selection = TextRange(lastText.length)
|
||||||
|
),
|
||||||
|
actionMode = if (lastText.isBlank()) ActionMode.RECORD_AUDIO else ActionMode.SEND,
|
||||||
|
replyTitle = null,
|
||||||
|
replyText = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
syncUiMessages()
|
||||||
|
|
||||||
|
val newMessage = editMessage?.copy(
|
||||||
|
replyMessage = if (currentReplyToCmId == null) null else editMessage?.replyMessage,
|
||||||
|
text = newText
|
||||||
|
) ?: return
|
||||||
|
|
||||||
|
Log.d("MessagesHistoryViewModelImpl", "editMessage: $newMessage")
|
||||||
|
|
||||||
|
messagesUseCase.edit(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
cmId = newMessage.cmId,
|
||||||
|
message = newMessage.text,
|
||||||
|
attachments = null,
|
||||||
|
formatData = newMessage.formatData
|
||||||
|
).listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = { error ->
|
||||||
|
Log.d("MessagesHistoryViewModelImpl", "editMessage: ERROR: $error")
|
||||||
|
},
|
||||||
|
success = {
|
||||||
|
viewModelScope.launch {
|
||||||
|
messagesUseCase.storeMessage(newMessage)
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
replyToCmId = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateFormatting(type: FormatDataType) {
|
||||||
|
val selectionRange = screenState.value.message.selection
|
||||||
|
val newItems = formatData.items.toMutableList()
|
||||||
|
val wasRemoved = newItems.removeIfCompat {
|
||||||
|
it.type == type &&
|
||||||
|
it.offset == selectionRange.start &&
|
||||||
|
it.offset + it.length == selectionRange.end
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!wasRemoved) {
|
||||||
|
newItems += VkMessage.FormatData.Item(
|
||||||
|
offset = selectionRange.start,
|
||||||
|
length = selectionRange.end - selectionRange.start,
|
||||||
|
type = type,
|
||||||
|
url = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
formatData = formatData.copy(items = newItems)
|
||||||
|
updateStyles()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateStyles() {
|
||||||
|
val annotations =
|
||||||
|
mutableListOf<AnnotatedString.Range<out AnnotatedString.Annotation>>()
|
||||||
|
|
||||||
|
formatData.items.forEach { item ->
|
||||||
|
val spanStyle = when (item.type) {
|
||||||
|
FormatDataType.BOLD -> SpanStyle(fontWeight = FontWeight.SemiBold)
|
||||||
|
FormatDataType.ITALIC -> SpanStyle(fontStyle = FontStyle.Italic)
|
||||||
|
FormatDataType.UNDERLINE -> SpanStyle(textDecoration = TextDecoration.Underline)
|
||||||
|
FormatDataType.URL -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
spanStyle?.let {
|
||||||
|
annotations += AnnotatedString.Range(
|
||||||
|
item = spanStyle,
|
||||||
|
start = item.offset,
|
||||||
|
end = item.offset + item.length
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val newText = AnnotatedString(
|
||||||
|
text = screenState.value.message.text,
|
||||||
|
annotations = annotations
|
||||||
|
)
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(message = old.message.copy(annotatedString = newText))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refreshMessagesFromDb() {
|
||||||
|
viewModelScope.launchDbRefresh(
|
||||||
|
load = {
|
||||||
|
val localMessages = messagesUseCase.getLocalMessages(screenState.value.convoId)
|
||||||
|
messages.setValue { localMessages }
|
||||||
|
},
|
||||||
|
after = ::syncUiMessages
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+232
@@ -0,0 +1,232 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.os.Build
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import androidx.core.graphics.drawable.toBitmapOrNull
|
||||||
|
import coil.imageLoader
|
||||||
|
import coil.request.ImageRequest
|
||||||
|
import dev.meloda.fast.common.extensions.launchDbRefresh
|
||||||
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.data.State
|
||||||
|
import dev.meloda.fast.data.VkUtils
|
||||||
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.domain.ConvoUseCase
|
||||||
|
import dev.meloda.fast.domain.MessagesUseCase
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.BaseError
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import dev.meloda.fast.model.api.domain.VkPhotoDomain
|
||||||
|
import dev.meloda.fast.ui.R
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
|
||||||
|
internal class MessagesHistoryMessageTransportActions(
|
||||||
|
private val applicationContext: Context,
|
||||||
|
private val viewModelScope: CoroutineScope,
|
||||||
|
private val convoUseCase: ConvoUseCase,
|
||||||
|
private val messagesUseCase: MessagesUseCase,
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>,
|
||||||
|
private val messages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val baseError: MutableStateFlow<BaseError?>,
|
||||||
|
private val syncUiMessages: () -> Unit,
|
||||||
|
private val onPinnedMessageChanged: (VkMessage?) -> Unit
|
||||||
|
) {
|
||||||
|
fun markAsImportant(messageIds: List<Long>, important: Boolean) {
|
||||||
|
messagesUseCase.markAsImportant(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
messageIds = messageIds,
|
||||||
|
important = important
|
||||||
|
).listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = {
|
||||||
|
viewModelScope.launch {
|
||||||
|
messageIds.forEach { messageId ->
|
||||||
|
messagesUseCase.getLocalMessageById(messageId)?.let { localMessage ->
|
||||||
|
messagesUseCase.storeMessage(localMessage.copy(isImportant = important))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteMessage(
|
||||||
|
messageIds: List<Long>,
|
||||||
|
spam: Boolean = false,
|
||||||
|
deleteForAll: Boolean = false,
|
||||||
|
onSuccess: () -> Unit = {}
|
||||||
|
) {
|
||||||
|
messagesUseCase.delete(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
messageIds = messageIds,
|
||||||
|
spam = spam,
|
||||||
|
deleteForAll = deleteForAll
|
||||||
|
).listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onSuccess()
|
||||||
|
val localMessageIds = mutableListOf<Long>()
|
||||||
|
messageIds.forEach { messageId ->
|
||||||
|
messagesUseCase.getLocalMessageById(messageId)?.let { localMessage ->
|
||||||
|
localMessageIds += localMessage.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
messagesUseCase.deleteLocalMessages(localMessageIds)
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pinMessage(messageId: Long) {
|
||||||
|
messagesUseCase.pin(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
messageId = messageId,
|
||||||
|
cmId = null
|
||||||
|
).listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = { pinnedMessage ->
|
||||||
|
viewModelScope.launch {
|
||||||
|
onPinnedMessageChanged(pinnedMessage)
|
||||||
|
messagesUseCase.storeMessage(pinnedMessage)
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun unpinMessage(messageId: Long) {
|
||||||
|
messagesUseCase.unpin(screenState.value.convoId)
|
||||||
|
.listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = {
|
||||||
|
viewModelScope.launch {
|
||||||
|
messagesUseCase.getLocalMessageById(messageId)?.let { localMessage ->
|
||||||
|
messagesUseCase.storeMessage(localMessage.copy(isPinned = false))
|
||||||
|
}
|
||||||
|
onPinnedMessageChanged(null)
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readMessage(message: VkMessage) {
|
||||||
|
messagesUseCase.markAsRead(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
startMessageId = message.id
|
||||||
|
).listenValue(viewModelScope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = ::handleError,
|
||||||
|
success = {
|
||||||
|
viewModelScope.launch {
|
||||||
|
convoUseCase.getLocalConvoById(screenState.value.convoId)?.let { localConvo ->
|
||||||
|
convoUseCase.storeConvos(
|
||||||
|
listOf(
|
||||||
|
localConvo.copy(
|
||||||
|
inRead = if (!message.isOut) message.id else localConvo.inRead,
|
||||||
|
outRead = if (message.isOut) message.id else localConvo.outRead
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
refreshMessagesFromDb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun copyMessage(message: VkMessage) {
|
||||||
|
val clipboardManager =
|
||||||
|
applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
|
||||||
|
val messageToCopy = message.text.orEmpty().trim()
|
||||||
|
if (messageToCopy.isEmpty()) {
|
||||||
|
val photo = with(message.attachments.orEmpty()) {
|
||||||
|
if (size == 1 && all { it is VkPhotoDomain }) {
|
||||||
|
first() as? VkPhotoDomain
|
||||||
|
} else null
|
||||||
|
} ?: return
|
||||||
|
|
||||||
|
val photoMaxSize = photo.getMaxSize() ?: return
|
||||||
|
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
|
val drawable = applicationContext.imageLoader.execute(
|
||||||
|
ImageRequest.Builder(applicationContext)
|
||||||
|
.data(photoMaxSize.url)
|
||||||
|
.build()
|
||||||
|
).drawable ?: return@launch
|
||||||
|
|
||||||
|
val imagesDir = File(applicationContext.cacheDir, "images")
|
||||||
|
if (!imagesDir.exists()) imagesDir.mkdirs()
|
||||||
|
val imageFile = File(imagesDir, "shared_image_id${photo.id}.png")
|
||||||
|
FileOutputStream(imageFile).use {
|
||||||
|
drawable.toBitmapOrNull()?.compress(Bitmap.CompressFormat.PNG, 100, it)
|
||||||
|
}
|
||||||
|
|
||||||
|
val uri = FileProvider.getUriForFile(
|
||||||
|
applicationContext,
|
||||||
|
"${applicationContext.packageName}.provider",
|
||||||
|
imageFile
|
||||||
|
)
|
||||||
|
|
||||||
|
val clip = ClipData.newUri(applicationContext.contentResolver, "Image", uri)
|
||||||
|
clipboardManager.setPrimaryClip(clip)
|
||||||
|
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
Toast.makeText(
|
||||||
|
applicationContext,
|
||||||
|
"Image copied to clipboard",
|
||||||
|
Toast.LENGTH_SHORT
|
||||||
|
).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
clipboardManager.setPrimaryClip(ClipData.newPlainText("Message", messageToCopy))
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
|
||||||
|
Toast.makeText(applicationContext, R.string.copied_to_clipboard, Toast.LENGTH_SHORT)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleError(error: State.Error) {
|
||||||
|
VkUtils.parseError(error)?.let { newBaseError ->
|
||||||
|
baseError.setValue { newBaseError }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refreshMessagesFromDb() {
|
||||||
|
viewModelScope.launchDbRefresh(
|
||||||
|
load = {
|
||||||
|
val localMessages = messagesUseCase.getLocalMessages(screenState.value.convoId)
|
||||||
|
messages.setValue { localMessages }
|
||||||
|
},
|
||||||
|
after = ::syncUiMessages
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessageNavigation
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
||||||
|
internal class MessagesHistoryNavigationActions(
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>,
|
||||||
|
private val messages: MutableStateFlow<List<VkMessage>>,
|
||||||
|
private val navigation: MutableStateFlow<MessageNavigation?>
|
||||||
|
) {
|
||||||
|
fun onTopBarClicked() {
|
||||||
|
val cmId = messages.value.firstOrNull()?.cmId ?: return
|
||||||
|
|
||||||
|
navigation.setValue {
|
||||||
|
MessageNavigation.ChatMaterials(
|
||||||
|
peerId = screenState.value.convoId,
|
||||||
|
cmId = cmId
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import dev.meloda.fast.common.extensions.orDots
|
||||||
|
import dev.meloda.fast.common.extensions.setValue
|
||||||
|
import dev.meloda.fast.data.VkMemoryCache
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlin.math.abs
|
||||||
|
|
||||||
|
internal class MessagesHistoryPinnedMessageHandler(
|
||||||
|
private val screenState: MutableStateFlow<MessagesHistoryScreenState>
|
||||||
|
) {
|
||||||
|
fun update(pinnedMessage: VkMessage?) {
|
||||||
|
if (pinnedMessage == null) {
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
pinnedMessage = null,
|
||||||
|
convo = old.convo.copy(
|
||||||
|
pinnedMessage = null,
|
||||||
|
pinnedMessageId = null
|
||||||
|
),
|
||||||
|
pinnedSummary = null,
|
||||||
|
pinnedTitle = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val pinnedUser = VkMemoryCache.getUser(pinnedMessage.fromId)
|
||||||
|
val pinnedGroup = VkMemoryCache.getGroup(abs(pinnedMessage.fromId))
|
||||||
|
val pinnedTitle = pinnedUser?.fullName ?: pinnedGroup?.name
|
||||||
|
|
||||||
|
val pinnedSummary = buildAnnotatedString {
|
||||||
|
pinnedMessage.text?.let(::append) ?: append("...")
|
||||||
|
}
|
||||||
|
|
||||||
|
screenState.setValue { old ->
|
||||||
|
old.copy(
|
||||||
|
pinnedMessage = pinnedMessage,
|
||||||
|
convo = old.convo.copy(
|
||||||
|
pinnedMessage = pinnedMessage,
|
||||||
|
pinnedMessageId = pinnedMessage.id
|
||||||
|
),
|
||||||
|
pinnedSummary = pinnedSummary,
|
||||||
|
pinnedTitle = pinnedTitle.orDots()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import dev.meloda.fast.common.extensions.listenValue
|
||||||
|
import dev.meloda.fast.data.processState
|
||||||
|
import dev.meloda.fast.domain.GetMessageReadPeersUseCase
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
internal class MessagesHistoryReadPeersLoader(
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val getMessageReadPeersUseCase: GetMessageReadPeersUseCase
|
||||||
|
) {
|
||||||
|
suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int =
|
||||||
|
suspendCancellableCoroutine { continuation ->
|
||||||
|
scope.launch {
|
||||||
|
getMessageReadPeersUseCase
|
||||||
|
.invoke(peerId = peerId, cmId = cmId)
|
||||||
|
.listenValue(scope) { state ->
|
||||||
|
state.processState(
|
||||||
|
error = { continuation.resume(-1) },
|
||||||
|
success = { count -> continuation.resume(count) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package dev.meloda.fast.messageshistory
|
||||||
|
|
||||||
|
import com.conena.nanokt.collections.indexOfFirstOrNull
|
||||||
|
import dev.meloda.fast.common.provider.ResourceProvider
|
||||||
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
|
import dev.meloda.fast.domain.util.asPresentation
|
||||||
|
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
|
||||||
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
|
import dev.meloda.fast.ui.model.vk.MessageUiItem
|
||||||
|
|
||||||
|
fun buildMessagesHistoryUiMessages(
|
||||||
|
messages: List<VkMessage>,
|
||||||
|
selectedMessages: List<VkMessage>,
|
||||||
|
screenState: MessagesHistoryScreenState,
|
||||||
|
resourceProvider: ResourceProvider,
|
||||||
|
): List<MessageUiItem> = messages.mapIndexed { index, message ->
|
||||||
|
message.asPresentation(
|
||||||
|
resourceProvider = resourceProvider,
|
||||||
|
showName = true,
|
||||||
|
prevMessage = messages.getOrNull(index + 1),
|
||||||
|
nextMessage = messages.getOrNull(index - 1),
|
||||||
|
showTimeInActionMessages = AppSettings.Experimental.showTimeInActionMessages,
|
||||||
|
convo = screenState.convo,
|
||||||
|
isSelected = screenState.editCmId == message.cmId ||
|
||||||
|
selectedMessages.indexOfFirstOrNull { it.id == message.id } != null
|
||||||
|
)
|
||||||
|
}
|
||||||
+4
-1
@@ -19,7 +19,7 @@ interface MessagesHistoryViewModel {
|
|||||||
val dialog: StateFlow<MessageDialog?>
|
val dialog: StateFlow<MessageDialog?>
|
||||||
val selectedMessages: StateFlow<List<VkMessage>>
|
val selectedMessages: StateFlow<List<VkMessage>>
|
||||||
|
|
||||||
val inputFieldFocusRequester: StateFlow<Boolean>
|
val showKeyboard: StateFlow<Boolean>
|
||||||
|
|
||||||
val isNeedToScrollToIndex: StateFlow<Int?>
|
val isNeedToScrollToIndex: StateFlow<Int?>
|
||||||
|
|
||||||
@@ -54,6 +54,7 @@ interface MessagesHistoryViewModel {
|
|||||||
fun onPinnedMessageClicked(messageId: Long)
|
fun onPinnedMessageClicked(messageId: Long)
|
||||||
fun onUnpinMessageClicked()
|
fun onUnpinMessageClicked()
|
||||||
|
|
||||||
|
fun onEditSelectedMessageClicked()
|
||||||
fun onDeleteSelectedMessagesClicked()
|
fun onDeleteSelectedMessagesClicked()
|
||||||
|
|
||||||
fun onBoldClicked()
|
fun onBoldClicked()
|
||||||
@@ -66,5 +67,7 @@ interface MessagesHistoryViewModel {
|
|||||||
|
|
||||||
fun onRequestReplyToMessage(cmId: Long)
|
fun onRequestReplyToMessage(cmId: Long)
|
||||||
|
|
||||||
|
fun onKeyboardShown()
|
||||||
|
|
||||||
suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int
|
suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int
|
||||||
}
|
}
|
||||||
|
|||||||
+143
-1130
File diff suppressed because it is too large
Load Diff
+3
-1
@@ -26,7 +26,8 @@ data class MessagesHistoryScreenState(
|
|||||||
val pinnedTitle: String?,
|
val pinnedTitle: String?,
|
||||||
val pinnedSummary: AnnotatedString?,
|
val pinnedSummary: AnnotatedString?,
|
||||||
val replyTitle: String?,
|
val replyTitle: String?,
|
||||||
val replyText: AnnotatedString?
|
val replyText: AnnotatedString?,
|
||||||
|
val editCmId: Long?,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -48,6 +49,7 @@ data class MessagesHistoryScreenState(
|
|||||||
pinnedSummary = null,
|
pinnedSummary = null,
|
||||||
replyTitle = null,
|
replyTitle = null,
|
||||||
replyText = null,
|
replyText = null,
|
||||||
|
editCmId = null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-5
@@ -81,7 +81,7 @@ fun InputBar(
|
|||||||
actionMode: ActionMode,
|
actionMode: ActionMode,
|
||||||
replyTitle: String?,
|
replyTitle: String?,
|
||||||
replyText: AnnotatedString?,
|
replyText: AnnotatedString?,
|
||||||
inputFieldFocusRequester: Boolean,
|
showKeyboard: Boolean,
|
||||||
onMessageInputChanged: (TextFieldValue) -> Unit = {},
|
onMessageInputChanged: (TextFieldValue) -> Unit = {},
|
||||||
onBoldRequested: () -> Unit = {},
|
onBoldRequested: () -> Unit = {},
|
||||||
onItalicRequested: () -> Unit = {},
|
onItalicRequested: () -> Unit = {},
|
||||||
@@ -92,7 +92,8 @@ fun InputBar(
|
|||||||
onEmojiButtonLongClicked: () -> Unit = {},
|
onEmojiButtonLongClicked: () -> Unit = {},
|
||||||
onAttachmentButtonClicked: () -> Unit = {},
|
onAttachmentButtonClicked: () -> Unit = {},
|
||||||
onActionButtonClicked: () -> Unit = {},
|
onActionButtonClicked: () -> Unit = {},
|
||||||
onReplyCloseClicked: () -> Unit = {}
|
onReplyCloseClicked: () -> Unit = {},
|
||||||
|
onKeyboardShown: () -> Unit
|
||||||
) {
|
) {
|
||||||
val view = LocalView.current
|
val view = LocalView.current
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -106,8 +107,9 @@ fun InputBar(
|
|||||||
|
|
||||||
val focusRequester = remember { FocusRequester() }
|
val focusRequester = remember { FocusRequester() }
|
||||||
|
|
||||||
LaunchedEffect(inputFieldFocusRequester) {
|
LaunchedEffect(showKeyboard) {
|
||||||
if (inputFieldFocusRequester) {
|
if (showKeyboard) {
|
||||||
|
onKeyboardShown()
|
||||||
focusRequester.requestFocus()
|
focusRequester.requestFocus()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -360,6 +362,7 @@ private fun InputBarPreview() {
|
|||||||
actionMode = ActionMode.SEND,
|
actionMode = ActionMode.SEND,
|
||||||
replyTitle = "Иннокентий Панфилович",
|
replyTitle = "Иннокентий Панфилович",
|
||||||
replyText = "Ого, ром!".annotated(),
|
replyText = "Ого, ром!".annotated(),
|
||||||
inputFieldFocusRequester = false
|
showKeyboard = false,
|
||||||
|
onKeyboardShown = {}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-2
@@ -29,7 +29,7 @@ fun MessagesHistoryRoute(
|
|||||||
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
||||||
val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle()
|
val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle()
|
||||||
val scrollIndex by viewModel.isNeedToScrollToIndex.collectAsStateWithLifecycle()
|
val scrollIndex by viewModel.isNeedToScrollToIndex.collectAsStateWithLifecycle()
|
||||||
val inputFieldFocusRequester by viewModel.inputFieldFocusRequester.collectAsStateWithLifecycle()
|
val showKeyboard by viewModel.showKeyboard.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
LaunchedEffect(navigationEvent) {
|
LaunchedEffect(navigationEvent) {
|
||||||
val needToConsume = when (val navigation = navigationEvent) {
|
val needToConsume = when (val navigation = navigationEvent) {
|
||||||
@@ -55,7 +55,7 @@ fun MessagesHistoryRoute(
|
|||||||
canPaginate = canPaginate,
|
canPaginate = canPaginate,
|
||||||
showEmojiButton = AppSettings.General.showEmojiButton,
|
showEmojiButton = AppSettings.General.showEmojiButton,
|
||||||
showAttachmentButton = AppSettings.General.showAttachmentButton,
|
showAttachmentButton = AppSettings.General.showAttachmentButton,
|
||||||
inputFieldFocusRequester = inputFieldFocusRequester,
|
showKeyboard = showKeyboard,
|
||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
onClose = viewModel::onCloseButtonClicked,
|
onClose = viewModel::onCloseButtonClicked,
|
||||||
onScrolledToIndex = viewModel::onScrolledToIndex,
|
onScrolledToIndex = viewModel::onScrolledToIndex,
|
||||||
@@ -72,6 +72,7 @@ fun MessagesHistoryRoute(
|
|||||||
onPhotoClicked = onNavigateToPhotoViewer,
|
onPhotoClicked = onNavigateToPhotoViewer,
|
||||||
onPinnedMessageClicked = viewModel::onPinnedMessageClicked,
|
onPinnedMessageClicked = viewModel::onPinnedMessageClicked,
|
||||||
onUnpinMessageButtonClicked = viewModel::onUnpinMessageClicked,
|
onUnpinMessageButtonClicked = viewModel::onUnpinMessageClicked,
|
||||||
|
onEditSelectedMessageClicked = viewModel::onEditSelectedMessageClicked,
|
||||||
onDeleteSelectedButtonClicked = viewModel::onDeleteSelectedMessagesClicked,
|
onDeleteSelectedButtonClicked = viewModel::onDeleteSelectedMessagesClicked,
|
||||||
onBoldRequested = viewModel::onBoldClicked,
|
onBoldRequested = viewModel::onBoldClicked,
|
||||||
onItalicRequested = viewModel::onItalicClicked,
|
onItalicRequested = viewModel::onItalicClicked,
|
||||||
@@ -80,6 +81,7 @@ fun MessagesHistoryRoute(
|
|||||||
onRegularRequested = viewModel::onRegularClicked,
|
onRegularRequested = viewModel::onRegularClicked,
|
||||||
onReplyCloseClicked = viewModel::onReplyCloseClicked,
|
onReplyCloseClicked = viewModel::onReplyCloseClicked,
|
||||||
onRequestReplyToMessage = viewModel::onRequestReplyToMessage,
|
onRequestReplyToMessage = viewModel::onRequestReplyToMessage,
|
||||||
|
onKeyboardShown = viewModel::onKeyboardShown
|
||||||
)
|
)
|
||||||
|
|
||||||
HandleDialogs(
|
HandleDialogs(
|
||||||
|
|||||||
+21
-7
@@ -31,12 +31,14 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalView
|
import androidx.compose.ui.platform.LocalView
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.input.TextFieldValue
|
import androidx.compose.ui.text.input.TextFieldValue
|
||||||
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.core.view.HapticFeedbackConstantsCompat
|
import androidx.core.view.HapticFeedbackConstantsCompat
|
||||||
import dev.chrisbanes.haze.HazeState
|
import dev.chrisbanes.haze.HazeState
|
||||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||||
|
import dev.meloda.fast.common.model.UiImage
|
||||||
import dev.meloda.fast.data.UserConfig
|
import dev.meloda.fast.data.UserConfig
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
import dev.meloda.fast.domain.util.indexOfMessageByCmId
|
import dev.meloda.fast.domain.util.indexOfMessageByCmId
|
||||||
@@ -69,13 +71,14 @@ fun MessagesHistoryScreen(
|
|||||||
canPaginate: Boolean = false,
|
canPaginate: Boolean = false,
|
||||||
showEmojiButton: Boolean = false,
|
showEmojiButton: Boolean = false,
|
||||||
showAttachmentButton: Boolean = false,
|
showAttachmentButton: Boolean = false,
|
||||||
inputFieldFocusRequester: Boolean,
|
showKeyboard: Boolean,
|
||||||
onBack: () -> Unit = {},
|
onBack: () -> Unit = {},
|
||||||
onClose: () -> Unit = {},
|
onClose: () -> Unit = {},
|
||||||
onScrolledToIndex: () -> Unit = {},
|
onScrolledToIndex: () -> Unit = {},
|
||||||
onSessionExpiredLogOutButtonClicked: () -> Unit = {},
|
onSessionExpiredLogOutButtonClicked: () -> Unit = {},
|
||||||
onTopBarClicked: () -> Unit = {},
|
onTopBarClicked: () -> Unit = {},
|
||||||
onRefresh: () -> Unit = {},
|
onRefresh: () -> Unit = {},
|
||||||
|
onEditSelectedMessageClicked: () -> Unit = {},
|
||||||
onPaginationConditionsMet: () -> Unit = {},
|
onPaginationConditionsMet: () -> Unit = {},
|
||||||
onMessageInputChanged: (TextFieldValue) -> Unit = {},
|
onMessageInputChanged: (TextFieldValue) -> Unit = {},
|
||||||
onAttachmentButtonClicked: () -> Unit = {},
|
onAttachmentButtonClicked: () -> Unit = {},
|
||||||
@@ -93,7 +96,8 @@ fun MessagesHistoryScreen(
|
|||||||
onUnderlineRequested: () -> Unit = {},
|
onUnderlineRequested: () -> Unit = {},
|
||||||
onRegularRequested: () -> Unit = {},
|
onRegularRequested: () -> Unit = {},
|
||||||
onReplyCloseClicked: () -> Unit = {},
|
onReplyCloseClicked: () -> Unit = {},
|
||||||
onRequestReplyToMessage: (cmId: Long) -> Unit = {}
|
onRequestReplyToMessage: (cmId: Long) -> Unit = {},
|
||||||
|
onKeyboardShown: () -> Unit
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val view = LocalView.current
|
val view = LocalView.current
|
||||||
@@ -114,7 +118,7 @@ fun MessagesHistoryScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
BackHandler(
|
BackHandler(
|
||||||
enabled = selectedMessages.isNotEmpty(),
|
enabled = selectedMessages.isNotEmpty() || screenState.editCmId != null,
|
||||||
onBack = onClose
|
onBack = onClose
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -162,6 +166,9 @@ fun MessagesHistoryScreen(
|
|||||||
derivedStateOf { selectedMessages.size == 1 }
|
derivedStateOf { selectedMessages.size == 1 }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val isLoadingText = stringResource(R.string.title_loading)
|
||||||
|
val editMessageText = stringResource(R.string.title_edit_message)
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentWindowInsets = WindowInsets.statusBars,
|
contentWindowInsets = WindowInsets.statusBars,
|
||||||
@@ -169,7 +176,8 @@ fun MessagesHistoryScreen(
|
|||||||
val topBarTitle by remember(screenState, selectedMessages) {
|
val topBarTitle by remember(screenState, selectedMessages) {
|
||||||
derivedStateOf {
|
derivedStateOf {
|
||||||
when {
|
when {
|
||||||
screenState.isLoading -> context.getString(R.string.title_loading)
|
screenState.isLoading -> isLoadingText
|
||||||
|
screenState.editCmId != null -> editMessageText
|
||||||
selectedMessages.isNotEmpty() -> "(${selectedMessages.size})"
|
selectedMessages.isNotEmpty() -> "(${selectedMessages.size})"
|
||||||
else -> screenState.title
|
else -> screenState.title
|
||||||
}
|
}
|
||||||
@@ -179,13 +187,16 @@ fun MessagesHistoryScreen(
|
|||||||
MessagesHistoryTopBarContainer(
|
MessagesHistoryTopBarContainer(
|
||||||
hazeState = hazeState,
|
hazeState = hazeState,
|
||||||
showReplyAction = showReplyAction,
|
showReplyAction = showReplyAction,
|
||||||
|
showEditAction = selectedMessages.size == 1,
|
||||||
topBarContainerColor = topBarContainerColor,
|
topBarContainerColor = topBarContainerColor,
|
||||||
topBarContainerColorAlpha = topBarContainerColorAlpha,
|
topBarContainerColorAlpha = topBarContainerColorAlpha,
|
||||||
isClickable = !(screenState.isLoading && messages.isEmpty()),
|
isClickable = !(screenState.isLoading && messages.isEmpty()),
|
||||||
isMessagesSelecting = selectedMessages.isNotEmpty(),
|
isMessagesSelecting = selectedMessages.isNotEmpty(),
|
||||||
isPeerAccount = screenState.convoId == UserConfig.userId,
|
isPeerAccount = screenState.convoId == UserConfig.userId,
|
||||||
avatar = screenState.avatar,
|
avatarUrl = screenState.avatar.takeIf { it is UiImage.Url }?.extractUrl(),
|
||||||
|
avatarResourceId = screenState.avatar.takeIf { it is UiImage.Resource }?.extractResId(),
|
||||||
title = topBarTitle,
|
title = topBarTitle,
|
||||||
|
isEditing = screenState.editCmId != null,
|
||||||
showHorizontalProgressBar = screenState.isLoading && messages.isNotEmpty(),
|
showHorizontalProgressBar = screenState.isLoading && messages.isNotEmpty(),
|
||||||
showPinnedContainer = !screenState.isLoading && pinnedMessage != null,
|
showPinnedContainer = !screenState.isLoading && pinnedMessage != null,
|
||||||
pinnedMessage = pinnedMessage,
|
pinnedMessage = pinnedMessage,
|
||||||
@@ -196,6 +207,7 @@ fun MessagesHistoryScreen(
|
|||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
onClose = onClose,
|
onClose = onClose,
|
||||||
onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked,
|
onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked,
|
||||||
|
onEditSelectedMessageClicked = onEditSelectedMessageClicked,
|
||||||
onRefresh = onRefresh,
|
onRefresh = onRefresh,
|
||||||
onPinnedMessageClicked = onPinnedMessageClicked,
|
onPinnedMessageClicked = onPinnedMessageClicked,
|
||||||
onUnpinMessageButtonClicked = onUnpinMessageButtonClicked
|
onUnpinMessageButtonClicked = onUnpinMessageButtonClicked
|
||||||
@@ -211,6 +223,7 @@ fun MessagesHistoryScreen(
|
|||||||
) {
|
) {
|
||||||
MessagesList(
|
MessagesList(
|
||||||
modifier = Modifier.align(Alignment.BottomStart),
|
modifier = Modifier.align(Alignment.BottomStart),
|
||||||
|
screenState = screenState,
|
||||||
hazeState = hazeState,
|
hazeState = hazeState,
|
||||||
listState = listState,
|
listState = listState,
|
||||||
hasPinnedMessage = pinnedMessage != null,
|
hasPinnedMessage = pinnedMessage != null,
|
||||||
@@ -259,12 +272,13 @@ fun MessagesHistoryScreen(
|
|||||||
actionMode = screenState.actionMode,
|
actionMode = screenState.actionMode,
|
||||||
replyTitle = screenState.replyTitle,
|
replyTitle = screenState.replyTitle,
|
||||||
replyText = screenState.replyText,
|
replyText = screenState.replyText,
|
||||||
inputFieldFocusRequester = inputFieldFocusRequester,
|
showKeyboard = showKeyboard,
|
||||||
onSetMessageBarHeight = { messageBarHeight = it },
|
onSetMessageBarHeight = { messageBarHeight = it },
|
||||||
onEmojiButtonLongClicked = onEmojiButtonLongClicked,
|
onEmojiButtonLongClicked = onEmojiButtonLongClicked,
|
||||||
onAttachmentButtonClicked = onAttachmentButtonClicked,
|
onAttachmentButtonClicked = onAttachmentButtonClicked,
|
||||||
onActionButtonClicked = onActionButtonClicked,
|
onActionButtonClicked = onActionButtonClicked,
|
||||||
onReplyCloseClicked = onReplyCloseClicked
|
onReplyCloseClicked = onReplyCloseClicked,
|
||||||
|
onKeyboardShown = onKeyboardShown
|
||||||
)
|
)
|
||||||
|
|
||||||
when {
|
when {
|
||||||
|
|||||||
+37
-20
@@ -2,6 +2,7 @@ package dev.meloda.fast.messageshistory.presentation
|
|||||||
|
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.Crossfade
|
import androidx.compose.animation.Crossfade
|
||||||
|
import androidx.compose.animation.animateContentSize
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
@@ -31,7 +32,6 @@ 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
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.painter.Painter
|
|
||||||
import androidx.compose.ui.platform.LocalView
|
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
|
||||||
@@ -44,11 +44,9 @@ 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.common.model.UiImage
|
|
||||||
import dev.meloda.fast.datastore.AppSettings
|
import dev.meloda.fast.datastore.AppSettings
|
||||||
import dev.meloda.fast.ui.R
|
import dev.meloda.fast.ui.R
|
||||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||||
import dev.meloda.fast.ui.util.getImage
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -56,16 +54,20 @@ fun MessagesHistoryTopBar(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
hazeState: HazeState,
|
hazeState: HazeState,
|
||||||
showReplyAction: Boolean,
|
showReplyAction: Boolean,
|
||||||
|
showEditAction: Boolean,
|
||||||
isClickable: Boolean,
|
isClickable: Boolean,
|
||||||
isMessagesSelecting: Boolean,
|
isMessagesSelecting: Boolean,
|
||||||
isPeerAccount: Boolean,
|
isPeerAccount: Boolean,
|
||||||
avatar: UiImage,
|
avatarUrl: String?,
|
||||||
|
avatarResourceId: Int?,
|
||||||
title: String,
|
title: String,
|
||||||
|
isEditing: Boolean,
|
||||||
onTopBarClicked: () -> Unit = {},
|
onTopBarClicked: () -> Unit = {},
|
||||||
onBack: () -> Unit = {},
|
onBack: () -> Unit = {},
|
||||||
onClose: () -> Unit = {},
|
onClose: () -> Unit = {},
|
||||||
onDeleteSelectedButtonClicked: () -> Unit = {},
|
onDeleteSelectedButtonClicked: () -> Unit = {},
|
||||||
onRefresh: () -> Unit = {}
|
onRefresh: () -> Unit = {},
|
||||||
|
onEditSelectedMessageClicked: () -> Unit = {}
|
||||||
) {
|
) {
|
||||||
val view = LocalView.current
|
val view = LocalView.current
|
||||||
val theme = LocalThemeConfig.current
|
val theme = LocalThemeConfig.current
|
||||||
@@ -96,7 +98,8 @@ fun MessagesHistoryTopBar(
|
|||||||
// modifier = Modifier.weight(1f),
|
// modifier = Modifier.weight(1f),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
if (!isMessagesSelecting) {
|
AnimatedVisibility(!isMessagesSelecting && !isEditing) {
|
||||||
|
Row {
|
||||||
if (isPeerAccount) {
|
if (isPeerAccount) {
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -114,19 +117,10 @@ fun MessagesHistoryTopBar(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val actualAvatar = avatar.getImage()
|
when {
|
||||||
|
avatarUrl != null -> {
|
||||||
if (actualAvatar is Painter) {
|
|
||||||
Image(
|
|
||||||
painter = actualAvatar,
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = Modifier
|
|
||||||
.size(36.dp)
|
|
||||||
.clip(CircleShape)
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
AsyncImage(
|
AsyncImage(
|
||||||
model = actualAvatar,
|
model = avatarUrl,
|
||||||
contentDescription = "Profile Image",
|
contentDescription = "Profile Image",
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(36.dp)
|
.size(36.dp)
|
||||||
@@ -134,12 +128,25 @@ fun MessagesHistoryTopBar(
|
|||||||
placeholder = painterResource(id = R.drawable.ic_account_circle_fill_round_24),
|
placeholder = painterResource(id = R.drawable.ic_account_circle_fill_round_24),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
avatarResourceId != null -> {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(avatarResourceId),
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier
|
||||||
|
.size(36.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Spacer(modifier = Modifier.width(12.dp))
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
|
modifier = Modifier.animateContentSize(),
|
||||||
text = title,
|
text = title,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
@@ -150,11 +157,11 @@ fun MessagesHistoryTopBar(
|
|||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
IconButton(
|
IconButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
if (!isMessagesSelecting) onBack()
|
if (!isMessagesSelecting && !isEditing) onBack()
|
||||||
else onClose()
|
else onClose()
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
Crossfade(targetState = !isMessagesSelecting) { state ->
|
Crossfade(targetState = !isMessagesSelecting && !isEditing) { state ->
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(
|
painter = painterResource(
|
||||||
if (state) {
|
if (state) {
|
||||||
@@ -210,6 +217,16 @@ fun MessagesHistoryTopBar(
|
|||||||
contentDescription = null
|
contentDescription = null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
AnimatedVisibility(showEditAction) {
|
||||||
|
IconButton(onClick = onEditSelectedMessageClicked) {
|
||||||
|
Icon(
|
||||||
|
painter = painterResource(R.drawable.ic_edit_round_24),
|
||||||
|
contentDescription = null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
IconButton(onClick = onDeleteSelectedButtonClicked) {
|
IconButton(onClick = onDeleteSelectedButtonClicked) {
|
||||||
Icon(
|
Icon(
|
||||||
painter = painterResource(R.drawable.ic_delete_round_24),
|
painter = painterResource(R.drawable.ic_delete_round_24),
|
||||||
|
|||||||
+11
-4
@@ -16,7 +16,6 @@ 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.common.extensions.orDots
|
import dev.meloda.fast.common.extensions.orDots
|
||||||
import dev.meloda.fast.common.model.UiImage
|
|
||||||
import dev.meloda.fast.model.api.domain.VkMessage
|
import dev.meloda.fast.model.api.domain.VkMessage
|
||||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||||
|
|
||||||
@@ -26,13 +25,16 @@ fun MessagesHistoryTopBarContainer(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
hazeState: HazeState,
|
hazeState: HazeState,
|
||||||
showReplyAction: Boolean,
|
showReplyAction: Boolean,
|
||||||
|
showEditAction: Boolean,
|
||||||
topBarContainerColor: Color,
|
topBarContainerColor: Color,
|
||||||
topBarContainerColorAlpha: Float,
|
topBarContainerColorAlpha: Float,
|
||||||
isClickable: Boolean,
|
isClickable: Boolean,
|
||||||
isMessagesSelecting: Boolean,
|
isMessagesSelecting: Boolean,
|
||||||
isPeerAccount: Boolean,
|
isPeerAccount: Boolean,
|
||||||
avatar: UiImage,
|
avatarUrl: String?,
|
||||||
|
avatarResourceId: Int?,
|
||||||
title: String,
|
title: String,
|
||||||
|
isEditing: Boolean,
|
||||||
showHorizontalProgressBar: Boolean,
|
showHorizontalProgressBar: Boolean,
|
||||||
showPinnedContainer: Boolean,
|
showPinnedContainer: Boolean,
|
||||||
pinnedMessage: VkMessage?,
|
pinnedMessage: VkMessage?,
|
||||||
@@ -44,6 +46,7 @@ fun MessagesHistoryTopBarContainer(
|
|||||||
onClose: () -> Unit = {},
|
onClose: () -> Unit = {},
|
||||||
onDeleteSelectedButtonClicked: () -> Unit = {},
|
onDeleteSelectedButtonClicked: () -> Unit = {},
|
||||||
onRefresh: () -> Unit = {},
|
onRefresh: () -> Unit = {},
|
||||||
|
onEditSelectedMessageClicked: () -> Unit = {},
|
||||||
onPinnedMessageClicked: (Long) -> Unit = {},
|
onPinnedMessageClicked: (Long) -> Unit = {},
|
||||||
onUnpinMessageButtonClicked: () -> Unit = {}
|
onUnpinMessageButtonClicked: () -> Unit = {}
|
||||||
) {
|
) {
|
||||||
@@ -66,16 +69,20 @@ fun MessagesHistoryTopBarContainer(
|
|||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
hazeState = hazeState,
|
hazeState = hazeState,
|
||||||
showReplyAction = showReplyAction,
|
showReplyAction = showReplyAction,
|
||||||
|
showEditAction = showEditAction,
|
||||||
isClickable = isClickable,
|
isClickable = isClickable,
|
||||||
isMessagesSelecting = isMessagesSelecting,
|
isMessagesSelecting = isMessagesSelecting,
|
||||||
isPeerAccount = isPeerAccount,
|
isPeerAccount = isPeerAccount,
|
||||||
avatar = avatar,
|
avatarUrl = avatarUrl,
|
||||||
|
avatarResourceId = avatarResourceId,
|
||||||
title = title,
|
title = title,
|
||||||
|
isEditing = isEditing,
|
||||||
onTopBarClicked = onTopBarClicked,
|
onTopBarClicked = onTopBarClicked,
|
||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
onClose = onClose,
|
onClose = onClose,
|
||||||
onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked,
|
onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked,
|
||||||
onRefresh = onRefresh
|
onRefresh = onRefresh,
|
||||||
|
onEditSelectedMessageClicked = onEditSelectedMessageClicked
|
||||||
)
|
)
|
||||||
|
|
||||||
if (showHorizontalProgressBar) {
|
if (showHorizontalProgressBar) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user