Compare commits
18 Commits
0.2.3
..
36504fe4b9
| Author | SHA1 | Date | |
|---|---|---|---|
| 36504fe4b9 | |||
| fc3b3cfcb3 | |||
| f11b8dc6f4 | |||
| 167f980f29 | |||
| d428af4ac4 | |||
| 63bae014c5 | |||
| ad54477d11 | |||
| c8bd485724 | |||
| 26a0630393 | |||
| 3d153df79c | |||
| 9061a39407 | |||
| d8c8820b32 | |||
| abfe25d051 | |||
| 574b230b26 | |||
| b31c0f30c5 | |||
| cb653eddc2 | |||
| df2c61d8d7 | |||
| 97c59a85b6 |
@@ -0,0 +1,56 @@
|
||||
name: Android CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
RELEASE_SIGN_KEY_ALIAS: ${{ secrets.RELEASE_SIGN_KEY_ALIAS }}
|
||||
RELEASE_SIGN_KEY_PASSWORD: ${{ secrets.RELEASE_SIGN_KEY_PASSWORD }}
|
||||
|
||||
jobs:
|
||||
android:
|
||||
runs-on: android-jdk21
|
||||
name: Build artifacts
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Make Gradle executable
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
- name: Build and sign release APK
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Find generated release APK name
|
||||
id: find_apk_release
|
||||
run: |
|
||||
APK_PATH=$(find app/build/outputs/apk/release -name "*.apk" | head -n 1)
|
||||
echo "APK_PATH=$APK_PATH" >> $GITEA_ENV
|
||||
echo "APK_NAME=$(basename $APK_PATH)" >> $GITEA_ENV
|
||||
|
||||
- name: Upload APK with original name
|
||||
uses: christopherhx/gitea-upload-artifact@v4
|
||||
with:
|
||||
name: ${{ env.APK_NAME }}
|
||||
path: ${{ env.APK_PATH }}
|
||||
|
||||
- name: Build and sign debug APK
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Find generated debug APK name
|
||||
id: find_apk_debug
|
||||
run: |
|
||||
APK_PATH=$(find app/build/outputs/apk/debug -name "*.apk" | head -n 1)
|
||||
echo "APK_PATH=$APK_PATH" >> $GITEA_ENV
|
||||
echo "APK_NAME=$(basename $APK_PATH)" >> $GITEA_ENV
|
||||
|
||||
- name: Upload APK with original name
|
||||
uses: christopherhx/gitea-upload-artifact@v4
|
||||
with:
|
||||
name: ${{ env.APK_NAME }}
|
||||
path: ${{ env.APK_PATH }}
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload APK with original name
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ env.APK_NAME }}
|
||||
path: ${{ env.APK_PATH }}
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload APK with original name
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ env.APK_NAME }}
|
||||
path: ${{ env.APK_PATH }}
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Upload release APK
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-release.apk
|
||||
path: app/build/outputs/apk/release/app-release.apk
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
run: ./gradlew bundleRelease
|
||||
|
||||
- name: Upload release Bundle
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-release.aab
|
||||
path: app/build/outputs/bundle/release/app-release.aab
|
||||
|
||||
@@ -15,3 +15,5 @@ build/
|
||||
local.properties
|
||||
.idea
|
||||
/.kotlin
|
||||
.hotswan/
|
||||
.java-version
|
||||
|
||||
@@ -43,6 +43,7 @@ Unofficial messenger for russian social network VKontakte
|
||||
- [ ] Forwarded messages
|
||||
- [ ] Wall post
|
||||
- [ ] Comment in wall post
|
||||
- [ ] Comment in channel
|
||||
- [ ] Poll
|
||||
- [ ] TODO
|
||||
- [x] Send messages
|
||||
|
||||
@@ -47,7 +47,7 @@ android {
|
||||
applicationIdSuffix = ".debug"
|
||||
}
|
||||
named("release") {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
signingConfig = signingConfigs.getByName("debugSigning")
|
||||
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
@@ -92,6 +92,7 @@ dependencies {
|
||||
implementation(projects.feature.photoviewer)
|
||||
implementation(projects.feature.createchat)
|
||||
|
||||
implementation(projects.core.logger)
|
||||
implementation(projects.core.common)
|
||||
implementation(projects.core.ui)
|
||||
implementation(projects.core.data)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:tools="http://schemas.android.com/tools"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
@@ -37,6 +37,12 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="dev.meloda.fast.presentation.CrashActivity"
|
||||
android:exported="false"
|
||||
android:process=":error_handler"
|
||||
android:theme="@style/CrashDialogTheme" />
|
||||
|
||||
<service
|
||||
android:name="dev.meloda.fast.service.longpolling.LongPollingService"
|
||||
android:enabled="true"
|
||||
|
||||
@@ -2,7 +2,6 @@ package dev.meloda.fast
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.os.LocaleListCompat
|
||||
@@ -23,6 +22,7 @@ import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.datastore.UserSettings
|
||||
import dev.meloda.fast.domain.GetCurrentAccountUseCase
|
||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.navigation.Main
|
||||
@@ -67,7 +67,8 @@ class MainViewModelImpl(
|
||||
private val getCurrentAccountUseCase: GetCurrentAccountUseCase,
|
||||
private val loadUserByIdUseCase: LoadUserByIdUseCase,
|
||||
private val userSettings: UserSettings,
|
||||
private val longPollController: LongPollController
|
||||
private val longPollController: LongPollController,
|
||||
private val logger: FastLogger
|
||||
) : MainViewModel, ViewModel() {
|
||||
|
||||
override val startDestination = MutableStateFlow<Any?>(null)
|
||||
@@ -203,7 +204,10 @@ class MainViewModelImpl(
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val currentAccount = getCurrentAccountUseCase()
|
||||
|
||||
Log.d("MainViewModel", "currentAccount: $currentAccount")
|
||||
logger.debug(
|
||||
this@MainViewModelImpl::class,
|
||||
"loadAccounts(): currentAccount: $currentAccount"
|
||||
)
|
||||
|
||||
listenLongPollState()
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package dev.meloda.fast.common
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.preference.PreferenceManager
|
||||
import coil.ImageLoader
|
||||
import coil.ImageLoaderFactory
|
||||
@@ -8,10 +10,16 @@ import com.skydoves.compose.stability.runtime.ComposeStabilityAnalyzer
|
||||
import dev.meloda.fast.auth.BuildConfig
|
||||
import dev.meloda.fast.common.di.applicationModule
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.logger.FastLogLevel
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.presentation.CrashActivity
|
||||
import org.koin.android.ext.android.get
|
||||
import org.koin.android.ext.koin.androidContext
|
||||
import org.koin.android.ext.koin.androidLogger
|
||||
import org.koin.core.context.GlobalContext.startKoin
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
class AppGlobal : Application(), ImageLoaderFactory {
|
||||
|
||||
@@ -20,12 +28,22 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
||||
|
||||
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
|
||||
AppSettings.init(preferences)
|
||||
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
|
||||
|
||||
initKoin()
|
||||
initCrashHandler()
|
||||
|
||||
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
|
||||
val logLevel =
|
||||
if (BuildConfig.DEBUG) FastLogLevel.DEBUG
|
||||
else FastLogLevel.ERROR
|
||||
|
||||
get<FastLogger>()
|
||||
.apply { setLogLevel(logLevel) }
|
||||
.also { FastLogger.setInstance(it) }
|
||||
}
|
||||
|
||||
override fun newImageLoader(): ImageLoader = get()
|
||||
|
||||
private fun initKoin() {
|
||||
startKoin {
|
||||
androidLogger()
|
||||
@@ -34,5 +52,37 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
||||
}
|
||||
}
|
||||
|
||||
override fun newImageLoader(): ImageLoader = get()
|
||||
private fun initCrashHandler() {
|
||||
val defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
|
||||
val crashLogsDirectory = File(filesDir.absolutePath + "/crashlogs")
|
||||
if (!crashLogsDirectory.exists()) {
|
||||
crashLogsDirectory.mkdirs()
|
||||
}
|
||||
|
||||
val crashLogFileName = "crash_" + System.currentTimeMillis() + ".txt"
|
||||
val crashLogFile = File(crashLogsDirectory.absolutePath + "/" + crashLogFileName)
|
||||
|
||||
FileOutputStream(crashLogFile).use { stream ->
|
||||
stream.write(throwable.stackTraceToString().toByteArray())
|
||||
}
|
||||
|
||||
if (AppSettings.Debug.showAlertAfterCrash) {
|
||||
try {
|
||||
val intent = Intent(this, CrashActivity::class.java)
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
||||
intent.putExtra("CRASH_LOG_FILE_URI", Uri.fromFile(crashLogFile))
|
||||
startActivity(intent)
|
||||
|
||||
exitProcess(0)
|
||||
} catch (e: Exception) {
|
||||
if (e !is RuntimeException) {
|
||||
defaultExceptionHandler?.uncaughtException(thread, throwable)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
defaultExceptionHandler?.uncaughtException(thread, throwable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@ import androidx.preference.PreferenceManager
|
||||
import coil.ImageLoader
|
||||
import coil.annotation.ExperimentalCoilApi
|
||||
import dev.meloda.fast.MainViewModelImpl
|
||||
import dev.meloda.fast.auth.captcha.di.captchaModule
|
||||
import dev.meloda.fast.auth.login.di.loginModule
|
||||
import dev.meloda.fast.auth.validation.di.validationModule
|
||||
import dev.meloda.fast.auth.authModule
|
||||
import dev.meloda.fast.chatmaterials.di.chatMaterialsModule
|
||||
import dev.meloda.fast.common.LongPollController
|
||||
import dev.meloda.fast.common.LongPollControllerImpl
|
||||
@@ -21,6 +19,7 @@ import dev.meloda.fast.convos.di.createChatModule
|
||||
import dev.meloda.fast.domain.di.domainModule
|
||||
import dev.meloda.fast.friends.di.friendsModule
|
||||
import dev.meloda.fast.languagepicker.di.languagePickerModule
|
||||
import dev.meloda.fast.logger.loggerModule
|
||||
import dev.meloda.fast.messageshistory.di.messagesHistoryModule
|
||||
import dev.meloda.fast.photoviewer.di.photoViewModule
|
||||
import dev.meloda.fast.profile.di.profileModule
|
||||
@@ -38,9 +37,7 @@ import org.koin.dsl.module
|
||||
val applicationModule = module {
|
||||
includes(domainModule)
|
||||
includes(
|
||||
loginModule,
|
||||
validationModule,
|
||||
captchaModule,
|
||||
authModule,
|
||||
convosModule,
|
||||
settingsModule,
|
||||
messagesHistoryModule,
|
||||
@@ -53,6 +50,8 @@ val applicationModule = module {
|
||||
createChatModule
|
||||
)
|
||||
|
||||
includes(loggerModule)
|
||||
|
||||
// TODO: 14/05/2024, Danil Nikolaev: extract all operations with preferences to standalone class
|
||||
singleOf(PreferenceManager::getDefaultSharedPreferences)
|
||||
single<Resources> { androidContext().resources }
|
||||
|
||||
@@ -8,9 +8,9 @@ import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.BottomNavigationItem
|
||||
import dev.meloda.fast.presentation.MainScreen
|
||||
import dev.meloda.fast.profile.navigation.Profile
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
import kotlinx.serialization.Serializable
|
||||
import dev.meloda.fast.ui.R
|
||||
|
||||
@Serializable
|
||||
object MainGraph
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.meloda.fast.presentation
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.components.MaterialDialog
|
||||
|
||||
@Composable
|
||||
fun AppCrashedDialog(
|
||||
stacktrace: String,
|
||||
onDismiss: () -> Unit,
|
||||
onShare: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var showTrace by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
MaterialDialog(
|
||||
modifier = modifier,
|
||||
onDismissRequest = onDismiss,
|
||||
title = stringResource(R.string.title_error),
|
||||
text = if (showTrace) stacktrace else stringResource(R.string.error_occurred),
|
||||
confirmText = stringResource(R.string.action_share),
|
||||
confirmAction = onShare,
|
||||
cancelText = stringResource(if (showTrace) R.string.action_hide_stacktrace else R.string.action_show_stacktrace),
|
||||
cancelAction = { showTrace = !showTrace },
|
||||
neutralText = stringResource(R.string.action_close),
|
||||
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package dev.meloda.fast.presentation
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.core.net.toFile
|
||||
import dev.meloda.fast.datastore.UserSettings
|
||||
import dev.meloda.fast.ui.theme.AppTheme
|
||||
import dev.meloda.fast.ui.util.isNeedToEnableDarkMode
|
||||
import org.koin.compose.koinInject
|
||||
import java.io.File
|
||||
|
||||
class CrashActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
|
||||
val crashLogFileUri = intent.getParcelableExtra<Uri>("CRASH_LOG_FILE_URI") ?: run {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val crashLogFile = crashLogFileUri.toFile().takeIf(File::exists) ?: run {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
|
||||
val stacktrace = crashLogFile.bufferedReader().readText()
|
||||
|
||||
setContent {
|
||||
val userSettings: UserSettings = koinInject()
|
||||
|
||||
AppTheme(
|
||||
useDarkTheme = isNeedToEnableDarkMode(darkMode = userSettings.darkMode.collectAsState().value),
|
||||
useDynamicColors = userSettings.enableDynamicColors.collectAsState().value,
|
||||
selectedColorScheme = 0,
|
||||
useAmoledBackground = userSettings.enableAmoledDark.collectAsState().value,
|
||||
useSystemFont = userSettings.useSystemFont.collectAsState().value
|
||||
) {
|
||||
AppCrashedDialog(
|
||||
stacktrace = stacktrace,
|
||||
onDismiss = { finish() },
|
||||
onShare = {
|
||||
val uri = FileProvider.getUriForFile(
|
||||
this,
|
||||
"$packageName.provider",
|
||||
crashLogFile
|
||||
)
|
||||
|
||||
val sendIntent = Intent().apply {
|
||||
action = Intent.ACTION_SEND
|
||||
type = "text/plain"
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
putExtra(Intent.EXTRA_STREAM, uri)
|
||||
clipData = ClipData.newRawUri(null, uri)
|
||||
}
|
||||
|
||||
val chooserIntent = Intent.createChooser(sendIntent, null)
|
||||
chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
startActivity(chooserIntent)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,11 @@ import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.core.content.ContextCompat
|
||||
@@ -24,10 +23,13 @@ import dev.meloda.fast.MainViewModel
|
||||
import dev.meloda.fast.MainViewModelImpl
|
||||
import dev.meloda.fast.common.AppConstants
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.service.OnlineService
|
||||
import dev.meloda.fast.service.longpolling.LongPollingService
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.common.LocalLogger
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
import org.koin.compose.koinInject
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
@@ -64,25 +66,26 @@ class MainActivity : AppCompatActivity() {
|
||||
requestNotificationPermissions()
|
||||
|
||||
setContent {
|
||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||
LaunchedEffect(viewModel) {
|
||||
Log.d("VM_CREATE", "onCreate: viewModel: $viewModel")
|
||||
}
|
||||
val logger: FastLogger = koinInject()
|
||||
|
||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||
LifecycleResumeEffect(true) {
|
||||
viewModel.onAppResumed(intent)
|
||||
onPauseOrDispose {}
|
||||
}
|
||||
|
||||
RootScreen(
|
||||
toggleLongPollService = { enable, inBackground ->
|
||||
toggleLongPollService(
|
||||
enable = enable,
|
||||
inBackground = inBackground ?: AppSettings.Experimental.longPollInBackground
|
||||
)
|
||||
},
|
||||
toggleOnlineService = ::toggleOnlineService
|
||||
)
|
||||
CompositionLocalProvider(LocalLogger provides logger) {
|
||||
RootScreen(
|
||||
toggleLongPollService = { enable, inBackground ->
|
||||
toggleLongPollService(
|
||||
enable = enable,
|
||||
inBackground = inBackground
|
||||
?: AppSettings.Experimental.longPollInBackground
|
||||
)
|
||||
},
|
||||
toggleOnlineService = ::toggleOnlineService
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ import dev.chrisbanes.haze.HazeState
|
||||
import dev.chrisbanes.haze.hazeEffect
|
||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||
import dev.chrisbanes.haze.materials.HazeMaterials
|
||||
import dev.meloda.fast.convos.navigation.ConvoGraph
|
||||
import dev.meloda.fast.convos.model.ConvoNavigationIntent
|
||||
import dev.meloda.fast.convos.navigation.convosGraph
|
||||
import dev.meloda.fast.friends.navigation.Friends
|
||||
import dev.meloda.fast.friends.navigation.friendsScreen
|
||||
@@ -198,19 +198,20 @@ fun MainScreen(
|
||||
},
|
||||
)
|
||||
convosGraph(
|
||||
activity = activity,
|
||||
onError = onError,
|
||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
||||
onNavigateToCreateChat = onNavigateToCreateChat,
|
||||
onScrolledToTop = {
|
||||
tabReselected = tabReselected.toMutableMap().also {
|
||||
it[ConvoGraph] = false
|
||||
handleNavigationIntent = { intent ->
|
||||
when (intent) {
|
||||
ConvoNavigationIntent.Back -> {}
|
||||
ConvoNavigationIntent.Archive -> {}
|
||||
ConvoNavigationIntent.CreateChat -> onNavigateToCreateChat()
|
||||
is ConvoNavigationIntent.MessagesHistory -> {
|
||||
onNavigateToMessagesHistory(intent.convoId)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
activity = activity,
|
||||
)
|
||||
profileScreen(
|
||||
activity = activity,
|
||||
onError = onError,
|
||||
onSettingsButtonClicked = onSettingsButtonClicked,
|
||||
onPhotoClicked = onPhotoClicked
|
||||
)
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.activity.compose.LocalActivity
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
@@ -41,6 +40,7 @@ import com.google.accompanist.permissions.rememberPermissionState
|
||||
import dev.meloda.fast.MainViewModel
|
||||
import dev.meloda.fast.MainViewModelImpl
|
||||
import dev.meloda.fast.auth.authNavGraph
|
||||
import dev.meloda.fast.auth.captcha.presentation.CaptchaScreen
|
||||
import dev.meloda.fast.auth.navigateToAuth
|
||||
import dev.meloda.fast.chatmaterials.navigation.chatMaterialsScreen
|
||||
import dev.meloda.fast.chatmaterials.navigation.navigateToChatMaterials
|
||||
@@ -48,6 +48,8 @@ import dev.meloda.fast.common.LongPollController
|
||||
import dev.meloda.fast.common.model.LongPollState
|
||||
import dev.meloda.fast.convos.navigation.createChatScreen
|
||||
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.languagepicker.navigation.languagePickerScreen
|
||||
import dev.meloda.fast.languagepicker.navigation.navigateToLanguagePicker
|
||||
@@ -60,6 +62,7 @@ import dev.meloda.fast.photoviewer.presentation.PhotoViewDialog
|
||||
import dev.meloda.fast.settings.navigation.navigateToSettings
|
||||
import dev.meloda.fast.settings.navigation.settingsScreen
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.common.LocalLogger
|
||||
import dev.meloda.fast.ui.common.LocalSizeConfig
|
||||
import dev.meloda.fast.ui.model.DeviceSize
|
||||
import dev.meloda.fast.ui.model.SizeConfig
|
||||
@@ -80,6 +83,7 @@ fun RootScreen(
|
||||
toggleLongPollService: (enable: Boolean, inBackground: Boolean?) -> Unit,
|
||||
toggleOnlineService: (enable: Boolean) -> Unit
|
||||
) {
|
||||
val logger = LocalLogger.current
|
||||
val resources = LocalResources.current
|
||||
|
||||
val userSettings: UserSettings = koinInject()
|
||||
@@ -89,10 +93,6 @@ fun RootScreen(
|
||||
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
||||
|
||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||
LaunchedEffect(viewModel) {
|
||||
Log.d("VM_CREATE", "RootScreen(): viewModel: $viewModel")
|
||||
}
|
||||
|
||||
val currentUser: VkUser? by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||
|
||||
val permissionState =
|
||||
@@ -123,13 +123,12 @@ fun RootScreen(
|
||||
}
|
||||
|
||||
LifecycleResumeEffect(longPollStateToApply) {
|
||||
Log.d("LongPollMainActivity", "longPollStateToApply: $longPollStateToApply")
|
||||
logger.debug("RootScreen", "longPollStateToApply: $longPollStateToApply")
|
||||
if (longPollStateToApply != LongPollState.Background) {
|
||||
if (longPollStateToApply.isLaunched() && longPollCurrentState.isLaunched()
|
||||
&& longPollCurrentState != longPollStateToApply
|
||||
) {
|
||||
toggleLongPollService(false, null)
|
||||
Log.d("LongPoll", "recreate()")
|
||||
}
|
||||
|
||||
toggleLongPollService(
|
||||
@@ -310,6 +309,9 @@ fun RootScreen(
|
||||
mutableStateOf<Pair<List<String>, Int?>?>(null)
|
||||
}
|
||||
|
||||
val captchaRedirectUri by AppSettings.getCaptchaRedirectUriFlow()
|
||||
.collectAsStateWithLifecycle()
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
NavHost(
|
||||
navController = navController,
|
||||
@@ -334,7 +336,7 @@ fun RootScreen(
|
||||
photoViewerInfo = listOf(url) to null
|
||||
},
|
||||
onMessageClicked = navController::navigateToMessagesHistory,
|
||||
onNavigateToCreateChat = navController::navigateToCreateChat
|
||||
onNavigateToCreateChat = navController::navigateToCreateChat,
|
||||
)
|
||||
|
||||
messagesHistoryScreen(
|
||||
@@ -381,6 +383,18 @@ fun RootScreen(
|
||||
},
|
||||
onDismiss = { photoViewerInfo = null }
|
||||
)
|
||||
|
||||
CaptchaScreen(
|
||||
captchaRedirectUri = captchaRedirectUri,
|
||||
onBack = {
|
||||
AppSettings.setCaptchaResult(CaptchaTokenResult.Cancelled)
|
||||
},
|
||||
onResult = { result ->
|
||||
AppSettings.setCaptchaResult(
|
||||
CaptchaTokenResult.Success(result)
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import android.os.IBinder
|
||||
import android.util.Log
|
||||
import dev.meloda.fast.common.extensions.createTimerFlow
|
||||
import dev.meloda.fast.data.UserConfig
|
||||
import dev.meloda.fast.domain.AccountUseCase
|
||||
import dev.meloda.fast.data.processState
|
||||
import dev.meloda.fast.domain.AccountUseCase
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -24,11 +25,12 @@ import kotlin.time.Duration.Companion.minutes
|
||||
|
||||
class OnlineService : Service() {
|
||||
|
||||
private val logger: FastLogger by inject()
|
||||
|
||||
private val job = SupervisorJob()
|
||||
|
||||
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
|
||||
Log.d(TAG, "error: $throwable")
|
||||
throwable.printStackTrace()
|
||||
logger.error(this::class.java, "CoroutineException", throwable)
|
||||
}
|
||||
|
||||
private val coroutineContext: CoroutineContext
|
||||
@@ -42,17 +44,20 @@ class OnlineService : Service() {
|
||||
private var onlineJob: Job? = null
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? {
|
||||
Log.d(STATE_TAG, "onBind: intent: $intent")
|
||||
logger.debug(this::class, "STATE: onBind(): intent: $intent")
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (startId > 1) return START_STICKY
|
||||
|
||||
Log.d(STATE_TAG, "onStartCommand: flags: $flags; startId: $startId\ninstance: $this")
|
||||
logger.debug(
|
||||
this::class,
|
||||
"STATE: onStartCommand(): flags: %s; startId: %s;\ninstance: %s"
|
||||
.format("$flags", "$startId", "$this")
|
||||
)
|
||||
|
||||
createTimer()
|
||||
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
@@ -68,13 +73,13 @@ class OnlineService : Service() {
|
||||
private fun setOnline() {
|
||||
if (onlineJob != null) return
|
||||
|
||||
Log.d(TAG, "setOnline()")
|
||||
logger.debug(this::class, "setOnline()")
|
||||
|
||||
onlineJob = coroutineScope.launch {
|
||||
val token = UserConfig.fastToken ?: UserConfig.accessToken
|
||||
|
||||
if (token.isBlank()) {
|
||||
Log.d(TAG, "setOnline: token is empty")
|
||||
logger.debug(this::class, "setOnline(): token is empty")
|
||||
return@launch
|
||||
}
|
||||
|
||||
@@ -84,10 +89,10 @@ class OnlineService : Service() {
|
||||
).onEach { state ->
|
||||
state.processState(
|
||||
error = { error ->
|
||||
Log.w(TAG, "setOnline(): error: $error")
|
||||
logger.error(this@OnlineService::class, "setOnline(): ERROR: $error")
|
||||
},
|
||||
success = { response ->
|
||||
Log.d(TAG, "setOnline(): success: $response")
|
||||
logger.debug(this@OnlineService::class, "setOnline(): response: $response")
|
||||
}
|
||||
)
|
||||
}.collect()
|
||||
@@ -96,7 +101,7 @@ class OnlineService : Service() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
Log.d(STATE_TAG, "onDestroy")
|
||||
logger.debug(this::class, "onDestroy()")
|
||||
|
||||
timerJob?.cancel("OnlineService destroyed")
|
||||
onlineJob?.cancel("OnlineService destroyed")
|
||||
|
||||
@@ -7,7 +7,6 @@ import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import com.conena.nanokt.android.app.stopForegroundCompat
|
||||
@@ -19,8 +18,10 @@ import dev.meloda.fast.common.model.LongPollState
|
||||
import dev.meloda.fast.data.UserConfig
|
||||
import dev.meloda.fast.data.processState
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||
import dev.meloda.fast.domain.LongPollUseCase
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||
import dev.meloda.fast.ui.R
|
||||
@@ -32,14 +33,16 @@ import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import org.koin.android.ext.android.inject
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class LongPollingService : Service() {
|
||||
|
||||
private val logger: FastLogger by inject()
|
||||
|
||||
private val longPollController: LongPollController by inject()
|
||||
|
||||
private val job = SupervisorJob()
|
||||
@@ -56,6 +59,7 @@ class LongPollingService : Service() {
|
||||
|
||||
private val longPollUseCase: LongPollUseCase by inject()
|
||||
private val updatesParser: LongPollUpdatesParser by inject()
|
||||
private val eventsHandler: LongPollEventsHandler by inject()
|
||||
|
||||
private var currentJob: Job? = null
|
||||
|
||||
@@ -63,20 +67,21 @@ class LongPollingService : Service() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Log.d(STATE_TAG, "onCreate()")
|
||||
logger.debug(this::class, "STATE: onCreate()")
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? {
|
||||
Log.d(STATE_TAG, "onBind: intent: $intent")
|
||||
logger.debug(this::class, "STATE: onBind(): intent: $intent")
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (startId > 1) return START_STICKY
|
||||
|
||||
Log.d(
|
||||
STATE_TAG,
|
||||
"onStartCommand: asForeground: $inBackground; flags: $flags; startId: $startId;\ninstance: $this"
|
||||
logger.debug(
|
||||
this::class,
|
||||
"STATE: onStartCommand(): asForeground: %s; flags: %s; startId: %s;\ninstance: %s"
|
||||
.format("$inBackground", "$flags", "$startId", "$this")
|
||||
)
|
||||
|
||||
startJob()
|
||||
@@ -131,11 +136,15 @@ class LongPollingService : Service() {
|
||||
|
||||
private fun startPolling(): Job {
|
||||
if (job.isCompleted || job.isCancelled) {
|
||||
Log.d(STATE_TAG, "Job is completed or cancelled")
|
||||
logger.debug(
|
||||
this::class,
|
||||
"startPolling(): Job is already done. isCompleted: %s; isCancelled: %s"
|
||||
.format("${job.isCompleted}", "${job.isCancelled}")
|
||||
)
|
||||
throw Exception("Job is over")
|
||||
}
|
||||
|
||||
Log.d(STATE_TAG, "Starting job...")
|
||||
logger.debug(this::class, "startPolling(): Starting job.")
|
||||
|
||||
return coroutineScope.launch(coroutineContext) {
|
||||
longPollController.updateCurrentState(
|
||||
@@ -193,7 +202,7 @@ class LongPollingService : Service() {
|
||||
if (updates == null) {
|
||||
failCount++
|
||||
} else {
|
||||
updates.forEach(updatesParser::parseNextUpdate)
|
||||
parseUpdates(updates)
|
||||
}
|
||||
|
||||
lastUpdatesResponse = getUpdatesResponse(serverInfo.copy(ts = newTs))
|
||||
@@ -204,18 +213,18 @@ class LongPollingService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getServerInfo(): VkLongPollData? = suspendCoroutine {
|
||||
private suspend fun getServerInfo(): VkLongPollData? = suspendCancellableCoroutine {
|
||||
longPollUseCase.getLongPollServer(
|
||||
needPts = true,
|
||||
version = VkConstants.LP_VERSION
|
||||
).listenValue(coroutineScope) { state ->
|
||||
state.processState(
|
||||
success = { response ->
|
||||
Log.d(TAG, "getServerInfo: serverInfoResponse: $response")
|
||||
logger.debug(this::class, "getServerInfo(): response: $response")
|
||||
it.resume(response)
|
||||
},
|
||||
error = { error ->
|
||||
Log.e(TAG, "getServerInfo: $error")
|
||||
logger.error(this::class, "getServerInfo(): ERROR: $error")
|
||||
it.resume(null)
|
||||
}
|
||||
)
|
||||
@@ -224,7 +233,7 @@ class LongPollingService : Service() {
|
||||
|
||||
private suspend fun getUpdatesResponse(
|
||||
server: VkLongPollData
|
||||
): LongPollUpdates? = suspendCoroutine {
|
||||
): LongPollUpdates? = suspendCancellableCoroutine {
|
||||
longPollUseCase.getLongPollUpdates(
|
||||
serverUrl = "https://${server.server}",
|
||||
key = server.key,
|
||||
@@ -235,19 +244,24 @@ class LongPollingService : Service() {
|
||||
).listenValue(coroutineScope) { state ->
|
||||
state.processState(
|
||||
success = { response ->
|
||||
Log.d(TAG, "lastUpdateResponse: $response")
|
||||
logger.debug(this::class, "getUpdatesResponse(): response: $response")
|
||||
it.resume(response)
|
||||
},
|
||||
error = { error ->
|
||||
Log.d(TAG, "getUpdatesResponse: error: $error")
|
||||
logger.debug(this::class, "getUpdatesResponse(): error: $error")
|
||||
it.resume(null)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun parseUpdates(updates: List<List<Any>>) {
|
||||
val parsedUpdates = updates.flatMap { updatesParser.parseNextUpdate(it) }
|
||||
eventsHandler.handleEvents(parsedUpdates)
|
||||
}
|
||||
|
||||
private fun handleError(throwable: Throwable) {
|
||||
Log.e(TAG, "error: $throwable")
|
||||
logger.error(this::class, "CoroutineException", throwable)
|
||||
|
||||
if (throwable !is NoAccessTokenException) {
|
||||
throwable.printStackTrace()
|
||||
@@ -262,7 +276,7 @@ class LongPollingService : Service() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
Log.d(STATE_TAG, "onDestroy")
|
||||
logger.debug(this::class, "STATE: onDestroy()")
|
||||
longPollController.updateCurrentState(LongPollState.Stopped)
|
||||
try {
|
||||
AppSettings.edit { putBoolean(KEY_LONG_POLL_WAS_DESTROYED, true) }
|
||||
@@ -274,7 +288,7 @@ class LongPollingService : Service() {
|
||||
}
|
||||
|
||||
override fun onTrimMemory(level: Int) {
|
||||
Log.d(STATE_TAG, "onTrimMemory. Level: $level")
|
||||
logger.debug(this::class, "STATE: onTrimMemory(): Level: $level")
|
||||
super.onTrimMemory(level)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package dev.meloda.fast.service.longpolling.di
|
||||
|
||||
import dev.meloda.fast.domain.LongPollEventsHandler
|
||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||
import dev.meloda.fast.domain.LongPollUseCase
|
||||
import dev.meloda.fast.domain.LongPollUseCaseImpl
|
||||
@@ -10,4 +11,5 @@ import org.koin.dsl.module
|
||||
val longPollModule = module {
|
||||
singleOf(::LongPollUseCaseImpl) bind LongPollUseCase::class
|
||||
singleOf(::LongPollUpdatesParser)
|
||||
singleOf(::LongPollEventsHandler)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import dev.meloda.fast.configureKotlinAndroid
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
@@ -14,9 +15,12 @@ class AndroidApplicationConventionPlugin : Plugin<Project> {
|
||||
extensions.configure<ApplicationExtension> {
|
||||
configureKotlinAndroid(this)
|
||||
defaultConfig {
|
||||
targetSdk = 36
|
||||
compileSdk = 36
|
||||
minSdk = 23
|
||||
minSdk = getVersionInt("minSdk")
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
targetSdk = getVersionInt("targetSdk")
|
||||
}
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import com.android.build.api.dsl.LibraryExtension
|
||||
import dev.meloda.fast.configureAndroidCompose
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.apply
|
||||
import org.gradle.kotlin.dsl.getByType
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
|
||||
class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
|
||||
override fun apply(target: Project) {
|
||||
@@ -12,9 +13,14 @@ class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
|
||||
apply(plugin = "org.jetbrains.kotlin.plugin.compose")
|
||||
apply(plugin = "com.github.skydoves.compose.stability.analyzer")
|
||||
|
||||
val extension = extensions.getByType<LibraryExtension>()
|
||||
extension.androidResources.enable = false
|
||||
configureAndroidCompose(extension)
|
||||
extensions.configure<LibraryExtension> {
|
||||
configureAndroidCompose(this)
|
||||
androidResources.enable = false
|
||||
defaultConfig {
|
||||
minSdk = getVersionInt("minSdk")
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import com.android.build.api.dsl.LibraryExtension
|
||||
import com.android.build.api.variant.LibraryAndroidComponentsExtension
|
||||
import dev.meloda.fast.configureKotlinAndroid
|
||||
import dev.meloda.fast.disableUnnecessaryAndroidTests
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
@@ -20,7 +21,13 @@ class AndroidLibraryConventionPlugin : Plugin<Project> {
|
||||
extensions.configure<LibraryExtension> {
|
||||
configureKotlinAndroid(this)
|
||||
androidResources.enable = false
|
||||
defaultConfig.testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
defaultConfig {
|
||||
minSdk = getVersionInt("minSdk")
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
}
|
||||
extensions.configure<LibraryAndroidComponentsExtension> {
|
||||
disableUnnecessaryAndroidTests(target)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import com.android.build.api.dsl.TestExtension
|
||||
import dev.meloda.fast.configureKotlinAndroid
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
@@ -13,7 +14,11 @@ class AndroidTestConventionPlugin : Plugin<Project> {
|
||||
|
||||
extensions.configure<TestExtension> {
|
||||
configureKotlinAndroid(this)
|
||||
defaultConfig.targetSdk = 36
|
||||
defaultConfig {
|
||||
minSdk = getVersionInt("minSdk")
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
targetSdk = getVersionInt("targetSdk")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ internal fun Project.configureKotlinAndroid(
|
||||
}
|
||||
|
||||
commonExtension.apply {
|
||||
compileSdk = 36
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
}
|
||||
|
||||
configureKotlin<KotlinAndroidProjectExtension>()
|
||||
@@ -61,6 +61,7 @@ private inline fun <reified T : KotlinBaseExtension> Project.configureKotlin() =
|
||||
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
|
||||
"-opt-in=kotlinx.coroutines.FlowPreview",
|
||||
"-Xannotation-default-target=param-property",
|
||||
"-Xcontext-parameters"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,3 +7,8 @@ import org.gradle.kotlin.dsl.getByType
|
||||
|
||||
val Project.libs
|
||||
get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
|
||||
|
||||
|
||||
fun Project.getVersionInt(alias: String): Int {
|
||||
return libs.findVersion(alias).get().requiredVersion.toInt()
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ object AppConstants {
|
||||
|
||||
const val INSTALL_APP_MIME_TYPE = "application/vnd.android.package-archive"
|
||||
|
||||
const val API_VERSION = "5.238"
|
||||
const val API_VERSION = "5.263"
|
||||
const val URL_OAUTH = "https://oauth.vk.ru"
|
||||
const val URL_API = "https://api.vk.ru/method"
|
||||
|
||||
|
||||
+2
-2
@@ -1,13 +1,13 @@
|
||||
package dev.meloda.fast.common.model
|
||||
|
||||
enum class LogLevel(val value: Int) {
|
||||
enum class NetworkLogLevel(val value: Int) {
|
||||
NONE(0),
|
||||
BASIC(1),
|
||||
HEADERS(2),
|
||||
BODY(3);
|
||||
|
||||
companion object {
|
||||
fun parse(value: Int): LogLevel = entries.firstOrNull { it.value == value }
|
||||
fun parse(value: Int): NetworkLogLevel = entries.firstOrNull { it.value == value }
|
||||
?: throw IllegalArgumentException("Unknown log level with value: $value")
|
||||
}
|
||||
}
|
||||
@@ -23,5 +23,6 @@ interface OAuthRepository {
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?,
|
||||
successToken: String?
|
||||
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain>
|
||||
}
|
||||
|
||||
@@ -79,7 +79,8 @@ class OAuthRepositoryImpl(
|
||||
VkOAuthError.NEED_CAPTCHA -> {
|
||||
OAuthErrorDomain.CaptchaRequiredError(
|
||||
captchaSid = response.captchaSid.orEmpty(),
|
||||
captchaImageUrl = response.captchaImage.orEmpty()
|
||||
captchaImageUrl = response.captchaImage.orEmpty(),
|
||||
redirectUri = response.redirectUri
|
||||
)
|
||||
}
|
||||
|
||||
@@ -122,6 +123,7 @@ class OAuthRepositoryImpl(
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?,
|
||||
successToken: String?
|
||||
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val requestModel = AuthDirectRequest(
|
||||
@@ -135,6 +137,7 @@ class OAuthRepositoryImpl(
|
||||
validationCode = validationCode,
|
||||
captchaSid = captchaSid,
|
||||
captchaKey = captchaKey,
|
||||
successToken = successToken
|
||||
)
|
||||
|
||||
oAuthService.getSilentToken(requestModel.map).mapResult(
|
||||
@@ -175,7 +178,8 @@ class OAuthRepositoryImpl(
|
||||
VkOAuthError.NEED_CAPTCHA -> {
|
||||
OAuthErrorDomain.CaptchaRequiredError(
|
||||
captchaSid = response.captchaSid.orEmpty(),
|
||||
captchaImageUrl = response.captchaImage.orEmpty()
|
||||
captchaImageUrl = response.captchaImage.orEmpty(),
|
||||
redirectUri = response.redirectUri
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 12,
|
||||
"identityHash": "5eca3b3da167aaf7e772977a1f4e56e2",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "users",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `firstName` TEXT NOT NULL, `lastName` TEXT NOT NULL, `isOnline` INTEGER NOT NULL, `isOnlineMobile` INTEGER NOT NULL, `onlineAppId` INTEGER, `lastSeen` INTEGER, `lastSeenStatus` TEXT, `birthday` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `photo400Orig` TEXT, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "firstName",
|
||||
"columnName": "firstName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastName",
|
||||
"columnName": "lastName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOnline",
|
||||
"columnName": "isOnline",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOnlineMobile",
|
||||
"columnName": "isOnlineMobile",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "onlineAppId",
|
||||
"columnName": "onlineAppId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastSeen",
|
||||
"columnName": "lastSeen",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastSeenStatus",
|
||||
"columnName": "lastSeenStatus",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "birthday",
|
||||
"columnName": "birthday",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo400Orig",
|
||||
"columnName": "photo400Orig",
|
||||
"affinity": "TEXT"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "groups",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `screenName` TEXT NOT NULL, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `membersCount` INTEGER, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenName",
|
||||
"columnName": "screenName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "membersCount",
|
||||
"columnName": "membersCount",
|
||||
"affinity": "INTEGER"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "messages",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `cmId` INTEGER NOT NULL, `text` TEXT, `isOut` INTEGER NOT NULL, `peerId` INTEGER NOT NULL, `fromId` INTEGER NOT NULL, `date` INTEGER NOT NULL, `randomId` INTEGER NOT NULL, `action` TEXT, `actionMemberId` INTEGER, `actionText` TEXT, `actionCmId` INTEGER, `actionMessage` TEXT, `updateTime` INTEGER, `isImportant` INTEGER NOT NULL, `forwardIds` TEXT, `attachments` TEXT, `replyMessageId` INTEGER, `geoType` TEXT, `pinnedAt` INTEGER, `isPinned` INTEGER NOT NULL, `isDeleted` INTEGER NOT NULL, `isSpam` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "cmId",
|
||||
"columnName": "cmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "text",
|
||||
"columnName": "text",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOut",
|
||||
"columnName": "isOut",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "peerId",
|
||||
"columnName": "peerId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fromId",
|
||||
"columnName": "fromId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "date",
|
||||
"columnName": "date",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "randomId",
|
||||
"columnName": "randomId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "action",
|
||||
"columnName": "action",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionMemberId",
|
||||
"columnName": "actionMemberId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionText",
|
||||
"columnName": "actionText",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionCmId",
|
||||
"columnName": "actionCmId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionMessage",
|
||||
"columnName": "actionMessage",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "updateTime",
|
||||
"columnName": "updateTime",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isImportant",
|
||||
"columnName": "isImportant",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "forwardIds",
|
||||
"columnName": "forwardIds",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "attachments",
|
||||
"columnName": "attachments",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "replyMessageId",
|
||||
"columnName": "replyMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "geoType",
|
||||
"columnName": "geoType",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pinnedAt",
|
||||
"columnName": "pinnedAt",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPinned",
|
||||
"columnName": "isPinned",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isDeleted",
|
||||
"columnName": "isDeleted",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isSpam",
|
||||
"columnName": "isSpam",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "convos",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `localId` INTEGER NOT NULL, `ownerId` INTEGER, `title` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `isPhantom` INTEGER NOT NULL, `lastCmId` INTEGER NOT NULL, `inReadCmId` INTEGER NOT NULL, `outReadCmId` INTEGER NOT NULL, `inRead` INTEGER NOT NULL, `outRead` INTEGER NOT NULL, `lastMessageId` INTEGER, `unreadCount` INTEGER NOT NULL, `membersCount` INTEGER, `canChangePin` INTEGER NOT NULL, `canChangeInfo` INTEGER NOT NULL, `majorId` INTEGER NOT NULL, `minorId` INTEGER NOT NULL, `pinnedMessageId` INTEGER, `peerType` TEXT NOT NULL, `isArchived` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "localId",
|
||||
"columnName": "localId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "ownerId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "title",
|
||||
"columnName": "title",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPhantom",
|
||||
"columnName": "isPhantom",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastCmId",
|
||||
"columnName": "lastCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "inReadCmId",
|
||||
"columnName": "inReadCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "outReadCmId",
|
||||
"columnName": "outReadCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "inRead",
|
||||
"columnName": "inRead",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "outRead",
|
||||
"columnName": "outRead",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastMessageId",
|
||||
"columnName": "lastMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "unreadCount",
|
||||
"columnName": "unreadCount",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "membersCount",
|
||||
"columnName": "membersCount",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "canChangePin",
|
||||
"columnName": "canChangePin",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "canChangeInfo",
|
||||
"columnName": "canChangeInfo",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "majorId",
|
||||
"columnName": "majorId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "minorId",
|
||||
"columnName": "minorId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "pinnedMessageId",
|
||||
"columnName": "pinnedMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "peerType",
|
||||
"columnName": "peerType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isArchived",
|
||||
"columnName": "isArchived",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '5eca3b3da167aaf7e772977a1f4e56e2')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import dev.meloda.fast.model.database.VkUserEntity
|
||||
VkConvoEntity::class
|
||||
],
|
||||
|
||||
version = 11
|
||||
version = 12
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class CacheDatabase : RoomDatabase() {
|
||||
|
||||
@@ -13,7 +13,7 @@ abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
||||
abstract suspend fun getAll(): List<VkConvoEntity>
|
||||
|
||||
@Query("SELECT * FROM convos WHERE id IN (:ids)")
|
||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkConvoEntity>
|
||||
abstract suspend fun getAllByIds(ids: List<Long>): List<VkConvoEntity>
|
||||
|
||||
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
||||
abstract suspend fun getById(id: Long): VkConvoEntity?
|
||||
@@ -23,8 +23,23 @@ abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
||||
abstract suspend fun getByIdWithMessage(id: Long): ConvoWithMessage?
|
||||
|
||||
@Query("DELETE FROM convos WHERE rowid IN (:ids)")
|
||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||
abstract suspend fun deleteByIds(ids: List<Long>): Int
|
||||
|
||||
@Query("UPDATE convos SET inReadCmId = :cmId, unreadCount = :unreadCount WHERE id = :convoId")
|
||||
abstract suspend fun updateReadIncoming(convoId: Long, cmId: Long, unreadCount: Int): Int
|
||||
|
||||
@Query("UPDATE convos SET outReadCmId = :cmId, unreadCount = :unreadCount WHERE id = :convoId")
|
||||
abstract suspend fun updateReadOutgoing(convoId: Long, cmId: Long, unreadCount: Int): Int
|
||||
|
||||
@Query("UPDATE convos SET isArchived = :isArchived WHERE id = :convoId")
|
||||
abstract suspend fun updateIsArchived(convoId: Long, isArchived: Boolean): Int
|
||||
|
||||
@Query("UPDATE convos SET majorId = :majorId WHERE id = :convoId")
|
||||
abstract suspend fun updateMajorId(convoId: Long, majorId: Int): Int
|
||||
|
||||
@Query("UPDATE convos SET minorId = :minorId WHERE id = :convoId")
|
||||
abstract suspend fun updateMinorId(convoId: Long, minorId: Int): Int
|
||||
|
||||
@Query("UPDATE convos SET lastCmId = :cmId WHERE id = :convoId")
|
||||
abstract suspend fun updateLastCmId(convoId: Long, cmId: Long): Int
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import dev.meloda.fast.model.database.VkMessageEntity
|
||||
@Dao
|
||||
abstract class MessageDao : EntityDao<VkMessageEntity> {
|
||||
|
||||
@Query("SELECT * FROM messages")
|
||||
@Query("SELECT * FROM messages WHERE isDeleted = 0 AND isSpam = 0")
|
||||
abstract suspend fun getAll(): List<VkMessageEntity>
|
||||
|
||||
@Query("SELECT * FROM messages WHERE peerId IS (:convoId)")
|
||||
@@ -21,4 +21,13 @@ abstract class MessageDao : EntityDao<VkMessageEntity> {
|
||||
|
||||
@Query("DELETE FROM messages WHERE id IN (:ids)")
|
||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||
|
||||
@Query("UPDATE messages SET isDeleted = :isDeleted WHERE peerId = :convoId AND cmId = :cmId")
|
||||
abstract suspend fun markAsDeleted(convoId: Long, cmId: Long, isDeleted: Boolean): Int
|
||||
|
||||
@Query("UPDATE messages SET isImportant = :isImportant WHERE peerId = :convoId AND cmId = :cmId")
|
||||
abstract suspend fun markAsImportant(convoId: Long, cmId: Long, isImportant: Boolean): Int
|
||||
|
||||
@Query("UPDATE messages SET isSpam = :isSpam WHERE peerId = :convoId AND cmId = :cmId")
|
||||
abstract suspend fun markAsSpam(convoId: Long, cmId: Long, isSpam: Boolean): Int
|
||||
}
|
||||
|
||||
@@ -3,14 +3,33 @@ package dev.meloda.fast.datastore
|
||||
import android.content.SharedPreferences
|
||||
import androidx.core.content.edit
|
||||
import dev.meloda.fast.common.model.DarkMode
|
||||
import dev.meloda.fast.common.model.LogLevel
|
||||
import dev.meloda.fast.common.model.NetworkLogLevel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlin.properties.Delegates
|
||||
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 {
|
||||
|
||||
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) {
|
||||
this.preferences = preferences
|
||||
}
|
||||
@@ -219,11 +238,11 @@ object AppSettings {
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_DEBUG_SHOW_CRASH_ALERT, value)
|
||||
|
||||
var networkLogLevel: LogLevel
|
||||
var networkLogLevel: NetworkLogLevel
|
||||
get() = get(
|
||||
SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL,
|
||||
SettingsKeys.DEFAULT_NETWORK_LOG_LEVEL
|
||||
).let(LogLevel::parse)
|
||||
).let(NetworkLogLevel::parse)
|
||||
set(level) = put(SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL, level.value)
|
||||
|
||||
var showDebugCategory: Boolean
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.database.dao.ConvoDao
|
||||
import dev.meloda.fast.database.dao.MessageDao
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.model.LongPollParsedEvent
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
|
||||
class LongPollEventsHandler(
|
||||
private val logger: FastLogger,
|
||||
private val convoUseCase: ConvoUseCase,
|
||||
private val messagesUseCase: MessagesUseCase,
|
||||
private val convoDao: ConvoDao,
|
||||
private val messageDao: MessageDao,
|
||||
) {
|
||||
private val job = SupervisorJob()
|
||||
|
||||
private val exceptionHandler =
|
||||
CoroutineExceptionHandler { _, throwable ->
|
||||
logger.error(this::class, "CoroutineException", throwable)
|
||||
}
|
||||
|
||||
private val coroutineContext: CoroutineContext
|
||||
get() = Dispatchers.Default + job + exceptionHandler
|
||||
|
||||
private val coroutineScope = CoroutineScope(coroutineContext)
|
||||
|
||||
suspend fun handleEvents(events: List<LongPollParsedEvent>) {
|
||||
events.forEach { handleNextEvent(it) }
|
||||
}
|
||||
|
||||
private suspend fun handleNextEvent(event: LongPollParsedEvent) {
|
||||
when (event) {
|
||||
is LongPollParsedEvent.AudioMessageListened -> {
|
||||
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.ChatArchived -> {
|
||||
val affectedRows = convoDao.updateIsArchived(
|
||||
convoId = event.convo.id,
|
||||
isArchived = event.convo.isArchived
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"isArchived ${event.convo.isArchived}: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.ChatCleared -> {
|
||||
val affectedRows = convoDao.updateLastCmId(
|
||||
convoId = event.peerId,
|
||||
cmId = event.toCmId
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"updateLastCmId: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.ChatMajorChanged -> {
|
||||
val affectedRows = convoDao.updateMajorId(
|
||||
convoId = event.peerId,
|
||||
majorId = event.majorId
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"updateMajorId: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.ChatMinorChanged -> {
|
||||
val affectedRows = convoDao.updateMinorId(
|
||||
convoId = event.peerId,
|
||||
minorId = event.minorId
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"updateMinorId: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.Interaction -> {
|
||||
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageCacheClear -> {
|
||||
messagesUseCase.storeMessage(event.message)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageDeleted -> {
|
||||
val affectedRows = messageDao.markAsDeleted(
|
||||
convoId = event.peerId,
|
||||
cmId = event.cmId,
|
||||
isDeleted = true
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"markDeleted: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageEdited -> {
|
||||
messagesUseCase.storeMessage(event.message)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageMarkedAsImportant -> {
|
||||
val affectedRows = messageDao.markAsImportant(
|
||||
convoId = event.peerId,
|
||||
cmId = event.cmId,
|
||||
isImportant = event.marked
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"markImportant: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageMarkedAsNotSpam -> {
|
||||
messagesUseCase.storeMessage(event.message)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageMarkedAsSpam -> {
|
||||
val affectedRows = messageDao.markAsSpam(
|
||||
convoId = event.peerId,
|
||||
cmId = event.cmId,
|
||||
isSpam = true
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"markSpam: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageRestored -> {
|
||||
messagesUseCase.storeMessage(event.message)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.MessageUpdated -> {
|
||||
messagesUseCase.storeMessage(event.message)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.NewMessage -> {
|
||||
messagesUseCase.storeMessage(event.message)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.IncomingMessageRead -> {
|
||||
val affectedRows = convoDao.updateReadIncoming(
|
||||
convoId = event.peerId,
|
||||
cmId = event.cmId,
|
||||
unreadCount = event.unreadCount
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"inMessageRead: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.OutgoingMessageRead -> {
|
||||
val affectedRows = convoDao.updateReadOutgoing(
|
||||
convoId = event.peerId,
|
||||
cmId = event.cmId,
|
||||
unreadCount = event.unreadCount
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
this::class,
|
||||
"outMessageRead: updated $affectedRows rows."
|
||||
)
|
||||
}
|
||||
|
||||
is LongPollParsedEvent.UnreadCounter -> {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
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
|
||||
@@ -8,6 +7,7 @@ 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.logger.FastLogger
|
||||
import dev.meloda.fast.model.ApiEvent
|
||||
import dev.meloda.fast.model.ConvoFlags
|
||||
import dev.meloda.fast.model.InteractionType
|
||||
@@ -22,12 +22,12 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
|
||||
class LongPollUpdatesParser(
|
||||
private val logger: FastLogger,
|
||||
private val convoUseCase: ConvoUseCase,
|
||||
private val messagesUseCase: MessagesUseCase
|
||||
) {
|
||||
@@ -35,8 +35,7 @@ class LongPollUpdatesParser(
|
||||
|
||||
private val exceptionHandler =
|
||||
CoroutineExceptionHandler { _, throwable ->
|
||||
Log.e("LongPollUpdatesParser", "error: $throwable")
|
||||
throwable.printStackTrace()
|
||||
logger.error(this::class, "CoroutineException", throwable)
|
||||
}
|
||||
|
||||
private val coroutineContext: CoroutineContext
|
||||
@@ -47,11 +46,14 @@ class LongPollUpdatesParser(
|
||||
private val listenersMap: MutableMap<LongPollEvent, MutableList<VkEventCallback<LongPollParsedEvent>>> =
|
||||
mutableMapOf()
|
||||
|
||||
fun parseNextUpdate(event: List<Any>) {
|
||||
suspend fun parseNextUpdate(event: List<Any>): List<LongPollParsedEvent> {
|
||||
val eventId = event.first().asInt()
|
||||
|
||||
when (val eventType = ApiEvent.parseOrNull(eventId)) {
|
||||
null -> Log.d("LongPollUpdatesParser", "parseNextUpdate: unknownEvent: $event")
|
||||
return when (val eventType = ApiEvent.parseOrNull(eventId)) {
|
||||
null -> {
|
||||
logger.debug(this::class, "parseNextUpdate(): unknownEvent: $event")
|
||||
emptyList()
|
||||
}
|
||||
|
||||
ApiEvent.MESSAGE_SET_FLAGS -> parseMessageSetFlags(eventType, event)
|
||||
ApiEvent.MESSAGE_CLEAR_FLAGS -> parseMessageClearFlags(eventType, event)
|
||||
@@ -77,8 +79,11 @@ class LongPollUpdatesParser(
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseMessageSetFlags(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseMessageSetFlags(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseMessageSetFlags(): $eventType: $event")
|
||||
|
||||
val cmId = event[1].asLong()
|
||||
val flags = event[2].asInt()
|
||||
@@ -97,12 +102,8 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsImportant>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]
|
||||
?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
|
||||
MessageFlags.SPAM -> {
|
||||
@@ -111,13 +112,7 @@ class LongPollUpdatesParser(
|
||||
cmId = cmId
|
||||
)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.MARKED_AS_SPAM]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsSpam>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MARKED_AS_SPAM]?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
|
||||
MessageFlags.DELETED -> {
|
||||
@@ -136,13 +131,7 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
}
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.MESSAGE_DELETED]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageDeleted>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MESSAGE_DELETED]?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
|
||||
MessageFlags.AUDIO_LISTENED -> {
|
||||
@@ -152,29 +141,37 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.AUDIO_MESSAGE_LISTENED]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.AudioMessageListened>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.AUDIO_MESSAGE_LISTENED]
|
||||
?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
MessageFlags.UNREAD -> Unit
|
||||
MessageFlags.OUTGOING -> Unit
|
||||
MessageFlags.FROM_GROUP_CHAT -> Unit
|
||||
MessageFlags.CANCEL_SPAM -> Unit
|
||||
MessageFlags.DELETED_FOR_ALL -> Unit
|
||||
MessageFlags.DO_NOT_SHOW_NOTIFICATION -> Unit
|
||||
MessageFlags.MESSAGE_WITH_REPLY -> Unit
|
||||
MessageFlags.REACTION -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
eventsToSend.forEach { eventToSend ->
|
||||
listenersMap[LongPollEvent.MESSAGE_SET_FLAGS]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(eventToSend)
|
||||
listeners.forEach { vkEventCallback ->
|
||||
vkEventCallback.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return eventsToSend
|
||||
}
|
||||
|
||||
private fun parseMessageClearFlags(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private suspend fun parseMessageClearFlags(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseMessageClearFlags(): $eventType: $event")
|
||||
|
||||
val cmId = event[1].asLong()
|
||||
val flags = event[2].asInt()
|
||||
@@ -184,7 +181,9 @@ class LongPollUpdatesParser(
|
||||
|
||||
val parsedFlags = MessageFlags.parse(flags)
|
||||
|
||||
coroutineScope.launch {
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
val message = loadMessage(peerId = peerId, cmId = cmId)
|
||||
|
||||
parsedFlags.forEach { flag ->
|
||||
when (flag) {
|
||||
MessageFlags.IMPORTANT -> {
|
||||
@@ -195,81 +194,65 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageMarkedAsImportant>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MARKED_AS_IMPORTANT]
|
||||
?.forEach { it.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
|
||||
if (message != null) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MARKED_AS_NOT_SPAM]
|
||||
?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MessageFlags.DELETED -> {
|
||||
withContext(Dispatchers.IO) {
|
||||
val message = loadMessage(
|
||||
peerId = peerId,
|
||||
cmId = cmId
|
||||
)
|
||||
message?.let {
|
||||
val eventToSend =
|
||||
LongPollParsedEvent.MessageRestored(message = message)
|
||||
eventsToSend += eventToSend
|
||||
if (message != null) {
|
||||
val eventToSend =
|
||||
LongPollParsedEvent.MessageRestored(message = message)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.MESSAGE_RESTORED]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.MessageRestored>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MESSAGE_RESTORED]
|
||||
?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
MessageFlags.UNREAD -> Unit
|
||||
MessageFlags.OUTGOING -> Unit
|
||||
MessageFlags.AUDIO_LISTENED -> Unit
|
||||
MessageFlags.FROM_GROUP_CHAT -> Unit
|
||||
MessageFlags.CANCEL_SPAM -> Unit
|
||||
MessageFlags.DELETED_FOR_ALL -> Unit
|
||||
MessageFlags.DO_NOT_SHOW_NOTIFICATION -> Unit
|
||||
MessageFlags.MESSAGE_WITH_REPLY -> Unit
|
||||
MessageFlags.REACTION -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
eventsToSend.forEach { eventToSend ->
|
||||
listenersMap[LongPollEvent.MESSAGE_CLEAR_FLAGS]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
vkEventCallback.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.MESSAGE_CLEAR_FLAGS]?.forEach { listener ->
|
||||
eventsToSend.forEach { listener.onEvent(it) }
|
||||
}
|
||||
|
||||
continuation.resume(eventsToSend)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseMessageNew(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private suspend fun parseMessageNew(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseMessageNew(): $eventType: $event")
|
||||
|
||||
val cmId = event[1].asLong()
|
||||
val peerId = event[4].asLong()
|
||||
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
val message =
|
||||
async { loadMessage(peerId = peerId, cmId = cmId) }.await()
|
||||
val message = async { loadMessage(peerId = peerId, cmId = cmId) }.await()
|
||||
|
||||
val convo =
|
||||
async {
|
||||
@@ -280,88 +263,88 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
}.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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
if (message != null) {
|
||||
val event = 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
|
||||
)
|
||||
|
||||
listenersMap[LongPollEvent.MESSAGE_NEW]?.forEach { it.onEvent(event) }
|
||||
continuation.resume(listOf(event))
|
||||
} else {
|
||||
continuation.resume(emptyList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseMessageEdit(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private suspend fun parseMessageEdit(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseMessageEdit(): $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))
|
||||
}
|
||||
}
|
||||
val message = loadMessage(peerId = peerId, cmId = cmId)
|
||||
if (message != null) {
|
||||
val event = LongPollParsedEvent.MessageEdited(message)
|
||||
listenersMap[LongPollEvent.MESSAGE_EDITED]?.forEach { it.onEvent(event) }
|
||||
continuation.resume(listOf(event))
|
||||
} else {
|
||||
continuation.resume(emptyList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseMessageReadIncoming(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseMessageReadIncoming(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseMessageReadIncoming(): $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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.IncomingMessageRead(
|
||||
peerId = peerId,
|
||||
cmId = cmId,
|
||||
unreadCount = unreadCount
|
||||
)
|
||||
listenersMap[LongPollEvent.INCOMING_MESSAGE_READ]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseMessageReadOutgoing(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseMessageReadOutgoing(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseMessageReadOutgoing(): $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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.OutgoingMessageRead(
|
||||
peerId = peerId,
|
||||
cmId = cmId,
|
||||
unreadCount = unreadCount
|
||||
)
|
||||
|
||||
listenersMap[LongPollEvent.OUTGOING_MESSAGE_READ]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseChatClearFlags(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private suspend fun parseChatClearFlags(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseChatClearFlags(): $eventType: $event")
|
||||
|
||||
val peerId = event[1].asLong()
|
||||
val flags = event[2].asInt()
|
||||
@@ -391,32 +374,37 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.ChatArchived>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
ConvoFlags.DISABLE_PUSH -> Unit
|
||||
ConvoFlags.DISABLE_SOUND -> Unit
|
||||
ConvoFlags.INCOMING_CHAT_REQUEST -> Unit
|
||||
ConvoFlags.DECLINED_CHAT_REQUEST -> Unit
|
||||
ConvoFlags.MENTION -> Unit
|
||||
ConvoFlags.HIDE_CHAT_FROM_SEARCH -> Unit
|
||||
ConvoFlags.BUSINESS_CHAT -> Unit
|
||||
ConvoFlags.MARKED_MESSAGE -> Unit
|
||||
ConvoFlags.DO_NOT_NOTIFY_MENTIONS_ALL_ONLINE -> Unit
|
||||
ConvoFlags.DO_NOT_NOTIFY_ALL_MENTIONS -> Unit
|
||||
ConvoFlags.MARKED_AS_UNREAD -> Unit
|
||||
ConvoFlags.CALL_IN_PROGRESS -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
eventsToSend.forEach { eventToSend ->
|
||||
listenersMap[LongPollEvent.CHAT_CLEAR_FLAGS]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(
|
||||
eventToSend
|
||||
)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.CHAT_CLEAR_FLAGS]?.forEach { listener ->
|
||||
eventsToSend.forEach { listener.onEvent(it) }
|
||||
}
|
||||
|
||||
continuation.resume(eventsToSend)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseChatSetFlags(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private suspend fun parseChatSetFlags(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseChatSetFlags(): $eventType: $event")
|
||||
|
||||
val peerId = event[1].asLong()
|
||||
val flags = event[2].asInt()
|
||||
@@ -446,89 +434,88 @@ class LongPollUpdatesParser(
|
||||
)
|
||||
eventsToSend += eventToSend
|
||||
|
||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent.ChatArchived>)
|
||||
?.onEvent(eventToSend)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.CHAT_ARCHIVED]?.forEach { it.onEvent(eventToSend) }
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
ConvoFlags.DISABLE_PUSH -> Unit
|
||||
ConvoFlags.DISABLE_SOUND -> Unit
|
||||
ConvoFlags.INCOMING_CHAT_REQUEST -> Unit
|
||||
ConvoFlags.DECLINED_CHAT_REQUEST -> Unit
|
||||
ConvoFlags.MENTION -> Unit
|
||||
ConvoFlags.HIDE_CHAT_FROM_SEARCH -> Unit
|
||||
ConvoFlags.BUSINESS_CHAT -> Unit
|
||||
ConvoFlags.MARKED_MESSAGE -> Unit
|
||||
ConvoFlags.DO_NOT_NOTIFY_MENTIONS_ALL_ONLINE -> Unit
|
||||
ConvoFlags.DO_NOT_NOTIFY_ALL_MENTIONS -> Unit
|
||||
ConvoFlags.MARKED_AS_UNREAD -> Unit
|
||||
ConvoFlags.CALL_IN_PROGRESS -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
eventsToSend.forEach { eventToSend ->
|
||||
listenersMap[LongPollEvent.CHAT_SET_FLAGS]?.let { listeners ->
|
||||
listeners.map { vkEventCallback ->
|
||||
(vkEventCallback as? VkEventCallback<LongPollParsedEvent>)?.onEvent(
|
||||
eventToSend
|
||||
)
|
||||
}
|
||||
}
|
||||
listenersMap[LongPollEvent.CHAT_SET_FLAGS]?.forEach { listener ->
|
||||
eventsToSend.forEach { listener.onEvent(it) }
|
||||
}
|
||||
|
||||
continuation.resume(eventsToSend)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseMessagesDeleted(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseMessagesDeleted(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseMessagesDeleted(): $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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.ChatCleared(
|
||||
peerId = peerId,
|
||||
toCmId = cmId
|
||||
)
|
||||
listenersMap[LongPollEvent.CHAT_CLEARED]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseChatMajorChanged(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseChatMajorChanged(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseChatMajorChanged(): $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,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.ChatMajorChanged(
|
||||
peerId = peerId,
|
||||
majorId = majorId,
|
||||
)
|
||||
listenersMap[LongPollEvent.CHAT_MAJOR_CHANGED]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseChatMinorChanged(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseChatMinorChanged(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseChatMinorChanged(): $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,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.ChatMinorChanged(
|
||||
peerId = peerId,
|
||||
minorId = minorId,
|
||||
)
|
||||
listenersMap[LongPollEvent.CHAT_MINOR_CHANGED]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseInteraction(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType: $event")
|
||||
private fun parseInteraction(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseInteraction(): $eventType: $event")
|
||||
|
||||
val interactionType = when (eventType) {
|
||||
ApiEvent.TYPING -> InteractionType.Typing
|
||||
@@ -536,7 +523,7 @@ class LongPollUpdatesParser(
|
||||
ApiEvent.PHOTO_UPLOADING -> InteractionType.Photo
|
||||
ApiEvent.VIDEO_UPLOADING -> InteractionType.Video
|
||||
ApiEvent.FILE_UPLOADING -> InteractionType.File
|
||||
else -> return
|
||||
else -> return emptyList()
|
||||
}
|
||||
|
||||
val longPollEvent: LongPollEvent = when (eventType) {
|
||||
@@ -545,7 +532,6 @@ class LongPollUpdatesParser(
|
||||
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()
|
||||
@@ -554,26 +540,25 @@ class LongPollUpdatesParser(
|
||||
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
|
||||
if (userIds.isEmpty()) return emptyList()
|
||||
|
||||
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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.Interaction(
|
||||
interactionType = interactionType,
|
||||
peerId = peerId,
|
||||
userIds = userIds,
|
||||
totalCount = totalCount,
|
||||
timestamp = timestamp
|
||||
)
|
||||
|
||||
listenersMap[longPollEvent]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseUnreadCounterUpdate(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
||||
private fun parseUnreadCounterUpdate(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> {
|
||||
logger.debug(this::class, "parseUnreadCounterUpdate(): $eventType: $event")
|
||||
|
||||
val unreadCount = event[1].asInt()
|
||||
val unreadUnmutedCount = event[2].asInt()
|
||||
@@ -583,58 +568,57 @@ class LongPollUpdatesParser(
|
||||
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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val event = LongPollParsedEvent.UnreadCounter(
|
||||
unread = unreadCount,
|
||||
unreadUnmuted = unreadUnmutedCount,
|
||||
showOnlyMuted = showOnlyMuted,
|
||||
business = businessNotifyUnreadCount,
|
||||
archive = archiveUnreadCount,
|
||||
archiveUnmuted = archiveUnreadUnmutedCount,
|
||||
archiveMentions = archiveMentionsCount
|
||||
)
|
||||
listenersMap[LongPollEvent.UNREAD_COUNTER_UPDATE]?.forEach { it.onEvent(event) }
|
||||
return listOf(event)
|
||||
}
|
||||
|
||||
private fun parseMessageUpdated(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
||||
private suspend fun parseMessageUpdated(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseMessageUpdated(): $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))
|
||||
}
|
||||
}
|
||||
val message = loadMessage(peerId = peerId, cmId = cmId)
|
||||
|
||||
if (message != null) {
|
||||
val event = LongPollParsedEvent.MessageUpdated(message)
|
||||
listenersMap[LongPollEvent.MESSAGE_UPDATED]?.forEach { it.onEvent(event) }
|
||||
continuation.resume(listOf(event))
|
||||
} else {
|
||||
continuation.resume(emptyList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseMessageCacheClear(eventType: ApiEvent, event: List<Any>) {
|
||||
Log.d("LongPollUpdatesParser", "$eventType $event")
|
||||
private suspend fun parseMessageCacheClear(
|
||||
eventType: ApiEvent,
|
||||
event: List<Any>
|
||||
): List<LongPollParsedEvent> = suspendCancellableCoroutine { continuation ->
|
||||
logger.debug(this::class, "parseMessageCacheClear(): $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))
|
||||
}
|
||||
}
|
||||
val message = loadMessage(messageId = messageId)
|
||||
if (message != null) {
|
||||
val event = LongPollParsedEvent.MessageCacheClear(message)
|
||||
listenersMap[LongPollEvent.MESSAGE_CACHE_CLEAR]?.forEach { it.onEvent(event) }
|
||||
continuation.resume(listOf(event))
|
||||
} else {
|
||||
continuation.resume(emptyList())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -643,7 +627,7 @@ class LongPollUpdatesParser(
|
||||
peerId: Long? = null,
|
||||
cmId: Long? = null,
|
||||
messageId: Long? = null
|
||||
): VkMessage? = suspendCoroutine { continuation ->
|
||||
): VkMessage? = suspendCancellableCoroutine { continuation ->
|
||||
require((peerId != null && cmId != null) || messageId != null)
|
||||
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
@@ -657,7 +641,7 @@ class LongPollUpdatesParser(
|
||||
).listenValue(this) { state ->
|
||||
state.processState(
|
||||
error = { error ->
|
||||
Log.e("LongPollUpdatesParser", "loadMessage: error: $error")
|
||||
logger.error(this::class, "loadMessage(): ERROR: $error")
|
||||
continuation.resume(null)
|
||||
},
|
||||
success = { response ->
|
||||
@@ -677,7 +661,7 @@ class LongPollUpdatesParser(
|
||||
peerId: Long,
|
||||
extended: Boolean = false,
|
||||
fields: String? = null
|
||||
): VkConvo? = suspendCoroutine { continuation ->
|
||||
): VkConvo? = suspendCancellableCoroutine { continuation ->
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
convoUseCase.getById(
|
||||
peerIds = listOf(peerId),
|
||||
@@ -686,7 +670,7 @@ class LongPollUpdatesParser(
|
||||
).listenValue(coroutineScope) { state ->
|
||||
state.processState(
|
||||
error = { error ->
|
||||
Log.e("LongPollUpdatesParser", "loadConvo: error: $error")
|
||||
logger.error(this::class, "loadConvo(): ERROR: $error")
|
||||
continuation.resume(null)
|
||||
},
|
||||
success = { response ->
|
||||
|
||||
@@ -21,7 +21,8 @@ interface OAuthUseCase {
|
||||
password: String,
|
||||
forceSms: Boolean,
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?
|
||||
captchaSid: String? = null,
|
||||
captchaKey: String? = null,
|
||||
successToken: String? = null
|
||||
): Flow<State<GetSilentTokenResponse>>
|
||||
}
|
||||
|
||||
@@ -48,7 +48,8 @@ class OAuthUseCaseImpl(
|
||||
forceSms: Boolean,
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?
|
||||
captchaKey: String?,
|
||||
successToken: String?
|
||||
): Flow<State<GetSilentTokenResponse>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
@@ -58,7 +59,8 @@ class OAuthUseCaseImpl(
|
||||
forceSms = forceSms,
|
||||
validationCode = validationCode,
|
||||
captchaSid = captchaSid,
|
||||
captchaKey = captchaKey
|
||||
captchaKey = captchaKey,
|
||||
successToken = successToken
|
||||
).asState()
|
||||
|
||||
emit(newState)
|
||||
|
||||
@@ -598,6 +598,7 @@ private fun getAttachmentIconByType(attachmentType: AttachmentType): UiImage? {
|
||||
AttachmentType.VIDEO_MESSAGE -> null
|
||||
AttachmentType.GROUP_CHAT_STICKER -> R.drawable.ic_sticker_fill_round_24
|
||||
AttachmentType.STICKER_PACK_PREVIEW -> null
|
||||
AttachmentType.CHANNEL_MESSAGE -> null
|
||||
}?.let(UiImage::Resource)
|
||||
}
|
||||
|
||||
@@ -687,6 +688,7 @@ fun getAttachmentUiText(
|
||||
AttachmentType.VIDEO_MESSAGE -> R.string.message_attachments_video_message
|
||||
AttachmentType.GROUP_CHAT_STICKER -> R.string.message_attachments_group_sticker
|
||||
AttachmentType.STICKER_PACK_PREVIEW -> R.string.message_attachments_sticker_pack_preview
|
||||
AttachmentType.CHANNEL_MESSAGE -> R.string.message_attachments_channel_message
|
||||
}.let(UiText::Resource)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
/build
|
||||
@@ -0,0 +1,11 @@
|
||||
plugins {
|
||||
alias(libs.plugins.fast.android.library)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "dev.meloda.fast.logger"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.koin.android)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.meloda.fast.logger;
|
||||
|
||||
enum class FastLogLevel {
|
||||
VERBOSE,
|
||||
DEBUG,
|
||||
INFO,
|
||||
WARNING,
|
||||
ERROR,
|
||||
ASSERT;
|
||||
|
||||
companion object {
|
||||
fun parse(value: Int): FastLogLevel {
|
||||
if (value !in 0..5) throw IllegalArgumentException("Unknown LogLevel value $value")
|
||||
return entries.first { it.ordinal == value }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dev.meloda.fast.logger
|
||||
|
||||
import android.util.Log
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
class FastLogger {
|
||||
companion object {
|
||||
|
||||
@Volatile
|
||||
private lateinit var instance: FastLogger
|
||||
|
||||
fun setInstance(logger: FastLogger) {
|
||||
if (::instance.isInitialized) {
|
||||
throw IllegalStateException("FastLogger has already been initialized.")
|
||||
}
|
||||
|
||||
instance = logger
|
||||
}
|
||||
|
||||
fun getInstance(): FastLogger {
|
||||
if (!::instance.isInitialized) {
|
||||
throw UninitializedPropertyAccessException("FastLogger is not initialized.")
|
||||
}
|
||||
return instance
|
||||
}
|
||||
}
|
||||
|
||||
private var logLevel: FastLogLevel = FastLogLevel.ERROR
|
||||
|
||||
fun setLogLevel(logLevel: FastLogLevel) {
|
||||
Log.v(this::class.java.simpleName, "Set LogLevel from ${this.logLevel} to $logLevel")
|
||||
this.logLevel = logLevel
|
||||
}
|
||||
|
||||
fun verbose(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||
verbose(clazz.simpleName, message, throwable)
|
||||
}
|
||||
|
||||
fun verbose(tag: String, message: String, throwable: Throwable? = null) {
|
||||
if (shouldLog(FastLogLevel.VERBOSE)) {
|
||||
Log.v(tag, message, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
fun debug(clazz: KClass<*>, message: String, throwable: Throwable? = null) {
|
||||
debug(clazz.java, message, throwable)
|
||||
}
|
||||
|
||||
fun debug(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||
debug(clazz.simpleName, message, throwable)
|
||||
}
|
||||
|
||||
fun debug(tag: String, message: String, throwable: Throwable? = null) {
|
||||
if (shouldLog(FastLogLevel.DEBUG)) {
|
||||
Log.d(tag, message, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
fun info(clazz: KClass<*>, message: String, throwable: Throwable? = null) {
|
||||
info(clazz.java, message, throwable)
|
||||
}
|
||||
|
||||
fun info(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||
info(clazz.simpleName, message, throwable)
|
||||
}
|
||||
|
||||
fun info(tag: String, message: String, throwable: Throwable? = null) {
|
||||
if (shouldLog(FastLogLevel.INFO)) {
|
||||
Log.i(tag, message, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
fun warning(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||
warning(clazz.simpleName, message, throwable)
|
||||
}
|
||||
|
||||
fun warning(tag: String, message: String, throwable: Throwable? = null) {
|
||||
if (shouldLog(FastLogLevel.WARNING)) {
|
||||
Log.w(tag, message, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
fun error(clazz: KClass<*>, message: String, throwable: Throwable? = null) {
|
||||
error(clazz.java, message, throwable)
|
||||
}
|
||||
|
||||
fun error(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||
error(clazz.simpleName, message, throwable)
|
||||
}
|
||||
|
||||
fun error(tag: String, message: String, throwable: Throwable? = null) {
|
||||
if (shouldLog(FastLogLevel.ERROR)) {
|
||||
Log.e(tag, message, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
fun assert(clazz: Class<*>, message: String, throwable: Throwable? = null) {
|
||||
assert(clazz.simpleName, message, throwable)
|
||||
}
|
||||
|
||||
fun assert(tag: String, message: String, throwable: Throwable? = null) {
|
||||
if (shouldLog(FastLogLevel.ASSERT)) {
|
||||
Log.wtf(tag, message, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldLog(level: FastLogLevel): Boolean = level.ordinal >= logLevel.ordinal
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.meloda.fast.logger
|
||||
|
||||
import org.koin.core.module.dsl.singleOf
|
||||
import org.koin.dsl.module
|
||||
|
||||
val loggerModule = module {
|
||||
singleOf(::FastLogger)
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package dev.meloda.fast.model.api.data
|
||||
|
||||
import android.util.Log
|
||||
|
||||
enum class AttachmentType(var value: String) {
|
||||
UNKNOWN("unknown"),
|
||||
PHOTO("photo"),
|
||||
@@ -30,7 +28,8 @@ enum class AttachmentType(var value: String) {
|
||||
ARTICLE("article"),
|
||||
VIDEO_MESSAGE("video_message"),
|
||||
GROUP_CHAT_STICKER("ugc_sticker"),
|
||||
STICKER_PACK_PREVIEW("sticker_pack_preview")
|
||||
STICKER_PACK_PREVIEW("sticker_pack_preview"),
|
||||
CHANNEL_MESSAGE("channel_message")
|
||||
;
|
||||
|
||||
fun isMultiple(): Boolean = this in listOf(PHOTO, VIDEO, AUDIO, FILE)
|
||||
@@ -41,10 +40,6 @@ enum class AttachmentType(var value: String) {
|
||||
it.value == value
|
||||
} ?: UNKNOWN
|
||||
|
||||
if (parsedValue == UNKNOWN) {
|
||||
Log.e("AttachmentType", "Unknown attachment type: $value")
|
||||
}
|
||||
|
||||
return parsedValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ data class VkAttachmentItemData(
|
||||
@Json(name = "article") val article: VkArticleData?,
|
||||
@Json(name = "video_message") val videoMessage: VkVideoMessageData?,
|
||||
@Json(name = "ugc_sticker") val groupSticker: VkGroupStickerData?,
|
||||
@Json(name = "sticker_pack_preview") val stickerPackPreview: VkStickerPackPreviewData?
|
||||
@Json(name = "sticker_pack_preview") val stickerPackPreview: VkStickerPackPreviewData?,
|
||||
@Json(name = "channel_message") val channelMessageData: VkChannelMessageData?
|
||||
) {
|
||||
fun toDomain(): VkAttachment = when (AttachmentType.parse(type)) {
|
||||
AttachmentType.UNKNOWN -> VkUnknownAttachment
|
||||
@@ -66,5 +67,6 @@ data class VkAttachmentItemData(
|
||||
AttachmentType.VIDEO_MESSAGE -> videoMessage?.toDomain()
|
||||
AttachmentType.GROUP_CHAT_STICKER -> groupSticker?.toDomain()
|
||||
AttachmentType.STICKER_PACK_PREVIEW -> stickerPackPreview?.toDomain()
|
||||
AttachmentType.CHANNEL_MESSAGE -> channelMessageData?.toDomain()
|
||||
} ?: VkUnknownAttachment
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package dev.meloda.fast.model.api.data
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
import com.squareup.moshi.JsonClass
|
||||
import dev.meloda.fast.model.api.domain.VkChannelMessage
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class VkChannelMessageData(
|
||||
@Json(name = "channel_id") val channelId: Long,
|
||||
@Json(name = "cmid") val cmId: Long,
|
||||
@Json(name = "author_id") val authorId: Long,
|
||||
@Json(name = "channel_info") val channelInfo: ChannelInfo,
|
||||
@Json(name = "channel_type") val channelType: String,
|
||||
@Json(name = "guid") val guid: String,
|
||||
@Json(name = "text") val text: String?,
|
||||
@Json(name = "time") val time: Long,
|
||||
@Json(name = "attachments") val attachments: List<VkAttachmentItemData> = emptyList(),
|
||||
) : VkAttachmentData {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class ChannelInfo(
|
||||
@Json(name = "photo_base") val photoBase: String?,
|
||||
@Json(name = "title") val title: String
|
||||
)
|
||||
|
||||
fun toDomain(): VkChannelMessage = VkChannelMessage(
|
||||
channelId = channelId,
|
||||
cmId = cmId,
|
||||
authorId = authorId,
|
||||
channelInfo = VkChannelMessage.ChannelInfo(
|
||||
title = channelInfo.title,
|
||||
photoBase = channelInfo.photoBase
|
||||
),
|
||||
channelType = channelType,
|
||||
guid = guid,
|
||||
text = text,
|
||||
time = time,
|
||||
attachments = attachments.map(VkAttachmentItemData::toDomain),
|
||||
)
|
||||
}
|
||||
@@ -117,5 +117,6 @@ fun VkMessageData.asDomain(): VkMessage = VkMessage(
|
||||
pinnedAt = pinnedAt,
|
||||
isPinned = isPinned == true,
|
||||
formatData = formatData?.asDomain(),
|
||||
isSpam = false
|
||||
isSpam = false,
|
||||
isDeleted = false
|
||||
)
|
||||
|
||||
@@ -56,5 +56,6 @@ data class VkPinnedMessageData(
|
||||
isPinned = true,
|
||||
isSpam = false,
|
||||
formatData = null,
|
||||
isDeleted = false
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import com.squareup.moshi.JsonClass
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class VkWidgetData(
|
||||
val id: Long
|
||||
val id: Long?
|
||||
) : VkAttachmentData {
|
||||
|
||||
fun toDomain() = VkWidgetDomain(id)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package dev.meloda.fast.model.api.domain
|
||||
|
||||
import dev.meloda.fast.model.api.data.AttachmentType
|
||||
|
||||
data class VkChannelMessage(
|
||||
val channelId: Long,
|
||||
val cmId: Long,
|
||||
val authorId: Long,
|
||||
val channelInfo: ChannelInfo,
|
||||
val channelType: String,
|
||||
val guid: String,
|
||||
val text: String?,
|
||||
val time: Long,
|
||||
val attachments: List<VkAttachment>?,
|
||||
) : VkAttachment {
|
||||
|
||||
data class ChannelInfo(
|
||||
val title: String,
|
||||
val photoBase: String?
|
||||
)
|
||||
|
||||
override val type: AttachmentType = AttachmentType.CHANNEL_MESSAGE
|
||||
}
|
||||
@@ -36,6 +36,8 @@ data class VkMessage(
|
||||
val group: VkGroupDomain?,
|
||||
val actionUser: VkUser?,
|
||||
val actionGroup: VkGroupDomain?,
|
||||
|
||||
val isDeleted: Boolean
|
||||
) {
|
||||
|
||||
fun isPeerChat() = peerId > 2_000_000_000
|
||||
@@ -111,7 +113,7 @@ fun VkMessage.asEntity(): VkMessageEntity = VkMessageEntity(
|
||||
actionCmId = actionCmId,
|
||||
actionMessage = actionMessage,
|
||||
updateTime = updateTime,
|
||||
important = isImportant,
|
||||
isImportant = isImportant,
|
||||
forwardIds = forwards.orEmpty().map(VkMessage::id),
|
||||
// TODO: 05/05/2024, Danil Nikolaev: save attachments
|
||||
attachments = emptyList(),
|
||||
@@ -119,4 +121,6 @@ fun VkMessage.asEntity(): VkMessageEntity = VkMessageEntity(
|
||||
geoType = geoType,
|
||||
pinnedAt = pinnedAt,
|
||||
isPinned = isPinned,
|
||||
isDeleted = isDeleted,
|
||||
isSpam = isSpam
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ package dev.meloda.fast.model.api.domain
|
||||
import dev.meloda.fast.model.api.data.AttachmentType
|
||||
|
||||
data class VkWidgetDomain(
|
||||
val id: Long
|
||||
val id: Long?
|
||||
) : VkAttachment {
|
||||
|
||||
override val type: AttachmentType = AttachmentType.WIDGET
|
||||
|
||||
@@ -12,7 +12,8 @@ data class AuthDirectRequest(
|
||||
val validationCode: String? = null,
|
||||
val captchaSid: String? = null,
|
||||
val captchaKey: String? = null,
|
||||
val trustedHash: String? = null
|
||||
val trustedHash: String? = null,
|
||||
val successToken: String? = null
|
||||
) {
|
||||
|
||||
val map
|
||||
@@ -31,6 +32,7 @@ data class AuthDirectRequest(
|
||||
captchaSid?.let { this["captcha_sid"] = it }
|
||||
captchaKey?.let { this["captcha_key"] = it }
|
||||
trustedHash?.let { this["trusted_hash"] = it }
|
||||
successToken?.let { this["success_token"] = it }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,13 +21,15 @@ data class VkMessageEntity(
|
||||
val actionCmId: Long?,
|
||||
val actionMessage: String?,
|
||||
val updateTime: Int?,
|
||||
val important: Boolean,
|
||||
val isImportant: Boolean,
|
||||
val forwardIds: List<Long>?,
|
||||
val attachments: List<String>?, // TODO: 01/05/2024, Danil Nikolaev: how to store???
|
||||
val replyMessageId: Long?,
|
||||
val geoType: String?,
|
||||
val pinnedAt: Int?,
|
||||
val isPinned: Boolean
|
||||
val isPinned: Boolean,
|
||||
val isDeleted: Boolean,
|
||||
val isSpam: Boolean
|
||||
)
|
||||
|
||||
fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
||||
@@ -45,7 +47,7 @@ fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
||||
actionCmId = actionCmId,
|
||||
actionMessage = actionMessage,
|
||||
updateTime = updateTime,
|
||||
isImportant = important,
|
||||
isImportant = isImportant,
|
||||
forwards = emptyList(),//forwards.orEmpty().map(VkMessageEntity::asExternalModel),
|
||||
// TODO: 05/05/2024, Danil Nikolaev: restore attachments
|
||||
attachments = attachments.orEmpty().map { VkUnknownAttachment },
|
||||
@@ -59,4 +61,5 @@ fun VkMessageEntity.asExternalModel(): VkMessage = VkMessage(
|
||||
isPinned = isPinned,
|
||||
isSpam = false,
|
||||
formatData = null,
|
||||
isDeleted = isDeleted
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ dependencies {
|
||||
api(projects.core.common)
|
||||
api(projects.core.model)
|
||||
api(projects.core.datastore)
|
||||
api(projects.core.logger)
|
||||
|
||||
implementation(libs.moshi.kotlin)
|
||||
implementation(libs.koin.android)
|
||||
|
||||
@@ -16,7 +16,8 @@ sealed class OAuthErrorDomain {
|
||||
|
||||
data class CaptchaRequiredError(
|
||||
val captchaSid: String,
|
||||
val captchaImageUrl: String
|
||||
val captchaImageUrl: String,
|
||||
val redirectUri: String?
|
||||
) : OAuthErrorDomain()
|
||||
|
||||
data class UserBannedError(
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package dev.meloda.fast.network
|
||||
|
||||
import android.util.Log
|
||||
import com.slack.eithernet.ApiException
|
||||
import com.slack.eithernet.errorType
|
||||
import com.slack.eithernet.toType
|
||||
import com.squareup.moshi.JsonDataException
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import okhttp3.ResponseBody
|
||||
import retrofit2.Converter
|
||||
import retrofit2.Retrofit
|
||||
@@ -16,7 +16,10 @@ import java.lang.reflect.Type
|
||||
*
|
||||
* допускает Unit как SuccessType в случае невозможности каста ответа в ErrorType
|
||||
*/
|
||||
class ResponseConverterFactory(private val converter: JsonConverter) : Converter.Factory() {
|
||||
class ResponseConverterFactory(
|
||||
private val converter: JsonConverter,
|
||||
private val logger: FastLogger
|
||||
) : Converter.Factory() {
|
||||
|
||||
override fun responseBodyConverter(
|
||||
type: Type,
|
||||
@@ -29,6 +32,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
||||
successType = type,
|
||||
errorRaw = errorRaw,
|
||||
converter = converter,
|
||||
logger = logger
|
||||
)
|
||||
}
|
||||
|
||||
@@ -36,6 +40,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
||||
private val successType: Type,
|
||||
private val errorRaw: Class<*>,
|
||||
private val converter: JsonConverter,
|
||||
private val logger: FastLogger
|
||||
) : Converter<ResponseBody, Any?> {
|
||||
override fun convert(value: ResponseBody): Any? {
|
||||
val string = value.string()
|
||||
@@ -53,6 +58,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
||||
},
|
||||
onFailure = { failure ->
|
||||
if (failure is JsonDataException) {
|
||||
logger.error(this::class, "convert(): ERROR", failure)
|
||||
throw ApiException(
|
||||
RestApiError(
|
||||
errorCode = -1,
|
||||
@@ -67,10 +73,11 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
|
||||
converter.fromJson(errorRaw, string)
|
||||
}.fold(
|
||||
onSuccess = { errorModel ->
|
||||
Log.d("ResponseBodyConverter", "convert: $errorModel")
|
||||
logger.debug(this::class, "convert(): errorModel: $errorModel")
|
||||
throw ApiException(errorModel)
|
||||
},
|
||||
onFailure = { exception ->
|
||||
logger.error(this::class, "convert(): INNER: ERROR", exception)
|
||||
if (!isUnit) {
|
||||
throw exception
|
||||
} else {
|
||||
|
||||
@@ -2,7 +2,8 @@ package dev.meloda.fast.network
|
||||
|
||||
enum class ValidationType(val value: String) {
|
||||
APP("2fa_app"),
|
||||
SMS("2fa_sms");
|
||||
SMS("sms"),
|
||||
SMS2("2fa_sms");
|
||||
|
||||
companion object {
|
||||
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.OAuthResultCallFactory
|
||||
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.VersionInterceptor
|
||||
import dev.meloda.fast.network.service.account.AccountService
|
||||
@@ -45,6 +46,7 @@ val networkModule = module {
|
||||
single { ChuckerInterceptor.Builder(get()).collector(get()).build() }
|
||||
singleOf(::VersionInterceptor)
|
||||
singleOf(::LanguageInterceptor)
|
||||
singleOf(::Error14HandlingInterceptor)
|
||||
|
||||
single<OkHttpClient>(named("auth")) {
|
||||
buildHttpClient(true)
|
||||
@@ -101,6 +103,7 @@ private fun Scope.buildHttpClient(forAuth: Boolean): OkHttpClient {
|
||||
addInterceptor(get(named("token_interceptor")) as Interceptor)
|
||||
}
|
||||
}
|
||||
.addInterceptor(get<Error14HandlingInterceptor>())
|
||||
.addInterceptor(get<VersionInterceptor>())
|
||||
.addInterceptor(get<LanguageInterceptor>())
|
||||
.addInterceptor(get<ChuckerInterceptor>())
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package dev.meloda.fast.network.interceptor
|
||||
|
||||
import dev.meloda.fast.common.extensions.listenValue
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.datastore.CaptchaTokenResult
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
class Error14HandlingInterceptor(private val logger: FastLogger) : Interceptor {
|
||||
|
||||
private companion object {
|
||||
private const val CAPTCHA_ERROR_CODE = 14
|
||||
private const val CAPTCHA_ERROR_KIND = "need_captcha"
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
}
|
||||
|
||||
private val cookie = AtomicReference<String?>(null)
|
||||
|
||||
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 = passCaptchaAndGetToken(redirectUri)
|
||||
return chain.proceed(chain.request().withCookie().withSuccessToken(token))
|
||||
}
|
||||
|
||||
private fun passCaptchaAndGetToken(redirectUri: String): String = synchronized(this) {
|
||||
val tokenResult = AtomicReference<Result<String>>(Result.failure(Exception("No result")))
|
||||
|
||||
executor.submit {
|
||||
AppSettings.setCaptchaRedirectUri(redirectUri)
|
||||
logger.debug(this::class, "passCaptchaAndGetToken: $redirectUri")
|
||||
|
||||
var job: Job? = null
|
||||
job = AppSettings.getCaptchaResultFlow()
|
||||
.listenValue(CoroutineScope(Dispatchers.IO)) {
|
||||
logger.debug(this::class, "passCaptchaAndGetToken: $it")
|
||||
if (it != CaptchaTokenResult.Initial) {
|
||||
synchronized(tokenResult) {
|
||||
logger.debug(
|
||||
this::class,
|
||||
"passCaptchaAndGetToken: SYNCHRONIZED: $it"
|
||||
)
|
||||
tokenResult.set(wrapResult(it))
|
||||
tokenResult.notifyAll()
|
||||
job?.cancel()
|
||||
logger.debug(
|
||||
this::class,
|
||||
"passCaptchaAndGetToken: NULL RESULT"
|
||||
)
|
||||
AppSettings.setCaptchaResult(CaptchaTokenResult.Initial)
|
||||
AppSettings.setCaptchaRedirectUri(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
synchronized(tokenResult) {
|
||||
if (tokenResult.get().getOrNull() == null) {
|
||||
tokenResult.wait()
|
||||
}
|
||||
|
||||
logger.debug(this::class, "passCaptchaAndGetToken: GET VALUE")
|
||||
tokenResult.get().getOrThrow()
|
||||
}
|
||||
}
|
||||
|
||||
private fun wrapResult(result: CaptchaTokenResult): Result<String> {
|
||||
return when (result) {
|
||||
// TODO: 03/05/2026, Danil Nikolaev: check again?
|
||||
CaptchaTokenResult.Null -> Result.success("")
|
||||
|
||||
CaptchaTokenResult.Cancelled, CaptchaTokenResult.Initial -> Result.success("")
|
||||
|
||||
is CaptchaTokenResult.Success -> Result.success(result.token)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE")
|
||||
private inline fun Any.wait() = (this as Object).wait()
|
||||
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE")
|
||||
private inline fun Any.notify() = (this as Object).notify()
|
||||
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE")
|
||||
private inline fun Any.notifyAll() = (this as Object).notifyAll()
|
||||
@@ -12,6 +12,7 @@ android {
|
||||
dependencies {
|
||||
api(projects.core.common)
|
||||
api(projects.core.model)
|
||||
api(projects.core.logger)
|
||||
implementation(projects.core.presentation)
|
||||
|
||||
implementation(libs.haze)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package dev.meloda.fast.ui.common
|
||||
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
|
||||
val LocalLogger = compositionLocalOf { FastLogger.getInstance() }
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.meloda.fast.ui.components
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Indication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
@@ -20,6 +21,8 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||
@@ -30,27 +33,32 @@ fun FastIconButton(
|
||||
onLongClick: (() -> Unit)? = null,
|
||||
enabled: Boolean = true,
|
||||
colors: IconButtonColors = IconButtonDefaults.iconButtonColors(),
|
||||
containerColor: Color = colors.containerColor(enabled),
|
||||
contentColor: Color = colors.contentColor(enabled),
|
||||
size: Dp = IconButtonTokens.StateLayerSize,
|
||||
shape: Shape = IconButtonTokens.StateLayerShape,
|
||||
alignment: Alignment = Alignment.Center,
|
||||
interactionSource: MutableInteractionSource? = null,
|
||||
indication: Indication = ripple(),
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
modifier
|
||||
.minimumInteractiveComponentSize()
|
||||
.size(IconButtonTokens.StateLayerSize)
|
||||
.clip(IconButtonTokens.StateLayerShape)
|
||||
.background(color = colors.containerColor(enabled))
|
||||
.size(size)
|
||||
.clip(shape)
|
||||
.background(containerColor)
|
||||
.combinedClickable(
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
enabled = enabled,
|
||||
interactionSource = interactionSource,
|
||||
indication = ripple()
|
||||
indication = indication
|
||||
),
|
||||
contentAlignment = Alignment.Center
|
||||
contentAlignment = alignment
|
||||
) {
|
||||
val contentColor = colors.contentColor(enabled)
|
||||
CompositionLocalProvider(LocalContentColor provides contentColor, content = content)
|
||||
CompositionLocalProvider(LocalContentColor provides contentColor) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package dev.meloda.fast.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.sizeIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.CornerBasedShape
|
||||
import androidx.compose.foundation.shape.CornerSize
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.VerticalDivider
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
|
||||
data class SegmentedButtonItem(
|
||||
val key: String,
|
||||
val iconResId: Int
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SegmentedButtonsRow(
|
||||
items: ImmutableList<SegmentedButtonItem>,
|
||||
onClick: (index: Int) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
containerShape: CornerBasedShape = RoundedCornerShape(24.dp),
|
||||
containerColor: Color = MaterialTheme.colorScheme.background,
|
||||
borderColor: Color = MaterialTheme.colorScheme.outlineVariant,
|
||||
borderSize: Dp = 1.dp,
|
||||
iconContainerWidth: Dp = 42.dp,
|
||||
iconContainerHeight: Dp = 36.dp,
|
||||
iconSize: Dp = 18.dp,
|
||||
showDividers: Boolean = true
|
||||
) {
|
||||
SegmentedButtonsRow(
|
||||
modifier = modifier.sizeIn(maxHeight = iconContainerHeight + borderSize),
|
||||
items = items.mapIndexed { index, item ->
|
||||
{
|
||||
val first = index == 0
|
||||
val last = index == items.lastIndex
|
||||
|
||||
if (showDividers && !first) {
|
||||
VerticalDivider(modifier = Modifier.padding(vertical = iconContainerHeight / 4))
|
||||
}
|
||||
|
||||
SegmentedButton(
|
||||
onClick = { onClick(index) },
|
||||
iconResId = item.iconResId,
|
||||
modifier = Modifier.size(
|
||||
iconContainerWidth,
|
||||
iconContainerHeight
|
||||
),
|
||||
iconSize = iconSize,
|
||||
shape = containerShape.copy(
|
||||
topStart = if (!first) CornerSize(0.dp) else containerShape.topStart,
|
||||
bottomStart = if (!first) CornerSize(0.dp) else containerShape.bottomStart,
|
||||
topEnd = if (!last) CornerSize(0.dp) else containerShape.topEnd,
|
||||
bottomEnd = if (!last) CornerSize(0.dp) else containerShape.bottomEnd
|
||||
)
|
||||
)
|
||||
}
|
||||
},
|
||||
containerShape = containerShape,
|
||||
containerColor = containerColor,
|
||||
borderColor = borderColor,
|
||||
borderSize = borderSize
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SegmentedButtonsRow(
|
||||
items: ImmutableList<@Composable () -> Unit>,
|
||||
modifier: Modifier = Modifier,
|
||||
containerShape: CornerBasedShape = RoundedCornerShape(24.dp),
|
||||
containerColor: Color = MaterialTheme.colorScheme.background,
|
||||
borderColor: Color = MaterialTheme.colorScheme.outlineVariant,
|
||||
borderSize: Dp = 1.dp,
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
.background(containerColor, containerShape)
|
||||
.border(borderSize, borderColor, containerShape)
|
||||
) {
|
||||
items.forEach { it.invoke() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SegmentedButton(
|
||||
onClick: () -> Unit,
|
||||
iconResId: Int,
|
||||
modifier: Modifier = Modifier,
|
||||
iconSize: Dp = 18.dp,
|
||||
shape: Shape = CircleShape
|
||||
) {
|
||||
FastIconButton(
|
||||
onClick = onClick,
|
||||
modifier = modifier,
|
||||
shape = shape
|
||||
) {
|
||||
Icon(
|
||||
modifier = Modifier.size(iconSize),
|
||||
painter = painterResource(iconResId),
|
||||
contentDescription = null
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ fun AppTheme(
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
|
||||
val colorScheme: ColorScheme = when {
|
||||
val colorScheme: ColorScheme = predefinedColorScheme ?: when {
|
||||
useDynamicColors && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
if (useDarkTheme) dynamicDarkColorScheme(context)
|
||||
else dynamicLightColorScheme(context)
|
||||
@@ -82,10 +82,6 @@ fun AppTheme(
|
||||
}
|
||||
}
|
||||
|
||||
val colorPrimary by animateColorAsState(colorScheme.primary)
|
||||
val colorSurface by animateColorAsState(colorScheme.surface)
|
||||
val colorBackground by animateColorAsState(colorScheme.background)
|
||||
|
||||
val typography = if (useSystemFont) {
|
||||
MaterialTheme.typography
|
||||
} else {
|
||||
@@ -118,12 +114,7 @@ fun AppTheme(
|
||||
}
|
||||
|
||||
MaterialExpressiveTheme(
|
||||
colorScheme = (predefinedColorScheme ?: colorScheme)
|
||||
.copy(
|
||||
primary = colorPrimary,
|
||||
background = colorBackground,
|
||||
surface = colorSurface
|
||||
),
|
||||
colorScheme = colorScheme,
|
||||
typography = typography,
|
||||
content = content
|
||||
)
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.graphics.painter.Painter
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.input.key.onKeyEvent
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
@@ -113,11 +114,12 @@ fun LazyListState.isScrollingUp(): Boolean {
|
||||
@Composable
|
||||
fun isNeedToEnableDarkMode(darkMode: DarkMode): Boolean {
|
||||
val context = LocalContext.current
|
||||
val configuration = LocalConfiguration.current
|
||||
|
||||
val appForceDarkMode = darkMode == DarkMode.ENABLED
|
||||
val appBatterySaver = darkMode == DarkMode.AUTO_BATTERY
|
||||
|
||||
val systemUiNightMode = context.resources.configuration.uiMode
|
||||
val systemUiNightMode = configuration.uiMode
|
||||
|
||||
val isSystemBatterySaver = context.getSystemService<PowerManager>()?.isPowerSaveMode == true
|
||||
val isSystemUsingDarkTheme =
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.meloda.fast.ui.util
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
||||
|
||||
@Immutable
|
||||
class ImmutableList<T>(val values: List<T>) : Collection<T> {
|
||||
@@ -57,3 +58,9 @@ class ImmutableList<T>(val values: List<T>) : Collection<T> {
|
||||
fun <T> emptyImmutableList(): ImmutableList<T> = ImmutableList(emptyList())
|
||||
|
||||
fun <T> immutableListOf(vararg elements: T) = ImmutableList(listOf(elements = elements))
|
||||
|
||||
inline fun <T> buildImmutableList(builderAction: MutableList<T>.() -> Unit): ImmutableList<T> {
|
||||
val mutableList = mutableListOf<T>()
|
||||
mutableList.apply(builderAction)
|
||||
return mutableList.toImmutableList()
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@
|
||||
<string name="message_attachments_video_message">Video message</string>
|
||||
<string name="message_attachments_group_sticker">Group sticker</string>
|
||||
<string name="message_attachments_sticker_pack_preview">Sticker pack preview</string>
|
||||
<string name="message_attachments_channel_message">Channel message</string>
|
||||
|
||||
<string name="chat_interaction_uploading_file">Uploading file</string>
|
||||
<string name="chat_interaction_uploading_photo">Uploading photo</string>
|
||||
@@ -303,4 +304,9 @@
|
||||
|
||||
<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="title_edit_message">Edit message</string>
|
||||
<string name="action_close">Close</string>
|
||||
<string name="action_hide_stacktrace">Hide stacktrace</string>
|
||||
<string name="action_show_stacktrace">Show stacktrace</string>
|
||||
</resources>
|
||||
|
||||
@@ -2,4 +2,13 @@
|
||||
<resources>
|
||||
|
||||
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar" />
|
||||
|
||||
<style name="CrashDialogTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<item name="android:windowIsTranslucent">true</item>
|
||||
<item name="android:windowBackground">@android:color/transparent</item>
|
||||
<item name="android:windowContentOverlay">@null</item>
|
||||
<item name="android:windowNoTitle">true</item>
|
||||
<item name="android:windowIsFloating">true</item>
|
||||
<item name="android:backgroundDimEnabled">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -3,7 +3,6 @@ package dev.meloda.fast.auth.login
|
||||
import androidx.compose.ui.test.assertHasClickAction
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import dev.meloda.fast.auth.login.presentation.LogoScreen
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
@@ -15,7 +14,7 @@ class LogoScreenTest {
|
||||
@Test
|
||||
fun goNextButton_isClickable() {
|
||||
composeTestRule.setContent {
|
||||
LogoScreen()
|
||||
|
||||
}
|
||||
|
||||
composeTestRule.onNodeWithTag(testTag = "go_next_fab").assertHasClickAction()
|
||||
|
||||
@@ -3,9 +3,6 @@ package dev.meloda.fast.auth
|
||||
import androidx.navigation.NavController
|
||||
import androidx.navigation.NavGraphBuilder
|
||||
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.loginScreen
|
||||
import dev.meloda.fast.auth.userbanned.model.UserBannedArguments
|
||||
@@ -28,11 +25,6 @@ fun NavGraphBuilder.authNavGraph(
|
||||
) {
|
||||
navigation<AuthGraph>(startDestination = Login) {
|
||||
loginScreen(
|
||||
onNavigateToCaptcha = { arguments ->
|
||||
navController.navigateToCaptcha(
|
||||
captchaImageUrl = URLEncoder.encode(arguments.captchaImageUrl, "utf-8")
|
||||
)
|
||||
},
|
||||
onNavigateToValidation = { arguments ->
|
||||
navController.navigateToValidation(
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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.login.di.loginModule
|
||||
import org.koin.dsl.module
|
||||
@@ -9,6 +8,5 @@ val authModule = module {
|
||||
includes(
|
||||
loginModule,
|
||||
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)
|
||||
}
|
||||
+150
-224
@@ -1,33 +1,21 @@
|
||||
package dev.meloda.fast.auth.captcha.presentation
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.ime
|
||||
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.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -37,237 +25,175 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
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.lifecycle.compose.collectAsStateWithLifecycle
|
||||
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 androidx.compose.ui.viewinterop.AndroidView
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.common.FastPreview
|
||||
import dev.meloda.fast.ui.common.LocalLogger
|
||||
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.TextFieldErrorText
|
||||
import dev.meloda.fast.ui.theme.AppTheme
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
import org.json.JSONObject
|
||||
|
||||
@Composable
|
||||
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
|
||||
)
|
||||
}
|
||||
private const val TAG = "CaptchaScreen"
|
||||
|
||||
@Composable
|
||||
fun CaptchaScreen(
|
||||
screenState: CaptchaScreenState = CaptchaScreenState.EMPTY,
|
||||
captchaRedirectUri: String?,
|
||||
onBack: () -> Unit = {},
|
||||
onCodeInputChanged: (String) -> Unit = {},
|
||||
onTextFieldDoneAction: () -> Unit = {},
|
||||
onDoneButtonClicked: () -> Unit = {}
|
||||
onResult: (String) -> Unit = {}
|
||||
) {
|
||||
var confirmedExit by remember {
|
||||
mutableStateOf(false)
|
||||
}
|
||||
val logger = LocalLogger.current
|
||||
|
||||
var showExitAlert by rememberSaveable {
|
||||
mutableStateOf(false)
|
||||
}
|
||||
|
||||
LaunchedEffect(confirmedExit) {
|
||||
if (confirmedExit) {
|
||||
onBack()
|
||||
if (captchaRedirectUri != null) {
|
||||
val focusManager = LocalFocusManager.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
LaunchedEffect(true) {
|
||||
focusManager.clearFocus(true)
|
||||
keyboardController?.hide()
|
||||
}
|
||||
}
|
||||
|
||||
BackHandler(enabled = !confirmedExit) {
|
||||
if (!confirmedExit) {
|
||||
showExitAlert = true
|
||||
var confirmedExit by remember {
|
||||
mutableStateOf(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (showExitAlert) {
|
||||
MaterialDialog(
|
||||
onDismissRequest = { showExitAlert = false },
|
||||
title = stringResource(id = R.string.warning_confirmation),
|
||||
text = stringResource(id = R.string.captcha_exit_warning),
|
||||
confirmAction = { confirmedExit = true },
|
||||
confirmText = stringResource(id = R.string.yes),
|
||||
cancelText = stringResource(id = R.string.no),
|
||||
actionInvokeDismiss = ActionInvokeDismiss.Always
|
||||
)
|
||||
}
|
||||
var showExitAlert by rememberSaveable {
|
||||
mutableStateOf(false)
|
||||
}
|
||||
|
||||
val focusManager = LocalFocusManager.current
|
||||
var isWebViewLoading by remember {
|
||||
mutableStateOf(true)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
contentWindowInsets = ScaffoldDefaults.contentWindowInsets.union(WindowInsets.ime)
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(30.dp),
|
||||
verticalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
ExtendedFloatingActionButton(
|
||||
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,
|
||||
)
|
||||
}
|
||||
)
|
||||
LaunchedEffect(confirmedExit) {
|
||||
if (confirmedExit) {
|
||||
onBack()
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = "Captcha",
|
||||
style = MaterialTheme.typography.displayMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground
|
||||
BackHandler(enabled = !confirmedExit) {
|
||||
if (!confirmedExit) {
|
||||
showExitAlert = true
|
||||
}
|
||||
}
|
||||
|
||||
FullScreenDialog(onDismiss = { showExitAlert = true }) {
|
||||
if (showExitAlert) {
|
||||
MaterialDialog(
|
||||
onDismissRequest = { showExitAlert = false },
|
||||
title = stringResource(id = R.string.warning_confirmation),
|
||||
text = stringResource(id = R.string.captcha_exit_warning),
|
||||
confirmAction = { confirmedExit = true },
|
||||
confirmText = stringResource(id = R.string.yes),
|
||||
cancelText = stringResource(id = R.string.no),
|
||||
actionInvokeDismiss = ActionInvokeDismiss.Always
|
||||
)
|
||||
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)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.navigationBarsPadding()
|
||||
.clickable(
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
indication = null,
|
||||
onClick = { showExitAlert = true }
|
||||
)
|
||||
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") },
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp)),
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_qr_code_round_24),
|
||||
contentDescription = "QR code icon",
|
||||
tint = if (showError) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.primary
|
||||
.fillMaxSize()
|
||||
.align(Alignment.BottomCenter),
|
||||
factory = { context ->
|
||||
val webview = WebView(context)
|
||||
webview.setBackgroundColor(0)
|
||||
webview.settings.javaScriptEnabled = true
|
||||
webview.webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
request: WebResourceRequest?
|
||||
): Boolean {
|
||||
logger.info(
|
||||
"CaptchaScreen",
|
||||
"WebViewClient(): shouldOverrideUrlLoading(): request: $request"
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onPageStarted(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
favicon: Bitmap?
|
||||
) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
isWebViewLoading = true
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
isWebViewLoading = false
|
||||
}
|
||||
)
|
||||
},
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(
|
||||
onDone = {
|
||||
focusManager.clearFocus()
|
||||
onTextFieldDoneAction()
|
||||
}
|
||||
),
|
||||
isError = showError
|
||||
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 = showError) {
|
||||
TextFieldErrorText(text = "Field must not be empty")
|
||||
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)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
FloatingActionButton(
|
||||
onClick = onDoneButtonClicked,
|
||||
containerColor = MaterialTheme.colorScheme.secondaryContainer,
|
||||
modifier = Modifier.align(Alignment.CenterHorizontally)
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_check_round_24),
|
||||
contentDescription = "Done icon",
|
||||
tint = MaterialTheme.colorScheme.onSecondaryContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@FastPreview
|
||||
@Composable
|
||||
private fun CaptchaScreenPreview() {
|
||||
AppTheme(useDarkTheme = isSystemInDarkTheme(), useDynamicColors = true) {
|
||||
CaptchaScreen(
|
||||
screenState = CaptchaScreenState.EMPTY.copy(
|
||||
code = "zcuecz"
|
||||
)
|
||||
)
|
||||
class WebCaptchaListener(
|
||||
private val onSuccessTokenReceived: (String) -> Unit,
|
||||
private val onCloseRequested: (String) -> Unit,
|
||||
private val logger: FastLogger
|
||||
) {
|
||||
@JavascriptInterface
|
||||
fun VKCaptchaGetResult(arg: String) {
|
||||
onSuccessTokenReceived(arg)
|
||||
logger.info(this::class, "VKCaptchaGetResult(): arg: $arg")
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun VKCaptchaCloseCaptcha(arg: String) {
|
||||
onCloseRequested(arg)
|
||||
logger.info(this::class, "VKCaptchaCloseCaptcha(): arg: $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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package dev.meloda.fast.auth.login
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dev.meloda.fast.auth.login.model.CaptchaArguments
|
||||
@@ -28,6 +27,7 @@ import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.datastore.UserSettings
|
||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||
import dev.meloda.fast.domain.OAuthUseCase
|
||||
import dev.meloda.fast.logger.FastLogger
|
||||
import dev.meloda.fast.model.database.AccountEntity
|
||||
import dev.meloda.fast.network.OAuthErrorDomain
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
@@ -48,7 +48,8 @@ class LoginViewModel(
|
||||
private val accountsRepository: AccountsRepository,
|
||||
private val loginValidator: LoginValidator,
|
||||
private val longPollController: LongPollController,
|
||||
private val userSettings: UserSettings
|
||||
private val userSettings: UserSettings,
|
||||
private val logger: FastLogger
|
||||
) : ViewModel() {
|
||||
private val _screenState = MutableStateFlow(LoginScreenState.EMPTY)
|
||||
val screenState = _screenState.asStateFlow()
|
||||
@@ -59,18 +60,12 @@ class LoginViewModel(
|
||||
private val _validationArguments = MutableStateFlow<LoginValidationArguments?>(null)
|
||||
val validationArguments = _validationArguments.asStateFlow()
|
||||
|
||||
private val _captchaArguments = MutableStateFlow<CaptchaArguments?>(null)
|
||||
val captchaArguments = _captchaArguments.asStateFlow()
|
||||
|
||||
private val _userBannedArguments = MutableStateFlow<LoginUserBannedArguments?>(null)
|
||||
val userBannedArguments = _userBannedArguments.asStateFlow()
|
||||
|
||||
private val _isNeedToOpenMain = MutableStateFlow(false)
|
||||
val isNeedToOpenMain = _isNeedToOpenMain.asStateFlow()
|
||||
|
||||
private val _isNeedToClearCaptchaCode = MutableStateFlow(false)
|
||||
val isNeedToClearCaptchaCode = _isNeedToClearCaptchaCode.asStateFlow()
|
||||
|
||||
private val _isNeedToClearValidationCode = MutableStateFlow(false)
|
||||
val isNeedToClearValidationCode = _isNeedToClearValidationCode.asStateFlow()
|
||||
|
||||
@@ -78,17 +73,10 @@ class LoginViewModel(
|
||||
screenState.map(loginValidator::validate)
|
||||
.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 validationCode = MutableStateFlow<String?>(null)
|
||||
|
||||
init {
|
||||
captchaCode.listenValue(viewModelScope) {
|
||||
if (it != null) {
|
||||
login()
|
||||
}
|
||||
}
|
||||
validationCode.listenValue(viewModelScope) {
|
||||
if (it != null) {
|
||||
login()
|
||||
@@ -113,7 +101,13 @@ class LoginViewModel(
|
||||
}
|
||||
|
||||
fun onBackPressed() {
|
||||
_screenState.setValue { old -> old.copy(showLogo = true) }
|
||||
_screenState.setValue { old ->
|
||||
old.copy(
|
||||
showLogo = true,
|
||||
loginError = false,
|
||||
passwordError = false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onPasswordVisibilityButtonClicked() {
|
||||
@@ -165,10 +159,6 @@ class LoginViewModel(
|
||||
_userBannedArguments.update { null }
|
||||
}
|
||||
|
||||
fun onNavigatedToCaptcha() {
|
||||
_captchaArguments.update { null }
|
||||
}
|
||||
|
||||
fun onNavigatedToValidation() {
|
||||
_validationArguments.update { null }
|
||||
}
|
||||
@@ -181,25 +171,9 @@ class LoginViewModel(
|
||||
_isNeedToClearValidationCode.update { false }
|
||||
}
|
||||
|
||||
fun onCaptchaCodeReceived(code: String?) {
|
||||
captchaCode.update { code }
|
||||
}
|
||||
|
||||
fun onCaptchaCodeCleared() {
|
||||
_isNeedToClearCaptchaCode.update { false }
|
||||
}
|
||||
|
||||
private fun login(forceSms: Boolean = false) {
|
||||
val currentState = screenState.value.copy()
|
||||
|
||||
Log.d(
|
||||
"LoginViewModel",
|
||||
"auth: login: ${currentState.login}; " +
|
||||
"password: ${currentState.password}; " +
|
||||
"2fa code: ${validationCode.value}; " +
|
||||
"captcha code: ${captchaCode.value}"
|
||||
)
|
||||
|
||||
processValidation()
|
||||
if (!validationState.value.contains(LoginValidationResult.Valid)) return
|
||||
|
||||
@@ -207,23 +181,18 @@ class LoginViewModel(
|
||||
|
||||
val currentValidationSid = validationSid.value
|
||||
val currentValidationCode = validationCode.value?.takeIf { currentValidationSid != null }
|
||||
val currentCaptchaSid = captchaSid.value
|
||||
val currentCaptchaCode = captchaCode.value?.takeIf { currentCaptchaSid != null }
|
||||
|
||||
oAuthUseCase.getSilentToken(
|
||||
login = currentState.login,
|
||||
password = currentState.password,
|
||||
forceSms = forceSms,
|
||||
validationCode = currentValidationCode,
|
||||
captchaSid = currentCaptchaSid,
|
||||
captchaKey = currentCaptchaCode
|
||||
).listenValue(viewModelScope) { state ->
|
||||
state.processState(
|
||||
error = { error ->
|
||||
Log.d("LoginViewModelImpl", "login: error: $error")
|
||||
logger.error(this::class, "getSilentToken(): ERROR: $error")
|
||||
|
||||
_screenState.updateValue { copy(isLoading = false) }
|
||||
captchaSid.setValue { null }
|
||||
|
||||
parseError(error)
|
||||
},
|
||||
@@ -286,7 +255,6 @@ class LoginViewModel(
|
||||
|
||||
startLongPoll()
|
||||
|
||||
captchaSid.update { null }
|
||||
validationSid.update { null }
|
||||
|
||||
loadUserByIdUseCase(
|
||||
@@ -333,11 +301,8 @@ class LoginViewModel(
|
||||
|
||||
is OAuthErrorDomain.CaptchaRequiredError -> {
|
||||
val arguments = CaptchaArguments(
|
||||
captchaSid = error.captchaSid,
|
||||
captchaImageUrl = error.captchaImageUrl
|
||||
redirectUri = error.redirectUri
|
||||
)
|
||||
_captchaArguments.update { arguments }
|
||||
captchaSid.update { error.captchaSid }
|
||||
}
|
||||
|
||||
OAuthErrorDomain.InvalidCredentialsError -> {
|
||||
|
||||
@@ -7,6 +7,5 @@ import kotlinx.serialization.Serializable
|
||||
@Serializable
|
||||
@Parcelize
|
||||
data class CaptchaArguments(
|
||||
val captchaSid: String,
|
||||
val captchaImageUrl: String
|
||||
val redirectUri: String?
|
||||
) : Parcelable
|
||||
|
||||
@@ -8,7 +8,6 @@ import androidx.navigation.NavController
|
||||
import androidx.navigation.NavGraphBuilder
|
||||
import androidx.navigation.compose.composable
|
||||
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.LoginValidationArguments
|
||||
import dev.meloda.fast.auth.login.presentation.LoginRoute
|
||||
@@ -19,7 +18,6 @@ import kotlinx.serialization.Serializable
|
||||
object Login
|
||||
|
||||
fun NavGraphBuilder.loginScreen(
|
||||
onNavigateToCaptcha: (CaptchaArguments) -> Unit,
|
||||
onNavigateToValidation: (LoginValidationArguments) -> Unit,
|
||||
onNavigateToMain: () -> Unit,
|
||||
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
|
||||
@@ -31,7 +29,6 @@ fun NavGraphBuilder.loginScreen(
|
||||
backStackEntry.sharedViewModel<LoginViewModel>(navController = navController)
|
||||
|
||||
val clearValidationCode by viewModel.isNeedToClearValidationCode.collectAsStateWithLifecycle()
|
||||
val clearCaptchaCode by viewModel.isNeedToClearCaptchaCode.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(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 captchaCode = backStackEntry.getCaptchaResult()
|
||||
|
||||
LoginRoute(
|
||||
onNavigateToUserBanned = onNavigateToUserBanned,
|
||||
onNavigateToMain = onNavigateToMain,
|
||||
onNavigateToCaptcha = onNavigateToCaptcha,
|
||||
onNavigateToValidation = onNavigateToValidation,
|
||||
onNavigateToSettings = onNavigateToSettings,
|
||||
validationCode = validationCode,
|
||||
captchaCode = captchaCode,
|
||||
viewModel = viewModel
|
||||
)
|
||||
}
|
||||
@@ -66,7 +53,3 @@ fun NavGraphBuilder.loginScreen(
|
||||
fun NavBackStackEntry.getValidationResult(): String? {
|
||||
return savedStateHandle["validation_code"]
|
||||
}
|
||||
|
||||
fun NavBackStackEntry.getCaptchaResult(): String? {
|
||||
return savedStateHandle["captcha_code"]
|
||||
}
|
||||
|
||||
+27
-24
@@ -31,9 +31,13 @@ import androidx.compose.material3.ScaffoldDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.autofill.ContentType
|
||||
@@ -58,7 +62,6 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import dev.meloda.fast.auth.login.LoginViewModel
|
||||
import dev.meloda.fast.auth.login.model.CaptchaArguments
|
||||
import dev.meloda.fast.auth.login.model.LoginDialog
|
||||
import dev.meloda.fast.auth.login.model.LoginScreenState
|
||||
import dev.meloda.fast.auth.login.model.LoginUserBannedArguments
|
||||
@@ -67,6 +70,8 @@ import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.common.LocalSizeConfig
|
||||
import dev.meloda.fast.ui.components.MaterialDialog
|
||||
import dev.meloda.fast.ui.components.TextFieldErrorText
|
||||
import dev.meloda.fast.ui.theme.AppTheme
|
||||
import dev.meloda.fast.ui.theme.ClassicColorScheme
|
||||
import dev.meloda.fast.ui.util.handleEnterKey
|
||||
import dev.meloda.fast.ui.util.handleTabKey
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
@@ -75,17 +80,14 @@ import org.koin.androidx.compose.koinViewModel
|
||||
fun LoginRoute(
|
||||
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
|
||||
onNavigateToMain: () -> Unit,
|
||||
onNavigateToCaptcha: (CaptchaArguments) -> Unit,
|
||||
onNavigateToValidation: (LoginValidationArguments) -> Unit,
|
||||
onNavigateToSettings: () -> Unit,
|
||||
validationCode: String?,
|
||||
captchaCode: String?,
|
||||
viewModel: LoginViewModel = koinViewModel()
|
||||
) {
|
||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
||||
val isNeedToOpenMain by viewModel.isNeedToOpenMain.collectAsStateWithLifecycle()
|
||||
val userBannedArguments by viewModel.userBannedArguments.collectAsStateWithLifecycle()
|
||||
val captchaArguments by viewModel.captchaArguments.collectAsStateWithLifecycle()
|
||||
val validationArguments by viewModel.validationArguments.collectAsStateWithLifecycle()
|
||||
val loginDialog by viewModel.loginDialog.collectAsStateWithLifecycle()
|
||||
|
||||
@@ -107,12 +109,6 @@ fun LoginRoute(
|
||||
onNavigateToUserBanned(arguments)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(captchaArguments) {
|
||||
captchaArguments?.let { arguments ->
|
||||
viewModel.onNavigatedToCaptcha()
|
||||
onNavigateToCaptcha(arguments)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(validationArguments) {
|
||||
validationArguments?.let { arguments ->
|
||||
viewModel.onNavigatedToValidation()
|
||||
@@ -122,21 +118,28 @@ fun LoginRoute(
|
||||
LaunchedEffect(validationCode) {
|
||||
viewModel.onValidationCodeReceived(validationCode)
|
||||
}
|
||||
LaunchedEffect(captchaCode) {
|
||||
viewModel.onCaptchaCodeReceived(captchaCode)
|
||||
}
|
||||
|
||||
LoginScreen(
|
||||
screenState = screenState,
|
||||
onLoginInputChanged = viewModel::onLoginInputChanged,
|
||||
onPasswordInputChanged = viewModel::onPasswordInputChanged,
|
||||
onPasswordFieldEnterKeyClicked = viewModel::onSignInButtonClicked,
|
||||
onPasswordVisibilityButtonClicked = viewModel::onPasswordVisibilityButtonClicked,
|
||||
onPasswordFieldGoAction = viewModel::onSignInButtonClicked,
|
||||
onSignInButtonClicked = viewModel::onSignInButtonClicked,
|
||||
onLogoClicked = viewModel::onLogoClicked,
|
||||
onLogoLongClicked = onNavigateToSettings
|
||||
)
|
||||
var useClassic by rememberSaveable { mutableStateOf(true) }
|
||||
|
||||
AppTheme(
|
||||
predefinedColorScheme = if (useClassic) ClassicColorScheme.lightScheme
|
||||
else lightColorScheme(),
|
||||
) {
|
||||
LoginScreen(
|
||||
screenState = screenState,
|
||||
onLoginInputChanged = viewModel::onLoginInputChanged,
|
||||
onPasswordInputChanged = viewModel::onPasswordInputChanged,
|
||||
onPasswordFieldEnterKeyClicked = viewModel::onSignInButtonClicked,
|
||||
onPasswordVisibilityButtonClicked = viewModel::onPasswordVisibilityButtonClicked,
|
||||
onPasswordFieldGoAction = viewModel::onSignInButtonClicked,
|
||||
onSignInButtonClicked = viewModel::onSignInButtonClicked,
|
||||
onLogoClicked = {
|
||||
viewModel.onLogoClicked()
|
||||
useClassic = !useClassic
|
||||
},
|
||||
onLogoLongClicked = onNavigateToSettings
|
||||
)
|
||||
}
|
||||
|
||||
HandleDialogs(
|
||||
loginDialog = loginDialog,
|
||||
|
||||
@@ -4,7 +4,6 @@ import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
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.validation.ValidationValidator
|
||||
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.data.processState
|
||||
import dev.meloda.fast.domain.AuthUseCase
|
||||
import dev.meloda.fast.network.ValidationType
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
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.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import dev.meloda.fast.auth.validation.ValidationViewModel
|
||||
import dev.meloda.fast.auth.validation.ValidationViewModelImpl
|
||||
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.common.FastPreview
|
||||
import dev.meloda.fast.ui.components.ActionInvokeDismiss
|
||||
@@ -119,7 +118,7 @@ fun ValidationScreen(
|
||||
val validationText by remember(validationType) {
|
||||
mutableStateOf(
|
||||
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"
|
||||
|
||||
null -> ""
|
||||
|
||||
+1
-5
@@ -1,6 +1,5 @@
|
||||
package dev.meloda.fast.chatmaterials.util
|
||||
|
||||
import android.util.Log
|
||||
import dev.meloda.fast.chatmaterials.model.UiChatMaterial
|
||||
import dev.meloda.fast.common.util.AndroidUtils
|
||||
import dev.meloda.fast.model.api.data.AttachmentType
|
||||
@@ -135,8 +134,5 @@ fun VkAttachmentHistoryMessage.asPresentation(): UiChatMaterial? =
|
||||
)
|
||||
}
|
||||
|
||||
else -> {
|
||||
Log.w("ChatMaterialMapper", "Unsupported type: $type")
|
||||
null
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package dev.meloda.fast.convos
|
||||
import android.content.Context
|
||||
import android.content.res.Resources
|
||||
import android.os.Bundle
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import coil.ImageLoader
|
||||
@@ -15,10 +16,12 @@ import dev.meloda.fast.common.extensions.listenValue
|
||||
import dev.meloda.fast.common.extensions.setValue
|
||||
import dev.meloda.fast.common.extensions.updateValue
|
||||
import dev.meloda.fast.convos.model.ConvoDialog
|
||||
import dev.meloda.fast.convos.model.ConvoNavigation
|
||||
import dev.meloda.fast.convos.model.ConvoIntent
|
||||
import dev.meloda.fast.convos.model.ConvoNavigationIntent
|
||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||
import dev.meloda.fast.convos.model.InteractionJob
|
||||
import dev.meloda.fast.convos.model.NewInteractionException
|
||||
import dev.meloda.fast.data.UserConfig
|
||||
import dev.meloda.fast.data.VkUtils
|
||||
import dev.meloda.fast.data.processState
|
||||
import dev.meloda.fast.datastore.UserSettings
|
||||
@@ -28,25 +31,23 @@ import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||
import dev.meloda.fast.domain.MessagesUseCase
|
||||
import dev.meloda.fast.domain.util.asPresentation
|
||||
import dev.meloda.fast.domain.util.extractAvatar
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.ConvosFilter
|
||||
import dev.meloda.fast.model.InteractionType
|
||||
import dev.meloda.fast.model.LongPollParsedEvent
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.ui.model.vk.ConvoOption
|
||||
import dev.meloda.fast.ui.model.vk.UiConvo
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
||||
import dev.meloda.fast.ui.util.buildImmutableList
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
@Immutable
|
||||
class ConvosViewModel(
|
||||
updatesParser: LongPollUpdatesParser,
|
||||
private val filter: ConvosFilter,
|
||||
val filter: ConvosFilter,
|
||||
private val convoUseCase: ConvoUseCase,
|
||||
private val messagesUseCase: MessagesUseCase,
|
||||
private val resources: Resources,
|
||||
@@ -55,43 +56,22 @@ class ConvosViewModel(
|
||||
private val applicationContext: Context,
|
||||
private val loadConvosByIdUseCase: LoadConvosByIdUseCase
|
||||
) : ViewModel() {
|
||||
private val _screenState = MutableStateFlow(ConvosScreenState.EMPTY)
|
||||
val screenState = _screenState.asStateFlow()
|
||||
|
||||
private val _navigation = MutableStateFlow<ConvoNavigation?>(null)
|
||||
val navigation = _navigation.asStateFlow()
|
||||
private val screenState = MutableStateFlow(ConvosScreenState.EMPTY)
|
||||
val screenStateFlow get() = screenState.asStateFlow()
|
||||
|
||||
private val _dialog = MutableStateFlow<ConvoDialog?>(null)
|
||||
val dialog = _dialog.asStateFlow()
|
||||
private val navigationIntent = MutableStateFlow<ConvoNavigationIntent?>(null)
|
||||
val navigationIntentFlow get() = navigationIntent.asStateFlow()
|
||||
|
||||
private val _convos = MutableStateFlow<List<VkConvo>>(emptyList())
|
||||
val convos = _convos.asStateFlow()
|
||||
private val convos: MutableList<VkConvo> = mutableListOf()
|
||||
|
||||
private val _uiConvos = MutableStateFlow<List<UiConvo>>(emptyList())
|
||||
val uiConvos = _uiConvos.asStateFlow()
|
||||
private val pinnedConvosCount get() = convos.count(VkConvo::isPinned)
|
||||
|
||||
private val pinnedConvosCount = convos.map { convos ->
|
||||
convos.count(VkConvo::isPinned)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, 0)
|
||||
|
||||
private val _baseError = MutableStateFlow<BaseError?>(null)
|
||||
val baseError = _baseError.asStateFlow()
|
||||
|
||||
private val _currentOffset = MutableStateFlow(0)
|
||||
val currentOffset = _currentOffset.asStateFlow()
|
||||
|
||||
private val _canPaginate = MutableStateFlow(false)
|
||||
val canPaginate = _canPaginate.asStateFlow()
|
||||
|
||||
private val expandedConvoId = MutableStateFlow(0L)
|
||||
|
||||
private val useContactNames: Boolean get() = userSettings.useContactNames.value
|
||||
private var currentOffset = 0
|
||||
|
||||
private val interactionsTimers = hashMapOf<Long, InteractionJob?>()
|
||||
|
||||
init {
|
||||
_screenState.updateValue { copy(isArchive = filter == ConvosFilter.ARCHIVE) }
|
||||
|
||||
loadConvos()
|
||||
|
||||
updatesParser.onNewMessage(::handleNewMessage)
|
||||
@@ -109,100 +89,143 @@ class ConvosViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun onNavigationConsumed() {
|
||||
_navigation.setValue { null }
|
||||
fun handleIntent(intent: ConvoIntent) {
|
||||
when (intent) {
|
||||
ConvoIntent.ArchiveClick -> {
|
||||
navigationIntent.setValue { ConvoNavigationIntent.Archive }
|
||||
}
|
||||
|
||||
ConvoIntent.Back -> {
|
||||
navigationIntent.setValue { ConvoNavigationIntent.Back }
|
||||
}
|
||||
|
||||
ConvoIntent.ConsumeScrollToTop -> Unit
|
||||
ConvoIntent.CreateChatClick -> {
|
||||
navigationIntent.setValue { ConvoNavigationIntent.CreateChat }
|
||||
}
|
||||
|
||||
ConvoIntent.ErrorActionButtonClick -> {
|
||||
onRefresh()
|
||||
}
|
||||
|
||||
is ConvoIntent.ItemClick -> {
|
||||
onConvoItemClick(intent.convoId)
|
||||
}
|
||||
|
||||
is ConvoIntent.ItemLongClick -> {
|
||||
onConvoItemLongClick(intent.convoId)
|
||||
}
|
||||
|
||||
is ConvoIntent.OptionItemClick -> {
|
||||
onOptionClicked(intent.option)
|
||||
}
|
||||
|
||||
ConvoIntent.PaginationConditionsMet -> {
|
||||
onPaginationConditionsMet()
|
||||
}
|
||||
|
||||
ConvoIntent.Refresh -> {
|
||||
onRefresh()
|
||||
}
|
||||
|
||||
is ConvoIntent.SetScrollIndex -> {
|
||||
setScrollIndex(intent.index)
|
||||
}
|
||||
|
||||
is ConvoIntent.SetScrollOffset -> {
|
||||
setScrollOffset(intent.offset)
|
||||
}
|
||||
|
||||
is ConvoIntent.Dialog -> {
|
||||
when (intent) {
|
||||
is ConvoIntent.Dialog.Cancel -> Unit
|
||||
is ConvoIntent.Dialog.Confirm -> onDialogConfirmed(intent.bundle)
|
||||
ConvoIntent.Dialog.Dismiss -> onDialogDismissed()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onDialogConfirmed(dialog: ConvoDialog, bundle: Bundle) {
|
||||
onDialogDismissed(dialog)
|
||||
fun onNavigationConsumed() {
|
||||
navigationIntent.setValue { null }
|
||||
}
|
||||
|
||||
private fun onDialogConfirmed(bundle: Bundle?) {
|
||||
val dialog = screenState.value.dialog ?: return
|
||||
onDialogDismissed()
|
||||
|
||||
val convo = with(screenState.value) {
|
||||
convos.find { it.id == expandedConvoId }
|
||||
} ?: return
|
||||
|
||||
when (dialog) {
|
||||
is ConvoDialog.ConvoDelete -> {
|
||||
deleteConvo(dialog.convoId)
|
||||
is ConvoDialog.Delete -> {
|
||||
deleteConvo(convo.id)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoPin -> {
|
||||
pinConvo(dialog.convoId, true)
|
||||
is ConvoDialog.Pin -> {
|
||||
pinConvo(convo.id, true)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoUnpin -> {
|
||||
pinConvo(dialog.convoId, false)
|
||||
is ConvoDialog.Unpin -> {
|
||||
pinConvo(convo.id, false)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoArchive -> {
|
||||
archiveConvo(dialog.convoId, true)
|
||||
is ConvoDialog.Archive -> {
|
||||
archiveConvo(convo.id, true)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoUnarchive -> {
|
||||
archiveConvo(dialog.convoId, false)
|
||||
is ConvoDialog.Unarchive -> {
|
||||
archiveConvo(convo.id, false)
|
||||
}
|
||||
}
|
||||
|
||||
expandedConvoId.setValue { 0 }
|
||||
collapseConvos(false)
|
||||
syncUiConvos()
|
||||
}
|
||||
|
||||
fun onDialogDismissed(dialog: ConvoDialog) {
|
||||
_dialog.setValue { null }
|
||||
private fun onDialogDismissed() {
|
||||
screenState.updateValue { copy(dialog = null) }
|
||||
}
|
||||
|
||||
fun onDialogItemPicked(dialog: ConvoDialog, bundle: Bundle) {
|
||||
when (dialog) {
|
||||
is ConvoDialog.ConvoDelete -> Unit
|
||||
is ConvoDialog.ConvoPin -> Unit
|
||||
is ConvoDialog.ConvoUnpin -> Unit
|
||||
is ConvoDialog.ConvoArchive -> Unit
|
||||
is ConvoDialog.ConvoUnarchive -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
fun onErrorButtonClicked() {
|
||||
when (baseError.value) {
|
||||
null -> Unit
|
||||
|
||||
is BaseError.ConnectionError,
|
||||
is BaseError.InternalError,
|
||||
is BaseError.SimpleError,
|
||||
is BaseError.UnknownError -> onRefresh()
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
fun onPaginationConditionsMet() {
|
||||
_currentOffset.update { convos.value.size }
|
||||
private fun onPaginationConditionsMet() {
|
||||
currentOffset = convos.size
|
||||
loadConvos()
|
||||
}
|
||||
|
||||
fun onRefresh() {
|
||||
private fun onErrorConsumed() {
|
||||
screenState.updateValue { copy(error = null) }
|
||||
}
|
||||
|
||||
private fun onRefresh() {
|
||||
onErrorConsumed()
|
||||
loadConvos(offset = 0)
|
||||
}
|
||||
|
||||
fun onConvoItemClick(convo: UiConvo) {
|
||||
private fun onConvoItemClick(convoId: Long) {
|
||||
collapseConvos()
|
||||
_navigation.setValue { ConvoNavigation.MessagesHistory(peerId = convo.id) }
|
||||
navigationIntent.setValue { ConvoNavigationIntent.MessagesHistory(convoId) }
|
||||
}
|
||||
|
||||
fun onConvoItemLongClick(convo: UiConvo) {
|
||||
expandedConvoId.setValue {
|
||||
if (convo.isExpanded) 0
|
||||
else convo.id
|
||||
}
|
||||
private fun onConvoItemLongClick(convoId: Long) {
|
||||
val isExpanded = screenState.value.convos.find { it.id == convoId }?.isExpanded == true
|
||||
|
||||
screenState.updateValue { copy(expandedConvoId = if (isExpanded) 0L else convoId) }
|
||||
syncUiConvos()
|
||||
}
|
||||
|
||||
fun onOptionClicked(
|
||||
convo: UiConvo,
|
||||
option: ConvoOption
|
||||
) {
|
||||
private fun onOptionClicked(option: ConvoOption) {
|
||||
val convo =
|
||||
screenState.value.convos.find { it.id == screenState.value.expandedConvoId } ?: return
|
||||
|
||||
when (option) {
|
||||
ConvoOption.Delete -> {
|
||||
_dialog.setValue { ConvoDialog.ConvoDelete(convo.id) }
|
||||
}
|
||||
ConvoOption.Delete -> setDialog(ConvoDialog.Delete)
|
||||
|
||||
ConvoOption.MarkAsRead -> {
|
||||
convo.lastMessageId?.let { lastMessageId ->
|
||||
val lastMessageId =
|
||||
screenState.value.convos.find { it.id == screenState.value.expandedConvoId }?.lastMessageId
|
||||
|
||||
if (lastMessageId != null) {
|
||||
readConvo(
|
||||
peerId = convo.id,
|
||||
startMessageId = lastMessageId
|
||||
@@ -211,48 +234,39 @@ class ConvosViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
ConvoOption.Pin -> {
|
||||
_dialog.setValue { ConvoDialog.ConvoPin(convo.id) }
|
||||
}
|
||||
|
||||
ConvoOption.Unpin -> {
|
||||
_dialog.setValue { ConvoDialog.ConvoUnpin(convo.id) }
|
||||
}
|
||||
|
||||
ConvoOption.Archive -> {
|
||||
_dialog.setValue { ConvoDialog.ConvoArchive(convo.id) }
|
||||
}
|
||||
|
||||
ConvoOption.Unarchive -> {
|
||||
_dialog.setValue { ConvoDialog.ConvoUnarchive(convo.id) }
|
||||
}
|
||||
ConvoOption.Pin -> setDialog(ConvoDialog.Pin)
|
||||
ConvoOption.Unpin -> setDialog(ConvoDialog.Unpin)
|
||||
ConvoOption.Archive -> setDialog(ConvoDialog.Archive)
|
||||
ConvoOption.Unarchive -> setDialog(ConvoDialog.Unarchive)
|
||||
}
|
||||
}
|
||||
|
||||
fun onErrorConsumed() {
|
||||
_baseError.setValue { null }
|
||||
private fun setScrollIndex(index: Int) {
|
||||
screenState.setValue { old -> old.copy(scrollIndex = index) }
|
||||
}
|
||||
|
||||
fun setScrollIndex(index: Int) {
|
||||
_screenState.setValue { old -> old.copy(scrollIndex = index) }
|
||||
private fun setScrollOffset(offset: Int) {
|
||||
screenState.setValue { old -> old.copy(scrollOffset = offset) }
|
||||
}
|
||||
|
||||
fun setScrollOffset(offset: Int) {
|
||||
_screenState.setValue { old -> old.copy(scrollOffset = offset) }
|
||||
private fun setDialog(dialog: ConvoDialog?) {
|
||||
screenState.updateValue { copy(dialog = dialog) }
|
||||
}
|
||||
|
||||
fun onCreateChatButtonClicked() {
|
||||
_navigation.setValue { ConvoNavigation.CreateChat }
|
||||
private fun replaceConvos(newConvos: List<VkConvo>) {
|
||||
convos.clear()
|
||||
convos.addAll(newConvos)
|
||||
}
|
||||
|
||||
private fun collapseConvos() {
|
||||
expandedConvoId.setValue { 0 }
|
||||
syncUiConvos()
|
||||
private fun collapseConvos(sync: Boolean = true) {
|
||||
screenState.updateValue { copy(expandedConvoId = null) }
|
||||
|
||||
if (sync) {
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadConvos(
|
||||
offset: Int = currentOffset.value
|
||||
) {
|
||||
private fun loadConvos(offset: Int = currentOffset) {
|
||||
convoUseCase.getConvos(
|
||||
count = LOAD_COUNT,
|
||||
offset = offset,
|
||||
@@ -260,23 +274,20 @@ class ConvosViewModel(
|
||||
).listenValue(viewModelScope) { state ->
|
||||
state.processState(
|
||||
error = { error ->
|
||||
val newBaseError = VkUtils.parseError(error)
|
||||
_baseError.update { newBaseError }
|
||||
screenState.updateValue { copy(error = VkUtils.parseError(error)) }
|
||||
},
|
||||
success = { response ->
|
||||
val convos = response
|
||||
val fullConvos = if (offset == 0) {
|
||||
convos
|
||||
val newConvos = if (offset == 0) {
|
||||
response
|
||||
} else {
|
||||
this.convos.value.plus(convos)
|
||||
convos.plus(response)
|
||||
}
|
||||
|
||||
val itemsCountSufficient = response.size == LOAD_COUNT
|
||||
|
||||
val paginationExhausted = !itemsCountSufficient &&
|
||||
this.convos.value.isNotEmpty()
|
||||
val paginationExhausted = !itemsCountSufficient && convos.isNotEmpty()
|
||||
|
||||
_screenState.updateValue {
|
||||
screenState.updateValue {
|
||||
copy(isPaginationExhausted = paginationExhausted)
|
||||
}
|
||||
|
||||
@@ -293,13 +304,14 @@ class ConvosViewModel(
|
||||
|
||||
convoUseCase.storeConvos(response)
|
||||
|
||||
_convos.emit(fullConvos)
|
||||
replaceConvos(newConvos)
|
||||
|
||||
screenState.updateValue { copy(canPaginate = itemsCountSufficient) }
|
||||
syncUiConvos()
|
||||
_canPaginate.setValue { itemsCountSufficient }
|
||||
}
|
||||
)
|
||||
|
||||
_screenState.setValue { old ->
|
||||
screenState.setValue { old ->
|
||||
old.copy(
|
||||
isLoading = offset == 0 && state.isLoading(),
|
||||
isPaginating = offset > 0 && state.isLoading()
|
||||
@@ -313,17 +325,17 @@ class ConvosViewModel(
|
||||
state.processState(
|
||||
error = {},
|
||||
success = {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == peerId }
|
||||
?: return@processState
|
||||
|
||||
newConvos.removeAt(convoIndex)
|
||||
_convos.update { newConvos.sorted() }
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
)
|
||||
_screenState.emit(screenState.value.copy(isLoading = state.isLoading()))
|
||||
screenState.emit(screenStateFlow.value.copy(isLoading = state.isLoading()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,7 +349,7 @@ class ConvosViewModel(
|
||||
LongPollParsedEvent.ChatMajorChanged(
|
||||
peerId = peerId,
|
||||
majorId = if (pin) {
|
||||
pinnedConvosCount.value.plus(1) * 16
|
||||
pinnedConvosCount.plus(1) * 16
|
||||
} else {
|
||||
0
|
||||
}
|
||||
@@ -346,7 +358,7 @@ class ConvosViewModel(
|
||||
}
|
||||
)
|
||||
|
||||
_screenState.setValue { old -> old.copy(isLoading = state.isLoading()) }
|
||||
screenState.setValue { old -> old.copy(isLoading = state.isLoading()) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,7 +368,7 @@ class ConvosViewModel(
|
||||
state.processState(
|
||||
error = {},
|
||||
success = {
|
||||
convos.value.find { it.id == peerId }?.let { convo ->
|
||||
convos.find { it.id == peerId }?.let { convo ->
|
||||
handleChatArchived(
|
||||
LongPollParsedEvent.ChatArchived(
|
||||
convo = convo,
|
||||
@@ -373,7 +385,7 @@ class ConvosViewModel(
|
||||
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
|
||||
val message = event.message
|
||||
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
||||
|
||||
@@ -391,8 +403,8 @@ class ConvosViewModel(
|
||||
val convo = (response.firstOrNull() ?: return@listenValue)
|
||||
.copy(lastMessage = message)
|
||||
|
||||
newConvos.add(pinnedConvosCount.value, convo)
|
||||
_convos.update { newConvos.sorted() }
|
||||
newConvos.add(pinnedConvosCount, convo)
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
)
|
||||
@@ -428,19 +440,17 @@ class ConvosViewModel(
|
||||
newConvos[convoIndex] = newConvo
|
||||
} else {
|
||||
newConvos.removeAt(convoIndex)
|
||||
|
||||
val toPosition = pinnedConvosCount.value
|
||||
newConvos.add(toPosition, newConvo)
|
||||
newConvos.add(pinnedConvosCount, newConvo)
|
||||
}
|
||||
|
||||
_convos.update { newConvos.sorted() }
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) {
|
||||
val message = event.message
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
|
||||
val convoIndex = newConvos.indexOfFirstOrNull { it.id == message.peerId }
|
||||
if (convoIndex == null) { // диалога нет в списке
|
||||
@@ -452,13 +462,14 @@ class ConvosViewModel(
|
||||
lastMessageId = message.id,
|
||||
lastCmId = message.cmId
|
||||
)
|
||||
_convos.update { newConvos }
|
||||
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||
@@ -472,13 +483,13 @@ class ConvosViewModel(
|
||||
unreadCount = event.unreadCount
|
||||
)
|
||||
|
||||
_convos.update { newConvos }
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||
@@ -492,7 +503,7 @@ class ConvosViewModel(
|
||||
unreadCount = event.unreadCount
|
||||
)
|
||||
|
||||
_convos.update { newConvos }
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
@@ -502,7 +513,7 @@ class ConvosViewModel(
|
||||
val peerId = event.peerId
|
||||
val userIds = event.userIds
|
||||
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoAndIndex =
|
||||
newConvos.findWithIndex { it.id == peerId }
|
||||
|
||||
@@ -513,7 +524,7 @@ class ConvosViewModel(
|
||||
interactionIds = userIds
|
||||
)
|
||||
|
||||
_convos.update { newConvos }
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
|
||||
interactionsTimers[peerId]?.let { interactionJob ->
|
||||
@@ -545,7 +556,7 @@ class ConvosViewModel(
|
||||
private fun stopInteraction(peerId: Long, interactionJob: InteractionJob) {
|
||||
interactionsTimers[peerId] ?: return
|
||||
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoAndIndex =
|
||||
newConvos.findWithIndex { it.id == peerId } ?: return
|
||||
|
||||
@@ -555,7 +566,7 @@ class ConvosViewModel(
|
||||
interactionIds = emptyList()
|
||||
)
|
||||
|
||||
_convos.update { newConvos }
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
|
||||
interactionJob.timerJob.cancel()
|
||||
@@ -563,7 +574,7 @@ class ConvosViewModel(
|
||||
}
|
||||
|
||||
private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||
|
||||
@@ -573,13 +584,13 @@ class ConvosViewModel(
|
||||
newConvos[convoIndex] =
|
||||
newConvos[convoIndex].copy(majorId = event.majorId)
|
||||
|
||||
_convos.setValue { newConvos.sorted() }
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||
|
||||
@@ -589,22 +600,23 @@ class ConvosViewModel(
|
||||
newConvos[convoIndex] =
|
||||
newConvos[convoIndex].copy(minorId = event.minorId)
|
||||
|
||||
_convos.setValue { newConvos.sorted() }
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
|
||||
val convoIndex = newConvos.indexOfFirstOrNull { it.id == event.peerId }
|
||||
|
||||
if (convoIndex == null) { // диалога нет в списке
|
||||
// pizdets
|
||||
} else {
|
||||
// TODO: 30.05.2026, Danil Nikolaev: reimplement
|
||||
newConvos.removeAt(convoIndex)
|
||||
|
||||
_convos.setValue { newConvos.sorted() }
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
@@ -612,7 +624,7 @@ class ConvosViewModel(
|
||||
private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) {
|
||||
val convo = event.convo
|
||||
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
|
||||
when (filter) {
|
||||
ConvosFilter.BUSINESS_NOTIFY -> Unit
|
||||
@@ -627,7 +639,7 @@ class ConvosViewModel(
|
||||
newConvos.removeAt(index)
|
||||
}
|
||||
|
||||
_convos.update { newConvos }
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
}
|
||||
|
||||
@@ -638,10 +650,10 @@ class ConvosViewModel(
|
||||
|
||||
newConvos.removeAt(index)
|
||||
} else {
|
||||
newConvos.add(pinnedConvosCount.value, convo)
|
||||
newConvos.add(pinnedConvosCount, convo)
|
||||
}
|
||||
|
||||
_convos.update { newConvos.sorted() }
|
||||
replaceConvos(newConvos.sorted())
|
||||
syncUiConvos()
|
||||
}
|
||||
}
|
||||
@@ -655,7 +667,7 @@ class ConvosViewModel(
|
||||
state.processState(
|
||||
error = {},
|
||||
success = {
|
||||
val newConvos = convos.value.toMutableList()
|
||||
val newConvos = convos.toMutableList()
|
||||
val convoIndex =
|
||||
newConvos.indexOfFirstOrNull { it.id == peerId }
|
||||
?: return@listenValue
|
||||
@@ -663,7 +675,7 @@ class ConvosViewModel(
|
||||
newConvos[convoIndex] =
|
||||
newConvos[convoIndex].copy(inRead = startMessageId)
|
||||
|
||||
_convos.update { newConvos }
|
||||
replaceConvos(newConvos)
|
||||
syncUiConvos()
|
||||
}
|
||||
)
|
||||
@@ -695,47 +707,44 @@ class ConvosViewModel(
|
||||
}
|
||||
|
||||
private fun syncUiConvos(): List<UiConvo> {
|
||||
val convos = convos.value
|
||||
|
||||
val newUiConvos = convos.map { convo ->
|
||||
val options = mutableListOf<ConvoOption>()
|
||||
convo.lastMessage?.run {
|
||||
if (!convo.isRead() && !this.isOut) {
|
||||
options += ConvoOption.MarkAsRead
|
||||
val options: ImmutableList<ConvoOption> = buildImmutableList {
|
||||
if (!convo.isRead() && convo.lastMessage != null && convo.lastMessage?.isOut == false) {
|
||||
add(ConvoOption.MarkAsRead)
|
||||
}
|
||||
|
||||
if (convo.isPinned()) {
|
||||
add(ConvoOption.Unpin)
|
||||
}
|
||||
|
||||
if (convos.size > 4 && pinnedConvosCount < 5 && !convo.isPinned()) {
|
||||
add(ConvoOption.Pin)
|
||||
}
|
||||
|
||||
when (filter) {
|
||||
ConvosFilter.BUSINESS_NOTIFY -> Unit
|
||||
ConvosFilter.ARCHIVE -> add(ConvoOption.Unarchive)
|
||||
|
||||
ConvosFilter.ALL,
|
||||
ConvosFilter.UNREAD -> {
|
||||
if (convo.id != UserConfig.userId) {
|
||||
add(ConvoOption.Archive)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
add(ConvoOption.Delete)
|
||||
}
|
||||
|
||||
val convosSize = this.convos.value.size
|
||||
val pinnedCount = pinnedConvosCount.value
|
||||
|
||||
val canPinOneMoreDialog =
|
||||
convosSize > 4 && pinnedCount < 5 && !convo.isPinned()
|
||||
|
||||
if (convo.isPinned()) {
|
||||
options += ConvoOption.Unpin
|
||||
} else if (canPinOneMoreDialog) {
|
||||
options += ConvoOption.Pin
|
||||
}
|
||||
|
||||
when (filter) {
|
||||
ConvosFilter.ARCHIVE -> ConvoOption.Unarchive
|
||||
|
||||
ConvosFilter.UNREAD,
|
||||
ConvosFilter.ALL -> ConvoOption.Archive
|
||||
|
||||
ConvosFilter.BUSINESS_NOTIFY -> null
|
||||
}?.let(options::add)
|
||||
|
||||
options += ConvoOption.Delete
|
||||
|
||||
convo.asPresentation(
|
||||
resources = resources,
|
||||
useContactName = useContactNames,
|
||||
isExpanded = expandedConvoId.value == convo.id,
|
||||
options = options.toImmutableList()
|
||||
useContactName = userSettings.useContactNames.value,
|
||||
isExpanded = screenState.value.expandedConvoId == convo.id,
|
||||
options = options
|
||||
)
|
||||
}
|
||||
_uiConvos.setValue { newUiConvos }
|
||||
|
||||
screenState.updateValue { copy(convos = newUiConvos.toImmutableList()) }
|
||||
|
||||
return newUiConvos
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import androidx.compose.runtime.Immutable
|
||||
|
||||
@Immutable
|
||||
sealed class ConvoDialog {
|
||||
data class ConvoPin(val convoId: Long) : ConvoDialog()
|
||||
data class ConvoUnpin(val convoId: Long) : ConvoDialog()
|
||||
data class ConvoDelete(val convoId: Long) : ConvoDialog()
|
||||
data class ConvoArchive(val convoId: Long) : ConvoDialog()
|
||||
data class ConvoUnarchive(val convoId: Long) : ConvoDialog()
|
||||
data object Pin : ConvoDialog()
|
||||
data object Unpin : ConvoDialog()
|
||||
data object Delete : ConvoDialog()
|
||||
data object Archive : ConvoDialog()
|
||||
data object Unarchive : ConvoDialog()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package dev.meloda.fast.convos.model
|
||||
|
||||
import android.os.Bundle
|
||||
import dev.meloda.fast.ui.model.vk.ConvoOption
|
||||
|
||||
sealed class ConvoIntent {
|
||||
data class ItemClick(val convoId: Long) : ConvoIntent()
|
||||
data class ItemLongClick(val convoId: Long) : ConvoIntent()
|
||||
data class OptionItemClick(val option: ConvoOption) : ConvoIntent()
|
||||
data object PaginationConditionsMet : ConvoIntent()
|
||||
|
||||
data object Back : ConvoIntent()
|
||||
data object Refresh : ConvoIntent()
|
||||
data object CreateChatClick : ConvoIntent()
|
||||
data object ArchiveClick : ConvoIntent()
|
||||
|
||||
data class SetScrollIndex(val index: Int) : ConvoIntent()
|
||||
data class SetScrollOffset(val offset: Int) : ConvoIntent()
|
||||
|
||||
data object ErrorActionButtonClick : ConvoIntent()
|
||||
|
||||
data object ConsumeScrollToTop : ConvoIntent()
|
||||
|
||||
sealed class Dialog : ConvoIntent() {
|
||||
data object Dismiss : Dialog()
|
||||
data class Confirm(val bundle: Bundle? = null) : Dialog()
|
||||
data class Cancel(val bundle: Bundle? = null) : Dialog()
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package dev.meloda.fast.convos.model
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
|
||||
@Immutable
|
||||
sealed class ConvoNavigation {
|
||||
|
||||
data class MessagesHistory(val peerId: Long) : ConvoNavigation()
|
||||
|
||||
data object CreateChat : ConvoNavigation()
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dev.meloda.fast.convos.model
|
||||
|
||||
sealed class ConvoNavigationIntent {
|
||||
|
||||
data object Back : ConvoNavigationIntent()
|
||||
data class MessagesHistory(val convoId: Long) : ConvoNavigationIntent()
|
||||
data object CreateChat : ConvoNavigationIntent()
|
||||
data object Archive : ConvoNavigationIntent()
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package dev.meloda.fast.convos.model
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.ui.model.vk.UiConvo
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
import dev.meloda.fast.ui.util.emptyImmutableList
|
||||
|
||||
@Immutable
|
||||
data class ConvosScreenState(
|
||||
@@ -10,7 +14,13 @@ data class ConvosScreenState(
|
||||
val profileImageUrl: String?,
|
||||
val scrollIndex: Int,
|
||||
val scrollOffset: Int,
|
||||
val isArchive: Boolean
|
||||
val canPaginate: Boolean,
|
||||
val expandedConvoId: Long?,
|
||||
val convos: ImmutableList<UiConvo>,
|
||||
val dialog: ConvoDialog?,
|
||||
|
||||
// TODO: 30.05.2026, Danil Nikolaev: remove
|
||||
val error: BaseError?
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@@ -21,7 +31,11 @@ data class ConvosScreenState(
|
||||
profileImageUrl = null,
|
||||
scrollIndex = 0,
|
||||
scrollOffset = 0,
|
||||
isArchive = false
|
||||
canPaginate = false,
|
||||
expandedConvoId = null,
|
||||
convos = emptyImmutableList(),
|
||||
dialog = null,
|
||||
error = null
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+44
-28
@@ -1,12 +1,16 @@
|
||||
package dev.meloda.fast.convos.navigation
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavGraphBuilder
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.navigation
|
||||
import dev.meloda.fast.convos.ConvosViewModel
|
||||
import dev.meloda.fast.convos.model.ConvoNavigationIntent
|
||||
import dev.meloda.fast.convos.presentation.ConvosRoute
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.ConvosFilter
|
||||
import dev.meloda.fast.ui.extensions.getOrThrow
|
||||
import dev.meloda.fast.ui.theme.LocalNavController
|
||||
@@ -24,44 +28,56 @@ object Convos
|
||||
object Archive
|
||||
|
||||
fun NavGraphBuilder.convosGraph(
|
||||
handleNavigationIntent: (ConvoNavigationIntent) -> Unit,
|
||||
activity: AppCompatActivity,
|
||||
onError: (BaseError) -> Unit,
|
||||
onNavigateToMessagesHistory: (id: Long) -> Unit,
|
||||
onNavigateToCreateChat: () -> Unit,
|
||||
onScrolledToTop: () -> Unit
|
||||
) {
|
||||
navigation<ConvoGraph>(
|
||||
startDestination = Convos
|
||||
) {
|
||||
val convosViewModel: ConvosViewModel = with(activity) {
|
||||
getViewModel(qualifier = named(ConvosFilter.ALL))
|
||||
}
|
||||
composable<Convos> {
|
||||
val navController = LocalNavController.getOrThrow()
|
||||
|
||||
ConvosRoute(
|
||||
viewModel = convosViewModel,
|
||||
onError = onError,
|
||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
||||
onNavigateToCreateChat = onNavigateToCreateChat,
|
||||
onNavigateToArchive = { navController.navigate(Archive) },
|
||||
onScrolledToTop = onScrolledToTop
|
||||
ConvosRootRoute(
|
||||
handleNavigationIntent = handleNavigationIntent,
|
||||
viewModel = with(activity) {
|
||||
getViewModel(named(ConvosFilter.ALL))
|
||||
}
|
||||
)
|
||||
}
|
||||
composable<Archive> {
|
||||
val navController = LocalNavController.getOrThrow()
|
||||
|
||||
ConvosRoute(
|
||||
ConvosRootRoute(
|
||||
handleNavigationIntent = handleNavigationIntent,
|
||||
viewModel = with(activity) {
|
||||
getViewModel<ConvosViewModel>(
|
||||
qualifier = named(ConvosFilter.ARCHIVE)
|
||||
)
|
||||
},
|
||||
onBack = navController::navigateUp,
|
||||
onError = onError,
|
||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
||||
onScrolledToTop = onScrolledToTop
|
||||
getViewModel<ConvosViewModel>(named(ConvosFilter.ARCHIVE))
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConvosRootRoute(
|
||||
handleNavigationIntent: (ConvoNavigationIntent) -> Unit,
|
||||
viewModel: ConvosViewModel
|
||||
) {
|
||||
val navController = LocalNavController.getOrThrow()
|
||||
|
||||
val screenState by viewModel.screenStateFlow.collectAsStateWithLifecycle()
|
||||
val navigationIntent by viewModel.navigationIntentFlow.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(navigationIntent) {
|
||||
navigationIntent?.let {
|
||||
when (navigationIntent) {
|
||||
ConvoNavigationIntent.Back -> navController.navigateUp()
|
||||
ConvoNavigationIntent.Archive -> navController.navigate(Archive)
|
||||
else -> handleNavigationIntent(it)
|
||||
}
|
||||
|
||||
viewModel.onNavigationConsumed()
|
||||
}
|
||||
}
|
||||
|
||||
ConvosRoute(
|
||||
handleIntent = viewModel::handleIntent,
|
||||
screenState = screenState,
|
||||
isArchive = viewModel.filter == ConvosFilter.ARCHIVE,
|
||||
)
|
||||
}
|
||||
|
||||
+18
-22
@@ -1,82 +1,78 @@
|
||||
package dev.meloda.fast.convos.presentation
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.res.vectorResource
|
||||
import androidx.core.os.bundleOf
|
||||
import dev.meloda.fast.convos.model.ConvoDialog
|
||||
import dev.meloda.fast.convos.model.ConvoIntent
|
||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.components.MaterialDialog
|
||||
|
||||
@Composable
|
||||
fun HandleDialogs(
|
||||
handleIntent: (ConvoIntent) -> Unit,
|
||||
screenState: ConvosScreenState,
|
||||
dialog: ConvoDialog?,
|
||||
onConfirmed: (ConvoDialog, Bundle) -> Unit = { _, _ -> },
|
||||
onDismissed: (ConvoDialog) -> Unit = {},
|
||||
onItemPicked: (ConvoDialog, Bundle) -> Unit = { _, _ -> }
|
||||
) {
|
||||
when (dialog) {
|
||||
when (screenState.dialog) {
|
||||
null -> Unit
|
||||
|
||||
is ConvoDialog.ConvoArchive -> {
|
||||
is ConvoDialog.Archive -> {
|
||||
MaterialDialog(
|
||||
onDismissRequest = { onDismissed(dialog) },
|
||||
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||
title = stringResource(id = R.string.confirm_archive_convo),
|
||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
||||
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||
confirmText = stringResource(id = R.string.action_archive),
|
||||
cancelText = stringResource(id = R.string.cancel),
|
||||
icon = ImageVector.vectorResource(R.drawable.ic_archive_fill_round_24)
|
||||
)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoUnarchive -> {
|
||||
is ConvoDialog.Unarchive -> {
|
||||
MaterialDialog(
|
||||
onDismissRequest = { onDismissed(dialog) },
|
||||
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||
title = stringResource(id = R.string.confirm_unarchive_convo),
|
||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
||||
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||
confirmText = stringResource(id = R.string.action_unarchive),
|
||||
cancelText = stringResource(id = R.string.cancel),
|
||||
icon = ImageVector.vectorResource(R.drawable.ic_unarchive_fill_round_24)
|
||||
)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoDelete -> {
|
||||
is ConvoDialog.Delete -> {
|
||||
val errorColor = MaterialTheme.colorScheme.error
|
||||
|
||||
MaterialDialog(
|
||||
onDismissRequest = { onDismissed(dialog) },
|
||||
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||
icon = ImageVector.vectorResource(R.drawable.ic_delete_fill_round_24),
|
||||
iconTint = errorColor,
|
||||
title = stringResource(id = R.string.confirm_delete_convo),
|
||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
||||
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||
confirmText = stringResource(id = R.string.action_delete),
|
||||
confirmContainerColor = errorColor,
|
||||
cancelText = stringResource(id = R.string.cancel),
|
||||
)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoPin -> {
|
||||
is ConvoDialog.Pin -> {
|
||||
MaterialDialog(
|
||||
onDismissRequest = { onDismissed(dialog) },
|
||||
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||
icon = ImageVector.vectorResource(R.drawable.ic_keep_fill_round_24),
|
||||
title = stringResource(id = R.string.confirm_pin_convo),
|
||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
||||
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||
confirmText = stringResource(id = R.string.action_pin),
|
||||
cancelText = stringResource(id = R.string.cancel),
|
||||
)
|
||||
}
|
||||
|
||||
is ConvoDialog.ConvoUnpin -> {
|
||||
is ConvoDialog.Unpin -> {
|
||||
MaterialDialog(
|
||||
onDismissRequest = { onDismissed(dialog) },
|
||||
onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
|
||||
icon = ImageVector.vectorResource(R.drawable.ic_keep_off_fill_round_24),
|
||||
title = stringResource(id = R.string.confirm_unpin_convo),
|
||||
confirmAction = { onConfirmed(dialog, bundleOf()) },
|
||||
confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
|
||||
confirmText = stringResource(id = R.string.action_unpin),
|
||||
cancelText = stringResource(id = R.string.cancel),
|
||||
)
|
||||
|
||||
@@ -62,9 +62,9 @@ val BirthdayColor = Color(0xffb00b69)
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun ConvoItem(
|
||||
onItemClick: (UiConvo) -> Unit,
|
||||
onItemLongClick: (convo: UiConvo) -> Unit,
|
||||
onOptionClicked: (UiConvo, ConvoOption) -> Unit,
|
||||
onItemClick: (convoId: Long) -> Unit,
|
||||
onItemLongClick: (convoId: Long) -> Unit,
|
||||
onOptionClicked: (ConvoOption) -> Unit,
|
||||
maxLines: Int,
|
||||
isUserAccount: Boolean,
|
||||
convo: UiConvo,
|
||||
@@ -81,9 +81,9 @@ fun ConvoItem(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
onClick = { onItemClick(convo) },
|
||||
onClick = { onItemClick(convo.id) },
|
||||
onLongClick = {
|
||||
onItemLongClick(convo)
|
||||
onItemLongClick(convo.id)
|
||||
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
}
|
||||
)
|
||||
@@ -281,7 +281,7 @@ fun ConvoItem(
|
||||
val builder =
|
||||
AnnotatedString.Builder(convo.message.text)
|
||||
|
||||
convo.message.spanStyles.map { spanStyleRange ->
|
||||
convo.message.spanStyles.forEach { spanStyleRange ->
|
||||
val updatedSpanStyle =
|
||||
if (spanStyleRange.item.color == Color.Red) {
|
||||
spanStyleRange.item.copy(color = MaterialTheme.colorScheme.primary)
|
||||
@@ -378,7 +378,7 @@ fun ConvoItem(
|
||||
}
|
||||
|
||||
ElevatedAssistChip(
|
||||
onClick = { onOptionClicked(convo, option) },
|
||||
onClick = { onOptionClicked(option) },
|
||||
leadingIcon = {
|
||||
option.icon.getResourcePainter()?.let { painter ->
|
||||
Icon(
|
||||
|
||||
@@ -36,12 +36,12 @@ import kotlinx.coroutines.launch
|
||||
fun ConvosList(
|
||||
modifier: Modifier = Modifier,
|
||||
convos: ImmutableList<UiConvo>,
|
||||
onConvosClick: (UiConvo) -> Unit,
|
||||
onConvosLongClick: (UiConvo) -> Unit,
|
||||
onConvosClick: (Long) -> Unit,
|
||||
onConvosLongClick: (Long) -> Unit,
|
||||
screenState: ConvosScreenState,
|
||||
state: LazyListState,
|
||||
maxLines: Int,
|
||||
onOptionClicked: (UiConvo, ConvoOption) -> Unit,
|
||||
onOptionClicked: (ConvoOption) -> Unit,
|
||||
padding: PaddingValues
|
||||
) {
|
||||
val theme = LocalThemeConfig.current
|
||||
|
||||
@@ -1,79 +1,23 @@
|
||||
package dev.meloda.fast.convos.presentation
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import dev.meloda.fast.convos.ConvosViewModel
|
||||
import dev.meloda.fast.convos.model.ConvoNavigation
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
||||
import dev.meloda.fast.convos.model.ConvoIntent
|
||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||
|
||||
@Composable
|
||||
fun ConvosRoute(
|
||||
viewModel: ConvosViewModel,
|
||||
onBack: (() -> Unit)? = null,
|
||||
onError: (BaseError) -> Unit,
|
||||
onNavigateToMessagesHistory: (convoId: Long) -> Unit,
|
||||
onNavigateToCreateChat: (() -> Unit)? = null,
|
||||
onNavigateToArchive: (() -> Unit)? = null,
|
||||
onScrolledToTop: () -> Unit,
|
||||
handleIntent: (ConvoIntent) -> Unit,
|
||||
screenState: ConvosScreenState,
|
||||
isArchive: Boolean,
|
||||
) {
|
||||
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
|
||||
val navigationEvent by viewModel.navigation.collectAsStateWithLifecycle()
|
||||
val convos by viewModel.uiConvos.collectAsStateWithLifecycle()
|
||||
val dialog by viewModel.dialog.collectAsStateWithLifecycle()
|
||||
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
||||
val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(navigationEvent) {
|
||||
val shouldBeConsumed: Boolean = when (val navigation = navigationEvent) {
|
||||
null -> false
|
||||
|
||||
is ConvoNavigation.CreateChat -> {
|
||||
onNavigateToCreateChat?.invoke()
|
||||
true
|
||||
}
|
||||
|
||||
is ConvoNavigation.MessagesHistory -> {
|
||||
onNavigateToMessagesHistory(navigation.peerId)
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldBeConsumed) viewModel.onNavigationConsumed()
|
||||
}
|
||||
|
||||
ConvosScreen(
|
||||
onBack = { onBack?.invoke() },
|
||||
handleIntent = handleIntent,
|
||||
screenState = screenState,
|
||||
convos = convos.toImmutableList(),
|
||||
baseError = baseError,
|
||||
canPaginate = canPaginate,
|
||||
onConvoItemClicked = viewModel::onConvoItemClick,
|
||||
onConvoItemLongClicked = viewModel::onConvoItemLongClick,
|
||||
onOptionClicked = viewModel::onOptionClicked,
|
||||
onPaginationConditionsMet = viewModel::onPaginationConditionsMet,
|
||||
onRefresh = viewModel::onRefresh,
|
||||
onCreateChatButtonClicked = viewModel::onCreateChatButtonClicked,
|
||||
onArchiveActionClicked = { onNavigateToArchive?.invoke() },
|
||||
setScrollIndex = viewModel::setScrollIndex,
|
||||
setScrollOffset = viewModel::setScrollOffset,
|
||||
onConsumeReselection = onScrolledToTop,
|
||||
onErrorViewButtonClicked = {
|
||||
if (baseError in listOf(BaseError.AccountBlocked, BaseError.SessionExpired)) {
|
||||
onError(requireNotNull(baseError))
|
||||
} else {
|
||||
viewModel.onErrorButtonClicked()
|
||||
}
|
||||
}
|
||||
isArchive = isArchive,
|
||||
)
|
||||
|
||||
HandleDialogs(
|
||||
handleIntent = handleIntent,
|
||||
screenState = screenState,
|
||||
dialog = dialog,
|
||||
onConfirmed = viewModel::onDialogConfirmed,
|
||||
onDismissed = viewModel::onDialogDismissed,
|
||||
onItemPicked = viewModel::onDialogItemPicked
|
||||
)
|
||||
}
|
||||
|
||||
+73
-94
@@ -19,7 +19,6 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.statusBars
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
@@ -53,53 +52,39 @@ import androidx.compose.ui.unit.DpOffset
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.skydoves.compose.stability.runtime.TraceRecomposition
|
||||
import dev.chrisbanes.haze.hazeEffect
|
||||
import dev.chrisbanes.haze.hazeSource
|
||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||
import dev.chrisbanes.haze.materials.HazeMaterials
|
||||
import dev.meloda.fast.convos.model.ConvoIntent
|
||||
import dev.meloda.fast.convos.model.ConvosScreenState
|
||||
import dev.meloda.fast.convos.navigation.ConvoGraph
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.components.FullScreenContainedLoader
|
||||
import dev.meloda.fast.ui.components.NoItemsView
|
||||
import dev.meloda.fast.ui.components.VkErrorView
|
||||
import dev.meloda.fast.ui.model.vk.ConvoOption
|
||||
import dev.meloda.fast.ui.model.vk.UiConvo
|
||||
import dev.meloda.fast.ui.components.SegmentedButtonItem
|
||||
import dev.meloda.fast.ui.components.SegmentedButtonsRow
|
||||
import dev.meloda.fast.ui.theme.LocalBottomPadding
|
||||
import dev.meloda.fast.ui.theme.LocalHazeState
|
||||
import dev.meloda.fast.ui.theme.LocalReselectedTab
|
||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
import dev.meloda.fast.ui.util.emptyImmutableList
|
||||
import dev.meloda.fast.ui.util.buildImmutableList
|
||||
import dev.meloda.fast.ui.util.isScrollingUp
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
@OptIn(
|
||||
ExperimentalMaterial3Api::class,
|
||||
ExperimentalHazeMaterialsApi::class, ExperimentalMaterial3ExpressiveApi::class,
|
||||
ExperimentalHazeMaterialsApi::class,
|
||||
ExperimentalMaterial3ExpressiveApi::class,
|
||||
)
|
||||
@Composable
|
||||
fun ConvosScreen(
|
||||
screenState: ConvosScreenState = ConvosScreenState.EMPTY,
|
||||
convos: ImmutableList<UiConvo> = emptyImmutableList(),
|
||||
baseError: BaseError? = null,
|
||||
canPaginate: Boolean = false,
|
||||
onBack: () -> Unit = {},
|
||||
onConvoItemClicked: (convo: UiConvo) -> Unit = {},
|
||||
onConvoItemLongClicked: (convo: UiConvo) -> Unit = {},
|
||||
onOptionClicked: (UiConvo, ConvoOption) -> Unit = { _, _ -> },
|
||||
onPaginationConditionsMet: () -> Unit = {},
|
||||
onRefresh: () -> Unit = {},
|
||||
onCreateChatButtonClicked: () -> Unit = {},
|
||||
onArchiveActionClicked: () -> Unit = {},
|
||||
setScrollIndex: (Int) -> Unit = {},
|
||||
setScrollOffset: (Int) -> Unit = {},
|
||||
onConsumeReselection: () -> Unit = {},
|
||||
onErrorViewButtonClicked: () -> Unit = {}
|
||||
handleIntent: (ConvoIntent) -> Unit,
|
||||
screenState: ConvosScreenState,
|
||||
isArchive: Boolean,
|
||||
) {
|
||||
val currentTheme = LocalThemeConfig.current
|
||||
val maxLines = if (currentTheme.enableMultiline) 2 else 1
|
||||
@@ -112,33 +97,33 @@ fun ConvosScreen(
|
||||
val currentTabReselected = LocalReselectedTab.current[ConvoGraph] == true
|
||||
LaunchedEffect(currentTabReselected) {
|
||||
if (currentTabReselected) {
|
||||
if (screenState.isArchive) {
|
||||
onBack.invoke()
|
||||
if (isArchive) {
|
||||
handleIntent(ConvoIntent.Back)
|
||||
} else {
|
||||
if (listState.firstVisibleItemIndex > 14) {
|
||||
listState.scrollToItem(14)
|
||||
}
|
||||
listState.animateScrollToItem(0)
|
||||
onConsumeReselection()
|
||||
handleIntent(ConvoIntent.ConsumeScrollToTop)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(listState) {
|
||||
snapshotFlow { listState.firstVisibleItemIndex }
|
||||
.debounce(500L)
|
||||
.collectLatest(setScrollIndex)
|
||||
.debounce(500L.milliseconds)
|
||||
.collectLatest { handleIntent(ConvoIntent.SetScrollIndex(it)) }
|
||||
}
|
||||
|
||||
LaunchedEffect(listState) {
|
||||
snapshotFlow { listState.firstVisibleItemScrollOffset }
|
||||
.debounce(500L)
|
||||
.collectLatest(setScrollOffset)
|
||||
.debounce(500L.milliseconds)
|
||||
.collectLatest { handleIntent(ConvoIntent.SetScrollOffset(it)) }
|
||||
}
|
||||
|
||||
val paginationConditionMet by remember(canPaginate, listState) {
|
||||
val paginationConditionMet by remember(screenState.canPaginate, listState) {
|
||||
derivedStateOf {
|
||||
canPaginate &&
|
||||
screenState.canPaginate &&
|
||||
(listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
|
||||
?: -9) >= (listState.layoutInfo.totalItemsCount - 6)
|
||||
}
|
||||
@@ -146,7 +131,7 @@ fun ConvosScreen(
|
||||
|
||||
LaunchedEffect(paginationConditionMet) {
|
||||
if (paginationConditionMet && !screenState.isPaginating) {
|
||||
onPaginationConditionsMet()
|
||||
handleIntent(ConvoIntent.PaginationConditionsMet)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,7 +166,7 @@ fun ConvosScreen(
|
||||
text = stringResource(
|
||||
id = when {
|
||||
screenState.isLoading -> R.string.title_loading
|
||||
screenState.isArchive -> R.string.title_archive
|
||||
isArchive -> R.string.title_archive
|
||||
else -> R.string.title_convos
|
||||
}
|
||||
),
|
||||
@@ -191,8 +176,8 @@ fun ConvosScreen(
|
||||
)
|
||||
},
|
||||
navigationIcon = {
|
||||
if (screenState.isArchive) {
|
||||
IconButton(onClick = onBack) {
|
||||
if (isArchive) {
|
||||
IconButton(onClick = { handleIntent(ConvoIntent.Back) }) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_arrow_back_round_24),
|
||||
contentDescription = null
|
||||
@@ -201,54 +186,47 @@ fun ConvosScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (!screenState.isArchive) {
|
||||
IconButton(onClick = onArchiveActionClicked) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_archive_round_24),
|
||||
contentDescription = null
|
||||
)
|
||||
val dropDownItems: List<@Composable () -> Unit> = buildList {}
|
||||
|
||||
val items = buildImmutableList {
|
||||
if (!isArchive) {
|
||||
add(SegmentedButtonItem("archive", R.drawable.ic_archive_round_24))
|
||||
}
|
||||
|
||||
if (AppSettings.General.showManualRefreshOptions) {
|
||||
add(SegmentedButtonItem("refresh", R.drawable.ic_refresh_round_24))
|
||||
}
|
||||
|
||||
if (dropDownItems.isNotEmpty()) {
|
||||
add(SegmentedButtonItem("more", R.drawable.ic_more_vert_round_24))
|
||||
}
|
||||
}
|
||||
|
||||
val dropDownItems = mutableListOf<@Composable () -> Unit>()
|
||||
|
||||
if (AppSettings.General.showManualRefreshOptions) {
|
||||
dropDownItems += {
|
||||
DropdownMenuItem(
|
||||
onClick = {
|
||||
onRefresh()
|
||||
dropDownMenuExpanded = false
|
||||
},
|
||||
text = {
|
||||
Text(text = stringResource(id = R.string.action_refresh))
|
||||
},
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_refresh_round_24),
|
||||
contentDescription = null
|
||||
)
|
||||
}
|
||||
)
|
||||
SegmentedButtonsRow(
|
||||
modifier = Modifier.padding(end = 8.dp),
|
||||
items = items,
|
||||
onClick = { index ->
|
||||
when (items[index].key) {
|
||||
"archive" -> handleIntent(ConvoIntent.ArchiveClick)
|
||||
"refresh" -> handleIntent(ConvoIntent.Refresh)
|
||||
"more" -> dropDownMenuExpanded = true
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (dropDownItems.isNotEmpty()) {
|
||||
IconButton(onClick = { dropDownMenuExpanded = true }) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_more_vert_round_24),
|
||||
contentDescription = null
|
||||
)
|
||||
DropdownMenu(
|
||||
modifier = Modifier.defaultMinSize(minWidth = 140.dp),
|
||||
expanded = dropDownMenuExpanded,
|
||||
onDismissRequest = { dropDownMenuExpanded = false },
|
||||
offset = DpOffset(x = (-4).dp, y = (-60).dp)
|
||||
) {
|
||||
dropDownItems.forEach { it.invoke() }
|
||||
}
|
||||
}
|
||||
|
||||
DropdownMenu(
|
||||
modifier = Modifier.defaultMinSize(minWidth = 140.dp),
|
||||
expanded = dropDownMenuExpanded,
|
||||
onDismissRequest = { dropDownMenuExpanded = false },
|
||||
offset = DpOffset(x = (-4).dp, y = (-60).dp)
|
||||
) {
|
||||
dropDownItems.forEach { it.invoke() }
|
||||
}
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = toolbarContainerColor.copy(
|
||||
@@ -268,7 +246,7 @@ fun ConvosScreen(
|
||||
)
|
||||
|
||||
val showHorizontalProgressBar by remember(screenState) {
|
||||
derivedStateOf { screenState.isLoading && convos.isNotEmpty() }
|
||||
derivedStateOf { screenState.isLoading && screenState.convos.isNotEmpty() }
|
||||
}
|
||||
AnimatedVisibility(showHorizontalProgressBar) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
@@ -279,14 +257,14 @@ fun ConvosScreen(
|
||||
}
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (!screenState.isArchive) {
|
||||
if (!isArchive) {
|
||||
val offsetY by animateIntAsState(
|
||||
targetValue = if (listState.isScrollingUp()) 0 else 600
|
||||
)
|
||||
|
||||
Column {
|
||||
FloatingActionButton(
|
||||
onClick = onCreateChatButtonClicked,
|
||||
onClick = { handleIntent(ConvoIntent.CreateChatClick) },
|
||||
modifier = Modifier.offset {
|
||||
IntOffset(0, offsetY)
|
||||
}
|
||||
@@ -303,14 +281,15 @@ fun ConvosScreen(
|
||||
}
|
||||
) { padding ->
|
||||
when {
|
||||
baseError != null -> {
|
||||
VkErrorView(
|
||||
baseError = baseError,
|
||||
onButtonClick = onErrorViewButtonClicked
|
||||
)
|
||||
}
|
||||
// TODO: 30.05.2026, Danil Nikolaev: move to UI State
|
||||
// baseError != null -> {
|
||||
// VkErrorView(
|
||||
// baseError = baseError,
|
||||
// onButtonClick = onErrorViewButtonClicked
|
||||
// )
|
||||
// }
|
||||
|
||||
screenState.isLoading && convos.isEmpty() -> FullScreenContainedLoader()
|
||||
screenState.isLoading && screenState.convos.isEmpty() -> FullScreenContainedLoader()
|
||||
|
||||
else -> {
|
||||
val pullToRefreshState = rememberPullToRefreshState()
|
||||
@@ -323,7 +302,7 @@ fun ConvosScreen(
|
||||
.padding(bottom = padding.calculateBottomPadding()),
|
||||
state = pullToRefreshState,
|
||||
isRefreshing = screenState.isLoading,
|
||||
onRefresh = onRefresh,
|
||||
onRefresh = { handleIntent(ConvoIntent.Refresh) },
|
||||
indicator = {
|
||||
PullToRefreshDefaults.Indicator(
|
||||
state = pullToRefreshState,
|
||||
@@ -335,9 +314,9 @@ fun ConvosScreen(
|
||||
}
|
||||
) {
|
||||
ConvosList(
|
||||
convos = convos,
|
||||
onConvosClick = onConvoItemClicked,
|
||||
onConvosLongClick = onConvoItemLongClicked,
|
||||
convos = screenState.convos,
|
||||
onConvosClick = { handleIntent(ConvoIntent.ItemClick(it)) },
|
||||
onConvosLongClick = { handleIntent(ConvoIntent.ItemLongClick(it)) },
|
||||
screenState = screenState,
|
||||
state = listState,
|
||||
maxLines = maxLines,
|
||||
@@ -346,14 +325,14 @@ fun ConvosScreen(
|
||||
} else {
|
||||
Modifier
|
||||
}.fillMaxSize(),
|
||||
onOptionClicked = onOptionClicked,
|
||||
onOptionClicked = { handleIntent(ConvoIntent.OptionItemClick(it)) },
|
||||
padding = padding
|
||||
)
|
||||
|
||||
if (convos.isEmpty()) {
|
||||
if (screenState.convos.isEmpty()) {
|
||||
NoItemsView(
|
||||
buttonText = stringResource(R.string.action_refresh),
|
||||
onButtonClick = onRefresh
|
||||
onButtonClick = { handleIntent(ConvoIntent.Refresh) }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user