16 Commits

Author SHA1 Message Date
melod1n f11b8dc6f4 refactor: consolidate convos state and intent handling 2026-05-30 15:39:43 +03:00
melod1n 167f980f29 refactor StateFlow exposure in ConvosViewModel 2026-05-30 12:01:06 +03:00
melod1n d428af4ac4 refactor: simplify Profile feature state management and update ViewModel 2026-05-30 11:46:14 +03:00
melod1n 63bae014c5 feat: replace settings icon button with segmented buttons in ProfileScreen 2026-05-30 11:43:48 +03:00
melod1n ad54477d11 feat: add segmented buttons to friends screen 2026-05-30 11:39:10 +03:00
melod1n c8bd485724 feat: add custom segmented buttons and refactor conversation screen actions 2026-05-30 11:33:32 +03:00
melod1n 26a0630393 Replace ACRA with custom crash dialog
* Add uncaught exception handler that saves stacktraces to local crash log files
* Show a Compose crash dialog with stacktrace toggle and share action
* Register crash handler activity in a separate process with dialog theme
* Remove ACRA dependencies and configuration
* Add crash dialog strings and ignore `.hotswan/`
2026-05-23 21:59:12 +03:00
melod1n 3d153df79c Update README.md 2026-05-23 08:58:52 +03:00
melod1n 9061a39407 update Gitea workflow 2026-05-23 08:58:52 +03:00
melod1n d8c8820b32 add Gitea workflow 2026-05-22 20:45:42 +03:00
melod1n abfe25d051 fix signing 2026-05-22 17:46:56 +03:00
melod1n 574b230b26 feat: add channel message support and refactor UI components
- Implement `VkChannelMessage` domain and data models for channel message attachments
- Add `CHANNEL_MESSAGE` to `AttachmentType` and map it to relevant UI resources and strings
- Refactor `Sticker` and `Gift` composables to accept URL strings instead of domain objects for better decoupling
- Simplify `AppTheme` by removing redundant color animations and passing the color scheme directly to `MaterialExpressiveTheme`
- Update `LoginScreen` to include a theme toggle (classic vs. light) and improve back-button behavior by resetting error states
- Bump VK API version from 5.238 to 5.263
- Adjust layout and padding for sticker and gift attachment previews
2026-05-19 22:54:44 +03:00
melod1n b31c0f30c5 build: update gradle wrapper and build logic conventions 2026-05-19 13:28:10 +03:00
melod1n cb653eddc2 refactor(auth): reuse network ValidationType for validation flow
Remove duplicate auth ValidationType and use the shared network model instead.
Add support for both "sms" and "2fa_sms" SMS validation values.
2026-05-03 06:53:56 +03:00
melod1n df2c61d8d7 feat(auth): add web captcha handling
- replace manual captcha screen with WebView-based VK captcha flow
- handle captcha error 14 by showing the captcha overlay and retrying with success_token
- pass captcha redirect/result state through AppSettings
- remove old captcha ViewModel, navigation, validation, and DI
- add ACRA crash reporting
- add WIP message edit mode UI/state
- update Gradle wrapper, SDK config, and dependencies
2026-05-03 05:49:16 +03:00
dependabot[bot] 97c59a85b6 Chore(deps): Bump actions/upload-artifact from 6 to 7 (#252)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-27 21:01:31 +03:00
99 changed files with 1762 additions and 1311 deletions
+56
View File
@@ -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 }}
+2 -2
View File
@@ -40,7 +40,7 @@ jobs:
echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV
- name: Upload APK with original name - name: Upload APK with original name
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v7
with: with:
name: ${{ env.APK_NAME }} name: ${{ env.APK_NAME }}
path: ${{ env.APK_PATH }} path: ${{ env.APK_PATH }}
@@ -56,7 +56,7 @@ jobs:
echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV
- name: Upload APK with original name - name: Upload APK with original name
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v7
with: with:
name: ${{ env.APK_NAME }} name: ${{ env.APK_NAME }}
path: ${{ env.APK_PATH }} path: ${{ env.APK_PATH }}
+2 -2
View File
@@ -34,7 +34,7 @@ jobs:
run: ./gradlew assembleRelease run: ./gradlew assembleRelease
- name: Upload release APK - name: Upload release APK
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v7
with: with:
name: app-release.apk name: app-release.apk
path: app/build/outputs/apk/release/app-release.apk path: app/build/outputs/apk/release/app-release.apk
@@ -43,7 +43,7 @@ jobs:
run: ./gradlew bundleRelease run: ./gradlew bundleRelease
- name: Upload release Bundle - name: Upload release Bundle
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v7
with: with:
name: app-release.aab name: app-release.aab
path: app/build/outputs/bundle/release/app-release.aab path: app/build/outputs/bundle/release/app-release.aab
+2
View File
@@ -15,3 +15,5 @@ build/
local.properties local.properties
.idea .idea
/.kotlin /.kotlin
.hotswan/
.java-version
+1
View File
@@ -43,6 +43,7 @@ Unofficial messenger for russian social network VKontakte
- [ ] Forwarded messages - [ ] Forwarded messages
- [ ] Wall post - [ ] Wall post
- [ ] Comment in wall post - [ ] Comment in wall post
- [ ] Comment in channel
- [ ] Poll - [ ] Poll
- [ ] TODO - [ ] TODO
- [x] Send messages - [x] Send messages
+1 -1
View File
@@ -47,7 +47,7 @@ android {
applicationIdSuffix = ".debug" applicationIdSuffix = ".debug"
} }
named("release") { named("release") {
signingConfig = signingConfigs.getByName("release") signingConfig = signingConfigs.getByName("debugSigning")
isMinifyEnabled = true isMinifyEnabled = true
isShrinkResources = true isShrinkResources = true
+8 -2
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:tools="http://schemas.android.com/tools" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
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.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
@@ -37,6 +37,12 @@
</intent-filter> </intent-filter>
</activity> </activity>
<activity
android:name="dev.meloda.fast.presentation.CrashActivity"
android:exported="false"
android:process=":error_handler"
android:theme="@style/CrashDialogTheme" />
<service <service
android:name="dev.meloda.fast.service.longpolling.LongPollingService" android:name="dev.meloda.fast.service.longpolling.LongPollingService"
android:enabled="true" android:enabled="true"
@@ -1,6 +1,8 @@
package dev.meloda.fast.common package dev.meloda.fast.common
import android.app.Application import android.app.Application
import android.content.Intent
import android.net.Uri
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import coil.ImageLoader import coil.ImageLoader
import coil.ImageLoaderFactory import coil.ImageLoaderFactory
@@ -8,10 +10,14 @@ import com.skydoves.compose.stability.runtime.ComposeStabilityAnalyzer
import dev.meloda.fast.auth.BuildConfig import dev.meloda.fast.auth.BuildConfig
import dev.meloda.fast.common.di.applicationModule import dev.meloda.fast.common.di.applicationModule
import dev.meloda.fast.datastore.AppSettings import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.presentation.CrashActivity
import org.koin.android.ext.android.get import org.koin.android.ext.android.get
import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.GlobalContext.startKoin import org.koin.core.context.GlobalContext.startKoin
import java.io.File
import java.io.FileOutputStream
import kotlin.system.exitProcess
class AppGlobal : Application(), ImageLoaderFactory { class AppGlobal : Application(), ImageLoaderFactory {
@@ -20,12 +26,14 @@ class AppGlobal : Application(), ImageLoaderFactory {
val preferences = PreferenceManager.getDefaultSharedPreferences(this) val preferences = PreferenceManager.getDefaultSharedPreferences(this)
AppSettings.init(preferences) AppSettings.init(preferences)
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
initKoin() initKoin()
initCrashHandler()
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
} }
override fun newImageLoader(): ImageLoader = get()
private fun initKoin() { private fun initKoin() {
startKoin { startKoin {
androidLogger() androidLogger()
@@ -34,5 +42,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.ImageLoader
import coil.annotation.ExperimentalCoilApi import coil.annotation.ExperimentalCoilApi
import dev.meloda.fast.MainViewModelImpl import dev.meloda.fast.MainViewModelImpl
import dev.meloda.fast.auth.captcha.di.captchaModule import dev.meloda.fast.auth.authModule
import dev.meloda.fast.auth.login.di.loginModule
import dev.meloda.fast.auth.validation.di.validationModule
import dev.meloda.fast.chatmaterials.di.chatMaterialsModule import dev.meloda.fast.chatmaterials.di.chatMaterialsModule
import dev.meloda.fast.common.LongPollController import dev.meloda.fast.common.LongPollController
import dev.meloda.fast.common.LongPollControllerImpl import dev.meloda.fast.common.LongPollControllerImpl
@@ -38,9 +36,7 @@ import org.koin.dsl.module
val applicationModule = module { val applicationModule = module {
includes(domainModule) includes(domainModule)
includes( includes(
loginModule, authModule,
validationModule,
captchaModule,
convosModule, convosModule,
settingsModule, settingsModule,
messagesHistoryModule, messagesHistoryModule,
@@ -8,9 +8,9 @@ import dev.meloda.fast.model.BaseError
import dev.meloda.fast.model.BottomNavigationItem import dev.meloda.fast.model.BottomNavigationItem
import dev.meloda.fast.presentation.MainScreen import dev.meloda.fast.presentation.MainScreen
import dev.meloda.fast.profile.navigation.Profile import dev.meloda.fast.profile.navigation.Profile
import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.util.ImmutableList import dev.meloda.fast.ui.util.ImmutableList
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import dev.meloda.fast.ui.R
@Serializable @Serializable
object MainGraph object MainGraph
@@ -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)
}
)
}
}
}
}
@@ -38,7 +38,7 @@ import dev.chrisbanes.haze.HazeState
import dev.chrisbanes.haze.hazeEffect import dev.chrisbanes.haze.hazeEffect
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
import dev.chrisbanes.haze.materials.HazeMaterials import dev.chrisbanes.haze.materials.HazeMaterials
import dev.meloda.fast.convos.navigation.ConvoGraph import dev.meloda.fast.convos.model.ConvoNavigationIntent
import dev.meloda.fast.convos.navigation.convosGraph import dev.meloda.fast.convos.navigation.convosGraph
import dev.meloda.fast.friends.navigation.Friends import dev.meloda.fast.friends.navigation.Friends
import dev.meloda.fast.friends.navigation.friendsScreen import dev.meloda.fast.friends.navigation.friendsScreen
@@ -198,19 +198,20 @@ fun MainScreen(
}, },
) )
convosGraph( convosGraph(
activity = activity, handleNavigationIntent = { intent ->
onError = onError, when (intent) {
onNavigateToMessagesHistory = onNavigateToMessagesHistory, ConvoNavigationIntent.Back -> {}
onNavigateToCreateChat = onNavigateToCreateChat, ConvoNavigationIntent.Archive -> {}
onScrolledToTop = { ConvoNavigationIntent.CreateChat -> onNavigateToCreateChat()
tabReselected = tabReselected.toMutableMap().also { is ConvoNavigationIntent.MessagesHistory -> {
it[ConvoGraph] = false onNavigateToMessagesHistory(intent.convoId)
}
} }
} },
activity = activity,
) )
profileScreen( profileScreen(
activity = activity, activity = activity,
onError = onError,
onSettingsButtonClicked = onSettingsButtonClicked, onSettingsButtonClicked = onSettingsButtonClicked,
onPhotoClicked = onPhotoClicked onPhotoClicked = onPhotoClicked
) )
@@ -41,6 +41,7 @@ import com.google.accompanist.permissions.rememberPermissionState
import dev.meloda.fast.MainViewModel import dev.meloda.fast.MainViewModel
import dev.meloda.fast.MainViewModelImpl import dev.meloda.fast.MainViewModelImpl
import dev.meloda.fast.auth.authNavGraph import dev.meloda.fast.auth.authNavGraph
import dev.meloda.fast.auth.captcha.presentation.CaptchaScreen
import dev.meloda.fast.auth.navigateToAuth import dev.meloda.fast.auth.navigateToAuth
import dev.meloda.fast.chatmaterials.navigation.chatMaterialsScreen import dev.meloda.fast.chatmaterials.navigation.chatMaterialsScreen
import dev.meloda.fast.chatmaterials.navigation.navigateToChatMaterials import dev.meloda.fast.chatmaterials.navigation.navigateToChatMaterials
@@ -48,6 +49,8 @@ import dev.meloda.fast.common.LongPollController
import dev.meloda.fast.common.model.LongPollState import dev.meloda.fast.common.model.LongPollState
import dev.meloda.fast.convos.navigation.createChatScreen import dev.meloda.fast.convos.navigation.createChatScreen
import dev.meloda.fast.convos.navigation.navigateToCreateChat import dev.meloda.fast.convos.navigation.navigateToCreateChat
import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.datastore.CaptchaTokenResult
import dev.meloda.fast.datastore.UserSettings import dev.meloda.fast.datastore.UserSettings
import dev.meloda.fast.languagepicker.navigation.languagePickerScreen import dev.meloda.fast.languagepicker.navigation.languagePickerScreen
import dev.meloda.fast.languagepicker.navigation.navigateToLanguagePicker import dev.meloda.fast.languagepicker.navigation.navigateToLanguagePicker
@@ -310,6 +313,9 @@ fun RootScreen(
mutableStateOf<Pair<List<String>, Int?>?>(null) mutableStateOf<Pair<List<String>, Int?>?>(null)
} }
val captchaRedirectUri by AppSettings.getCaptchaRedirectUriFlow()
.collectAsStateWithLifecycle()
Box(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.fillMaxSize()) {
NavHost( NavHost(
navController = navController, navController = navController,
@@ -334,7 +340,7 @@ fun RootScreen(
photoViewerInfo = listOf(url) to null photoViewerInfo = listOf(url) to null
}, },
onMessageClicked = navController::navigateToMessagesHistory, onMessageClicked = navController::navigateToMessagesHistory,
onNavigateToCreateChat = navController::navigateToCreateChat onNavigateToCreateChat = navController::navigateToCreateChat,
) )
messagesHistoryScreen( messagesHistoryScreen(
@@ -381,6 +387,18 @@ fun RootScreen(
}, },
onDismiss = { photoViewerInfo = null } onDismiss = { photoViewerInfo = null }
) )
CaptchaScreen(
captchaRedirectUri = captchaRedirectUri,
onBack = {
AppSettings.setCaptchaResult(CaptchaTokenResult.Cancelled)
},
onResult = { result ->
AppSettings.setCaptchaResult(
CaptchaTokenResult.Success(result)
)
},
)
} }
} }
} }
@@ -32,10 +32,10 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import org.koin.android.ext.android.inject import org.koin.android.ext.android.inject
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.time.Duration.Companion.seconds import kotlin.time.Duration.Companion.seconds
class LongPollingService : Service() { class LongPollingService : Service() {
@@ -204,7 +204,7 @@ class LongPollingService : Service() {
} }
} }
private suspend fun getServerInfo(): VkLongPollData? = suspendCoroutine { private suspend fun getServerInfo(): VkLongPollData? = suspendCancellableCoroutine {
longPollUseCase.getLongPollServer( longPollUseCase.getLongPollServer(
needPts = true, needPts = true,
version = VkConstants.LP_VERSION version = VkConstants.LP_VERSION
@@ -224,7 +224,7 @@ class LongPollingService : Service() {
private suspend fun getUpdatesResponse( private suspend fun getUpdatesResponse(
server: VkLongPollData server: VkLongPollData
): LongPollUpdates? = suspendCoroutine { ): LongPollUpdates? = suspendCancellableCoroutine {
longPollUseCase.getLongPollUpdates( longPollUseCase.getLongPollUpdates(
serverUrl = "https://${server.server}", serverUrl = "https://${server.server}",
key = server.key, key = server.key,
@@ -1,5 +1,6 @@
import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.dsl.ApplicationExtension
import dev.meloda.fast.configureKotlinAndroid import dev.meloda.fast.configureKotlinAndroid
import dev.meloda.fast.getVersionInt
import org.gradle.api.Plugin import org.gradle.api.Plugin
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.configure
@@ -14,9 +15,12 @@ class AndroidApplicationConventionPlugin : Plugin<Project> {
extensions.configure<ApplicationExtension> { extensions.configure<ApplicationExtension> {
configureKotlinAndroid(this) configureKotlinAndroid(this)
defaultConfig { defaultConfig {
targetSdk = 36 minSdk = getVersionInt("minSdk")
compileSdk = 36 compileSdk = getVersionInt("compileSdk")
minSdk = 23 targetSdk = getVersionInt("targetSdk")
}
lint {
abortOnError = false
} }
} }
} }
@@ -1,9 +1,10 @@
import com.android.build.api.dsl.LibraryExtension import com.android.build.api.dsl.LibraryExtension
import dev.meloda.fast.configureAndroidCompose import dev.meloda.fast.configureAndroidCompose
import dev.meloda.fast.getVersionInt
import org.gradle.api.Plugin import org.gradle.api.Plugin
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.configure
class AndroidLibraryComposeConventionPlugin : Plugin<Project> { class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
override fun apply(target: Project) { override fun apply(target: Project) {
@@ -12,9 +13,14 @@ class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
apply(plugin = "org.jetbrains.kotlin.plugin.compose") apply(plugin = "org.jetbrains.kotlin.plugin.compose")
apply(plugin = "com.github.skydoves.compose.stability.analyzer") apply(plugin = "com.github.skydoves.compose.stability.analyzer")
val extension = extensions.getByType<LibraryExtension>() extensions.configure<LibraryExtension> {
extension.androidResources.enable = false configureAndroidCompose(this)
configureAndroidCompose(extension) androidResources.enable = false
defaultConfig {
minSdk = getVersionInt("minSdk")
compileSdk = getVersionInt("compileSdk")
}
}
} }
} }
} }
@@ -2,6 +2,7 @@ import com.android.build.api.dsl.LibraryExtension
import com.android.build.api.variant.LibraryAndroidComponentsExtension import com.android.build.api.variant.LibraryAndroidComponentsExtension
import dev.meloda.fast.configureKotlinAndroid import dev.meloda.fast.configureKotlinAndroid
import dev.meloda.fast.disableUnnecessaryAndroidTests import dev.meloda.fast.disableUnnecessaryAndroidTests
import dev.meloda.fast.getVersionInt
import org.gradle.api.Plugin import org.gradle.api.Plugin
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.configure
@@ -20,7 +21,13 @@ class AndroidLibraryConventionPlugin : Plugin<Project> {
extensions.configure<LibraryExtension> { extensions.configure<LibraryExtension> {
configureKotlinAndroid(this) configureKotlinAndroid(this)
androidResources.enable = false androidResources.enable = false
defaultConfig.testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" defaultConfig {
minSdk = getVersionInt("minSdk")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
lint {
abortOnError = false
}
} }
extensions.configure<LibraryAndroidComponentsExtension> { extensions.configure<LibraryAndroidComponentsExtension> {
disableUnnecessaryAndroidTests(target) disableUnnecessaryAndroidTests(target)
@@ -1,5 +1,6 @@
import com.android.build.api.dsl.TestExtension import com.android.build.api.dsl.TestExtension
import dev.meloda.fast.configureKotlinAndroid import dev.meloda.fast.configureKotlinAndroid
import dev.meloda.fast.getVersionInt
import org.gradle.api.Plugin import org.gradle.api.Plugin
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.configure
@@ -13,7 +14,11 @@ class AndroidTestConventionPlugin : Plugin<Project> {
extensions.configure<TestExtension> { extensions.configure<TestExtension> {
configureKotlinAndroid(this) configureKotlinAndroid(this)
defaultConfig.targetSdk = 36 defaultConfig {
minSdk = getVersionInt("minSdk")
compileSdk = getVersionInt("compileSdk")
targetSdk = getVersionInt("targetSdk")
}
} }
} }
} }
@@ -24,7 +24,7 @@ internal fun Project.configureKotlinAndroid(
} }
commonExtension.apply { commonExtension.apply {
compileSdk = 36 compileSdk = getVersionInt("compileSdk")
} }
configureKotlin<KotlinAndroidProjectExtension>() configureKotlin<KotlinAndroidProjectExtension>()
@@ -61,6 +61,7 @@ private inline fun <reified T : KotlinBaseExtension> Project.configureKotlin() =
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
"-opt-in=kotlinx.coroutines.FlowPreview", "-opt-in=kotlinx.coroutines.FlowPreview",
"-Xannotation-default-target=param-property", "-Xannotation-default-target=param-property",
"-Xcontext-parameters"
) )
} }
} }
@@ -7,3 +7,8 @@ import org.gradle.kotlin.dsl.getByType
val Project.libs val Project.libs
get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs") get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
fun Project.getVersionInt(alias: String): Int {
return libs.findVersion(alias).get().requiredVersion.toInt()
}
@@ -4,7 +4,7 @@ object AppConstants {
const val INSTALL_APP_MIME_TYPE = "application/vnd.android.package-archive" 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_OAUTH = "https://oauth.vk.ru"
const val URL_API = "https://api.vk.ru/method" const val URL_API = "https://api.vk.ru/method"
@@ -23,5 +23,6 @@ interface OAuthRepository {
validationCode: String?, validationCode: String?,
captchaSid: String?, captchaSid: String?,
captchaKey: String?, captchaKey: String?,
successToken: String?
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> ): ApiResult<GetSilentTokenResponse, OAuthErrorDomain>
} }
@@ -79,7 +79,8 @@ class OAuthRepositoryImpl(
VkOAuthError.NEED_CAPTCHA -> { VkOAuthError.NEED_CAPTCHA -> {
OAuthErrorDomain.CaptchaRequiredError( OAuthErrorDomain.CaptchaRequiredError(
captchaSid = response.captchaSid.orEmpty(), captchaSid = response.captchaSid.orEmpty(),
captchaImageUrl = response.captchaImage.orEmpty() captchaImageUrl = response.captchaImage.orEmpty(),
redirectUri = response.redirectUri
) )
} }
@@ -122,6 +123,7 @@ class OAuthRepositoryImpl(
validationCode: String?, validationCode: String?,
captchaSid: String?, captchaSid: String?,
captchaKey: String?, captchaKey: String?,
successToken: String?
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> = ): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val requestModel = AuthDirectRequest( val requestModel = AuthDirectRequest(
@@ -135,6 +137,7 @@ class OAuthRepositoryImpl(
validationCode = validationCode, validationCode = validationCode,
captchaSid = captchaSid, captchaSid = captchaSid,
captchaKey = captchaKey, captchaKey = captchaKey,
successToken = successToken
) )
oAuthService.getSilentToken(requestModel.map).mapResult( oAuthService.getSilentToken(requestModel.map).mapResult(
@@ -175,7 +178,8 @@ class OAuthRepositoryImpl(
VkOAuthError.NEED_CAPTCHA -> { VkOAuthError.NEED_CAPTCHA -> {
OAuthErrorDomain.CaptchaRequiredError( OAuthErrorDomain.CaptchaRequiredError(
captchaSid = response.captchaSid.orEmpty(), captchaSid = response.captchaSid.orEmpty(),
captchaImageUrl = response.captchaImage.orEmpty() captchaImageUrl = response.captchaImage.orEmpty(),
redirectUri = response.redirectUri
) )
} }
@@ -4,13 +4,32 @@ import android.content.SharedPreferences
import androidx.core.content.edit import androidx.core.content.edit
import dev.meloda.fast.common.model.DarkMode import dev.meloda.fast.common.model.DarkMode
import dev.meloda.fast.common.model.LogLevel import dev.meloda.fast.common.model.LogLevel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlin.properties.Delegates import kotlin.properties.Delegates
import kotlin.reflect.KClass import kotlin.reflect.KClass
sealed class CaptchaTokenResult {
data object Initial : CaptchaTokenResult()
data object Null : CaptchaTokenResult()
data object Cancelled : CaptchaTokenResult()
data class Success(val token: String) : CaptchaTokenResult()
}
object AppSettings { object AppSettings {
private var preferences: SharedPreferences by Delegates.notNull() private var preferences: SharedPreferences by Delegates.notNull()
private val captchaResult = MutableStateFlow<CaptchaTokenResult>(CaptchaTokenResult.Initial)
fun getCaptchaResultFlow(): StateFlow<CaptchaTokenResult> = captchaResult.asStateFlow()
fun setCaptchaResult(result: CaptchaTokenResult) = captchaResult.update { result }
private val captchaRedirectUri = MutableStateFlow<String?>(null)
fun getCaptchaRedirectUriFlow() = captchaRedirectUri.asStateFlow()
fun setCaptchaRedirectUri(redirectUri: String?) = captchaRedirectUri.update { redirectUri }
fun init(preferences: SharedPreferences) { fun init(preferences: SharedPreferences) {
this.preferences = preferences this.preferences = preferences
} }
@@ -21,7 +21,8 @@ interface OAuthUseCase {
password: String, password: String,
forceSms: Boolean, forceSms: Boolean,
validationCode: String?, validationCode: String?,
captchaSid: String?, captchaSid: String? = null,
captchaKey: String? captchaKey: String? = null,
successToken: String? = null
): Flow<State<GetSilentTokenResponse>> ): Flow<State<GetSilentTokenResponse>>
} }
@@ -48,7 +48,8 @@ class OAuthUseCaseImpl(
forceSms: Boolean, forceSms: Boolean,
validationCode: String?, validationCode: String?,
captchaSid: String?, captchaSid: String?,
captchaKey: String? captchaKey: String?,
successToken: String?
): Flow<State<GetSilentTokenResponse>> = flow { ): Flow<State<GetSilentTokenResponse>> = flow {
emit(State.Loading) emit(State.Loading)
@@ -58,7 +59,8 @@ class OAuthUseCaseImpl(
forceSms = forceSms, forceSms = forceSms,
validationCode = validationCode, validationCode = validationCode,
captchaSid = captchaSid, captchaSid = captchaSid,
captchaKey = captchaKey captchaKey = captchaKey,
successToken = successToken
).asState() ).asState()
emit(newState) emit(newState)
@@ -598,6 +598,7 @@ private fun getAttachmentIconByType(attachmentType: AttachmentType): UiImage? {
AttachmentType.VIDEO_MESSAGE -> null AttachmentType.VIDEO_MESSAGE -> null
AttachmentType.GROUP_CHAT_STICKER -> R.drawable.ic_sticker_fill_round_24 AttachmentType.GROUP_CHAT_STICKER -> R.drawable.ic_sticker_fill_round_24
AttachmentType.STICKER_PACK_PREVIEW -> null AttachmentType.STICKER_PACK_PREVIEW -> null
AttachmentType.CHANNEL_MESSAGE -> null
}?.let(UiImage::Resource) }?.let(UiImage::Resource)
} }
@@ -687,6 +688,7 @@ fun getAttachmentUiText(
AttachmentType.VIDEO_MESSAGE -> R.string.message_attachments_video_message AttachmentType.VIDEO_MESSAGE -> R.string.message_attachments_video_message
AttachmentType.GROUP_CHAT_STICKER -> R.string.message_attachments_group_sticker AttachmentType.GROUP_CHAT_STICKER -> R.string.message_attachments_group_sticker
AttachmentType.STICKER_PACK_PREVIEW -> R.string.message_attachments_sticker_pack_preview AttachmentType.STICKER_PACK_PREVIEW -> R.string.message_attachments_sticker_pack_preview
AttachmentType.CHANNEL_MESSAGE -> R.string.message_attachments_channel_message
}.let(UiText::Resource) }.let(UiText::Resource)
} }
@@ -30,7 +30,8 @@ enum class AttachmentType(var value: String) {
ARTICLE("article"), ARTICLE("article"),
VIDEO_MESSAGE("video_message"), VIDEO_MESSAGE("video_message"),
GROUP_CHAT_STICKER("ugc_sticker"), 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) fun isMultiple(): Boolean = this in listOf(PHOTO, VIDEO, AUDIO, FILE)
@@ -35,7 +35,8 @@ data class VkAttachmentItemData(
@Json(name = "article") val article: VkArticleData?, @Json(name = "article") val article: VkArticleData?,
@Json(name = "video_message") val videoMessage: VkVideoMessageData?, @Json(name = "video_message") val videoMessage: VkVideoMessageData?,
@Json(name = "ugc_sticker") val groupSticker: VkGroupStickerData?, @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)) { fun toDomain(): VkAttachment = when (AttachmentType.parse(type)) {
AttachmentType.UNKNOWN -> VkUnknownAttachment AttachmentType.UNKNOWN -> VkUnknownAttachment
@@ -66,5 +67,6 @@ data class VkAttachmentItemData(
AttachmentType.VIDEO_MESSAGE -> videoMessage?.toDomain() AttachmentType.VIDEO_MESSAGE -> videoMessage?.toDomain()
AttachmentType.GROUP_CHAT_STICKER -> groupSticker?.toDomain() AttachmentType.GROUP_CHAT_STICKER -> groupSticker?.toDomain()
AttachmentType.STICKER_PACK_PREVIEW -> stickerPackPreview?.toDomain() AttachmentType.STICKER_PACK_PREVIEW -> stickerPackPreview?.toDomain()
AttachmentType.CHANNEL_MESSAGE -> channelMessageData?.toDomain()
} ?: VkUnknownAttachment } ?: 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),
)
}
@@ -5,7 +5,7 @@ import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class VkWidgetData( data class VkWidgetData(
val id: Long val id: Long?
) : VkAttachmentData { ) : VkAttachmentData {
fun toDomain() = VkWidgetDomain(id) fun toDomain() = VkWidgetDomain(id)
@@ -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
}
@@ -3,7 +3,7 @@ package dev.meloda.fast.model.api.domain
import dev.meloda.fast.model.api.data.AttachmentType import dev.meloda.fast.model.api.data.AttachmentType
data class VkWidgetDomain( data class VkWidgetDomain(
val id: Long val id: Long?
) : VkAttachment { ) : VkAttachment {
override val type: AttachmentType = AttachmentType.WIDGET override val type: AttachmentType = AttachmentType.WIDGET
@@ -12,7 +12,8 @@ data class AuthDirectRequest(
val validationCode: String? = null, val validationCode: String? = null,
val captchaSid: String? = null, val captchaSid: String? = null,
val captchaKey: String? = null, val captchaKey: String? = null,
val trustedHash: String? = null val trustedHash: String? = null,
val successToken: String? = null
) { ) {
val map val map
@@ -31,6 +32,7 @@ data class AuthDirectRequest(
captchaSid?.let { this["captcha_sid"] = it } captchaSid?.let { this["captcha_sid"] = it }
captchaKey?.let { this["captcha_key"] = it } captchaKey?.let { this["captcha_key"] = it }
trustedHash?.let { this["trusted_hash"] = it } trustedHash?.let { this["trusted_hash"] = it }
successToken?.let { this["success_token"] = it }
} }
} }
@@ -16,7 +16,8 @@ sealed class OAuthErrorDomain {
data class CaptchaRequiredError( data class CaptchaRequiredError(
val captchaSid: String, val captchaSid: String,
val captchaImageUrl: String val captchaImageUrl: String,
val redirectUri: String?
) : OAuthErrorDomain() ) : OAuthErrorDomain()
data class UserBannedError( data class UserBannedError(
@@ -53,6 +53,7 @@ class ResponseConverterFactory(private val converter: JsonConverter) : Converter
}, },
onFailure = { failure -> onFailure = { failure ->
if (failure is JsonDataException) { if (failure is JsonDataException) {
Log.d("ResponseBodyConverter", "convertJsonDataException: $failure")
throw ApiException( throw ApiException(
RestApiError( RestApiError(
errorCode = -1, errorCode = -1,
@@ -2,7 +2,8 @@ package dev.meloda.fast.network
enum class ValidationType(val value: String) { enum class ValidationType(val value: String) {
APP("2fa_app"), APP("2fa_app"),
SMS("2fa_sms"); SMS("sms"),
SMS2("2fa_sms");
companion object { companion object {
fun parse(value: String): ValidationType = fun parse(value: String): ValidationType =
@@ -11,6 +11,7 @@ import dev.meloda.fast.network.JsonConverter
import dev.meloda.fast.network.MoshiConverter import dev.meloda.fast.network.MoshiConverter
import dev.meloda.fast.network.OAuthResultCallFactory import dev.meloda.fast.network.OAuthResultCallFactory
import dev.meloda.fast.network.ResponseConverterFactory import dev.meloda.fast.network.ResponseConverterFactory
import dev.meloda.fast.network.interceptor.Error14HandlingInterceptor
import dev.meloda.fast.network.interceptor.LanguageInterceptor import dev.meloda.fast.network.interceptor.LanguageInterceptor
import dev.meloda.fast.network.interceptor.VersionInterceptor import dev.meloda.fast.network.interceptor.VersionInterceptor
import dev.meloda.fast.network.service.account.AccountService import dev.meloda.fast.network.service.account.AccountService
@@ -45,6 +46,7 @@ val networkModule = module {
single { ChuckerInterceptor.Builder(get()).collector(get()).build() } single { ChuckerInterceptor.Builder(get()).collector(get()).build() }
singleOf(::VersionInterceptor) singleOf(::VersionInterceptor)
singleOf(::LanguageInterceptor) singleOf(::LanguageInterceptor)
singleOf(::Error14HandlingInterceptor)
single<OkHttpClient>(named("auth")) { single<OkHttpClient>(named("auth")) {
buildHttpClient(true) buildHttpClient(true)
@@ -101,6 +103,7 @@ private fun Scope.buildHttpClient(forAuth: Boolean): OkHttpClient {
addInterceptor(get(named("token_interceptor")) as Interceptor) addInterceptor(get(named("token_interceptor")) as Interceptor)
} }
} }
.addInterceptor(get<Error14HandlingInterceptor>())
.addInterceptor(get<VersionInterceptor>()) .addInterceptor(get<VersionInterceptor>())
.addInterceptor(get<LanguageInterceptor>()) .addInterceptor(get<LanguageInterceptor>())
.addInterceptor(get<ChuckerInterceptor>()) .addInterceptor(get<ChuckerInterceptor>())
@@ -0,0 +1,145 @@
package dev.meloda.fast.network.interceptor
import android.util.Log
import dev.meloda.fast.common.extensions.listenValue
import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.datastore.CaptchaTokenResult
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 domains: Set<String> = emptySet(),
) : Interceptor {
private val cookie = AtomicReference<String?>(null)
private companion object {
private const val CAPTCHA_ERROR_CODE = 14
private const val CAPTCHA_ERROR_KIND = "need_captcha"
private val executor = Executors.newSingleThreadExecutor()
}
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)
Log.d("Error14Interceptor", "passCaptchaAndGetToken: $redirectUri")
var job: Job? = null
job = AppSettings.getCaptchaResultFlow()
.listenValue(CoroutineScope(Dispatchers.IO)) {
Log.d("Error14Interceptor", "passCaptchaAndGetToken: $it")
if (it != CaptchaTokenResult.Initial) {
synchronized(tokenResult) {
Log.d(
"Error14Interceptor",
"passCaptchaAndGetToken: SYNCHRONIZED: $it"
)
tokenResult.set(wrapResult(it))
tokenResult.notifyAll()
job?.cancel()
Log.d(
"Error14Interceptor",
"passCaptchaAndGetToken: NULL RESULT"
)
AppSettings.setCaptchaResult(CaptchaTokenResult.Initial)
AppSettings.setCaptchaRedirectUri(null)
}
}
}
}
synchronized(tokenResult) {
if (tokenResult.get().getOrNull() == null) {
tokenResult.wait()
}
Log.d("Error14Interceptor", "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()
@@ -1,6 +1,7 @@
package dev.meloda.fast.ui.components package dev.meloda.fast.ui.components
import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Indication
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -20,6 +21,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3ExpressiveApi::class) @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3ExpressiveApi::class)
@@ -30,27 +33,32 @@ fun FastIconButton(
onLongClick: (() -> Unit)? = null, onLongClick: (() -> Unit)? = null,
enabled: Boolean = true, enabled: Boolean = true,
colors: IconButtonColors = IconButtonDefaults.iconButtonColors(), 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, interactionSource: MutableInteractionSource? = null,
indication: Indication = ripple(),
content: @Composable () -> Unit content: @Composable () -> Unit
) { ) {
Box( Box(
modifier = modifier =
modifier modifier
.minimumInteractiveComponentSize() .minimumInteractiveComponentSize()
.size(IconButtonTokens.StateLayerSize) .size(size)
.clip(IconButtonTokens.StateLayerShape) .clip(shape)
.background(color = colors.containerColor(enabled)) .background(containerColor)
.combinedClickable( .combinedClickable(
onClick = onClick, onClick = onClick,
onLongClick = onLongClick, onLongClick = onLongClick,
enabled = enabled, enabled = enabled,
interactionSource = interactionSource, interactionSource = interactionSource,
indication = ripple() indication = indication
), ),
contentAlignment = Alignment.Center contentAlignment = alignment
) { ) {
val contentColor = colors.contentColor(enabled) CompositionLocalProvider(LocalContentColor provides contentColor) { content() }
CompositionLocalProvider(LocalContentColor provides contentColor, content = 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 context = LocalContext.current
val colorScheme: ColorScheme = when { val colorScheme: ColorScheme = predefinedColorScheme ?: when {
useDynamicColors && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { useDynamicColors && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
if (useDarkTheme) dynamicDarkColorScheme(context) if (useDarkTheme) dynamicDarkColorScheme(context)
else dynamicLightColorScheme(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) { val typography = if (useSystemFont) {
MaterialTheme.typography MaterialTheme.typography
} else { } else {
@@ -118,12 +114,7 @@ fun AppTheme(
} }
MaterialExpressiveTheme( MaterialExpressiveTheme(
colorScheme = (predefinedColorScheme ?: colorScheme) colorScheme = colorScheme,
.copy(
primary = colorPrimary,
background = colorBackground,
surface = colorSurface
),
typography = typography, typography = typography,
content = content content = content
) )
@@ -18,6 +18,7 @@ import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
@@ -113,11 +114,12 @@ fun LazyListState.isScrollingUp(): Boolean {
@Composable @Composable
fun isNeedToEnableDarkMode(darkMode: DarkMode): Boolean { fun isNeedToEnableDarkMode(darkMode: DarkMode): Boolean {
val context = LocalContext.current val context = LocalContext.current
val configuration = LocalConfiguration.current
val appForceDarkMode = darkMode == DarkMode.ENABLED val appForceDarkMode = darkMode == DarkMode.ENABLED
val appBatterySaver = darkMode == DarkMode.AUTO_BATTERY val appBatterySaver = darkMode == DarkMode.AUTO_BATTERY
val systemUiNightMode = context.resources.configuration.uiMode val systemUiNightMode = configuration.uiMode
val isSystemBatterySaver = context.getSystemService<PowerManager>()?.isPowerSaveMode == true val isSystemBatterySaver = context.getSystemService<PowerManager>()?.isPowerSaveMode == true
val isSystemUsingDarkTheme = val isSystemUsingDarkTheme =
@@ -1,6 +1,7 @@
package dev.meloda.fast.ui.util package dev.meloda.fast.ui.util
import androidx.compose.runtime.Immutable import androidx.compose.runtime.Immutable
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
@Immutable @Immutable
class ImmutableList<T>(val values: List<T>) : Collection<T> { 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> emptyImmutableList(): ImmutableList<T> = ImmutableList(emptyList())
fun <T> immutableListOf(vararg elements: T) = ImmutableList(listOf(elements = elements)) 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()
}
+6
View File
@@ -88,6 +88,7 @@
<string name="message_attachments_video_message">Video message</string> <string name="message_attachments_video_message">Video message</string>
<string name="message_attachments_group_sticker">Group sticker</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_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_file">Uploading file</string>
<string name="chat_interaction_uploading_photo">Uploading photo</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_with_title">Are you sure you want to create chat «%s»?</string>
<string name="confirm_chat_create_empty_with_title">Are you sure you want to create chat «%s» only with yourself?</string> <string name="confirm_chat_create_empty_with_title">Are you sure you want to create chat «%s» only with yourself?</string>
<string name="title_edit_message">Edit message</string>
<string name="action_close">Close</string>
<string name="action_hide_stacktrace">Hide stacktrace</string>
<string name="action_show_stacktrace">Show stacktrace</string>
</resources> </resources>
+9
View File
@@ -2,4 +2,13 @@
<resources> <resources>
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar" /> <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> </resources>
@@ -3,7 +3,6 @@ package dev.meloda.fast.auth.login
import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithTag
import dev.meloda.fast.auth.login.presentation.LogoScreen
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@@ -15,7 +14,7 @@ class LogoScreenTest {
@Test @Test
fun goNextButton_isClickable() { fun goNextButton_isClickable() {
composeTestRule.setContent { composeTestRule.setContent {
LogoScreen()
} }
composeTestRule.onNodeWithTag(testTag = "go_next_fab").assertHasClickAction() composeTestRule.onNodeWithTag(testTag = "go_next_fab").assertHasClickAction()
@@ -3,9 +3,6 @@ package dev.meloda.fast.auth
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder import androidx.navigation.NavGraphBuilder
import androidx.navigation.navigation import androidx.navigation.navigation
import dev.meloda.fast.auth.captcha.navigation.captchaScreen
import dev.meloda.fast.auth.captcha.navigation.navigateToCaptcha
import dev.meloda.fast.auth.captcha.navigation.setCaptchaResult
import dev.meloda.fast.auth.login.navigation.Login import dev.meloda.fast.auth.login.navigation.Login
import dev.meloda.fast.auth.login.navigation.loginScreen import dev.meloda.fast.auth.login.navigation.loginScreen
import dev.meloda.fast.auth.userbanned.model.UserBannedArguments import dev.meloda.fast.auth.userbanned.model.UserBannedArguments
@@ -28,11 +25,6 @@ fun NavGraphBuilder.authNavGraph(
) { ) {
navigation<AuthGraph>(startDestination = Login) { navigation<AuthGraph>(startDestination = Login) {
loginScreen( loginScreen(
onNavigateToCaptcha = { arguments ->
navController.navigateToCaptcha(
captchaImageUrl = URLEncoder.encode(arguments.captchaImageUrl, "utf-8")
)
},
onNavigateToValidation = { arguments -> onNavigateToValidation = { arguments ->
navController.navigateToValidation( navController.navigateToValidation(
ValidationArguments( ValidationArguments(
@@ -70,17 +62,6 @@ fun NavGraphBuilder.authNavGraph(
} }
) )
captchaScreen(
onBack = {
navController.setCaptchaResult(null)
navController.navigateUp()
},
onResult = { code ->
navController.setCaptchaResult(code)
navController.popBackStack()
}
)
userBannedRoute(onBack = navController::navigateUp) userBannedRoute(onBack = navController::navigateUp)
} }
} }
@@ -1,6 +1,5 @@
package dev.meloda.fast.auth package dev.meloda.fast.auth
import dev.meloda.fast.auth.captcha.di.captchaModule
import dev.meloda.fast.auth.validation.di.validationModule import dev.meloda.fast.auth.validation.di.validationModule
import dev.meloda.fast.auth.login.di.loginModule import dev.meloda.fast.auth.login.di.loginModule
import org.koin.dsl.module import org.koin.dsl.module
@@ -9,6 +8,5 @@ val authModule = module {
includes( includes(
loginModule, loginModule,
validationModule, validationModule,
captchaModule,
) )
} }
@@ -1,69 +0,0 @@
package dev.meloda.fast.auth.captcha
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import dev.meloda.fast.auth.captcha.model.CaptchaScreenState
import dev.meloda.fast.auth.captcha.navigation.Captcha
import dev.meloda.fast.auth.captcha.validation.CaptchaValidator
import dev.meloda.fast.common.extensions.setValue
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.net.URLDecoder
interface CaptchaViewModel {
val screenState: StateFlow<CaptchaScreenState>
val isNeedToOpenLogin: StateFlow<Boolean>
fun onCodeInputChanged(newCode: String)
fun onTextFieldDoneAction()
fun onDoneButtonClicked()
fun onNavigatedToLogin()
}
class CaptchaViewModelImpl(
private val validator: CaptchaValidator,
savedStateHandle: SavedStateHandle
) : CaptchaViewModel, ViewModel() {
override val screenState = MutableStateFlow(CaptchaScreenState.EMPTY)
override val isNeedToOpenLogin = MutableStateFlow(false)
init {
val captchaImage = Captcha.from(savedStateHandle).captchaImageUrl
screenState.setValue { old ->
old.copy(captchaImageUrl = URLDecoder.decode(captchaImage, "utf-8"))
}
}
override fun onCodeInputChanged(newCode: String) {
val newState = screenState.value.copy(code = newCode.trim())
screenState.update { newState }
processValidation()
}
override fun onTextFieldDoneAction() {
onDoneButtonClicked()
}
override fun onDoneButtonClicked() {
if (!processValidation()) return
isNeedToOpenLogin.update { true }
}
override fun onNavigatedToLogin() {
screenState.update { CaptchaScreenState.EMPTY }
isNeedToOpenLogin.update { false }
}
private fun processValidation(): Boolean {
val isValid = validator.validate(screenState.value).isValid()
screenState.setValue { old -> old.copy(codeError = !isValid) }
return isValid
}
}
@@ -1,14 +0,0 @@
package dev.meloda.fast.auth.captcha.di
import dev.meloda.fast.auth.captcha.CaptchaViewModel
import dev.meloda.fast.auth.captcha.CaptchaViewModelImpl
import dev.meloda.fast.auth.captcha.validation.CaptchaValidator
import org.koin.core.module.dsl.singleOf
import org.koin.core.module.dsl.viewModelOf
import org.koin.dsl.bind
import org.koin.dsl.module
val captchaModule = module {
singleOf(::CaptchaValidator)
viewModelOf(::CaptchaViewModelImpl) bind CaptchaViewModel::class
}
@@ -1,16 +0,0 @@
package dev.meloda.fast.auth.captcha.model
data class CaptchaScreenState(
val captchaImageUrl: String,
val code: String,
val codeError: Boolean
) {
companion object {
val EMPTY = CaptchaScreenState(
captchaImageUrl = "",
code = "",
codeError = false
)
}
}
@@ -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
}
@@ -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)
}
@@ -1,33 +1,22 @@
package dev.meloda.fast.auth.captcha.presentation package dev.meloda.fast.auth.captcha.presentation
import android.graphics.Bitmap
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image import androidx.compose.animation.fadeIn
import androidx.compose.foundation.border import androidx.compose.animation.fadeOut
import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.ime import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScaffoldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -37,237 +26,169 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import coil.compose.AsyncImage
import dev.meloda.fast.auth.captcha.CaptchaViewModel
import dev.meloda.fast.auth.captcha.CaptchaViewModelImpl
import dev.meloda.fast.auth.captcha.model.CaptchaScreenState
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.common.FastPreview
import dev.meloda.fast.ui.components.ActionInvokeDismiss import dev.meloda.fast.ui.components.ActionInvokeDismiss
import dev.meloda.fast.ui.components.FullScreenDialog
import dev.meloda.fast.ui.components.MaterialDialog import dev.meloda.fast.ui.components.MaterialDialog
import dev.meloda.fast.ui.components.TextFieldErrorText import org.json.JSONObject
import dev.meloda.fast.ui.theme.AppTheme
import org.koin.androidx.compose.koinViewModel
@Composable private const val TAG = "CaptchaScreen"
fun CaptchaRoute(
onBack: () -> Unit,
onResult: (String) -> Unit,
viewModel: CaptchaViewModel = koinViewModel<CaptchaViewModelImpl>()
) {
LocalViewModelStoreOwner.current
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
val isNeedToOpenLogin by viewModel.isNeedToOpenLogin.collectAsStateWithLifecycle()
LaunchedEffect(isNeedToOpenLogin) {
if (isNeedToOpenLogin) {
viewModel.onNavigatedToLogin()
onResult(screenState.code)
}
}
CaptchaScreen(
screenState = screenState,
onBack = onBack,
onCodeInputChanged = viewModel::onCodeInputChanged,
onTextFieldDoneAction = viewModel::onTextFieldDoneAction,
onDoneButtonClicked = viewModel::onDoneButtonClicked
)
}
@Composable @Composable
fun CaptchaScreen( fun CaptchaScreen(
screenState: CaptchaScreenState = CaptchaScreenState.EMPTY, captchaRedirectUri: String?,
onBack: () -> Unit = {}, onBack: () -> Unit = {},
onCodeInputChanged: (String) -> Unit = {}, onResult: (String) -> Unit = {}
onTextFieldDoneAction: () -> Unit = {},
onDoneButtonClicked: () -> Unit = {}
) { ) {
var confirmedExit by remember { if (captchaRedirectUri != null) {
mutableStateOf(false) val focusManager = LocalFocusManager.current
} val keyboardController = LocalSoftwareKeyboardController.current
LaunchedEffect(true) {
var showExitAlert by rememberSaveable { focusManager.clearFocus(true)
mutableStateOf(false) keyboardController?.hide()
}
LaunchedEffect(confirmedExit) {
if (confirmedExit) {
onBack()
} }
}
BackHandler(enabled = !confirmedExit) { var confirmedExit by remember {
if (!confirmedExit) { mutableStateOf(false)
showExitAlert = true
} }
}
if (showExitAlert) { var showExitAlert by rememberSaveable {
MaterialDialog( mutableStateOf(false)
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
)
}
val focusManager = LocalFocusManager.current var isWebViewLoading by remember {
mutableStateOf(true)
}
Scaffold( LaunchedEffect(confirmedExit) {
contentWindowInsets = ScaffoldDefaults.contentWindowInsets.union(WindowInsets.ime) if (confirmedExit) {
) { padding -> onBack()
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,
)
}
)
Column( BackHandler(enabled = !confirmedExit) {
modifier = Modifier.fillMaxWidth(), if (!confirmedExit) {
) { showExitAlert = true
Text( }
text = "Captcha", }
style = MaterialTheme.typography.displayMedium,
color = MaterialTheme.colorScheme.onBackground 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, Box(
modifier = Modifier.fillMaxWidth() modifier = Modifier
) { .fillMaxSize()
Text( .navigationBarsPadding()
text = "To proceed with your action, enter a code from the picture", .clickable(
style = MaterialTheme.typography.bodyLarge, interactionSource = remember { MutableInteractionSource() },
color = MaterialTheme.colorScheme.onBackground, indication = null,
modifier = Modifier.weight(0.5f) onClick = { showExitAlert = true }
) )
Spacer(modifier = Modifier.width(24.dp)) ) {
AndroidView(
val imageModifier = Modifier
.border(
2.dp,
MaterialTheme.colorScheme.primary,
shape = RoundedCornerShape(10.dp)
)
.clip(RoundedCornerShape(10.dp))
.height(48.dp)
.width(130.dp)
if (LocalView.current.isInEditMode) {
Image(
painter = painterResource(id = R.drawable.img_test_captcha),
contentDescription = "Captcha image",
modifier = imageModifier
)
} else {
AsyncImage(
model = screenState.captchaImageUrl,
contentDescription = "Captcha image",
contentScale = ContentScale.FillBounds,
modifier = imageModifier
)
}
}
Spacer(modifier = Modifier.height(30.dp))
var code by remember { mutableStateOf(TextFieldValue(screenState.code)) }
val showError = screenState.codeError
TextField(
value = code,
onValueChange = { newText ->
code = newText
onCodeInputChanged(newText.text)
},
label = { Text(text = "Code") },
placeholder = { Text(text = "Code") },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxSize()
.clip(RoundedCornerShape(10.dp)), .align(Alignment.BottomCenter),
leadingIcon = { factory = { context ->
Icon( val webview = WebView(context)
painter = painterResource(id = R.drawable.ic_qr_code_round_24), webview.setBackgroundColor(0)
contentDescription = "QR code icon", webview.settings.javaScriptEnabled = true
tint = if (showError) { webview.webViewClient = object : WebViewClient() {
MaterialTheme.colorScheme.error override fun shouldOverrideUrlLoading(
} else { view: WebView?,
MaterialTheme.colorScheme.primary request: WebResourceRequest?
): Boolean {
Log.i(TAG, "shouldOverrideUrlLoading: $request")
return false
}
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()
} }
), webview.addJavascriptInterface(
isError = showError 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) { AnimatedVisibility(
TextFieldErrorText(text = "Field must not be empty") 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 class WebCaptchaListener(
@Composable private val onSuccessTokenReceived: (String) -> Unit,
private fun CaptchaScreenPreview() { private val onCloseRequested: (String) -> Unit
AppTheme(useDarkTheme = isSystemInDarkTheme(), useDynamicColors = true) { ) {
CaptchaScreen( private val tag = "WebCaptchaListener"
screenState = CaptchaScreenState.EMPTY.copy(
code = "zcuecz" @JavascriptInterface
) fun VKCaptchaGetResult(arg: String) {
) onSuccessTokenReceived(arg)
Log.i(tag, "VKCaptchaGetResult($arg)")
}
@JavascriptInterface
fun VKCaptchaCloseCaptcha(arg: String) {
onCloseRequested(arg)
Log.i(tag, "VKCaptchaCloseCaptcha($arg)")
} }
} }
@@ -1,14 +0,0 @@
package dev.meloda.fast.auth.captcha.validation
import dev.meloda.fast.auth.captcha.model.CaptchaScreenState
import dev.meloda.fast.auth.captcha.model.CaptchaValidationResult
class CaptchaValidator {
fun validate(screenState: CaptchaScreenState): CaptchaValidationResult {
return when {
screenState.code.trim().isEmpty() -> CaptchaValidationResult.Empty
else -> CaptchaValidationResult.Valid
}
}
}
@@ -59,18 +59,12 @@ class LoginViewModel(
private val _validationArguments = MutableStateFlow<LoginValidationArguments?>(null) private val _validationArguments = MutableStateFlow<LoginValidationArguments?>(null)
val validationArguments = _validationArguments.asStateFlow() val validationArguments = _validationArguments.asStateFlow()
private val _captchaArguments = MutableStateFlow<CaptchaArguments?>(null)
val captchaArguments = _captchaArguments.asStateFlow()
private val _userBannedArguments = MutableStateFlow<LoginUserBannedArguments?>(null) private val _userBannedArguments = MutableStateFlow<LoginUserBannedArguments?>(null)
val userBannedArguments = _userBannedArguments.asStateFlow() val userBannedArguments = _userBannedArguments.asStateFlow()
private val _isNeedToOpenMain = MutableStateFlow(false) private val _isNeedToOpenMain = MutableStateFlow(false)
val isNeedToOpenMain = _isNeedToOpenMain.asStateFlow() val isNeedToOpenMain = _isNeedToOpenMain.asStateFlow()
private val _isNeedToClearCaptchaCode = MutableStateFlow(false)
val isNeedToClearCaptchaCode = _isNeedToClearCaptchaCode.asStateFlow()
private val _isNeedToClearValidationCode = MutableStateFlow(false) private val _isNeedToClearValidationCode = MutableStateFlow(false)
val isNeedToClearValidationCode = _isNeedToClearValidationCode.asStateFlow() val isNeedToClearValidationCode = _isNeedToClearValidationCode.asStateFlow()
@@ -78,17 +72,10 @@ class LoginViewModel(
screenState.map(loginValidator::validate) screenState.map(loginValidator::validate)
.stateIn(viewModelScope, SharingStarted.Eagerly, listOf(LoginValidationResult.Empty)) .stateIn(viewModelScope, SharingStarted.Eagerly, listOf(LoginValidationResult.Empty))
private val captchaSid = MutableStateFlow<String?>(null)
private val captchaCode = MutableStateFlow<String?>(null)
private val validationSid = MutableStateFlow<String?>(null) private val validationSid = MutableStateFlow<String?>(null)
private val validationCode = MutableStateFlow<String?>(null) private val validationCode = MutableStateFlow<String?>(null)
init { init {
captchaCode.listenValue(viewModelScope) {
if (it != null) {
login()
}
}
validationCode.listenValue(viewModelScope) { validationCode.listenValue(viewModelScope) {
if (it != null) { if (it != null) {
login() login()
@@ -113,7 +100,13 @@ class LoginViewModel(
} }
fun onBackPressed() { fun onBackPressed() {
_screenState.setValue { old -> old.copy(showLogo = true) } _screenState.setValue { old ->
old.copy(
showLogo = true,
loginError = false,
passwordError = false
)
}
} }
fun onPasswordVisibilityButtonClicked() { fun onPasswordVisibilityButtonClicked() {
@@ -165,10 +158,6 @@ class LoginViewModel(
_userBannedArguments.update { null } _userBannedArguments.update { null }
} }
fun onNavigatedToCaptcha() {
_captchaArguments.update { null }
}
fun onNavigatedToValidation() { fun onNavigatedToValidation() {
_validationArguments.update { null } _validationArguments.update { null }
} }
@@ -181,25 +170,9 @@ class LoginViewModel(
_isNeedToClearValidationCode.update { false } _isNeedToClearValidationCode.update { false }
} }
fun onCaptchaCodeReceived(code: String?) {
captchaCode.update { code }
}
fun onCaptchaCodeCleared() {
_isNeedToClearCaptchaCode.update { false }
}
private fun login(forceSms: Boolean = false) { private fun login(forceSms: Boolean = false) {
val currentState = screenState.value.copy() val currentState = screenState.value.copy()
Log.d(
"LoginViewModel",
"auth: login: ${currentState.login}; " +
"password: ${currentState.password}; " +
"2fa code: ${validationCode.value}; " +
"captcha code: ${captchaCode.value}"
)
processValidation() processValidation()
if (!validationState.value.contains(LoginValidationResult.Valid)) return if (!validationState.value.contains(LoginValidationResult.Valid)) return
@@ -207,23 +180,18 @@ class LoginViewModel(
val currentValidationSid = validationSid.value val currentValidationSid = validationSid.value
val currentValidationCode = validationCode.value?.takeIf { currentValidationSid != null } val currentValidationCode = validationCode.value?.takeIf { currentValidationSid != null }
val currentCaptchaSid = captchaSid.value
val currentCaptchaCode = captchaCode.value?.takeIf { currentCaptchaSid != null }
oAuthUseCase.getSilentToken( oAuthUseCase.getSilentToken(
login = currentState.login, login = currentState.login,
password = currentState.password, password = currentState.password,
forceSms = forceSms, forceSms = forceSms,
validationCode = currentValidationCode, validationCode = currentValidationCode,
captchaSid = currentCaptchaSid,
captchaKey = currentCaptchaCode
).listenValue(viewModelScope) { state -> ).listenValue(viewModelScope) { state ->
state.processState( state.processState(
error = { error -> error = { error ->
Log.d("LoginViewModelImpl", "login: error: $error") Log.d("LoginViewModelImpl", "login: error: $error")
_screenState.updateValue { copy(isLoading = false) } _screenState.updateValue { copy(isLoading = false) }
captchaSid.setValue { null }
parseError(error) parseError(error)
}, },
@@ -286,7 +254,6 @@ class LoginViewModel(
startLongPoll() startLongPoll()
captchaSid.update { null }
validationSid.update { null } validationSid.update { null }
loadUserByIdUseCase( loadUserByIdUseCase(
@@ -333,11 +300,8 @@ class LoginViewModel(
is OAuthErrorDomain.CaptchaRequiredError -> { is OAuthErrorDomain.CaptchaRequiredError -> {
val arguments = CaptchaArguments( val arguments = CaptchaArguments(
captchaSid = error.captchaSid, redirectUri = error.redirectUri
captchaImageUrl = error.captchaImageUrl
) )
_captchaArguments.update { arguments }
captchaSid.update { error.captchaSid }
} }
OAuthErrorDomain.InvalidCredentialsError -> { OAuthErrorDomain.InvalidCredentialsError -> {
@@ -7,6 +7,5 @@ import kotlinx.serialization.Serializable
@Serializable @Serializable
@Parcelize @Parcelize
data class CaptchaArguments( data class CaptchaArguments(
val captchaSid: String, val redirectUri: String?
val captchaImageUrl: String
) : Parcelable ) : Parcelable
@@ -8,7 +8,6 @@ import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import dev.meloda.fast.auth.login.LoginViewModel import dev.meloda.fast.auth.login.LoginViewModel
import dev.meloda.fast.auth.login.model.CaptchaArguments
import dev.meloda.fast.auth.login.model.LoginUserBannedArguments import dev.meloda.fast.auth.login.model.LoginUserBannedArguments
import dev.meloda.fast.auth.login.model.LoginValidationArguments import dev.meloda.fast.auth.login.model.LoginValidationArguments
import dev.meloda.fast.auth.login.presentation.LoginRoute import dev.meloda.fast.auth.login.presentation.LoginRoute
@@ -19,7 +18,6 @@ import kotlinx.serialization.Serializable
object Login object Login
fun NavGraphBuilder.loginScreen( fun NavGraphBuilder.loginScreen(
onNavigateToCaptcha: (CaptchaArguments) -> Unit,
onNavigateToValidation: (LoginValidationArguments) -> Unit, onNavigateToValidation: (LoginValidationArguments) -> Unit,
onNavigateToMain: () -> Unit, onNavigateToMain: () -> Unit,
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit, onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
@@ -31,7 +29,6 @@ fun NavGraphBuilder.loginScreen(
backStackEntry.sharedViewModel<LoginViewModel>(navController = navController) backStackEntry.sharedViewModel<LoginViewModel>(navController = navController)
val clearValidationCode by viewModel.isNeedToClearValidationCode.collectAsStateWithLifecycle() val clearValidationCode by viewModel.isNeedToClearValidationCode.collectAsStateWithLifecycle()
val clearCaptchaCode by viewModel.isNeedToClearCaptchaCode.collectAsStateWithLifecycle()
LaunchedEffect(clearValidationCode) { LaunchedEffect(clearValidationCode) {
if (clearValidationCode) { if (clearValidationCode) {
@@ -40,24 +37,14 @@ fun NavGraphBuilder.loginScreen(
} }
} }
LaunchedEffect(clearCaptchaCode) {
if (clearCaptchaCode) {
backStackEntry.savedStateHandle["captcha_code"] = null
viewModel.onCaptchaCodeCleared()
}
}
val validationCode = backStackEntry.getValidationResult() val validationCode = backStackEntry.getValidationResult()
val captchaCode = backStackEntry.getCaptchaResult()
LoginRoute( LoginRoute(
onNavigateToUserBanned = onNavigateToUserBanned, onNavigateToUserBanned = onNavigateToUserBanned,
onNavigateToMain = onNavigateToMain, onNavigateToMain = onNavigateToMain,
onNavigateToCaptcha = onNavigateToCaptcha,
onNavigateToValidation = onNavigateToValidation, onNavigateToValidation = onNavigateToValidation,
onNavigateToSettings = onNavigateToSettings, onNavigateToSettings = onNavigateToSettings,
validationCode = validationCode, validationCode = validationCode,
captchaCode = captchaCode,
viewModel = viewModel viewModel = viewModel
) )
} }
@@ -66,7 +53,3 @@ fun NavGraphBuilder.loginScreen(
fun NavBackStackEntry.getValidationResult(): String? { fun NavBackStackEntry.getValidationResult(): String? {
return savedStateHandle["validation_code"] return savedStateHandle["validation_code"]
} }
fun NavBackStackEntry.getCaptchaResult(): String? {
return savedStateHandle["captcha_code"]
}
@@ -31,9 +31,13 @@ import androidx.compose.material3.ScaffoldDefaults
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField import androidx.compose.material3.TextField
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
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.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.ContentType import androidx.compose.ui.autofill.ContentType
@@ -58,7 +62,6 @@ import androidx.compose.ui.unit.dp
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import dev.meloda.fast.auth.login.LoginViewModel import dev.meloda.fast.auth.login.LoginViewModel
import dev.meloda.fast.auth.login.model.CaptchaArguments
import dev.meloda.fast.auth.login.model.LoginDialog import dev.meloda.fast.auth.login.model.LoginDialog
import dev.meloda.fast.auth.login.model.LoginScreenState import dev.meloda.fast.auth.login.model.LoginScreenState
import dev.meloda.fast.auth.login.model.LoginUserBannedArguments 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.common.LocalSizeConfig
import dev.meloda.fast.ui.components.MaterialDialog import dev.meloda.fast.ui.components.MaterialDialog
import dev.meloda.fast.ui.components.TextFieldErrorText 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.handleEnterKey
import dev.meloda.fast.ui.util.handleTabKey import dev.meloda.fast.ui.util.handleTabKey
import org.koin.androidx.compose.koinViewModel import org.koin.androidx.compose.koinViewModel
@@ -75,17 +80,14 @@ import org.koin.androidx.compose.koinViewModel
fun LoginRoute( fun LoginRoute(
onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit, onNavigateToUserBanned: (LoginUserBannedArguments) -> Unit,
onNavigateToMain: () -> Unit, onNavigateToMain: () -> Unit,
onNavigateToCaptcha: (CaptchaArguments) -> Unit,
onNavigateToValidation: (LoginValidationArguments) -> Unit, onNavigateToValidation: (LoginValidationArguments) -> Unit,
onNavigateToSettings: () -> Unit, onNavigateToSettings: () -> Unit,
validationCode: String?, validationCode: String?,
captchaCode: String?,
viewModel: LoginViewModel = koinViewModel() viewModel: LoginViewModel = koinViewModel()
) { ) {
val screenState by viewModel.screenState.collectAsStateWithLifecycle() val screenState by viewModel.screenState.collectAsStateWithLifecycle()
val isNeedToOpenMain by viewModel.isNeedToOpenMain.collectAsStateWithLifecycle() val isNeedToOpenMain by viewModel.isNeedToOpenMain.collectAsStateWithLifecycle()
val userBannedArguments by viewModel.userBannedArguments.collectAsStateWithLifecycle() val userBannedArguments by viewModel.userBannedArguments.collectAsStateWithLifecycle()
val captchaArguments by viewModel.captchaArguments.collectAsStateWithLifecycle()
val validationArguments by viewModel.validationArguments.collectAsStateWithLifecycle() val validationArguments by viewModel.validationArguments.collectAsStateWithLifecycle()
val loginDialog by viewModel.loginDialog.collectAsStateWithLifecycle() val loginDialog by viewModel.loginDialog.collectAsStateWithLifecycle()
@@ -107,12 +109,6 @@ fun LoginRoute(
onNavigateToUserBanned(arguments) onNavigateToUserBanned(arguments)
} }
} }
LaunchedEffect(captchaArguments) {
captchaArguments?.let { arguments ->
viewModel.onNavigatedToCaptcha()
onNavigateToCaptcha(arguments)
}
}
LaunchedEffect(validationArguments) { LaunchedEffect(validationArguments) {
validationArguments?.let { arguments -> validationArguments?.let { arguments ->
viewModel.onNavigatedToValidation() viewModel.onNavigatedToValidation()
@@ -122,21 +118,28 @@ fun LoginRoute(
LaunchedEffect(validationCode) { LaunchedEffect(validationCode) {
viewModel.onValidationCodeReceived(validationCode) viewModel.onValidationCodeReceived(validationCode)
} }
LaunchedEffect(captchaCode) {
viewModel.onCaptchaCodeReceived(captchaCode)
}
LoginScreen( var useClassic by rememberSaveable { mutableStateOf(true) }
screenState = screenState,
onLoginInputChanged = viewModel::onLoginInputChanged, AppTheme(
onPasswordInputChanged = viewModel::onPasswordInputChanged, predefinedColorScheme = if (useClassic) ClassicColorScheme.lightScheme
onPasswordFieldEnterKeyClicked = viewModel::onSignInButtonClicked, else lightColorScheme(),
onPasswordVisibilityButtonClicked = viewModel::onPasswordVisibilityButtonClicked, ) {
onPasswordFieldGoAction = viewModel::onSignInButtonClicked, LoginScreen(
onSignInButtonClicked = viewModel::onSignInButtonClicked, screenState = screenState,
onLogoClicked = viewModel::onLogoClicked, onLoginInputChanged = viewModel::onLoginInputChanged,
onLogoLongClicked = onNavigateToSettings onPasswordInputChanged = viewModel::onPasswordInputChanged,
) onPasswordFieldEnterKeyClicked = viewModel::onSignInButtonClicked,
onPasswordVisibilityButtonClicked = viewModel::onPasswordVisibilityButtonClicked,
onPasswordFieldGoAction = viewModel::onSignInButtonClicked,
onSignInButtonClicked = viewModel::onSignInButtonClicked,
onLogoClicked = {
viewModel.onLogoClicked()
useClassic = !useClassic
},
onLogoLongClicked = onNavigateToSettings
)
}
HandleDialogs( HandleDialogs(
loginDialog = loginDialog, loginDialog = loginDialog,
@@ -4,7 +4,6 @@ import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dev.meloda.fast.auth.validation.model.ValidationScreenState import dev.meloda.fast.auth.validation.model.ValidationScreenState
import dev.meloda.fast.auth.validation.model.ValidationType
import dev.meloda.fast.auth.validation.navigation.Validation import dev.meloda.fast.auth.validation.navigation.Validation
import dev.meloda.fast.auth.validation.validation.ValidationValidator import dev.meloda.fast.auth.validation.validation.ValidationValidator
import dev.meloda.fast.common.extensions.createTimerFlow import dev.meloda.fast.common.extensions.createTimerFlow
@@ -12,6 +11,7 @@ import dev.meloda.fast.common.extensions.listenValue
import dev.meloda.fast.common.extensions.setValue import dev.meloda.fast.common.extensions.setValue
import dev.meloda.fast.data.processState import dev.meloda.fast.data.processState
import dev.meloda.fast.domain.AuthUseCase import dev.meloda.fast.domain.AuthUseCase
import dev.meloda.fast.network.ValidationType
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -1,10 +0,0 @@
package dev.meloda.fast.auth.validation.model
enum class ValidationType(val value: String) {
SMS("sms"), APP("2fa_app");
companion object {
fun parse(value: String): ValidationType = entries.firstOrNull { it.value == value }
?: throw IllegalArgumentException("Unknown validation type with value: $value")
}
}
@@ -47,13 +47,12 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import dev.meloda.fast.auth.validation.ValidationViewModel import dev.meloda.fast.auth.validation.ValidationViewModel
import dev.meloda.fast.auth.validation.ValidationViewModelImpl import dev.meloda.fast.auth.validation.ValidationViewModelImpl
import dev.meloda.fast.auth.validation.model.ValidationScreenState import dev.meloda.fast.auth.validation.model.ValidationScreenState
import dev.meloda.fast.auth.validation.model.ValidationType import dev.meloda.fast.network.ValidationType
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.common.FastPreview import dev.meloda.fast.ui.common.FastPreview
import dev.meloda.fast.ui.components.ActionInvokeDismiss import dev.meloda.fast.ui.components.ActionInvokeDismiss
@@ -119,7 +118,7 @@ fun ValidationScreen(
val validationText by remember(validationType) { val validationText by remember(validationType) {
mutableStateOf( mutableStateOf(
when (validationType) { when (validationType) {
ValidationType.SMS -> "SMS with the code is sent to ${screenState.phoneMask}" ValidationType.SMS, ValidationType.SMS2 -> "SMS with the code is sent to ${screenState.phoneMask}"
ValidationType.APP -> "Enter the code from the code generator application" ValidationType.APP -> "Enter the code from the code generator application"
null -> "" null -> ""
@@ -3,6 +3,7 @@ package dev.meloda.fast.convos
import android.content.Context import android.content.Context
import android.content.res.Resources import android.content.res.Resources
import android.os.Bundle import android.os.Bundle
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import coil.ImageLoader import coil.ImageLoader
@@ -15,10 +16,12 @@ import dev.meloda.fast.common.extensions.listenValue
import dev.meloda.fast.common.extensions.setValue import dev.meloda.fast.common.extensions.setValue
import dev.meloda.fast.common.extensions.updateValue import dev.meloda.fast.common.extensions.updateValue
import dev.meloda.fast.convos.model.ConvoDialog import dev.meloda.fast.convos.model.ConvoDialog
import dev.meloda.fast.convos.model.ConvoNavigation import dev.meloda.fast.convos.model.ConvoIntent
import dev.meloda.fast.convos.model.ConvoNavigationIntent
import dev.meloda.fast.convos.model.ConvosScreenState import dev.meloda.fast.convos.model.ConvosScreenState
import dev.meloda.fast.convos.model.InteractionJob import dev.meloda.fast.convos.model.InteractionJob
import dev.meloda.fast.convos.model.NewInteractionException import dev.meloda.fast.convos.model.NewInteractionException
import dev.meloda.fast.data.UserConfig
import dev.meloda.fast.data.VkUtils import dev.meloda.fast.data.VkUtils
import dev.meloda.fast.data.processState import dev.meloda.fast.data.processState
import dev.meloda.fast.datastore.UserSettings import dev.meloda.fast.datastore.UserSettings
@@ -28,25 +31,23 @@ import dev.meloda.fast.domain.LongPollUpdatesParser
import dev.meloda.fast.domain.MessagesUseCase import dev.meloda.fast.domain.MessagesUseCase
import dev.meloda.fast.domain.util.asPresentation import dev.meloda.fast.domain.util.asPresentation
import dev.meloda.fast.domain.util.extractAvatar import dev.meloda.fast.domain.util.extractAvatar
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.model.ConvosFilter import dev.meloda.fast.model.ConvosFilter
import dev.meloda.fast.model.InteractionType import dev.meloda.fast.model.InteractionType
import dev.meloda.fast.model.LongPollParsedEvent import dev.meloda.fast.model.LongPollParsedEvent
import dev.meloda.fast.model.api.domain.VkConvo import dev.meloda.fast.model.api.domain.VkConvo
import dev.meloda.fast.ui.model.vk.ConvoOption import dev.meloda.fast.ui.model.vk.ConvoOption
import dev.meloda.fast.ui.model.vk.UiConvo import dev.meloda.fast.ui.model.vk.UiConvo
import dev.meloda.fast.ui.util.ImmutableList
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
import dev.meloda.fast.ui.util.buildImmutableList
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
@Immutable
class ConvosViewModel( class ConvosViewModel(
updatesParser: LongPollUpdatesParser, updatesParser: LongPollUpdatesParser,
private val filter: ConvosFilter, val filter: ConvosFilter,
private val convoUseCase: ConvoUseCase, private val convoUseCase: ConvoUseCase,
private val messagesUseCase: MessagesUseCase, private val messagesUseCase: MessagesUseCase,
private val resources: Resources, private val resources: Resources,
@@ -55,43 +56,22 @@ class ConvosViewModel(
private val applicationContext: Context, private val applicationContext: Context,
private val loadConvosByIdUseCase: LoadConvosByIdUseCase private val loadConvosByIdUseCase: LoadConvosByIdUseCase
) : ViewModel() { ) : ViewModel() {
private val _screenState = MutableStateFlow(ConvosScreenState.EMPTY)
val screenState = _screenState.asStateFlow()
private val _navigation = MutableStateFlow<ConvoNavigation?>(null) private val screenState = MutableStateFlow(ConvosScreenState.EMPTY)
val navigation = _navigation.asStateFlow() val screenStateFlow get() = screenState.asStateFlow()
private val _dialog = MutableStateFlow<ConvoDialog?>(null) private val navigationIntent = MutableStateFlow<ConvoNavigationIntent?>(null)
val dialog = _dialog.asStateFlow() val navigationIntentFlow get() = navigationIntent.asStateFlow()
private val _convos = MutableStateFlow<List<VkConvo>>(emptyList()) private val convos: MutableList<VkConvo> = mutableListOf()
val convos = _convos.asStateFlow()
private val _uiConvos = MutableStateFlow<List<UiConvo>>(emptyList()) private val pinnedConvosCount get() = convos.count(VkConvo::isPinned)
val uiConvos = _uiConvos.asStateFlow()
private val pinnedConvosCount = convos.map { convos -> private var currentOffset = 0
convos.count(VkConvo::isPinned)
}.stateIn(viewModelScope, SharingStarted.Eagerly, 0)
private val _baseError = MutableStateFlow<BaseError?>(null)
val baseError = _baseError.asStateFlow()
private val _currentOffset = MutableStateFlow(0)
val currentOffset = _currentOffset.asStateFlow()
private val _canPaginate = MutableStateFlow(false)
val canPaginate = _canPaginate.asStateFlow()
private val expandedConvoId = MutableStateFlow(0L)
private val useContactNames: Boolean get() = userSettings.useContactNames.value
private val interactionsTimers = hashMapOf<Long, InteractionJob?>() private val interactionsTimers = hashMapOf<Long, InteractionJob?>()
init { init {
_screenState.updateValue { copy(isArchive = filter == ConvosFilter.ARCHIVE) }
loadConvos() loadConvos()
updatesParser.onNewMessage(::handleNewMessage) updatesParser.onNewMessage(::handleNewMessage)
@@ -109,100 +89,143 @@ class ConvosViewModel(
} }
} }
fun onNavigationConsumed() { fun handleIntent(intent: ConvoIntent) {
_navigation.setValue { null } 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) { fun onNavigationConsumed() {
onDialogDismissed(dialog) 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) { when (dialog) {
is ConvoDialog.ConvoDelete -> { is ConvoDialog.Delete -> {
deleteConvo(dialog.convoId) deleteConvo(convo.id)
} }
is ConvoDialog.ConvoPin -> { is ConvoDialog.Pin -> {
pinConvo(dialog.convoId, true) pinConvo(convo.id, true)
} }
is ConvoDialog.ConvoUnpin -> { is ConvoDialog.Unpin -> {
pinConvo(dialog.convoId, false) pinConvo(convo.id, false)
} }
is ConvoDialog.ConvoArchive -> { is ConvoDialog.Archive -> {
archiveConvo(dialog.convoId, true) archiveConvo(convo.id, true)
} }
is ConvoDialog.ConvoUnarchive -> { is ConvoDialog.Unarchive -> {
archiveConvo(dialog.convoId, false) archiveConvo(convo.id, false)
} }
} }
expandedConvoId.setValue { 0 } collapseConvos(false)
syncUiConvos() syncUiConvos()
} }
fun onDialogDismissed(dialog: ConvoDialog) { private fun onDialogDismissed() {
_dialog.setValue { null } screenState.updateValue { copy(dialog = null) }
} }
fun onDialogItemPicked(dialog: ConvoDialog, bundle: Bundle) { private fun onPaginationConditionsMet() {
when (dialog) { currentOffset = convos.size
is ConvoDialog.ConvoDelete -> Unit
is ConvoDialog.ConvoPin -> Unit
is ConvoDialog.ConvoUnpin -> Unit
is ConvoDialog.ConvoArchive -> Unit
is ConvoDialog.ConvoUnarchive -> Unit
}
}
fun onErrorButtonClicked() {
when (baseError.value) {
null -> Unit
is BaseError.ConnectionError,
is BaseError.InternalError,
is BaseError.SimpleError,
is BaseError.UnknownError -> onRefresh()
else -> Unit
}
}
fun onPaginationConditionsMet() {
_currentOffset.update { convos.value.size }
loadConvos() loadConvos()
} }
fun onRefresh() { private fun onErrorConsumed() {
screenState.updateValue { copy(error = null) }
}
private fun onRefresh() {
onErrorConsumed() onErrorConsumed()
loadConvos(offset = 0) loadConvos(offset = 0)
} }
fun onConvoItemClick(convo: UiConvo) { private fun onConvoItemClick(convoId: Long) {
collapseConvos() collapseConvos()
_navigation.setValue { ConvoNavigation.MessagesHistory(peerId = convo.id) } navigationIntent.setValue { ConvoNavigationIntent.MessagesHistory(convoId) }
} }
fun onConvoItemLongClick(convo: UiConvo) { private fun onConvoItemLongClick(convoId: Long) {
expandedConvoId.setValue { val isExpanded = screenState.value.convos.find { it.id == convoId }?.isExpanded == true
if (convo.isExpanded) 0
else convo.id screenState.updateValue { copy(expandedConvoId = if (isExpanded) 0L else convoId) }
}
syncUiConvos() syncUiConvos()
} }
fun onOptionClicked( private fun onOptionClicked(option: ConvoOption) {
convo: UiConvo, val convo =
option: ConvoOption screenState.value.convos.find { it.id == screenState.value.expandedConvoId } ?: return
) {
when (option) { when (option) {
ConvoOption.Delete -> { ConvoOption.Delete -> setDialog(ConvoDialog.Delete)
_dialog.setValue { ConvoDialog.ConvoDelete(convo.id) }
}
ConvoOption.MarkAsRead -> { ConvoOption.MarkAsRead -> {
convo.lastMessageId?.let { lastMessageId -> val lastMessageId =
screenState.value.convos.find { it.id == screenState.value.expandedConvoId }?.lastMessageId
if (lastMessageId != null) {
readConvo( readConvo(
peerId = convo.id, peerId = convo.id,
startMessageId = lastMessageId startMessageId = lastMessageId
@@ -211,48 +234,39 @@ class ConvosViewModel(
} }
} }
ConvoOption.Pin -> { ConvoOption.Pin -> setDialog(ConvoDialog.Pin)
_dialog.setValue { ConvoDialog.ConvoPin(convo.id) } ConvoOption.Unpin -> setDialog(ConvoDialog.Unpin)
} ConvoOption.Archive -> setDialog(ConvoDialog.Archive)
ConvoOption.Unarchive -> setDialog(ConvoDialog.Unarchive)
ConvoOption.Unpin -> {
_dialog.setValue { ConvoDialog.ConvoUnpin(convo.id) }
}
ConvoOption.Archive -> {
_dialog.setValue { ConvoDialog.ConvoArchive(convo.id) }
}
ConvoOption.Unarchive -> {
_dialog.setValue { ConvoDialog.ConvoUnarchive(convo.id) }
}
} }
} }
fun onErrorConsumed() { private fun setScrollIndex(index: Int) {
_baseError.setValue { null } screenState.setValue { old -> old.copy(scrollIndex = index) }
} }
fun setScrollIndex(index: Int) { private fun setScrollOffset(offset: Int) {
_screenState.setValue { old -> old.copy(scrollIndex = index) } screenState.setValue { old -> old.copy(scrollOffset = offset) }
} }
fun setScrollOffset(offset: Int) { private fun setDialog(dialog: ConvoDialog?) {
_screenState.setValue { old -> old.copy(scrollOffset = offset) } screenState.updateValue { copy(dialog = dialog) }
} }
fun onCreateChatButtonClicked() { private fun replaceConvos(newConvos: List<VkConvo>) {
_navigation.setValue { ConvoNavigation.CreateChat } convos.clear()
convos.addAll(newConvos)
} }
private fun collapseConvos() { private fun collapseConvos(sync: Boolean = true) {
expandedConvoId.setValue { 0 } screenState.updateValue { copy(expandedConvoId = null) }
syncUiConvos()
if (sync) {
syncUiConvos()
}
} }
private fun loadConvos( private fun loadConvos(offset: Int = currentOffset) {
offset: Int = currentOffset.value
) {
convoUseCase.getConvos( convoUseCase.getConvos(
count = LOAD_COUNT, count = LOAD_COUNT,
offset = offset, offset = offset,
@@ -260,23 +274,20 @@ class ConvosViewModel(
).listenValue(viewModelScope) { state -> ).listenValue(viewModelScope) { state ->
state.processState( state.processState(
error = { error -> error = { error ->
val newBaseError = VkUtils.parseError(error) screenState.updateValue { copy(error = VkUtils.parseError(error)) }
_baseError.update { newBaseError }
}, },
success = { response -> success = { response ->
val convos = response val newConvos = if (offset == 0) {
val fullConvos = if (offset == 0) { response
convos
} else { } else {
this.convos.value.plus(convos) convos.plus(response)
} }
val itemsCountSufficient = response.size == LOAD_COUNT val itemsCountSufficient = response.size == LOAD_COUNT
val paginationExhausted = !itemsCountSufficient && val paginationExhausted = !itemsCountSufficient && convos.isNotEmpty()
this.convos.value.isNotEmpty()
_screenState.updateValue { screenState.updateValue {
copy(isPaginationExhausted = paginationExhausted) copy(isPaginationExhausted = paginationExhausted)
} }
@@ -293,13 +304,14 @@ class ConvosViewModel(
convoUseCase.storeConvos(response) convoUseCase.storeConvos(response)
_convos.emit(fullConvos) replaceConvos(newConvos)
screenState.updateValue { copy(canPaginate = itemsCountSufficient) }
syncUiConvos() syncUiConvos()
_canPaginate.setValue { itemsCountSufficient }
} }
) )
_screenState.setValue { old -> screenState.setValue { old ->
old.copy( old.copy(
isLoading = offset == 0 && state.isLoading(), isLoading = offset == 0 && state.isLoading(),
isPaginating = offset > 0 && state.isLoading() isPaginating = offset > 0 && state.isLoading()
@@ -313,17 +325,17 @@ class ConvosViewModel(
state.processState( state.processState(
error = {}, error = {},
success = { success = {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == peerId } newConvos.indexOfFirstOrNull { it.id == peerId }
?: return@processState ?: return@processState
newConvos.removeAt(convoIndex) newConvos.removeAt(convoIndex)
_convos.update { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
) )
_screenState.emit(screenState.value.copy(isLoading = state.isLoading())) screenState.emit(screenStateFlow.value.copy(isLoading = state.isLoading()))
} }
} }
@@ -337,7 +349,7 @@ class ConvosViewModel(
LongPollParsedEvent.ChatMajorChanged( LongPollParsedEvent.ChatMajorChanged(
peerId = peerId, peerId = peerId,
majorId = if (pin) { majorId = if (pin) {
pinnedConvosCount.value.plus(1) * 16 pinnedConvosCount.plus(1) * 16
} else { } else {
0 0
} }
@@ -346,7 +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( state.processState(
error = {}, error = {},
success = { success = {
convos.value.find { it.id == peerId }?.let { convo -> convos.find { it.id == peerId }?.let { convo ->
handleChatArchived( handleChatArchived(
LongPollParsedEvent.ChatArchived( LongPollParsedEvent.ChatArchived(
convo = convo, convo = convo,
@@ -373,7 +385,7 @@ class ConvosViewModel(
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) { private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
val message = event.message val message = event.message
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == message.peerId } newConvos.indexOfFirstOrNull { it.id == message.peerId }
@@ -391,8 +403,8 @@ class ConvosViewModel(
val convo = (response.firstOrNull() ?: return@listenValue) val convo = (response.firstOrNull() ?: return@listenValue)
.copy(lastMessage = message) .copy(lastMessage = message)
newConvos.add(pinnedConvosCount.value, convo) newConvos.add(pinnedConvosCount, convo)
_convos.update { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
) )
@@ -428,19 +440,17 @@ class ConvosViewModel(
newConvos[convoIndex] = newConvo newConvos[convoIndex] = newConvo
} else { } else {
newConvos.removeAt(convoIndex) newConvos.removeAt(convoIndex)
newConvos.add(pinnedConvosCount, newConvo)
val toPosition = pinnedConvosCount.value
newConvos.add(toPosition, newConvo)
} }
_convos.update { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
} }
private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) { private fun handleEditedMessage(event: LongPollParsedEvent.MessageEdited) {
val message = event.message val message = event.message
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = newConvos.indexOfFirstOrNull { it.id == message.peerId } val convoIndex = newConvos.indexOfFirstOrNull { it.id == message.peerId }
if (convoIndex == null) { // диалога нет в списке if (convoIndex == null) { // диалога нет в списке
@@ -452,13 +462,14 @@ class ConvosViewModel(
lastMessageId = message.id, lastMessageId = message.id,
lastCmId = message.cmId lastCmId = message.cmId
) )
_convos.update { newConvos }
replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
} }
} }
private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) { private fun handleReadIncomingMessage(event: LongPollParsedEvent.IncomingMessageRead) {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == event.peerId } newConvos.indexOfFirstOrNull { it.id == event.peerId }
@@ -472,13 +483,13 @@ class ConvosViewModel(
unreadCount = event.unreadCount unreadCount = event.unreadCount
) )
_convos.update { newConvos } replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
} }
} }
private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) { private fun handleReadOutgoingMessage(event: LongPollParsedEvent.OutgoingMessageRead) {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == event.peerId } newConvos.indexOfFirstOrNull { it.id == event.peerId }
@@ -492,7 +503,7 @@ class ConvosViewModel(
unreadCount = event.unreadCount unreadCount = event.unreadCount
) )
_convos.update { newConvos } replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
} }
} }
@@ -502,7 +513,7 @@ class ConvosViewModel(
val peerId = event.peerId val peerId = event.peerId
val userIds = event.userIds val userIds = event.userIds
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoAndIndex = val convoAndIndex =
newConvos.findWithIndex { it.id == peerId } newConvos.findWithIndex { it.id == peerId }
@@ -513,7 +524,7 @@ class ConvosViewModel(
interactionIds = userIds interactionIds = userIds
) )
_convos.update { newConvos } replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
interactionsTimers[peerId]?.let { interactionJob -> interactionsTimers[peerId]?.let { interactionJob ->
@@ -545,7 +556,7 @@ class ConvosViewModel(
private fun stopInteraction(peerId: Long, interactionJob: InteractionJob) { private fun stopInteraction(peerId: Long, interactionJob: InteractionJob) {
interactionsTimers[peerId] ?: return interactionsTimers[peerId] ?: return
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoAndIndex = val convoAndIndex =
newConvos.findWithIndex { it.id == peerId } ?: return newConvos.findWithIndex { it.id == peerId } ?: return
@@ -555,7 +566,7 @@ class ConvosViewModel(
interactionIds = emptyList() interactionIds = emptyList()
) )
_convos.update { newConvos } replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
interactionJob.timerJob.cancel() interactionJob.timerJob.cancel()
@@ -563,7 +574,7 @@ class ConvosViewModel(
} }
private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) { private fun handleChatMajorChanged(event: LongPollParsedEvent.ChatMajorChanged) {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == event.peerId } newConvos.indexOfFirstOrNull { it.id == event.peerId }
@@ -573,13 +584,13 @@ class ConvosViewModel(
newConvos[convoIndex] = newConvos[convoIndex] =
newConvos[convoIndex].copy(majorId = event.majorId) newConvos[convoIndex].copy(majorId = event.majorId)
_convos.setValue { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
} }
private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) { private fun handleChatMinorChanged(event: LongPollParsedEvent.ChatMinorChanged) {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == event.peerId } newConvos.indexOfFirstOrNull { it.id == event.peerId }
@@ -589,13 +600,13 @@ class ConvosViewModel(
newConvos[convoIndex] = newConvos[convoIndex] =
newConvos[convoIndex].copy(minorId = event.minorId) newConvos[convoIndex].copy(minorId = event.minorId)
_convos.setValue { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
} }
private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) { private fun handleChatClearing(event: LongPollParsedEvent.ChatCleared) {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = newConvos.indexOfFirstOrNull { it.id == event.peerId } val convoIndex = newConvos.indexOfFirstOrNull { it.id == event.peerId }
@@ -604,7 +615,7 @@ class ConvosViewModel(
} else { } else {
newConvos.removeAt(convoIndex) newConvos.removeAt(convoIndex)
_convos.setValue { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
} }
@@ -612,7 +623,7 @@ class ConvosViewModel(
private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) { private fun handleChatArchived(event: LongPollParsedEvent.ChatArchived) {
val convo = event.convo val convo = event.convo
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
when (filter) { when (filter) {
ConvosFilter.BUSINESS_NOTIFY -> Unit ConvosFilter.BUSINESS_NOTIFY -> Unit
@@ -627,7 +638,7 @@ class ConvosViewModel(
newConvos.removeAt(index) newConvos.removeAt(index)
} }
_convos.update { newConvos } replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
} }
@@ -638,10 +649,10 @@ class ConvosViewModel(
newConvos.removeAt(index) newConvos.removeAt(index)
} else { } else {
newConvos.add(pinnedConvosCount.value, convo) newConvos.add(pinnedConvosCount, convo)
} }
_convos.update { newConvos.sorted() } replaceConvos(newConvos.sorted())
syncUiConvos() syncUiConvos()
} }
} }
@@ -655,7 +666,7 @@ class ConvosViewModel(
state.processState( state.processState(
error = {}, error = {},
success = { success = {
val newConvos = convos.value.toMutableList() val newConvos = convos.toMutableList()
val convoIndex = val convoIndex =
newConvos.indexOfFirstOrNull { it.id == peerId } newConvos.indexOfFirstOrNull { it.id == peerId }
?: return@listenValue ?: return@listenValue
@@ -663,7 +674,7 @@ class ConvosViewModel(
newConvos[convoIndex] = newConvos[convoIndex] =
newConvos[convoIndex].copy(inRead = startMessageId) newConvos[convoIndex].copy(inRead = startMessageId)
_convos.update { newConvos } replaceConvos(newConvos)
syncUiConvos() syncUiConvos()
} }
) )
@@ -695,47 +706,44 @@ class ConvosViewModel(
} }
private fun syncUiConvos(): List<UiConvo> { private fun syncUiConvos(): List<UiConvo> {
val convos = convos.value
val newUiConvos = convos.map { convo -> val newUiConvos = convos.map { convo ->
val options = mutableListOf<ConvoOption>() val options: ImmutableList<ConvoOption> = buildImmutableList {
convo.lastMessage?.run { if (!convo.isRead() && convo.lastMessage != null && convo.lastMessage?.isOut == false) {
if (!convo.isRead() && !this.isOut) { add(ConvoOption.MarkAsRead)
options += ConvoOption.MarkAsRead
} }
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( convo.asPresentation(
resources = resources, resources = resources,
useContactName = useContactNames, useContactName = userSettings.useContactNames.value,
isExpanded = expandedConvoId.value == convo.id, isExpanded = screenState.value.expandedConvoId == convo.id,
options = options.toImmutableList() options = options
) )
} }
_uiConvos.setValue { newUiConvos }
screenState.updateValue { copy(convos = newUiConvos.toImmutableList()) }
return newUiConvos return newUiConvos
} }
@@ -4,9 +4,9 @@ import androidx.compose.runtime.Immutable
@Immutable @Immutable
sealed class ConvoDialog { sealed class ConvoDialog {
data class ConvoPin(val convoId: Long) : ConvoDialog() data object Pin : ConvoDialog()
data class ConvoUnpin(val convoId: Long) : ConvoDialog() data object Unpin : ConvoDialog()
data class ConvoDelete(val convoId: Long) : ConvoDialog() data object Delete : ConvoDialog()
data class ConvoArchive(val convoId: Long) : ConvoDialog() data object Archive : ConvoDialog()
data class ConvoUnarchive(val convoId: Long) : ConvoDialog() data object Unarchive : ConvoDialog()
} }
@@ -0,0 +1,29 @@
package dev.meloda.fast.convos.model
import android.os.Bundle
import dev.meloda.fast.ui.model.vk.ConvoOption
sealed class ConvoIntent {
data class ItemClick(val convoId: Long) : ConvoIntent()
data class ItemLongClick(val convoId: Long) : ConvoIntent()
data class OptionItemClick(val option: ConvoOption) : ConvoIntent()
data object PaginationConditionsMet : ConvoIntent()
data object Back : ConvoIntent()
data object Refresh : ConvoIntent()
data object CreateChatClick : ConvoIntent()
data object ArchiveClick : ConvoIntent()
data class SetScrollIndex(val index: Int) : ConvoIntent()
data class SetScrollOffset(val offset: Int) : ConvoIntent()
data object ErrorActionButtonClick : ConvoIntent()
data object ConsumeScrollToTop : ConvoIntent()
sealed class Dialog : ConvoIntent() {
data object Dismiss : Dialog()
data class Confirm(val bundle: Bundle? = null) : Dialog()
data class Cancel(val bundle: Bundle? = null) : Dialog()
}
}
@@ -1,11 +0,0 @@
package dev.meloda.fast.convos.model
import androidx.compose.runtime.Immutable
@Immutable
sealed class ConvoNavigation {
data class MessagesHistory(val peerId: Long) : ConvoNavigation()
data object CreateChat : ConvoNavigation()
}
@@ -0,0 +1,9 @@
package dev.meloda.fast.convos.model
sealed class ConvoNavigationIntent {
data object Back : ConvoNavigationIntent()
data class MessagesHistory(val convoId: Long) : ConvoNavigationIntent()
data object CreateChat : ConvoNavigationIntent()
data object Archive : ConvoNavigationIntent()
}
@@ -1,6 +1,10 @@
package dev.meloda.fast.convos.model package dev.meloda.fast.convos.model
import androidx.compose.runtime.Immutable import androidx.compose.runtime.Immutable
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.ui.model.vk.UiConvo
import dev.meloda.fast.ui.util.ImmutableList
import dev.meloda.fast.ui.util.emptyImmutableList
@Immutable @Immutable
data class ConvosScreenState( data class ConvosScreenState(
@@ -10,7 +14,13 @@ data class ConvosScreenState(
val profileImageUrl: String?, val profileImageUrl: String?,
val scrollIndex: Int, val scrollIndex: Int,
val scrollOffset: Int, val scrollOffset: Int,
val isArchive: Boolean val canPaginate: Boolean,
val expandedConvoId: Long?,
val convos: ImmutableList<UiConvo>,
val dialog: ConvoDialog?,
// TODO: 30.05.2026, Danil Nikolaev: remove
val error: BaseError?
) { ) {
companion object { companion object {
@@ -21,7 +31,11 @@ data class ConvosScreenState(
profileImageUrl = null, profileImageUrl = null,
scrollIndex = 0, scrollIndex = 0,
scrollOffset = 0, scrollOffset = 0,
isArchive = false canPaginate = false,
expandedConvoId = null,
convos = emptyImmutableList(),
dialog = null,
error = null
) )
} }
} }
@@ -1,12 +1,16 @@
package dev.meloda.fast.convos.navigation package dev.meloda.fast.convos.navigation
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavGraphBuilder import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.navigation import androidx.navigation.navigation
import dev.meloda.fast.convos.ConvosViewModel import dev.meloda.fast.convos.ConvosViewModel
import dev.meloda.fast.convos.model.ConvoNavigationIntent
import dev.meloda.fast.convos.presentation.ConvosRoute import dev.meloda.fast.convos.presentation.ConvosRoute
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.model.ConvosFilter import dev.meloda.fast.model.ConvosFilter
import dev.meloda.fast.ui.extensions.getOrThrow import dev.meloda.fast.ui.extensions.getOrThrow
import dev.meloda.fast.ui.theme.LocalNavController import dev.meloda.fast.ui.theme.LocalNavController
@@ -24,44 +28,56 @@ object Convos
object Archive object Archive
fun NavGraphBuilder.convosGraph( fun NavGraphBuilder.convosGraph(
handleNavigationIntent: (ConvoNavigationIntent) -> Unit,
activity: AppCompatActivity, activity: AppCompatActivity,
onError: (BaseError) -> Unit,
onNavigateToMessagesHistory: (id: Long) -> Unit,
onNavigateToCreateChat: () -> Unit,
onScrolledToTop: () -> Unit
) { ) {
navigation<ConvoGraph>( navigation<ConvoGraph>(
startDestination = Convos startDestination = Convos
) { ) {
val convosViewModel: ConvosViewModel = with(activity) {
getViewModel(qualifier = named(ConvosFilter.ALL))
}
composable<Convos> { composable<Convos> {
val navController = LocalNavController.getOrThrow() ConvosRootRoute(
handleNavigationIntent = handleNavigationIntent,
ConvosRoute( viewModel = with(activity) {
viewModel = convosViewModel, getViewModel(named(ConvosFilter.ALL))
onError = onError, }
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
onNavigateToCreateChat = onNavigateToCreateChat,
onNavigateToArchive = { navController.navigate(Archive) },
onScrolledToTop = onScrolledToTop
) )
} }
composable<Archive> { composable<Archive> {
val navController = LocalNavController.getOrThrow() ConvosRootRoute(
handleNavigationIntent = handleNavigationIntent,
ConvosRoute(
viewModel = with(activity) { viewModel = with(activity) {
getViewModel<ConvosViewModel>( getViewModel<ConvosViewModel>(named(ConvosFilter.ARCHIVE))
qualifier = named(ConvosFilter.ARCHIVE) }
)
},
onBack = navController::navigateUp,
onError = onError,
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
onScrolledToTop = onScrolledToTop
) )
} }
} }
} }
@Composable
private fun ConvosRootRoute(
handleNavigationIntent: (ConvoNavigationIntent) -> Unit,
viewModel: ConvosViewModel
) {
val navController = LocalNavController.getOrThrow()
val screenState by viewModel.screenStateFlow.collectAsStateWithLifecycle()
val navigationIntent by viewModel.navigationIntentFlow.collectAsStateWithLifecycle()
LaunchedEffect(navigationIntent) {
navigationIntent?.let {
when (navigationIntent) {
ConvoNavigationIntent.Back -> navController.navigateUp()
ConvoNavigationIntent.Archive -> navController.navigate(Archive)
else -> handleNavigationIntent(it)
}
viewModel.onNavigationConsumed()
}
}
ConvosRoute(
handleIntent = viewModel::handleIntent,
screenState = screenState,
isArchive = viewModel.filter == ConvosFilter.ARCHIVE,
)
}
@@ -1,82 +1,78 @@
package dev.meloda.fast.convos.presentation package dev.meloda.fast.convos.presentation
import android.os.Bundle
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource import androidx.compose.ui.res.vectorResource
import androidx.core.os.bundleOf
import dev.meloda.fast.convos.model.ConvoDialog import dev.meloda.fast.convos.model.ConvoDialog
import dev.meloda.fast.convos.model.ConvoIntent
import dev.meloda.fast.convos.model.ConvosScreenState import dev.meloda.fast.convos.model.ConvosScreenState
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.components.MaterialDialog import dev.meloda.fast.ui.components.MaterialDialog
@Composable @Composable
fun HandleDialogs( fun HandleDialogs(
handleIntent: (ConvoIntent) -> Unit,
screenState: ConvosScreenState, screenState: ConvosScreenState,
dialog: ConvoDialog?,
onConfirmed: (ConvoDialog, Bundle) -> Unit = { _, _ -> },
onDismissed: (ConvoDialog) -> Unit = {},
onItemPicked: (ConvoDialog, Bundle) -> Unit = { _, _ -> }
) { ) {
when (dialog) { when (screenState.dialog) {
null -> Unit null -> Unit
is ConvoDialog.ConvoArchive -> { is ConvoDialog.Archive -> {
MaterialDialog( MaterialDialog(
onDismissRequest = { onDismissed(dialog) }, onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
title = stringResource(id = R.string.confirm_archive_convo), title = stringResource(id = R.string.confirm_archive_convo),
confirmAction = { onConfirmed(dialog, bundleOf()) }, confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
confirmText = stringResource(id = R.string.action_archive), confirmText = stringResource(id = R.string.action_archive),
cancelText = stringResource(id = R.string.cancel), cancelText = stringResource(id = R.string.cancel),
icon = ImageVector.vectorResource(R.drawable.ic_archive_fill_round_24) icon = ImageVector.vectorResource(R.drawable.ic_archive_fill_round_24)
) )
} }
is ConvoDialog.ConvoUnarchive -> { is ConvoDialog.Unarchive -> {
MaterialDialog( MaterialDialog(
onDismissRequest = { onDismissed(dialog) }, onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
title = stringResource(id = R.string.confirm_unarchive_convo), title = stringResource(id = R.string.confirm_unarchive_convo),
confirmAction = { onConfirmed(dialog, bundleOf()) }, confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
confirmText = stringResource(id = R.string.action_unarchive), confirmText = stringResource(id = R.string.action_unarchive),
cancelText = stringResource(id = R.string.cancel), cancelText = stringResource(id = R.string.cancel),
icon = ImageVector.vectorResource(R.drawable.ic_unarchive_fill_round_24) icon = ImageVector.vectorResource(R.drawable.ic_unarchive_fill_round_24)
) )
} }
is ConvoDialog.ConvoDelete -> { is ConvoDialog.Delete -> {
val errorColor = MaterialTheme.colorScheme.error val errorColor = MaterialTheme.colorScheme.error
MaterialDialog( MaterialDialog(
onDismissRequest = { onDismissed(dialog) }, onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
icon = ImageVector.vectorResource(R.drawable.ic_delete_fill_round_24), icon = ImageVector.vectorResource(R.drawable.ic_delete_fill_round_24),
iconTint = errorColor, iconTint = errorColor,
title = stringResource(id = R.string.confirm_delete_convo), title = stringResource(id = R.string.confirm_delete_convo),
confirmAction = { onConfirmed(dialog, bundleOf()) }, confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
confirmText = stringResource(id = R.string.action_delete), confirmText = stringResource(id = R.string.action_delete),
confirmContainerColor = errorColor, confirmContainerColor = errorColor,
cancelText = stringResource(id = R.string.cancel), cancelText = stringResource(id = R.string.cancel),
) )
} }
is ConvoDialog.ConvoPin -> { is ConvoDialog.Pin -> {
MaterialDialog( MaterialDialog(
onDismissRequest = { onDismissed(dialog) }, onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
icon = ImageVector.vectorResource(R.drawable.ic_keep_fill_round_24), icon = ImageVector.vectorResource(R.drawable.ic_keep_fill_round_24),
title = stringResource(id = R.string.confirm_pin_convo), title = stringResource(id = R.string.confirm_pin_convo),
confirmAction = { onConfirmed(dialog, bundleOf()) }, confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
confirmText = stringResource(id = R.string.action_pin), confirmText = stringResource(id = R.string.action_pin),
cancelText = stringResource(id = R.string.cancel), cancelText = stringResource(id = R.string.cancel),
) )
} }
is ConvoDialog.ConvoUnpin -> { is ConvoDialog.Unpin -> {
MaterialDialog( MaterialDialog(
onDismissRequest = { onDismissed(dialog) }, onDismissRequest = { handleIntent(ConvoIntent.Dialog.Dismiss) },
icon = ImageVector.vectorResource(R.drawable.ic_keep_off_fill_round_24), icon = ImageVector.vectorResource(R.drawable.ic_keep_off_fill_round_24),
title = stringResource(id = R.string.confirm_unpin_convo), title = stringResource(id = R.string.confirm_unpin_convo),
confirmAction = { onConfirmed(dialog, bundleOf()) }, confirmAction = { handleIntent(ConvoIntent.Dialog.Confirm()) },
confirmText = stringResource(id = R.string.action_unpin), confirmText = stringResource(id = R.string.action_unpin),
cancelText = stringResource(id = R.string.cancel), cancelText = stringResource(id = R.string.cancel),
) )
@@ -62,9 +62,9 @@ val BirthdayColor = Color(0xffb00b69)
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
fun ConvoItem( fun ConvoItem(
onItemClick: (UiConvo) -> Unit, onItemClick: (convoId: Long) -> Unit,
onItemLongClick: (convo: UiConvo) -> Unit, onItemLongClick: (convoId: Long) -> Unit,
onOptionClicked: (UiConvo, ConvoOption) -> Unit, onOptionClicked: (ConvoOption) -> Unit,
maxLines: Int, maxLines: Int,
isUserAccount: Boolean, isUserAccount: Boolean,
convo: UiConvo, convo: UiConvo,
@@ -81,9 +81,9 @@ fun ConvoItem(
modifier = modifier modifier = modifier
.fillMaxWidth() .fillMaxWidth()
.combinedClickable( .combinedClickable(
onClick = { onItemClick(convo) }, onClick = { onItemClick(convo.id) },
onLongClick = { onLongClick = {
onItemLongClick(convo) onItemLongClick(convo.id)
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress) hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
} }
) )
@@ -281,7 +281,7 @@ fun ConvoItem(
val builder = val builder =
AnnotatedString.Builder(convo.message.text) AnnotatedString.Builder(convo.message.text)
convo.message.spanStyles.map { spanStyleRange -> convo.message.spanStyles.forEach { spanStyleRange ->
val updatedSpanStyle = val updatedSpanStyle =
if (spanStyleRange.item.color == Color.Red) { if (spanStyleRange.item.color == Color.Red) {
spanStyleRange.item.copy(color = MaterialTheme.colorScheme.primary) spanStyleRange.item.copy(color = MaterialTheme.colorScheme.primary)
@@ -378,7 +378,7 @@ fun ConvoItem(
} }
ElevatedAssistChip( ElevatedAssistChip(
onClick = { onOptionClicked(convo, option) }, onClick = { onOptionClicked(option) },
leadingIcon = { leadingIcon = {
option.icon.getResourcePainter()?.let { painter -> option.icon.getResourcePainter()?.let { painter ->
Icon( Icon(
@@ -36,12 +36,12 @@ import kotlinx.coroutines.launch
fun ConvosList( fun ConvosList(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
convos: ImmutableList<UiConvo>, convos: ImmutableList<UiConvo>,
onConvosClick: (UiConvo) -> Unit, onConvosClick: (Long) -> Unit,
onConvosLongClick: (UiConvo) -> Unit, onConvosLongClick: (Long) -> Unit,
screenState: ConvosScreenState, screenState: ConvosScreenState,
state: LazyListState, state: LazyListState,
maxLines: Int, maxLines: Int,
onOptionClicked: (UiConvo, ConvoOption) -> Unit, onOptionClicked: (ConvoOption) -> Unit,
padding: PaddingValues padding: PaddingValues
) { ) {
val theme = LocalThemeConfig.current val theme = LocalThemeConfig.current
@@ -1,79 +1,23 @@
package dev.meloda.fast.convos.presentation package dev.meloda.fast.convos.presentation
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import dev.meloda.fast.convos.model.ConvoIntent
import androidx.compose.runtime.getValue import dev.meloda.fast.convos.model.ConvosScreenState
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import dev.meloda.fast.convos.ConvosViewModel
import dev.meloda.fast.convos.model.ConvoNavigation
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
@Composable @Composable
fun ConvosRoute( fun ConvosRoute(
viewModel: ConvosViewModel, handleIntent: (ConvoIntent) -> Unit,
onBack: (() -> Unit)? = null, screenState: ConvosScreenState,
onError: (BaseError) -> Unit, isArchive: Boolean,
onNavigateToMessagesHistory: (convoId: Long) -> Unit,
onNavigateToCreateChat: (() -> Unit)? = null,
onNavigateToArchive: (() -> Unit)? = null,
onScrolledToTop: () -> Unit,
) { ) {
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
val navigationEvent by viewModel.navigation.collectAsStateWithLifecycle()
val convos by viewModel.uiConvos.collectAsStateWithLifecycle()
val dialog by viewModel.dialog.collectAsStateWithLifecycle()
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle()
LaunchedEffect(navigationEvent) {
val shouldBeConsumed: Boolean = when (val navigation = navigationEvent) {
null -> false
is ConvoNavigation.CreateChat -> {
onNavigateToCreateChat?.invoke()
true
}
is ConvoNavigation.MessagesHistory -> {
onNavigateToMessagesHistory(navigation.peerId)
true
}
}
if (shouldBeConsumed) viewModel.onNavigationConsumed()
}
ConvosScreen( ConvosScreen(
onBack = { onBack?.invoke() }, handleIntent = handleIntent,
screenState = screenState, screenState = screenState,
convos = convos.toImmutableList(), isArchive = isArchive,
baseError = baseError,
canPaginate = canPaginate,
onConvoItemClicked = viewModel::onConvoItemClick,
onConvoItemLongClicked = viewModel::onConvoItemLongClick,
onOptionClicked = viewModel::onOptionClicked,
onPaginationConditionsMet = viewModel::onPaginationConditionsMet,
onRefresh = viewModel::onRefresh,
onCreateChatButtonClicked = viewModel::onCreateChatButtonClicked,
onArchiveActionClicked = { onNavigateToArchive?.invoke() },
setScrollIndex = viewModel::setScrollIndex,
setScrollOffset = viewModel::setScrollOffset,
onConsumeReselection = onScrolledToTop,
onErrorViewButtonClicked = {
if (baseError in listOf(BaseError.AccountBlocked, BaseError.SessionExpired)) {
onError(requireNotNull(baseError))
} else {
viewModel.onErrorButtonClicked()
}
}
) )
HandleDialogs( HandleDialogs(
handleIntent = handleIntent,
screenState = screenState, screenState = screenState,
dialog = dialog,
onConfirmed = viewModel::onDialogConfirmed,
onDismissed = viewModel::onDialogDismissed,
onItemPicked = viewModel::onDialogItemPicked
) )
} }
@@ -19,7 +19,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.FloatingActionButton 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.IntOffset
import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.skydoves.compose.stability.runtime.TraceRecomposition
import dev.chrisbanes.haze.hazeEffect import dev.chrisbanes.haze.hazeEffect
import dev.chrisbanes.haze.hazeSource import dev.chrisbanes.haze.hazeSource
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
import dev.chrisbanes.haze.materials.HazeMaterials import dev.chrisbanes.haze.materials.HazeMaterials
import dev.meloda.fast.convos.model.ConvoIntent
import dev.meloda.fast.convos.model.ConvosScreenState import dev.meloda.fast.convos.model.ConvosScreenState
import dev.meloda.fast.convos.navigation.ConvoGraph import dev.meloda.fast.convos.navigation.ConvoGraph
import dev.meloda.fast.datastore.AppSettings import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.components.FullScreenContainedLoader import dev.meloda.fast.ui.components.FullScreenContainedLoader
import dev.meloda.fast.ui.components.NoItemsView import dev.meloda.fast.ui.components.NoItemsView
import dev.meloda.fast.ui.components.VkErrorView import dev.meloda.fast.ui.components.SegmentedButtonItem
import dev.meloda.fast.ui.model.vk.ConvoOption import dev.meloda.fast.ui.components.SegmentedButtonsRow
import dev.meloda.fast.ui.model.vk.UiConvo
import dev.meloda.fast.ui.theme.LocalBottomPadding import dev.meloda.fast.ui.theme.LocalBottomPadding
import dev.meloda.fast.ui.theme.LocalHazeState import dev.meloda.fast.ui.theme.LocalHazeState
import dev.meloda.fast.ui.theme.LocalReselectedTab import dev.meloda.fast.ui.theme.LocalReselectedTab
import dev.meloda.fast.ui.theme.LocalThemeConfig import dev.meloda.fast.ui.theme.LocalThemeConfig
import dev.meloda.fast.ui.util.ImmutableList import dev.meloda.fast.ui.util.buildImmutableList
import dev.meloda.fast.ui.util.emptyImmutableList
import dev.meloda.fast.ui.util.isScrollingUp import dev.meloda.fast.ui.util.isScrollingUp
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.debounce
import kotlin.time.Duration.Companion.milliseconds
@OptIn( @OptIn(
ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class,
ExperimentalHazeMaterialsApi::class, ExperimentalMaterial3ExpressiveApi::class, ExperimentalHazeMaterialsApi::class,
ExperimentalMaterial3ExpressiveApi::class,
) )
@Composable @Composable
fun ConvosScreen( fun ConvosScreen(
screenState: ConvosScreenState = ConvosScreenState.EMPTY, handleIntent: (ConvoIntent) -> Unit,
convos: ImmutableList<UiConvo> = emptyImmutableList(), screenState: ConvosScreenState,
baseError: BaseError? = null, isArchive: Boolean,
canPaginate: Boolean = false,
onBack: () -> Unit = {},
onConvoItemClicked: (convo: UiConvo) -> Unit = {},
onConvoItemLongClicked: (convo: UiConvo) -> Unit = {},
onOptionClicked: (UiConvo, ConvoOption) -> Unit = { _, _ -> },
onPaginationConditionsMet: () -> Unit = {},
onRefresh: () -> Unit = {},
onCreateChatButtonClicked: () -> Unit = {},
onArchiveActionClicked: () -> Unit = {},
setScrollIndex: (Int) -> Unit = {},
setScrollOffset: (Int) -> Unit = {},
onConsumeReselection: () -> Unit = {},
onErrorViewButtonClicked: () -> Unit = {}
) { ) {
val currentTheme = LocalThemeConfig.current val currentTheme = LocalThemeConfig.current
val maxLines = if (currentTheme.enableMultiline) 2 else 1 val maxLines = if (currentTheme.enableMultiline) 2 else 1
@@ -112,33 +97,33 @@ fun ConvosScreen(
val currentTabReselected = LocalReselectedTab.current[ConvoGraph] == true val currentTabReselected = LocalReselectedTab.current[ConvoGraph] == true
LaunchedEffect(currentTabReselected) { LaunchedEffect(currentTabReselected) {
if (currentTabReselected) { if (currentTabReselected) {
if (screenState.isArchive) { if (isArchive) {
onBack.invoke() handleIntent(ConvoIntent.Back)
} else { } else {
if (listState.firstVisibleItemIndex > 14) { if (listState.firstVisibleItemIndex > 14) {
listState.scrollToItem(14) listState.scrollToItem(14)
} }
listState.animateScrollToItem(0) listState.animateScrollToItem(0)
onConsumeReselection() handleIntent(ConvoIntent.ConsumeScrollToTop)
} }
} }
} }
LaunchedEffect(listState) { LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemIndex } snapshotFlow { listState.firstVisibleItemIndex }
.debounce(500L) .debounce(500L.milliseconds)
.collectLatest(setScrollIndex) .collectLatest { handleIntent(ConvoIntent.SetScrollIndex(it)) }
} }
LaunchedEffect(listState) { LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemScrollOffset } snapshotFlow { listState.firstVisibleItemScrollOffset }
.debounce(500L) .debounce(500L.milliseconds)
.collectLatest(setScrollOffset) .collectLatest { handleIntent(ConvoIntent.SetScrollOffset(it)) }
} }
val paginationConditionMet by remember(canPaginate, listState) { val paginationConditionMet by remember(screenState.canPaginate, listState) {
derivedStateOf { derivedStateOf {
canPaginate && screenState.canPaginate &&
(listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index (listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
?: -9) >= (listState.layoutInfo.totalItemsCount - 6) ?: -9) >= (listState.layoutInfo.totalItemsCount - 6)
} }
@@ -146,7 +131,7 @@ fun ConvosScreen(
LaunchedEffect(paginationConditionMet) { LaunchedEffect(paginationConditionMet) {
if (paginationConditionMet && !screenState.isPaginating) { if (paginationConditionMet && !screenState.isPaginating) {
onPaginationConditionsMet() handleIntent(ConvoIntent.PaginationConditionsMet)
} }
} }
@@ -181,7 +166,7 @@ fun ConvosScreen(
text = stringResource( text = stringResource(
id = when { id = when {
screenState.isLoading -> R.string.title_loading screenState.isLoading -> R.string.title_loading
screenState.isArchive -> R.string.title_archive isArchive -> R.string.title_archive
else -> R.string.title_convos else -> R.string.title_convos
} }
), ),
@@ -191,8 +176,8 @@ fun ConvosScreen(
) )
}, },
navigationIcon = { navigationIcon = {
if (screenState.isArchive) { if (isArchive) {
IconButton(onClick = onBack) { IconButton(onClick = { handleIntent(ConvoIntent.Back) }) {
Icon( Icon(
painter = painterResource(R.drawable.ic_arrow_back_round_24), painter = painterResource(R.drawable.ic_arrow_back_round_24),
contentDescription = null contentDescription = null
@@ -201,54 +186,47 @@ fun ConvosScreen(
} }
}, },
actions = { actions = {
if (!screenState.isArchive) { val dropDownItems: List<@Composable () -> Unit> = buildList {}
IconButton(onClick = onArchiveActionClicked) {
Icon( val items = buildImmutableList {
painter = painterResource(R.drawable.ic_archive_round_24), if (!isArchive) {
contentDescription = null 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) { SegmentedButtonsRow(
dropDownItems += { modifier = Modifier.padding(end = 8.dp),
DropdownMenuItem( items = items,
onClick = { onClick = { index ->
onRefresh() when (items[index].key) {
dropDownMenuExpanded = false "archive" -> handleIntent(ConvoIntent.ArchiveClick)
}, "refresh" -> handleIntent(ConvoIntent.Refresh)
text = { "more" -> dropDownMenuExpanded = true
Text(text = stringResource(id = R.string.action_refresh))
}, else -> Unit
leadingIcon = { }
Icon(
painter = painterResource(R.drawable.ic_refresh_round_24),
contentDescription = null
)
}
)
} }
} )
if (dropDownItems.isNotEmpty()) { if (dropDownItems.isNotEmpty()) {
IconButton(onClick = { dropDownMenuExpanded = true }) { DropdownMenu(
Icon( modifier = Modifier.defaultMinSize(minWidth = 140.dp),
painter = painterResource(R.drawable.ic_more_vert_round_24), expanded = dropDownMenuExpanded,
contentDescription = null 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( colors = TopAppBarDefaults.topAppBarColors(
containerColor = toolbarContainerColor.copy( containerColor = toolbarContainerColor.copy(
@@ -268,7 +246,7 @@ fun ConvosScreen(
) )
val showHorizontalProgressBar by remember(screenState) { val showHorizontalProgressBar by remember(screenState) {
derivedStateOf { screenState.isLoading && convos.isNotEmpty() } derivedStateOf { screenState.isLoading && screenState.convos.isNotEmpty() }
} }
AnimatedVisibility(showHorizontalProgressBar) { AnimatedVisibility(showHorizontalProgressBar) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
@@ -279,14 +257,14 @@ fun ConvosScreen(
} }
}, },
floatingActionButton = { floatingActionButton = {
if (!screenState.isArchive) { if (!isArchive) {
val offsetY by animateIntAsState( val offsetY by animateIntAsState(
targetValue = if (listState.isScrollingUp()) 0 else 600 targetValue = if (listState.isScrollingUp()) 0 else 600
) )
Column { Column {
FloatingActionButton( FloatingActionButton(
onClick = onCreateChatButtonClicked, onClick = { handleIntent(ConvoIntent.CreateChatClick) },
modifier = Modifier.offset { modifier = Modifier.offset {
IntOffset(0, offsetY) IntOffset(0, offsetY)
} }
@@ -303,14 +281,15 @@ fun ConvosScreen(
} }
) { padding -> ) { padding ->
when { when {
baseError != null -> { // TODO: 30.05.2026, Danil Nikolaev: move to UI State
VkErrorView( // baseError != null -> {
baseError = baseError, // VkErrorView(
onButtonClick = onErrorViewButtonClicked // baseError = baseError,
) // onButtonClick = onErrorViewButtonClicked
} // )
// }
screenState.isLoading && convos.isEmpty() -> FullScreenContainedLoader() screenState.isLoading && screenState.convos.isEmpty() -> FullScreenContainedLoader()
else -> { else -> {
val pullToRefreshState = rememberPullToRefreshState() val pullToRefreshState = rememberPullToRefreshState()
@@ -323,7 +302,7 @@ fun ConvosScreen(
.padding(bottom = padding.calculateBottomPadding()), .padding(bottom = padding.calculateBottomPadding()),
state = pullToRefreshState, state = pullToRefreshState,
isRefreshing = screenState.isLoading, isRefreshing = screenState.isLoading,
onRefresh = onRefresh, onRefresh = { handleIntent(ConvoIntent.Refresh) },
indicator = { indicator = {
PullToRefreshDefaults.Indicator( PullToRefreshDefaults.Indicator(
state = pullToRefreshState, state = pullToRefreshState,
@@ -335,9 +314,9 @@ fun ConvosScreen(
} }
) { ) {
ConvosList( ConvosList(
convos = convos, convos = screenState.convos,
onConvosClick = onConvoItemClicked, onConvosClick = { handleIntent(ConvoIntent.ItemClick(it)) },
onConvosLongClick = onConvoItemLongClicked, onConvosLongClick = { handleIntent(ConvoIntent.ItemLongClick(it)) },
screenState = screenState, screenState = screenState,
state = listState, state = listState,
maxLines = maxLines, maxLines = maxLines,
@@ -346,14 +325,14 @@ fun ConvosScreen(
} else { } else {
Modifier Modifier
}.fillMaxSize(), }.fillMaxSize(),
onOptionClicked = onOptionClicked, onOptionClicked = { handleIntent(ConvoIntent.OptionItemClick(it)) },
padding = padding padding = padding
) )
if (convos.isEmpty()) { if (screenState.convos.isEmpty()) {
NoItemsView( NoItemsView(
buttonText = stringResource(R.string.action_refresh), buttonText = stringResource(R.string.action_refresh),
onButtonClick = onRefresh onButtonClick = { handleIntent(ConvoIntent.Refresh) }
) )
} }
} }
@@ -38,6 +38,7 @@ import dev.meloda.fast.ui.theme.LocalThemeConfig
import dev.meloda.fast.ui.util.ImmutableList import dev.meloda.fast.ui.util.ImmutableList
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.debounce
import kotlin.time.Duration.Companion.milliseconds
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -47,7 +48,6 @@ fun FriendsScreen(
orderType: String, orderType: String,
padding: PaddingValues, padding: PaddingValues,
tabIndex: Int, tabIndex: Int,
onSessionExpiredLogOutButtonClicked: () -> Unit = {},
onPhotoClicked: (url: String) -> Unit = {}, onPhotoClicked: (url: String) -> Unit = {},
onMessageClicked: (userid: Long) -> Unit = {}, onMessageClicked: (userid: Long) -> Unit = {},
setCanScrollBackward: (Boolean) -> Unit = {}, setCanScrollBackward: (Boolean) -> Unit = {},
@@ -100,13 +100,13 @@ fun FriendsScreen(
LaunchedEffect(listState) { LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemIndex } snapshotFlow { listState.firstVisibleItemIndex }
.debounce(250L) .debounce(250L.milliseconds)
.collectLatest(viewModel::setScrollIndex) .collectLatest(viewModel::setScrollIndex)
} }
LaunchedEffect(listState) { LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemScrollOffset } snapshotFlow { listState.firstVisibleItemScrollOffset }
.debounce(250L) .debounce(250L.milliseconds)
.collectLatest(viewModel::setScrollOffset) .collectLatest(viewModel::setScrollOffset)
} }
@@ -9,12 +9,11 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryTabRow import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
@@ -34,7 +33,6 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -47,11 +45,14 @@ import dev.meloda.fast.model.BaseError
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.components.ActionInvokeDismiss import dev.meloda.fast.ui.components.ActionInvokeDismiss
import dev.meloda.fast.ui.components.MaterialDialog import dev.meloda.fast.ui.components.MaterialDialog
import dev.meloda.fast.ui.components.SegmentedButtonItem
import dev.meloda.fast.ui.components.SegmentedButtonsRow
import dev.meloda.fast.ui.components.SelectionType import dev.meloda.fast.ui.components.SelectionType
import dev.meloda.fast.ui.model.TabItem import dev.meloda.fast.ui.model.TabItem
import dev.meloda.fast.ui.theme.LocalHazeState import dev.meloda.fast.ui.theme.LocalHazeState
import dev.meloda.fast.ui.theme.LocalThemeConfig import dev.meloda.fast.ui.theme.LocalThemeConfig
import dev.meloda.fast.ui.util.ImmutableList import dev.meloda.fast.ui.util.ImmutableList
import dev.meloda.fast.ui.util.buildImmutableList
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class) @OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class)
@@ -189,16 +190,24 @@ fun FriendsRoute(
), ),
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
actions = { actions = {
IconButton( val items = buildImmutableList {
onClick = { add(
showOrderDialog = true SegmentedButtonItem(
} "filter",
) { R.drawable.ic_filter_list_round_24
Icon( )
painter = painterResource(R.drawable.ic_filter_list_round_24),
contentDescription = null
) )
} }
SegmentedButtonsRow(
modifier = Modifier.padding(end = 8.dp),
items = items,
onClick = { index ->
when (items[index].key) {
"filter" -> showOrderDialog = true
}
}
)
} }
) )
PrimaryTabRow( PrimaryTabRow(
@@ -234,7 +243,6 @@ fun FriendsRoute(
orderType = orderType, orderType = orderType,
padding = padding, padding = padding,
tabIndex = index, tabIndex = index,
onSessionExpiredLogOutButtonClicked = { onError(BaseError.SessionExpired) },
onPhotoClicked = onPhotoClicked, onPhotoClicked = onPhotoClicked,
onMessageClicked = onMessageClicked, onMessageClicked = onMessageClicked,
setCanScrollBackward = { canScrollBackward = it }, setCanScrollBackward = { canScrollBackward = it },
@@ -19,7 +19,7 @@ interface MessagesHistoryViewModel {
val dialog: StateFlow<MessageDialog?> val dialog: StateFlow<MessageDialog?>
val selectedMessages: StateFlow<List<VkMessage>> val selectedMessages: StateFlow<List<VkMessage>>
val inputFieldFocusRequester: StateFlow<Boolean> val showKeyboard: StateFlow<Boolean>
val isNeedToScrollToIndex: StateFlow<Int?> val isNeedToScrollToIndex: StateFlow<Int?>
@@ -54,6 +54,7 @@ interface MessagesHistoryViewModel {
fun onPinnedMessageClicked(messageId: Long) fun onPinnedMessageClicked(messageId: Long)
fun onUnpinMessageClicked() fun onUnpinMessageClicked()
fun onEditSelectedMessageClicked()
fun onDeleteSelectedMessagesClicked() fun onDeleteSelectedMessagesClicked()
fun onBoldClicked() fun onBoldClicked()
@@ -66,5 +67,7 @@ interface MessagesHistoryViewModel {
fun onRequestReplyToMessage(cmId: Long) fun onRequestReplyToMessage(cmId: Long)
fun onKeyboardShown()
suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int
} }
@@ -45,6 +45,7 @@ import dev.meloda.fast.domain.MessagesUseCase
import dev.meloda.fast.domain.util.asPresentation import dev.meloda.fast.domain.util.asPresentation
import dev.meloda.fast.domain.util.extractAvatar import dev.meloda.fast.domain.util.extractAvatar
import dev.meloda.fast.domain.util.extractReplySummary import dev.meloda.fast.domain.util.extractReplySummary
import dev.meloda.fast.domain.util.extractReplyTitle
import dev.meloda.fast.domain.util.extractTitle import dev.meloda.fast.domain.util.extractTitle
import dev.meloda.fast.messageshistory.model.ActionMode import dev.meloda.fast.messageshistory.model.ActionMode
import dev.meloda.fast.messageshistory.model.MessageDialog import dev.meloda.fast.messageshistory.model.MessageDialog
@@ -55,7 +56,6 @@ import dev.meloda.fast.messageshistory.navigation.MessagesHistory
import dev.meloda.fast.model.BaseError import dev.meloda.fast.model.BaseError
import dev.meloda.fast.model.LongPollParsedEvent import dev.meloda.fast.model.LongPollParsedEvent
import dev.meloda.fast.model.api.domain.FormatDataType import dev.meloda.fast.model.api.domain.FormatDataType
import dev.meloda.fast.model.api.domain.VkAttachment
import dev.meloda.fast.model.api.domain.VkMessage import dev.meloda.fast.model.api.domain.VkMessage
import dev.meloda.fast.model.api.domain.VkPhotoDomain import dev.meloda.fast.model.api.domain.VkPhotoDomain
import dev.meloda.fast.network.VkErrorCode import dev.meloda.fast.network.VkErrorCode
@@ -65,6 +65,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.serialization.json.add import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonArray
@@ -73,7 +74,6 @@ import kotlinx.serialization.json.put
import java.io.File import java.io.File
import java.io.FileOutputStream import java.io.FileOutputStream
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.math.abs import kotlin.math.abs
import kotlin.random.Random import kotlin.random.Random
@@ -94,7 +94,7 @@ class MessagesHistoryViewModelImpl(
override val dialog = MutableStateFlow<MessageDialog?>(null) override val dialog = MutableStateFlow<MessageDialog?>(null)
override val selectedMessages = MutableStateFlow<List<VkMessage>>(emptyList()) override val selectedMessages = MutableStateFlow<List<VkMessage>>(emptyList())
override val inputFieldFocusRequester = MutableStateFlow(false) override val showKeyboard = MutableStateFlow(false)
override val isNeedToScrollToIndex = MutableStateFlow<Int?>(null) override val isNeedToScrollToIndex = MutableStateFlow<Int?>(null)
@@ -115,6 +115,8 @@ class MessagesHistoryViewModelImpl(
private var replyToCmId: Long? = null private var replyToCmId: Long? = null
private var editMessage: VkMessage? = null
init { init {
val arguments = MessagesHistory.from(savedStateHandle).arguments val arguments = MessagesHistory.from(savedStateHandle).arguments
@@ -229,7 +231,7 @@ class MessagesHistoryViewModelImpl(
override fun onDialogItemPicked(dialog: MessageDialog, bundle: Bundle) { override fun onDialogItemPicked(dialog: MessageDialog, bundle: Bundle) {
when (dialog) { when (dialog) {
is MessageDialog.MessageOptions -> { is MessageDialog.MessageOptions -> {
val messageId = bundle.getLong("messageId") // val messageId = bundle.getLong("messageId")
val cmId = bundle.getLong("cmId") val cmId = bundle.getLong("cmId")
when (val option = bundle.getParcelableCompat("option", MessageOption::class)) { when (val option = bundle.getParcelableCompat("option", MessageOption::class)) {
@@ -289,7 +291,10 @@ class MessagesHistoryViewModelImpl(
} }
} }
MessageOption.Edit -> {} MessageOption.Edit -> {
editMessage(cmId)
syncUiMessages()
}
MessageOption.Delete -> { MessageOption.Delete -> {
this.dialog.setValue { this.dialog.setValue {
@@ -313,7 +318,14 @@ class MessagesHistoryViewModelImpl(
} }
override fun onCloseButtonClicked() { override fun onCloseButtonClicked() {
selectedMessages.setValue { emptyList() } if (selectedMessages.value.isNotEmpty()) {
selectedMessages.setValue { emptyList() }
}
if (screenState.value.editCmId != null) {
stopEditMessage()
}
syncUiMessages() syncUiMessages()
} }
@@ -329,8 +341,20 @@ class MessagesHistoryViewModelImpl(
screenState.setValue { old -> screenState.setValue { old ->
old.copy( old.copy(
message = newText, message = newText,
actionMode = if (newText.text.isBlank()) ActionMode.RECORD_AUDIO actionMode =
else ActionMode.SEND when {
screenState.value.editCmId != null -> {
// TODO: 13/03/2026, Danil Nikolaev: also check if attachments is empty
if (newText.text.trim().isEmpty()) {
ActionMode.DELETE
} else {
ActionMode.EDIT
}
}
newText.text.trim().isEmpty() -> ActionMode.RECORD_AUDIO
else -> ActionMode.SEND
}
) )
} }
updateStyles() updateStyles()
@@ -347,13 +371,9 @@ class MessagesHistoryViewModelImpl(
override fun onActionButtonClicked() { override fun onActionButtonClicked() {
when (screenState.value.actionMode) { when (screenState.value.actionMode) {
ActionMode.DELETE -> { ActionMode.DELETE -> confirmDeleteCurrentEditMessage()
} ActionMode.EDIT -> editCurrentEditMessage()
ActionMode.EDIT -> {
}
ActionMode.RECORD_AUDIO -> { ActionMode.RECORD_AUDIO -> {
screenState.setValue { it.copy(actionMode = ActionMode.RECORD_VIDEO) } screenState.setValue { it.copy(actionMode = ActionMode.RECORD_VIDEO) }
@@ -429,6 +449,16 @@ class MessagesHistoryViewModelImpl(
} }
} }
override fun onEditSelectedMessageClicked() {
val cmId = selectedMessages.value.firstOrNull()?.cmId ?: return
selectedMessages.setValue { emptyList() }
editMessage(cmId)
syncUiMessages()
}
override fun onDeleteSelectedMessagesClicked() { override fun onDeleteSelectedMessagesClicked() {
dialog.setValue { dialog.setValue {
MessageDialog.MessagesDelete(selectedMessages.value) MessageDialog.MessagesDelete(selectedMessages.value)
@@ -438,7 +468,7 @@ class MessagesHistoryViewModelImpl(
private fun replyToMessage(cmId: Long) { private fun replyToMessage(cmId: Long) {
val messageToReply = messages.value.find { it.cmId == cmId } ?: return val messageToReply = messages.value.find { it.cmId == cmId } ?: return
inputFieldFocusRequester.setValue { true } showKeyboard.setValue { true }
replyToCmId = cmId replyToCmId = cmId
screenState.setValue { old -> screenState.setValue { old ->
old.copy( old.copy(
@@ -448,6 +478,56 @@ class MessagesHistoryViewModelImpl(
} }
} }
private fun editMessage(cmId: Long) {
this.screenState.setValue { old ->
old.copy(editCmId = cmId)
}
val messageToEdit = messages.value.firstOrNull { it.cmId == cmId } ?: return
editMessage = messageToEdit
lastMessageText = screenState.value.message.text
var newState = screenState.value.copy(
message = TextFieldValue(
text = messageToEdit.text.orEmpty(),
selection = TextRange(messageToEdit.text.orEmpty().length)
),
actionMode = ActionMode.EDIT
)
messageToEdit.replyMessage?.let { reply ->
replyToCmId = reply.cmId
newState = newState.copy(
replyTitle = reply.extractReplyTitle(),
replyText = reply.extractReplySummary(resourceProvider.resources)
)
}
showKeyboard.setValue { true }
screenState.setValue { newState }
}
private fun stopEditMessage() {
val lastText = lastMessageText.orEmpty().trim()
screenState.setValue { old ->
old.copy(
editCmId = null,
message = TextFieldValue(
text = lastText,
selection = TextRange(lastText.length)
),
actionMode = if (lastText.isBlank()) ActionMode.RECORD_AUDIO
else ActionMode.SEND,
// TODO: 13/03/2026, Danil Nikolaev: use last reply
replyTitle = null,
replyText = null
)
}
}
private var formatData = VkMessage.FormatData("1", emptyList()) private var formatData = VkMessage.FormatData("1", emptyList())
private fun updateStyles() { private fun updateStyles() {
@@ -580,23 +660,28 @@ class MessagesHistoryViewModelImpl(
replyToMessage(cmId) replyToMessage(cmId)
} }
override suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int = suspendCoroutine { override fun onKeyboardShown() {
viewModelScope.launch { showKeyboard.setValue { false }
getMessageReadPeersUseCase
.invoke(peerId = peerId, cmId = cmId)
.listenValue(viewModelScope) { state ->
state.processState(
error = { error ->
it.resume(-1)
},
success = { count ->
it.resume(count)
}
)
}
}
} }
override suspend fun loadMessageReadPeers(peerId: Long, cmId: Long): Int =
suspendCancellableCoroutine {
viewModelScope.launch {
getMessageReadPeersUseCase
.invoke(peerId = peerId, cmId = cmId)
.listenValue(viewModelScope) { state ->
state.processState(
error = { error ->
it.resume(-1)
},
success = { count ->
it.resume(count)
}
)
}
}
}
private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) { private fun handleNewMessage(event: LongPollParsedEvent.NewMessage) {
val message = event.message val message = event.message
@@ -988,11 +1073,13 @@ class MessagesHistoryViewModelImpl(
message = newMessage.text, message = newMessage.text,
forward = forward, forward = forward,
attachments = null, attachments = null,
formatData = newMessage.formatData formatData = newMessage.formatData,
).listenValue(viewModelScope) { state -> ).listenValue(viewModelScope) { state ->
state.processState( state.processState(
any = { sendingMessages.remove(newMessage) }, any = { sendingMessages.remove(newMessage) },
error = { error -> error = { error ->
Log.d("MessagesHistoryViewModelImpl", "sendMessage: ERROR: $error")
val failedId = -500_000L - failedMessages.size val failedId = -500_000L - failedMessages.size
val newFailedMessage = newMessage.copy(id = failedId) val newFailedMessage = newMessage.copy(id = failedId)
failedMessages += newFailedMessage failedMessages += newFailedMessage
@@ -1015,6 +1102,51 @@ class MessagesHistoryViewModelImpl(
} }
} }
private fun confirmDeleteCurrentEditMessage() {
val currentMessage = editMessage ?: return
this.dialog.setValue {
MessageDialog.MessageDelete(currentMessage)
}
}
private fun editCurrentEditMessage() {
replyToCmId = null
val newText = screenState.value.message.text
val lastText = lastMessageText.orEmpty().trim()
screenState.setValue { old ->
old.copy(
editCmId = null,
message = TextFieldValue(
text = lastText,
selection = TextRange(lastText.length)
),
actionMode = if (lastText.isBlank()) ActionMode.RECORD_AUDIO
else ActionMode.SEND,
// TODO: 13/03/2026, Danil Nikolaev: save last reply
replyTitle = null,
replyText = null
)
}
syncUiMessages()
// TODO: 13/03/2026, Danil Nikolaev: actually edit message
val newMessage = editMessage?.copy(
replyMessage = if (replyToCmId == null) null else editMessage?.replyMessage,
text = newText
) ?: return
// TODO: 13/03/2026, Danil Nikolaev: check if message is exact same, then do not edit
Log.d("MessagesHistoryViewModelImpl", "editMessage: $newMessage")
}
private fun markAsImportant( private fun markAsImportant(
messageIds: List<Long>, messageIds: List<Long>,
important: Boolean, important: Boolean,
@@ -1118,29 +1250,6 @@ class MessagesHistoryViewModelImpl(
} }
} }
fun editMessage(
originalMessage: VkMessage,
peerid: Long,
messageid: Long,
newText: String? = null,
attachments: List<VkAttachment>? = null,
) {
viewModelScope.launch(Dispatchers.IO) {
// sendRequest {
// messagesRepository.edit(
// MessagesEditRequest(
// peerId = peerId,
// messageId = messageId,
// message = newText,
// attachments = attachments
// )
// )
// } ?: return@launch
// TODO: 25.08.2023, Danil Nikolaev: update message
}
}
private fun readMessage(message: VkMessage) { private fun readMessage(message: VkMessage) {
messagesUseCase.markAsRead( messagesUseCase.markAsRead(
peerId = screenState.value.convoId, peerId = screenState.value.convoId,
@@ -1237,7 +1346,8 @@ class MessagesHistoryViewModelImpl(
nextMessage = messages.getOrNull(index - 1), nextMessage = messages.getOrNull(index - 1),
showTimeInActionMessages = AppSettings.Experimental.showTimeInActionMessages, showTimeInActionMessages = AppSettings.Experimental.showTimeInActionMessages,
convo = screenState.value.convo, convo = screenState.value.convo,
isSelected = selectedMessages.indexOfFirstOrNull { it.id == message.id } != null isSelected = screenState.value.editCmId == message.cmId ||
selectedMessages.indexOfFirstOrNull { it.id == message.id } != null
) )
} }
uiMessages.setValue { newUiMessages } uiMessages.setValue { newUiMessages }
@@ -26,7 +26,8 @@ data class MessagesHistoryScreenState(
val pinnedTitle: String?, val pinnedTitle: String?,
val pinnedSummary: AnnotatedString?, val pinnedSummary: AnnotatedString?,
val replyTitle: String?, val replyTitle: String?,
val replyText: AnnotatedString? val replyText: AnnotatedString?,
val editCmId: Long?,
) { ) {
companion object { companion object {
@@ -48,6 +49,7 @@ data class MessagesHistoryScreenState(
pinnedSummary = null, pinnedSummary = null,
replyTitle = null, replyTitle = null,
replyText = null, replyText = null,
editCmId = null,
) )
} }
} }
@@ -81,7 +81,7 @@ fun InputBar(
actionMode: ActionMode, actionMode: ActionMode,
replyTitle: String?, replyTitle: String?,
replyText: AnnotatedString?, replyText: AnnotatedString?,
inputFieldFocusRequester: Boolean, showKeyboard: Boolean,
onMessageInputChanged: (TextFieldValue) -> Unit = {}, onMessageInputChanged: (TextFieldValue) -> Unit = {},
onBoldRequested: () -> Unit = {}, onBoldRequested: () -> Unit = {},
onItalicRequested: () -> Unit = {}, onItalicRequested: () -> Unit = {},
@@ -92,7 +92,8 @@ fun InputBar(
onEmojiButtonLongClicked: () -> Unit = {}, onEmojiButtonLongClicked: () -> Unit = {},
onAttachmentButtonClicked: () -> Unit = {}, onAttachmentButtonClicked: () -> Unit = {},
onActionButtonClicked: () -> Unit = {}, onActionButtonClicked: () -> Unit = {},
onReplyCloseClicked: () -> Unit = {} onReplyCloseClicked: () -> Unit = {},
onKeyboardShown: () -> Unit
) { ) {
val view = LocalView.current val view = LocalView.current
val context = LocalContext.current val context = LocalContext.current
@@ -106,8 +107,9 @@ fun InputBar(
val focusRequester = remember { FocusRequester() } val focusRequester = remember { FocusRequester() }
LaunchedEffect(inputFieldFocusRequester) { LaunchedEffect(showKeyboard) {
if (inputFieldFocusRequester) { if (showKeyboard) {
onKeyboardShown()
focusRequester.requestFocus() focusRequester.requestFocus()
} }
} }
@@ -360,6 +362,7 @@ private fun InputBarPreview() {
actionMode = ActionMode.SEND, actionMode = ActionMode.SEND,
replyTitle = "Иннокентий Панфилович", replyTitle = "Иннокентий Панфилович",
replyText = "Ого, ром!".annotated(), replyText = "Ого, ром!".annotated(),
inputFieldFocusRequester = false showKeyboard = false,
onKeyboardShown = {}
) )
} }
@@ -29,7 +29,7 @@ fun MessagesHistoryRoute(
val baseError by viewModel.baseError.collectAsStateWithLifecycle() val baseError by viewModel.baseError.collectAsStateWithLifecycle()
val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle() val canPaginate by viewModel.canPaginate.collectAsStateWithLifecycle()
val scrollIndex by viewModel.isNeedToScrollToIndex.collectAsStateWithLifecycle() val scrollIndex by viewModel.isNeedToScrollToIndex.collectAsStateWithLifecycle()
val inputFieldFocusRequester by viewModel.inputFieldFocusRequester.collectAsStateWithLifecycle() val showKeyboard by viewModel.showKeyboard.collectAsStateWithLifecycle()
LaunchedEffect(navigationEvent) { LaunchedEffect(navigationEvent) {
val needToConsume = when (val navigation = navigationEvent) { val needToConsume = when (val navigation = navigationEvent) {
@@ -55,7 +55,7 @@ fun MessagesHistoryRoute(
canPaginate = canPaginate, canPaginate = canPaginate,
showEmojiButton = AppSettings.General.showEmojiButton, showEmojiButton = AppSettings.General.showEmojiButton,
showAttachmentButton = AppSettings.General.showAttachmentButton, showAttachmentButton = AppSettings.General.showAttachmentButton,
inputFieldFocusRequester = inputFieldFocusRequester, showKeyboard = showKeyboard,
onBack = onBack, onBack = onBack,
onClose = viewModel::onCloseButtonClicked, onClose = viewModel::onCloseButtonClicked,
onScrolledToIndex = viewModel::onScrolledToIndex, onScrolledToIndex = viewModel::onScrolledToIndex,
@@ -72,6 +72,7 @@ fun MessagesHistoryRoute(
onPhotoClicked = onNavigateToPhotoViewer, onPhotoClicked = onNavigateToPhotoViewer,
onPinnedMessageClicked = viewModel::onPinnedMessageClicked, onPinnedMessageClicked = viewModel::onPinnedMessageClicked,
onUnpinMessageButtonClicked = viewModel::onUnpinMessageClicked, onUnpinMessageButtonClicked = viewModel::onUnpinMessageClicked,
onEditSelectedMessageClicked = viewModel::onEditSelectedMessageClicked,
onDeleteSelectedButtonClicked = viewModel::onDeleteSelectedMessagesClicked, onDeleteSelectedButtonClicked = viewModel::onDeleteSelectedMessagesClicked,
onBoldRequested = viewModel::onBoldClicked, onBoldRequested = viewModel::onBoldClicked,
onItalicRequested = viewModel::onItalicClicked, onItalicRequested = viewModel::onItalicClicked,
@@ -80,6 +81,7 @@ fun MessagesHistoryRoute(
onRegularRequested = viewModel::onRegularClicked, onRegularRequested = viewModel::onRegularClicked,
onReplyCloseClicked = viewModel::onReplyCloseClicked, onReplyCloseClicked = viewModel::onReplyCloseClicked,
onRequestReplyToMessage = viewModel::onRequestReplyToMessage, onRequestReplyToMessage = viewModel::onRequestReplyToMessage,
onKeyboardShown = viewModel::onKeyboardShown
) )
HandleDialogs( HandleDialogs(
@@ -31,12 +31,14 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.view.HapticFeedbackConstantsCompat import androidx.core.view.HapticFeedbackConstantsCompat
import dev.chrisbanes.haze.HazeState import dev.chrisbanes.haze.HazeState
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
import dev.meloda.fast.common.model.UiImage
import dev.meloda.fast.data.UserConfig import dev.meloda.fast.data.UserConfig
import dev.meloda.fast.datastore.AppSettings import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.domain.util.indexOfMessageByCmId import dev.meloda.fast.domain.util.indexOfMessageByCmId
@@ -69,13 +71,14 @@ fun MessagesHistoryScreen(
canPaginate: Boolean = false, canPaginate: Boolean = false,
showEmojiButton: Boolean = false, showEmojiButton: Boolean = false,
showAttachmentButton: Boolean = false, showAttachmentButton: Boolean = false,
inputFieldFocusRequester: Boolean, showKeyboard: Boolean,
onBack: () -> Unit = {}, onBack: () -> Unit = {},
onClose: () -> Unit = {}, onClose: () -> Unit = {},
onScrolledToIndex: () -> Unit = {}, onScrolledToIndex: () -> Unit = {},
onSessionExpiredLogOutButtonClicked: () -> Unit = {}, onSessionExpiredLogOutButtonClicked: () -> Unit = {},
onTopBarClicked: () -> Unit = {}, onTopBarClicked: () -> Unit = {},
onRefresh: () -> Unit = {}, onRefresh: () -> Unit = {},
onEditSelectedMessageClicked: () -> Unit = {},
onPaginationConditionsMet: () -> Unit = {}, onPaginationConditionsMet: () -> Unit = {},
onMessageInputChanged: (TextFieldValue) -> Unit = {}, onMessageInputChanged: (TextFieldValue) -> Unit = {},
onAttachmentButtonClicked: () -> Unit = {}, onAttachmentButtonClicked: () -> Unit = {},
@@ -93,7 +96,8 @@ fun MessagesHistoryScreen(
onUnderlineRequested: () -> Unit = {}, onUnderlineRequested: () -> Unit = {},
onRegularRequested: () -> Unit = {}, onRegularRequested: () -> Unit = {},
onReplyCloseClicked: () -> Unit = {}, onReplyCloseClicked: () -> Unit = {},
onRequestReplyToMessage: (cmId: Long) -> Unit = {} onRequestReplyToMessage: (cmId: Long) -> Unit = {},
onKeyboardShown: () -> Unit
) { ) {
val context = LocalContext.current val context = LocalContext.current
val view = LocalView.current val view = LocalView.current
@@ -114,7 +118,7 @@ fun MessagesHistoryScreen(
} }
BackHandler( BackHandler(
enabled = selectedMessages.isNotEmpty(), enabled = selectedMessages.isNotEmpty() || screenState.editCmId != null,
onBack = onClose onBack = onClose
) )
@@ -162,6 +166,9 @@ fun MessagesHistoryScreen(
derivedStateOf { selectedMessages.size == 1 } derivedStateOf { selectedMessages.size == 1 }
} }
val isLoadingText = stringResource(R.string.title_loading)
val editMessageText = stringResource(R.string.title_edit_message)
Scaffold( Scaffold(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
contentWindowInsets = WindowInsets.statusBars, contentWindowInsets = WindowInsets.statusBars,
@@ -169,7 +176,8 @@ fun MessagesHistoryScreen(
val topBarTitle by remember(screenState, selectedMessages) { val topBarTitle by remember(screenState, selectedMessages) {
derivedStateOf { derivedStateOf {
when { when {
screenState.isLoading -> context.getString(R.string.title_loading) screenState.isLoading -> isLoadingText
screenState.editCmId != null -> editMessageText
selectedMessages.isNotEmpty() -> "(${selectedMessages.size})" selectedMessages.isNotEmpty() -> "(${selectedMessages.size})"
else -> screenState.title else -> screenState.title
} }
@@ -179,13 +187,16 @@ fun MessagesHistoryScreen(
MessagesHistoryTopBarContainer( MessagesHistoryTopBarContainer(
hazeState = hazeState, hazeState = hazeState,
showReplyAction = showReplyAction, showReplyAction = showReplyAction,
showEditAction = selectedMessages.size == 1,
topBarContainerColor = topBarContainerColor, topBarContainerColor = topBarContainerColor,
topBarContainerColorAlpha = topBarContainerColorAlpha, topBarContainerColorAlpha = topBarContainerColorAlpha,
isClickable = !(screenState.isLoading && messages.isEmpty()), isClickable = !(screenState.isLoading && messages.isEmpty()),
isMessagesSelecting = selectedMessages.isNotEmpty(), isMessagesSelecting = selectedMessages.isNotEmpty(),
isPeerAccount = screenState.convoId == UserConfig.userId, isPeerAccount = screenState.convoId == UserConfig.userId,
avatar = screenState.avatar, avatarUrl = screenState.avatar.takeIf { it is UiImage.Url }?.extractUrl(),
avatarResourceId = screenState.avatar.takeIf { it is UiImage.Resource }?.extractResId(),
title = topBarTitle, title = topBarTitle,
isEditing = screenState.editCmId != null,
showHorizontalProgressBar = screenState.isLoading && messages.isNotEmpty(), showHorizontalProgressBar = screenState.isLoading && messages.isNotEmpty(),
showPinnedContainer = !screenState.isLoading && pinnedMessage != null, showPinnedContainer = !screenState.isLoading && pinnedMessage != null,
pinnedMessage = pinnedMessage, pinnedMessage = pinnedMessage,
@@ -196,6 +207,7 @@ fun MessagesHistoryScreen(
onBack = onBack, onBack = onBack,
onClose = onClose, onClose = onClose,
onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked, onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked,
onEditSelectedMessageClicked = onEditSelectedMessageClicked,
onRefresh = onRefresh, onRefresh = onRefresh,
onPinnedMessageClicked = onPinnedMessageClicked, onPinnedMessageClicked = onPinnedMessageClicked,
onUnpinMessageButtonClicked = onUnpinMessageButtonClicked onUnpinMessageButtonClicked = onUnpinMessageButtonClicked
@@ -211,6 +223,7 @@ fun MessagesHistoryScreen(
) { ) {
MessagesList( MessagesList(
modifier = Modifier.align(Alignment.BottomStart), modifier = Modifier.align(Alignment.BottomStart),
screenState = screenState,
hazeState = hazeState, hazeState = hazeState,
listState = listState, listState = listState,
hasPinnedMessage = pinnedMessage != null, hasPinnedMessage = pinnedMessage != null,
@@ -259,12 +272,13 @@ fun MessagesHistoryScreen(
actionMode = screenState.actionMode, actionMode = screenState.actionMode,
replyTitle = screenState.replyTitle, replyTitle = screenState.replyTitle,
replyText = screenState.replyText, replyText = screenState.replyText,
inputFieldFocusRequester = inputFieldFocusRequester, showKeyboard = showKeyboard,
onSetMessageBarHeight = { messageBarHeight = it }, onSetMessageBarHeight = { messageBarHeight = it },
onEmojiButtonLongClicked = onEmojiButtonLongClicked, onEmojiButtonLongClicked = onEmojiButtonLongClicked,
onAttachmentButtonClicked = onAttachmentButtonClicked, onAttachmentButtonClicked = onAttachmentButtonClicked,
onActionButtonClicked = onActionButtonClicked, onActionButtonClicked = onActionButtonClicked,
onReplyCloseClicked = onReplyCloseClicked onReplyCloseClicked = onReplyCloseClicked,
onKeyboardShown = onKeyboardShown
) )
when { when {
@@ -2,6 +2,7 @@ package dev.meloda.fast.messageshistory.presentation
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade import androidx.compose.animation.Crossfade
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
@@ -31,7 +32,6 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -44,11 +44,9 @@ import dev.chrisbanes.haze.HazeState
import dev.chrisbanes.haze.hazeEffect import dev.chrisbanes.haze.hazeEffect
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
import dev.chrisbanes.haze.materials.HazeMaterials import dev.chrisbanes.haze.materials.HazeMaterials
import dev.meloda.fast.common.model.UiImage
import dev.meloda.fast.datastore.AppSettings import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.theme.LocalThemeConfig import dev.meloda.fast.ui.theme.LocalThemeConfig
import dev.meloda.fast.ui.util.getImage
@OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class) @OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class)
@Composable @Composable
@@ -56,16 +54,20 @@ fun MessagesHistoryTopBar(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
hazeState: HazeState, hazeState: HazeState,
showReplyAction: Boolean, showReplyAction: Boolean,
showEditAction: Boolean,
isClickable: Boolean, isClickable: Boolean,
isMessagesSelecting: Boolean, isMessagesSelecting: Boolean,
isPeerAccount: Boolean, isPeerAccount: Boolean,
avatar: UiImage, avatarUrl: String?,
avatarResourceId: Int?,
title: String, title: String,
isEditing: Boolean,
onTopBarClicked: () -> Unit = {}, onTopBarClicked: () -> Unit = {},
onBack: () -> Unit = {}, onBack: () -> Unit = {},
onClose: () -> Unit = {}, onClose: () -> Unit = {},
onDeleteSelectedButtonClicked: () -> Unit = {}, onDeleteSelectedButtonClicked: () -> Unit = {},
onRefresh: () -> Unit = {} onRefresh: () -> Unit = {},
onEditSelectedMessageClicked: () -> Unit = {}
) { ) {
val view = LocalView.current val view = LocalView.current
val theme = LocalThemeConfig.current val theme = LocalThemeConfig.current
@@ -96,50 +98,55 @@ fun MessagesHistoryTopBar(
// modifier = Modifier.weight(1f), // modifier = Modifier.weight(1f),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
if (!isMessagesSelecting) { AnimatedVisibility(!isMessagesSelecting && !isEditing) {
if (isPeerAccount) { Row {
Box( if (isPeerAccount) {
modifier = Modifier Box(
.size(36.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primary)
) {
Icon(
modifier = Modifier
.align(Alignment.Center)
.size(24.dp),
painter = painterResource(id = R.drawable.ic_bookmark_round_24),
contentDescription = "Favorites icon",
tint = MaterialTheme.colorScheme.onPrimary
)
}
} else {
val actualAvatar = avatar.getImage()
if (actualAvatar is Painter) {
Image(
painter = actualAvatar,
contentDescription = null,
modifier = Modifier modifier = Modifier
.size(36.dp) .size(36.dp)
.clip(CircleShape) .clip(CircleShape)
) .background(MaterialTheme.colorScheme.primary)
) {
Icon(
modifier = Modifier
.align(Alignment.Center)
.size(24.dp),
painter = painterResource(id = R.drawable.ic_bookmark_round_24),
contentDescription = "Favorites icon",
tint = MaterialTheme.colorScheme.onPrimary
)
}
} else { } else {
AsyncImage( when {
model = actualAvatar, avatarUrl != null -> {
contentDescription = "Profile Image", AsyncImage(
modifier = Modifier model = avatarUrl,
.size(36.dp) contentDescription = "Profile Image",
.clip(CircleShape), modifier = Modifier
placeholder = painterResource(id = R.drawable.ic_account_circle_fill_round_24), .size(36.dp)
) .clip(CircleShape),
} placeholder = painterResource(id = R.drawable.ic_account_circle_fill_round_24),
} )
}
Spacer(modifier = Modifier.width(12.dp)) avatarResourceId != null -> {
Image(
painter = painterResource(avatarResourceId),
contentDescription = null,
modifier = Modifier
.size(36.dp)
.clip(CircleShape)
)
}
}
}
Spacer(modifier = Modifier.width(12.dp))
}
} }
Text( Text(
modifier = Modifier.animateContentSize(),
text = title, text = title,
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
@@ -150,11 +157,11 @@ fun MessagesHistoryTopBar(
navigationIcon = { navigationIcon = {
IconButton( IconButton(
onClick = { onClick = {
if (!isMessagesSelecting) onBack() if (!isMessagesSelecting && !isEditing) onBack()
else onClose() else onClose()
} }
) { ) {
Crossfade(targetState = !isMessagesSelecting) { state -> Crossfade(targetState = !isMessagesSelecting && !isEditing) { state ->
Icon( Icon(
painter = painterResource( painter = painterResource(
if (state) { if (state) {
@@ -210,6 +217,16 @@ fun MessagesHistoryTopBar(
contentDescription = null contentDescription = null
) )
} }
AnimatedVisibility(showEditAction) {
IconButton(onClick = onEditSelectedMessageClicked) {
Icon(
painter = painterResource(R.drawable.ic_edit_round_24),
contentDescription = null
)
}
}
IconButton(onClick = onDeleteSelectedButtonClicked) { IconButton(onClick = onDeleteSelectedButtonClicked) {
Icon( Icon(
painter = painterResource(R.drawable.ic_delete_round_24), painter = painterResource(R.drawable.ic_delete_round_24),
@@ -16,7 +16,6 @@ import dev.chrisbanes.haze.hazeEffect
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
import dev.chrisbanes.haze.materials.HazeMaterials import dev.chrisbanes.haze.materials.HazeMaterials
import dev.meloda.fast.common.extensions.orDots import dev.meloda.fast.common.extensions.orDots
import dev.meloda.fast.common.model.UiImage
import dev.meloda.fast.model.api.domain.VkMessage import dev.meloda.fast.model.api.domain.VkMessage
import dev.meloda.fast.ui.theme.LocalThemeConfig import dev.meloda.fast.ui.theme.LocalThemeConfig
@@ -26,13 +25,16 @@ fun MessagesHistoryTopBarContainer(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
hazeState: HazeState, hazeState: HazeState,
showReplyAction: Boolean, showReplyAction: Boolean,
showEditAction: Boolean,
topBarContainerColor: Color, topBarContainerColor: Color,
topBarContainerColorAlpha: Float, topBarContainerColorAlpha: Float,
isClickable: Boolean, isClickable: Boolean,
isMessagesSelecting: Boolean, isMessagesSelecting: Boolean,
isPeerAccount: Boolean, isPeerAccount: Boolean,
avatar: UiImage, avatarUrl: String?,
avatarResourceId: Int?,
title: String, title: String,
isEditing: Boolean,
showHorizontalProgressBar: Boolean, showHorizontalProgressBar: Boolean,
showPinnedContainer: Boolean, showPinnedContainer: Boolean,
pinnedMessage: VkMessage?, pinnedMessage: VkMessage?,
@@ -44,6 +46,7 @@ fun MessagesHistoryTopBarContainer(
onClose: () -> Unit = {}, onClose: () -> Unit = {},
onDeleteSelectedButtonClicked: () -> Unit = {}, onDeleteSelectedButtonClicked: () -> Unit = {},
onRefresh: () -> Unit = {}, onRefresh: () -> Unit = {},
onEditSelectedMessageClicked: () -> Unit = {},
onPinnedMessageClicked: (Long) -> Unit = {}, onPinnedMessageClicked: (Long) -> Unit = {},
onUnpinMessageButtonClicked: () -> Unit = {} onUnpinMessageButtonClicked: () -> Unit = {}
) { ) {
@@ -66,16 +69,20 @@ fun MessagesHistoryTopBarContainer(
modifier = modifier, modifier = modifier,
hazeState = hazeState, hazeState = hazeState,
showReplyAction = showReplyAction, showReplyAction = showReplyAction,
showEditAction = showEditAction,
isClickable = isClickable, isClickable = isClickable,
isMessagesSelecting = isMessagesSelecting, isMessagesSelecting = isMessagesSelecting,
isPeerAccount = isPeerAccount, isPeerAccount = isPeerAccount,
avatar = avatar, avatarUrl = avatarUrl,
avatarResourceId = avatarResourceId,
title = title, title = title,
isEditing = isEditing,
onTopBarClicked = onTopBarClicked, onTopBarClicked = onTopBarClicked,
onBack = onBack, onBack = onBack,
onClose = onClose, onClose = onClose,
onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked, onDeleteSelectedButtonClicked = onDeleteSelectedButtonClicked,
onRefresh = onRefresh onRefresh = onRefresh,
onEditSelectedMessageClicked = onEditSelectedMessageClicked
) )
if (showHorizontalProgressBar) { if (showHorizontalProgressBar) {
@@ -46,6 +46,7 @@ import androidx.core.view.HapticFeedbackConstantsCompat
import dev.chrisbanes.haze.HazeState import dev.chrisbanes.haze.HazeState
import dev.chrisbanes.haze.hazeSource import dev.chrisbanes.haze.hazeSource
import dev.meloda.fast.datastore.AppSettings import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
import dev.meloda.fast.model.api.domain.VkAttachment import dev.meloda.fast.model.api.domain.VkAttachment
import dev.meloda.fast.model.api.domain.VkFileDomain import dev.meloda.fast.model.api.domain.VkFileDomain
import dev.meloda.fast.model.api.domain.VkLinkDomain import dev.meloda.fast.model.api.domain.VkLinkDomain
@@ -60,6 +61,7 @@ import kotlinx.coroutines.launch
@Composable @Composable
fun MessagesList( fun MessagesList(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
screenState: MessagesHistoryScreenState,
hasPinnedMessage: Boolean, hasPinnedMessage: Boolean,
hazeState: HazeState, hazeState: HazeState,
listState: LazyListState, listState: LazyListState,
@@ -226,47 +228,55 @@ fun MessagesList(
fadeOutSpec = null fadeOutSpec = null
) else Modifier ) else Modifier
) )
.combinedClickable( .then(
onLongClick = { if (screenState.editCmId == null) {
if (AppSettings.General.enableHaptic) { Modifier
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) .combinedClickable(
} onLongClick = {
onMessageLongClicked(item.id) if (AppSettings.General.enableHaptic) {
}, view.performHapticFeedback(
onClick = { onMessageClicked(item.id) } HapticFeedbackConstants.LONG_PRESS
) )
.pointerInput(item.cmId) { }
detectHorizontalDragGestures( onMessageLongClicked(item.id)
onDragCancel = { },
if (offsetX == -100f) { onClick = { onMessageClicked(item.id) }
onRequestMessageReply(item.cmId) )
} .pointerInput(item.cmId) {
detectHorizontalDragGestures(
onDragCancel = {
if (offsetX == -100f) {
onRequestMessageReply(item.cmId)
}
scope.launch { scope.launch {
animate = true animate = true
offsetX = 0f offsetX = 0f
offsetAnimatable.animateTo(0f) offsetAnimatable.animateTo(0f)
animate = false animate = false
} }
}, },
onDragEnd = { onDragEnd = {
if (offsetX == -100f) { if (offsetX == -100f) {
onRequestMessageReply(item.cmId) onRequestMessageReply(item.cmId)
} }
scope.launch { scope.launch {
animate = true animate = true
offsetX = 0f offsetX = 0f
offsetAnimatable.animateTo(0f) offsetAnimatable.animateTo(0f)
animate = false animate = false
}
},
onHorizontalDrag = { change, dragAmount ->
change.consume()
offsetX =
(offsetX + dragAmount).coerceIn(-100f, 0f)
}
)
} }
}, } else Modifier
onHorizontalDrag = { change, dragAmount -> ),
change.consume()
offsetX = (offsetX + dragAmount).coerceIn(-100f, 0f)
}
)
},
color = backgroundColor color = backgroundColor
) { ) {
if (item.isOut) { if (item.isOut) {
@@ -119,12 +119,15 @@ fun Attachments(
AttachmentType.STICKER -> { AttachmentType.STICKER -> {
Sticker( Sticker(
item = attachment as VkStickerDomain url = (attachment as VkStickerDomain).getUrl(
width = 256,
withBackground = false
)
) )
} }
AttachmentType.GIFT -> { AttachmentType.GIFT -> {
Gift(item = attachment as VkGiftDomain) Gift(url = (attachment as VkGiftDomain).getDefaultThumbSizeOrLess())
} }
AttachmentType.VIDEO_MESSAGE -> { AttachmentType.VIDEO_MESSAGE -> {
@@ -21,25 +21,24 @@ import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage import coil.compose.AsyncImage
import dev.meloda.fast.model.api.domain.VkGiftDomain
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
@Composable @Composable
fun Gift( fun Gift(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
item: VkGiftDomain url: String
) { ) {
Column( Column(
modifier = modifier.width(192.dp), modifier = modifier
.width(208.dp)
.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp) verticalArrangement = Arrangement.spacedBy(4.dp)
) { ) {
AsyncImage( AsyncImage(
model = item.getDefaultThumbSizeOrLess(), model = url,
contentDescription = null, contentDescription = null,
contentScale = ContentScale.Crop, contentScale = ContentScale.Crop,
modifier = Modifier modifier = Modifier.size(192.dp)
.padding(8.dp)
.fillMaxWidth()
) )
Row( Row(
@@ -10,27 +10,23 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage import coil.compose.AsyncImage
import dev.meloda.fast.model.api.domain.VkStickerDomain
@Composable @Composable
fun Sticker( fun Sticker(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
item: VkStickerDomain url: String?
) { ) {
Box( Box(
modifier = modifier.size(192.dp), modifier = modifier
.size(208.dp)
.padding(8.dp),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
AsyncImage( AsyncImage(
model = item.getUrl( model = url,
width = 256,
withBackground = false
),
contentDescription = null, contentDescription = null,
contentScale = ContentScale.Crop, contentScale = ContentScale.Crop,
modifier = Modifier modifier = Modifier.fillMaxSize()
.padding(8.dp)
.fillMaxSize()
) )
} }
} }
@@ -5,49 +5,33 @@ import androidx.lifecycle.viewModelScope
import dev.meloda.fast.common.VkConstants import dev.meloda.fast.common.VkConstants
import dev.meloda.fast.common.extensions.listenValue import dev.meloda.fast.common.extensions.listenValue
import dev.meloda.fast.common.extensions.setValue import dev.meloda.fast.common.extensions.setValue
import dev.meloda.fast.data.State
import dev.meloda.fast.data.UserConfig import dev.meloda.fast.data.UserConfig
import dev.meloda.fast.data.processState import dev.meloda.fast.data.processState
import dev.meloda.fast.domain.GetLocalUserByIdUseCase import dev.meloda.fast.domain.GetLocalUserByIdUseCase
import dev.meloda.fast.domain.LoadUserByIdUseCase import dev.meloda.fast.domain.LoadUserByIdUseCase
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.network.VkErrorCode
import dev.meloda.fast.profile.model.ProfileScreenState import dev.meloda.fast.profile.model.ProfileScreenState
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
interface ProfileViewModel { class ProfileViewModel(
val screenState: StateFlow<ProfileScreenState>
val baseError: StateFlow<BaseError?>
}
class ProfileViewModelImpl(
private val getLocalUserByIdUseCase: GetLocalUserByIdUseCase, private val getLocalUserByIdUseCase: GetLocalUserByIdUseCase,
private val loadUserByIdUseCase: LoadUserByIdUseCase private val loadUserByIdUseCase: LoadUserByIdUseCase
) : ViewModel(), ProfileViewModel { ) : ViewModel() {
override val screenState = MutableStateFlow(ProfileScreenState.EMPTY) private val screenState = MutableStateFlow(ProfileScreenState.EMPTY)
override val baseError = MutableStateFlow<BaseError?>(null)
init { init {
getLocalAccountInfo() getLocalAccountInfo()
} }
fun screenStateFlow(): StateFlow<ProfileScreenState> = screenState.asStateFlow()
private fun getLocalAccountInfo() { private fun getLocalAccountInfo() {
getLocalUserByIdUseCase(UserConfig.userId) getLocalUserByIdUseCase(UserConfig.userId)
.listenValue(viewModelScope) { state -> .listenValue(viewModelScope) { state ->
state.processState( state.processState(
error = { error -> error = {
if (error is State.Error.ApiError) {
when (error.errorCode) {
VkErrorCode.USER_AUTHORIZATION_FAILED -> {
baseError.setValue { BaseError.SessionExpired }
}
else -> Unit
}
}
screenState.setValue { old -> screenState.setValue { old ->
old.copy( old.copy(
avatarUrl = null, avatarUrl = null,
@@ -1,9 +1,9 @@
package dev.meloda.fast.profile.di package dev.meloda.fast.profile.di
import dev.meloda.fast.profile.ProfileViewModelImpl import dev.meloda.fast.profile.ProfileViewModel
import org.koin.core.module.dsl.viewModelOf import org.koin.core.module.dsl.viewModelOf
import org.koin.dsl.module import org.koin.dsl.module
val profileModule = module { val profileModule = module {
viewModelOf(::ProfileViewModelImpl) viewModelOf(::ProfileViewModel)
} }
@@ -1,11 +1,11 @@
package dev.meloda.fast.profile.navigation package dev.meloda.fast.profile.navigation
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavGraphBuilder import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.profile.ProfileViewModel import dev.meloda.fast.profile.ProfileViewModel
import dev.meloda.fast.profile.ProfileViewModelImpl
import dev.meloda.fast.profile.presentation.ProfileRoute import dev.meloda.fast.profile.presentation.ProfileRoute
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import org.koin.androidx.viewmodel.ext.android.getViewModel import org.koin.androidx.viewmodel.ext.android.getViewModel
@@ -15,19 +15,18 @@ object Profile
fun NavGraphBuilder.profileScreen( fun NavGraphBuilder.profileScreen(
activity: AppCompatActivity, activity: AppCompatActivity,
onError: (BaseError) -> Unit,
onSettingsButtonClicked: () -> Unit, onSettingsButtonClicked: () -> Unit,
onPhotoClicked: (url: String) -> Unit onPhotoClicked: (url: String) -> Unit
) { ) {
val viewModel: ProfileViewModel = with(activity) { val viewModel: ProfileViewModel = with(activity) { getViewModel() }
getViewModel<ProfileViewModelImpl>()
}
composable<Profile> { composable<Profile> {
val screenState by viewModel.screenStateFlow().collectAsStateWithLifecycle()
ProfileRoute( ProfileRoute(
onError = onError, screenState = screenState,
onSettingsButtonClicked = onSettingsButtonClicked, onSettingsButtonClicked = onSettingsButtonClicked,
onPhotoClicked = onPhotoClicked, onPhotoClicked = onPhotoClicked,
viewModel = viewModel
) )
} }
} }
@@ -14,15 +14,12 @@ import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
@@ -31,28 +28,21 @@ import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage import coil.compose.AsyncImage
import dev.meloda.fast.model.BaseError
import dev.meloda.fast.profile.ProfileViewModel
import dev.meloda.fast.profile.ProfileViewModelImpl
import dev.meloda.fast.profile.model.ProfileScreenState import dev.meloda.fast.profile.model.ProfileScreenState
import dev.meloda.fast.ui.R import dev.meloda.fast.ui.R
import org.koin.androidx.compose.koinViewModel import dev.meloda.fast.ui.components.SegmentedButtonItem
import dev.meloda.fast.ui.components.SegmentedButtonsRow
import dev.meloda.fast.ui.util.buildImmutableList
@Composable @Composable
fun ProfileRoute( fun ProfileRoute(
onError: (BaseError) -> Unit, screenState: ProfileScreenState,
onSettingsButtonClicked: () -> Unit, onSettingsButtonClicked: () -> Unit,
onPhotoClicked: (url: String) -> Unit, onPhotoClicked: (url: String) -> Unit,
viewModel: ProfileViewModel = koinViewModel<ProfileViewModelImpl>()
) { ) {
val screenState by viewModel.screenState.collectAsStateWithLifecycle()
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
ProfileScreen( ProfileScreen(
screenState = screenState, screenState = screenState,
baseError = baseError,
onSettingsButtonClicked = onSettingsButtonClicked, onSettingsButtonClicked = onSettingsButtonClicked,
onPhotoClicked = onPhotoClicked onPhotoClicked = onPhotoClicked
) )
@@ -63,7 +53,6 @@ fun ProfileRoute(
@Composable @Composable
fun ProfileScreen( fun ProfileScreen(
screenState: ProfileScreenState = ProfileScreenState.EMPTY, screenState: ProfileScreenState = ProfileScreenState.EMPTY,
baseError: BaseError? = null,
onSettingsButtonClicked: () -> Unit = {}, onSettingsButtonClicked: () -> Unit = {},
onPhotoClicked: (url: String) -> Unit = {} onPhotoClicked: (url: String) -> Unit = {}
) { ) {
@@ -72,12 +61,19 @@ fun ProfileScreen(
TopAppBar( TopAppBar(
title = {}, title = {},
actions = { actions = {
IconButton(onClick = onSettingsButtonClicked) { val items = buildImmutableList {
Icon( add(SegmentedButtonItem("settings", R.drawable.ic_settings_round_24))
painter = painterResource(R.drawable.ic_settings_round_24),
contentDescription = null
)
} }
SegmentedButtonsRow(
modifier = Modifier.padding(end = 8.dp),
items = items,
onClick = { index ->
when (items[index].key) {
"settings" -> onSettingsButtonClicked()
}
}
)
}, },
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent) colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
) )
+25 -14
View File
@@ -1,35 +1,46 @@
[versions] [versions]
agp = "9.0.0" #noinspection UnusedVersionCatalogEntry
minSdk = "23"
#noinspection UnusedVersionCatalogEntry
compileSdk = "37"
#noinspection UnusedVersionCatalogEntry
targetSdk = "37"
agp = "9.2.0"
retrofit = "3.0.0" retrofit = "3.0.0"
eithernet = "2.0.0" eithernet = "2.0.0"
haze = "1.7.1" haze = "1.7.2"
kotlin = "2.3.10" kotlin = "2.3.21"
ksp = "2.3.4" ksp = "2.3.7"
moduleGraph = "2.9.0" moduleGraph = "2.9.1"
versions = "0.53.0" versions = "0.54.0"
stability-analyzer = "0.6.6" stability-analyzer = "0.7.5"
compose-bom = "2026.01.01" compose-bom = "2026.04.01"
koin = "4.1.1" koin = "4.2.1"
accompanist = "0.37.3" accompanist = "0.37.3"
coil = "2.7.0" coil = "2.7.0"
coroutines = "1.10.2" coroutines = "1.10.2"
junit = "4.13.2" junit = "4.13.2"
chucker = "4.3.0" chucker = "4.3.1"
guava = "33.5.0-jre" guava = "33.6.0-jre"
lifecycle = "2.10.0" lifecycle = "2.10.0"
core-ktx = "1.17.0" core-ktx = "1.18.0"
material = "1.13.0" material = "1.13.0"
loggingInterceptor = "5.3.2" loggingInterceptor = "5.3.2"
moshi = "1.15.2" moshi = "1.15.2"
room = "2.8.4" room = "2.8.4"
preference-ktx = "1.2.1" preference-ktx = "1.2.1"
nanokt = "1.3.0" nanokt = "1.3.0"
androidx-navigation = "2.9.6" androidx-navigation = "2.9.8"
serialization = "1.10.0" serialization = "1.11.0"
okhttp = "5.3.2"
[libraries] [libraries]
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version.ref = "accompanist" } accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version.ref = "accompanist" }
coil = { module = "io.coil-kt:coil", version.ref = "coil" } coil = { module = "io.coil-kt:coil", version.ref = "coil" }
coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coil" } coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coil" }
Binary file not shown.
+3 -1
View File
@@ -1,7 +1,9 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=10000 networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored Regular → Executable
+5 -9
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
# #
# Copyright © 2015-2021 the original authors. # Copyright © 2015 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -86,8 +86,7 @@ done
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -115,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;; NONSTOP* ) nonstop=true ;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@@ -173,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" ) JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -206,15 +203,14 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command: # Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped. # and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line. # treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available. # Stop when "xargs" is not available.
Vendored
+10 -22
View File
@@ -23,8 +23,8 @@
@rem @rem
@rem ########################################################################## @rem ##########################################################################
@rem Set local scope for the variables with windows NT shell @rem Set local scope for the variables, and ensure extensions are enabled
if "%OS%"=="Windows_NT" setlocal setlocal EnableExtensions
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@@ -51,7 +51,7 @@ echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2 echo location of your Java installation. 1>&2
goto fail "%COMSPEC%" /c exit 1
:findJavaFromJavaHome :findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
@@ -65,30 +65,18 @@ echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2 echo location of your Java installation. 1>&2
goto fail "%COMSPEC%" /c exit 1
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* @rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:end :exitWithErrorLevel
@rem End local scope for the variables with windows NT shell @rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
if %ERRORLEVEL% equ 0 goto mainEnd "%COMSPEC%" /c exit %ERRORLEVEL%
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega