From 02efbd466ec590321bb6805741c3b90d7e590aa9 Mon Sep 17 00:00:00 2001 From: Kharazi Date: Sun, 22 Nov 2026 15:23:44 +0330 Subject: [PATCH] feat(android): improve chat media playback and large file downloads Let people keep listening across conversations and watch a video while it downloads. Include the companion chat, sign-in, avatar and QA changes used with these features. Assisted-by: Codex:GPT-6 Signed-off-by: Hossein Kharazi --- app/build.gradle.kts | 28 +- app/proguard-plus-optimized.pro | 51 +++ .../talk/jobs/GetFirebasePushTokenWorker.kt | 0 .../firebase/NCFirebaseMessagingService.kt | 0 .../talk/utils/ClosedInterfaceImpl.kt | 0 app/src/main/AndroidManifest.xml | 6 +- .../talk/account/BrowserLoginActivity.kt | 24 +- .../talk/account/data/LoginRepository.kt | 2 +- .../BrowserLoginActivityViewModel.kt | 36 +- .../nextcloud/talk/activities/MainActivity.kt | 5 - .../talk/api/LoggingHttpInterceptor.kt | 7 +- .../java/com/nextcloud/talk/api/NcApi.java | 11 +- .../application/NextcloudTalkApplication.kt | 11 +- .../call/components/AvatarWithFallback.kt | 36 +- .../com/nextcloud/talk/chat/ChatActivity.kt | 413 +++++------------- .../talk/chat/MessageInputFragment.kt | 14 +- .../talk/chat/data/io/MediaRecorderManager.kt | 8 + .../chat/data/io/MessageAudioController.kt | 144 ++++++ .../talk/chat/data/io/MessageAudioPlayback.kt | 146 +++++++ .../chat/data/io/VoiceMessageMediaService.kt | 22 +- .../chat/ui/model/MessageAudioProjection.kt | 49 +++ .../ConversationsListActivity.kt | 11 +- .../conversationlist/ui/ConversationList.kt | 59 +-- .../ui/ConversationListItem.kt | 79 ++-- .../ui/ConversationsListScreen.kt | 4 +- .../ui/ScrollDirectionTracker.kt | 28 ++ .../talk/extensions/ImageViewExtensions.kt | 22 +- .../nextcloud/talk/jobs/CacheFileWriter.kt | 42 ++ .../talk/jobs/CancellableStreamCopy.kt | 32 ++ .../talk/jobs/DownloadFileToCacheWorker.kt | 135 +++--- .../nextcloud/talk/jobs/DownloadProgress.kt | 14 + .../nextcloud/talk/jobs/ExportVideoWorker.kt | 85 ++++ .../activities/MediaViewerActivity.kt | 55 ++- .../activities/MediaViewerScreen.kt | 237 +++++++--- .../mediaviewer/activities/VideoExporter.kt | 71 +++ .../activities/VideoPlaybackController.kt | 125 ++++++ .../activities/VideoPlaybackGuard.kt | 27 ++ .../activities/VideoPlaybackPolicy.kt | 18 + .../talk/mediaviewer/model/VideoAction.kt | 9 + .../stream/ProgressiveVideoDataSource.kt | 128 ++++++ .../stream/ProgressiveVideoFile.kt | 94 ++++ .../stream/VideoDownloadRegistry.kt | 23 + .../mediaviewer/stream/VideoRangeResponse.kt | 27 ++ .../mediaviewer/stream/VideoStreamSource.kt | 23 + .../viewmodels/MediaViewerViewModel.kt | 150 +++++-- .../talk/ui/ComposeWaveformSeekbar.kt | 70 +-- .../com/nextcloud/talk/ui/MessageAudioBar.kt | 202 +++++++++ .../nextcloud/talk/ui/MessageAudioControls.kt | 129 ++++++ .../talk/ui/chat/AttachmentDetails.kt | 51 +++ .../talk/ui/chat/AudioFileMessage.kt | 168 ++++--- .../talk/ui/chat/ChatMessageScaffold.kt | 8 +- .../nextcloud/talk/ui/chat/ChatMessageView.kt | 5 +- .../talk/ui/chat/ChatScrollPolicy.kt | 13 + .../nextcloud/talk/ui/chat/ChatTypography.kt | 13 + .../com/nextcloud/talk/ui/chat/ChatView.kt | 77 ++-- .../talk/ui/chat/CompactFileMessage.kt | 157 +++++++ .../talk/ui/chat/MediaGroupMessage.kt | 127 ++---- .../nextcloud/talk/ui/chat/MediaMessage.kt | 47 +- .../nextcloud/talk/ui/chat/SystemMessage.kt | 41 +- .../nextcloud/talk/ui/chat/VideoActions.kt | 57 +++ .../talk/ui/chat/VisibleFileDownloads.kt | 19 + .../nextcloud/talk/ui/chat/VoiceMessage.kt | 133 +++--- .../ui/theme/TalkSpecificViewThemeUtils.kt | 46 +- .../talk/utils/CharacterAvatarUtils.kt | 52 +-- .../talk/utils/DefaultUserAvatarImage.kt | 40 ++ .../nextcloud/talk/utils/FileViewerUtils.kt | 10 +- .../utils/UserAvatarRequestInterceptor.kt | 32 ++ .../utils/UserAvatarResponseInterceptor.kt | 49 +++ .../drawable-night/account_circle_48dp.xml | 14 +- .../drawable-night/account_circle_96dp.xml | 13 +- .../main/res/drawable/account_circle_48dp.xml | 14 +- .../main/res/drawable/account_circle_96dp.xml | 13 +- app/src/main/res/layout/activity_chat.xml | 7 +- .../main/res/values-night/avatar_colors.xml | 11 + .../values-night/chat_system_log_colors.xml | 10 + app/src/main/res/values-night/colors.xml | 2 + app/src/main/res/values/avatar_colors.xml | 11 + .../res/values/chat_system_log_colors.xml | 10 + app/src/main/res/values/colors.xml | 2 + app/src/main/res/values/strings.xml | 9 + app/src/qa/AndroidManifest.xml | 20 + app/src/qa/ic_launcher-web.png | Bin 31078 -> 14892 bytes .../talk/utils/ClosedInterfaceImpl.java | 28 -- .../res/drawable/ic_launcher_background.xml | 23 +- .../res/drawable/ic_launcher_foreground.xml | 13 +- app/src/qa/res/mipmap-anydpi/ic_launcher.xml | 24 + app/src/qa/res/mipmap-hdpi/ic_launcher.png | Bin 5184 -> 0 bytes app/src/qa/res/mipmap-mdpi/ic_launcher.png | Bin 3229 -> 0 bytes app/src/qa/res/mipmap-xhdpi/ic_launcher.png | Bin 7299 -> 0 bytes app/src/qa/res/mipmap-xxhdpi/ic_launcher.png | Bin 11233 -> 0 bytes app/src/qa/res/mipmap-xxxhdpi/ic_launcher.png | Bin 16182 -> 0 bytes .../BrowserLoginActivityViewModelTest.kt | 131 +++++- .../talk/api/FileDownloadStreamingTest.kt | 102 +++++ .../talk/chat/VoiceMessageSpeedTest.kt | 67 +++ .../chat/data/io/MessageAudioPlaybackTest.kt | 204 +++++++++ .../chat/data/io/MessageAudioPolicyTest.kt | 50 +++ .../ui/ScrollDirectionTrackerTest.kt | 39 ++ .../talk/jobs/CacheFileWriterTest.kt | 105 +++++ .../talk/jobs/DownloadProgressTest.kt | 27 ++ .../activities/VideoPlaybackGuardTest.kt | 55 +++ .../activities/VideoPlaybackPolicyTest.kt | 35 ++ .../stream/ProgressiveVideoDataSourceTest.kt | 111 +++++ .../stream/ProgressiveVideoFileTest.kt | 99 +++++ .../stream/VideoRangeResponseTest.kt | 26 ++ .../talk/ui/chat/ChatScrollPolicyTest.kt | 48 ++ .../talk/ui/chat/VisibleFileDownloadsTest.kt | 56 +++ .../talk/utils/CharacterAvatarUtilsTest.kt | 45 +- .../UserAvatarResponseInterceptorTest.kt | 264 +++++++++++ gradle/verification-metadata.xml | 58 +++ 109 files changed, 4626 insertions(+), 1177 deletions(-) create mode 100644 app/proguard-plus-optimized.pro rename app/src/{gplay => googlePush}/java/com/nextcloud/talk/jobs/GetFirebasePushTokenWorker.kt (100%) rename app/src/{gplay => googlePush}/java/com/nextcloud/talk/services/firebase/NCFirebaseMessagingService.kt (100%) rename app/src/{gplay => googlePush}/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.kt (100%) create mode 100644 app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioController.kt create mode 100644 app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioPlayback.kt create mode 100644 app/src/main/java/com/nextcloud/talk/chat/ui/model/MessageAudioProjection.kt create mode 100644 app/src/main/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTracker.kt create mode 100644 app/src/main/java/com/nextcloud/talk/jobs/CacheFileWriter.kt create mode 100644 app/src/main/java/com/nextcloud/talk/jobs/CancellableStreamCopy.kt create mode 100644 app/src/main/java/com/nextcloud/talk/jobs/DownloadProgress.kt create mode 100644 app/src/main/java/com/nextcloud/talk/jobs/ExportVideoWorker.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoExporter.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackController.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuard.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicy.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/model/VideoAction.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSource.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFile.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoDownloadRegistry.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponse.kt create mode 100644 app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoStreamSource.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/MessageAudioBar.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/MessageAudioControls.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/chat/AttachmentDetails.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/chat/ChatScrollPolicy.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/chat/ChatTypography.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/chat/CompactFileMessage.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/chat/VideoActions.kt create mode 100644 app/src/main/java/com/nextcloud/talk/ui/chat/VisibleFileDownloads.kt create mode 100644 app/src/main/java/com/nextcloud/talk/utils/DefaultUserAvatarImage.kt create mode 100644 app/src/main/java/com/nextcloud/talk/utils/UserAvatarRequestInterceptor.kt create mode 100644 app/src/main/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptor.kt create mode 100644 app/src/main/res/values-night/avatar_colors.xml create mode 100644 app/src/main/res/values-night/chat_system_log_colors.xml create mode 100644 app/src/main/res/values/avatar_colors.xml create mode 100644 app/src/main/res/values/chat_system_log_colors.xml create mode 100644 app/src/qa/AndroidManifest.xml delete mode 100644 app/src/qa/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.java create mode 100644 app/src/qa/res/mipmap-anydpi/ic_launcher.xml delete mode 100644 app/src/qa/res/mipmap-hdpi/ic_launcher.png delete mode 100644 app/src/qa/res/mipmap-mdpi/ic_launcher.png delete mode 100644 app/src/qa/res/mipmap-xhdpi/ic_launcher.png delete mode 100644 app/src/qa/res/mipmap-xxhdpi/ic_launcher.png delete mode 100644 app/src/qa/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 app/src/test/java/com/nextcloud/talk/api/FileDownloadStreamingTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/chat/VoiceMessageSpeedTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPlaybackTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPolicyTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTrackerTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/jobs/CacheFileWriterTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/jobs/DownloadProgressTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuardTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicyTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSourceTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFileTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponseTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/ui/chat/ChatScrollPolicyTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/ui/chat/VisibleFileDownloadsTest.kt create mode 100644 app/src/test/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptorTest.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 64a7887103e..200d860258c 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -4,6 +4,8 @@ * SPDX-FileCopyrightText: 2017-2026 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: GPL-3.0-or-later */ +import com.android.build.api.variant.HasHostTestsBuilder +import com.android.build.api.variant.HostTestBuilder import com.github.spotbugs.snom.Confidence import com.github.spotbugs.snom.Effort import com.github.spotbugs.snom.SpotBugsTask @@ -94,12 +96,19 @@ android { dimension = "default" versionCode = 250010052 versionName = "25.1.0 RC2" + providers.gradleProperty("voiceTestAbi").orNull?.let { abi -> + require(abi in setOf("arm64-v8a", "armeabi-v7a")) { "Unsupported voice test ABI: $abi" } + ndk.abiFilters.add(abi) + } } } sourceSets { // Adds exported schema location as test app assets. getByName("androidTest").assets.srcDir("$projectDir/schemas") + listOf("gplay", "qa").forEach { flavor -> + getByName(flavor).kotlin.directories.add("src/googlePush/java") + } } testOptions { @@ -114,7 +123,12 @@ android { buildTypes { release { - isMinifyEnabled = false + val plusOptimize = providers.gradleProperty("plusOptimize").orNull == "true" + isMinifyEnabled = plusOptimize + isDebuggable = false + if (plusOptimize) { + proguardFiles("proguard-plus-optimized.pro") + } proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" @@ -165,6 +179,12 @@ android { } } +androidComponents { + beforeVariants(selector().withName("qaRelease")) { + (it as HasHostTestsBuilder).hostTests[HostTestBuilder.UNIT_TEST_TYPE]?.enable = true + } +} + tasks.named("check") { dependsOn("spotbugsGplayDebug", "lint", "ktlintCheck", "detekt") } @@ -332,8 +352,10 @@ dependencies { implementation("com.github.nextcloud.android-common:core:0.34.0") implementation("com.github.nextcloud-deps:android-talk-webrtc:155.8059.1") - "gplayImplementation"("com.google.android.gms:play-services-base:18.11.1") - "gplayImplementation"("com.google.firebase:firebase-messaging:26.0.0") + listOf("gplay", "qa").forEach { flavor -> + add("${flavor}Implementation", "com.google.android.gms:play-services-base:18.11.1") + add("${flavor}Implementation", "com.google.firebase:firebase-messaging:26.0.0") + } implementation("org.unifiedpush.android:connector:3.3.5") "genericImplementation"("org.unifiedpush.android:embedded-fcm-distributor:3.1.0") diff --git a/app/proguard-plus-optimized.pro b/app/proguard-plus-optimized.pro new file mode 100644 index 00000000000..3572c656c82 --- /dev/null +++ b/app/proguard-plus-optimized.pro @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: GPL-3.0-or-later + +# Optimize Compose rendering while retaining the existing reflection, JNI and serialization surface. +# Broad shrinking/renaming requires separate end-to-end validation of accounts, push and calls. +-dontshrink +-dontobfuscate +-keepattributes * +-keep class !androidx.compose.**,!com.nextcloud.talk.ui.chat.**,!com.nextcloud.talk.conversationlist.ui.**,** { *; } + +# These absent types are referenced by retained third-party code, outside the optimization scope. +# Keep the exceptions exact so new missing dependencies still fail the build. +# Tink's optional HTTP key downloader, legacy GeoGson formatting and optional Firebase analytics. +-dontwarn com.google.api.client.http.GenericUrl +-dontwarn com.google.api.client.http.HttpHeaders +-dontwarn com.google.api.client.http.HttpRequest +-dontwarn com.google.api.client.http.HttpRequestFactory +-dontwarn com.google.api.client.http.HttpResponse +-dontwarn com.google.api.client.http.HttpTransport +-dontwarn com.google.api.client.http.javanet.NetHttpTransport$Builder +-dontwarn com.google.api.client.http.javanet.NetHttpTransport +-dontwarn com.google.common.base.Objects$ToStringHelper +-dontwarn com.google.firebase.analytics.connector.AnalyticsConnector +# Desktop-only JTS drawing and Commons Lang method-handle adapter. +-dontwarn java.awt.Font +-dontwarn java.awt.Rectangle +-dontwarn java.awt.Shape +-dontwarn java.awt.font.FontRenderContext +-dontwarn java.awt.font.GlyphVector +-dontwarn java.awt.geom.AffineTransform +-dontwarn java.awt.geom.Ellipse2D$Double +-dontwarn java.awt.geom.GeneralPath +-dontwarn java.awt.geom.Line2D$Double +-dontwarn java.awt.geom.PathIterator +-dontwarn java.awt.geom.Point2D$Double +-dontwarn java.awt.geom.Point2D +-dontwarn java.awt.geom.Rectangle2D$Double +-dontwarn java.awt.geom.Rectangle2D +-dontwarn java.lang.invoke.MethodHandleProxies +# JavaCPP's Maven build tooling and Joda's optional conversion annotations. +-dontwarn org.apache.maven.artifact.Artifact +-dontwarn org.apache.maven.model.Build +-dontwarn org.apache.maven.plugin.AbstractMojo +-dontwarn org.apache.maven.plugin.MojoExecutionException +-dontwarn org.apache.maven.plugin.descriptor.PluginDescriptor +-dontwarn org.apache.maven.plugin.logging.Log +-dontwarn org.apache.maven.plugins.annotations.Mojo +-dontwarn org.apache.maven.plugins.annotations.Parameter +-dontwarn org.apache.maven.project.MavenProject +-dontwarn org.joda.convert.FromString +-dontwarn org.joda.convert.ToString diff --git a/app/src/gplay/java/com/nextcloud/talk/jobs/GetFirebasePushTokenWorker.kt b/app/src/googlePush/java/com/nextcloud/talk/jobs/GetFirebasePushTokenWorker.kt similarity index 100% rename from app/src/gplay/java/com/nextcloud/talk/jobs/GetFirebasePushTokenWorker.kt rename to app/src/googlePush/java/com/nextcloud/talk/jobs/GetFirebasePushTokenWorker.kt diff --git a/app/src/gplay/java/com/nextcloud/talk/services/firebase/NCFirebaseMessagingService.kt b/app/src/googlePush/java/com/nextcloud/talk/services/firebase/NCFirebaseMessagingService.kt similarity index 100% rename from app/src/gplay/java/com/nextcloud/talk/services/firebase/NCFirebaseMessagingService.kt rename to app/src/googlePush/java/com/nextcloud/talk/services/firebase/NCFirebaseMessagingService.kt diff --git a/app/src/gplay/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.kt b/app/src/googlePush/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.kt similarity index 100% rename from app/src/gplay/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.kt rename to app/src/googlePush/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 4c27ccc2c81..87f99b5b274 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -222,7 +222,11 @@ { - if (viewModel.waitingForBrowserState.value) { - viewModel.setWaitingForBrowser(false) - viewModel.handleWebBrowserLogin() - } else { - viewModel.setWaitingForBrowser(true) - launchDefaultWebBrowser(state.loginUrl) - } + viewModel.onBrowserOpened() + launchDefaultWebBrowser(state.loginUrl) } BrowserLoginActivityViewModel.InitialLoginViewState.None -> {} } @@ -111,7 +113,9 @@ class BrowserLoginActivity : BaseActivity() { } BrowserLoginActivityViewModel.PostLoginViewState.PostLoginError -> { logger.e(TAG, "Post login step failed") - Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_SHORT).show() + Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_INDEFINITE) + .setAction(R.string.nc_retry) { viewModel.handleWebBrowserLogin() } + .show() } BrowserLoginActivityViewModel.PostLoginViewState.PostLoginTooManyLoginAttempts -> { logger.e(TAG, "Login refused because of too many failed logins") @@ -169,14 +173,12 @@ class BrowserLoginActivity : BaseActivity() { viewThemeUtils.material.colorProgressBar(binding.progressBar) binding.cancelLoginBtn.setOnClickListener { - viewModel.cancelLogin() onBackPressedDispatcher.onBackPressed() } } private fun launchDefaultWebBrowser(url: String) { val intent = Intent(Intent.ACTION_VIEW, url.toUri()) - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } @@ -184,12 +186,14 @@ class BrowserLoginActivity : BaseActivity() { val intent = Intent(context, AccountVerificationActivity::class.java) intent.putExtras(bundle) startActivity(intent) + finish() } private fun restartApp() { val intent = Intent(context, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) + finish() } public override fun onDestroy() { diff --git a/app/src/main/java/com/nextcloud/talk/account/data/LoginRepository.kt b/app/src/main/java/com/nextcloud/talk/account/data/LoginRepository.kt index d0f52f72798..70a187ec552 100644 --- a/app/src/main/java/com/nextcloud/talk/account/data/LoginRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/account/data/LoginRepository.kt @@ -29,7 +29,7 @@ class LoginRepository(val network: NetworkLoginDataSource, val local: LocalLogin companion object { val TAG: String = LoginRepository::class.java.simpleName - private const val INTERVAL = 250L + private const val INTERVAL = 1000L private const val HTTP_OK = 200 /** The status of a [LoginCompletion] for a login the server refused because of too many failed logins. */ diff --git a/app/src/main/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModel.kt b/app/src/main/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModel.kt index 43cf3877727..aca6b8f78ef 100644 --- a/app/src/main/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModel.kt @@ -13,16 +13,18 @@ import androidx.lifecycle.viewModelScope import com.nextcloud.talk.account.data.LoginRepository import com.nextcloud.talk.account.data.model.LoginCompletion import com.nextcloud.talk.account.data.model.LoginResponse +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRepository) : ViewModel() { companion object { private val TAG = BrowserLoginActivityViewModel::class.java.simpleName + private const val LOGIN_TIMEOUT_MS = 20 * 60 * 1000L } sealed class InitialLoginViewState { @@ -47,14 +49,14 @@ class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRep private val _postLoginState = MutableStateFlow(PostLoginViewState.None) val postLoginState: StateFlow = _postLoginState - private val _waitingForBrowserState = MutableStateFlow(false) - val waitingForBrowserState = _waitingForBrowserState.asStateFlow() - - fun setWaitingForBrowser(value: Boolean) { - _waitingForBrowserState.value = value + fun onBrowserOpened() { + _initialLoginRequestState.value = InitialLoginViewState.None } private var savedResponse: LoginResponse? = null + private var pollingStarted = false + private var initialLoginJob: Job? = null + private var loginJob: Job? = null // The view model survives a recreation of the activity, which starts the login again. A started login is // continued instead of starting a second one, whose session the browser would not authorize. After process @@ -69,7 +71,7 @@ class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRep fun startWebBrowserLogin(baseUrl: String, reAuth: Boolean = false, accountToReauthorize: Long? = null) { if (!startLoginOnce()) return - viewModelScope.launch { + initialLoginJob = viewModelScope.launch { val response = repository.startLoginFlow(baseUrl, reAuth, accountToReauthorize) savedResponse = response @@ -80,20 +82,25 @@ class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRep _initialLoginRequestState.value = InitialLoginViewState.InitialLoginRequestSuccess(response.loginUrl) + handleWebBrowserLogin() } } fun handleWebBrowserLogin() { + if (pollingStarted && _postLoginState.value != PostLoginViewState.PostLoginError) return savedResponse?.let { response -> - viewModelScope.launch { - _postLoginState.value = postLoginStateFor(repository.pollLogin(response)) + pollingStarted = true + _postLoginState.value = PostLoginViewState.None + loginJob = viewModelScope.launch { + val completion = withTimeoutOrNull(LOGIN_TIMEOUT_MS) { repository.pollLogin(response) } + _postLoginState.value = postLoginStateFor(completion) } } } fun loginWithQR(dataString: String, reAuth: Boolean = false, accountToReauthorize: Long? = null) { if (!startLoginOnce()) return - viewModelScope.launch { + loginJob = viewModelScope.launch { _postLoginState.value = postLoginStateFor(repository.startLoginFlowFromQR(dataString, reAuth, accountToReauthorize)) } @@ -101,7 +108,7 @@ class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRep fun loginWithOTPQR(dataString: String, reAuth: Boolean = false, accountToReauthorize: Long? = null) { if (!startLoginOnce()) return - viewModelScope.launch { + loginJob = viewModelScope.launch { _postLoginState.value = postLoginStateFor(repository.startOTPLoginFlow(dataString, reAuth, accountToReauthorize)) } @@ -125,5 +132,10 @@ class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRep LoginRepository.LoginResult.RemovalPending -> PostLoginViewState.PostLoginRemovalPending } - fun cancelLogin() = repository.cancelLoginFlow() + fun cancelLogin() { + initialLoginJob?.cancel() + loginJob?.cancel() + repository.cancelLoginFlow() + savedResponse = null + } } diff --git a/app/src/main/java/com/nextcloud/talk/activities/MainActivity.kt b/app/src/main/java/com/nextcloud/talk/activities/MainActivity.kt index 2fca99c028f..7cc863d4e53 100644 --- a/app/src/main/java/com/nextcloud/talk/activities/MainActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/activities/MainActivity.kt @@ -23,7 +23,6 @@ import androidx.core.net.toUri import androidx.lifecycle.lifecycleScope import autodagger.AutoInjector import com.google.android.material.snackbar.Snackbar -import com.nextcloud.talk.BuildConfig import com.nextcloud.talk.R import com.nextcloud.talk.account.BrowserLoginActivity import com.nextcloud.talk.account.ServerSelectionActivity @@ -80,10 +79,6 @@ class MainActivity : super.onCreate(savedInstanceState) - if (BuildConfig.DEBUG) { - Toast.makeText(this, "Build flavor: " + BuildConfig.FLAVOR, Toast.LENGTH_LONG).show() - } - // Set the default theme to replace the launch screen theme. setTheme(R.style.AppTheme) binding = ActivityMainBinding.inflate(layoutInflater) diff --git a/app/src/main/java/com/nextcloud/talk/api/LoggingHttpInterceptor.kt b/app/src/main/java/com/nextcloud/talk/api/LoggingHttpInterceptor.kt index d82ebe834b8..0cb102474d1 100644 --- a/app/src/main/java/com/nextcloud/talk/api/LoggingHttpInterceptor.kt +++ b/app/src/main/java/com/nextcloud/talk/api/LoggingHttpInterceptor.kt @@ -12,6 +12,8 @@ import com.nextcloud.talk.logger.LogsRepository import okhttp3.Interceptor import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Invocation +import retrofit2.http.Streaming import javax.inject.Inject class LoggingHttpInterceptor @Inject constructor( @@ -34,7 +36,10 @@ class LoggingHttpInterceptor @Inject constructor( sb.clear() } }.apply { - level = HttpLoggingInterceptor.Level.BODY + val streaming = chain.request().tag( + Invocation::class.java + )?.method()?.isAnnotationPresent(Streaming::class.java) + level = if (streaming == true) HttpLoggingInterceptor.Level.HEADERS else HttpLoggingInterceptor.Level.BODY redactHeader("Authorization") redactHeader("Proxy-Authorization") }.intercept(chain) diff --git a/app/src/main/java/com/nextcloud/talk/api/NcApi.java b/app/src/main/java/com/nextcloud/talk/api/NcApi.java index 23ebf6e82d1..9691f2b94e3 100644 --- a/app/src/main/java/com/nextcloud/talk/api/NcApi.java +++ b/app/src/main/java/com/nextcloud/talk/api/NcApi.java @@ -63,6 +63,7 @@ import retrofit2.http.Part; import retrofit2.http.Query; import retrofit2.http.QueryMap; +import retrofit2.http.Streaming; import retrofit2.http.Url; public interface NcApi { @@ -445,9 +446,17 @@ Observable> checkIfFileExists(@Header("Authorization") String aut @Url String url); @GET + @Streaming Call downloadFile(@Header("Authorization") String authorization, @Url String url); + @GET + @Streaming + Call downloadVideoRange(@Header("Authorization") String authorization, + @Url String url, + @Header("Range") String range, + @Header("If-Range") String validator); + @DELETE Observable deleteChatMessage(@Header("Authorization") String authorization, @Url String url); @@ -649,4 +658,4 @@ Observable acceptInvitation(@Header("Authorization") String auth @DELETE Observable rejectInvitation(@Header("Authorization") String authorization, @Url String url); -} \ No newline at end of file +} diff --git a/app/src/main/java/com/nextcloud/talk/application/NextcloudTalkApplication.kt b/app/src/main/java/com/nextcloud/talk/application/NextcloudTalkApplication.kt index 2b592961139..2be8f1b077a 100644 --- a/app/src/main/java/com/nextcloud/talk/application/NextcloudTalkApplication.kt +++ b/app/src/main/java/com/nextcloud/talk/application/NextcloudTalkApplication.kt @@ -27,6 +27,9 @@ import autodagger.AutoComponent import autodagger.AutoInjector import coil.Coil import coil.ImageLoader +import com.nextcloud.talk.utils.DefaultUserAvatarImage +import com.nextcloud.talk.utils.UserAvatarRequestInterceptor +import com.nextcloud.talk.utils.UserAvatarResponseInterceptor import coil.decode.GifDecoder import coil.decode.ImageDecoderDecoder import coil.decode.SvgDecoder @@ -301,6 +304,7 @@ class NextcloudTalkApplication : } .crossfade(true) // Show a short crossfade when loading images from network or disk into an ImageView. .components { + add(UserAvatarRequestInterceptor()) if (SDK_INT >= P) { add(ImageDecoderDecoder.Factory()) } else { @@ -313,7 +317,12 @@ class NextcloudTalkApplication : imageLoaderBuilder.logger(DebugLogger()) } - imageLoaderBuilder.okHttpClient(okHttpClient) + val defaultAvatar = DefaultUserAvatarImage(applicationContext) + imageLoaderBuilder.okHttpClient( + okHttpClient.newBuilder() + .addInterceptor(UserAvatarResponseInterceptor(defaultAvatar::bytes)) + .build() + ) return imageLoaderBuilder.build() } diff --git a/app/src/main/java/com/nextcloud/talk/call/components/AvatarWithFallback.kt b/app/src/main/java/com/nextcloud/talk/call/components/AvatarWithFallback.kt index 5ad09da0fab..c4237b9d573 100644 --- a/app/src/main/java/com/nextcloud/talk/call/components/AvatarWithFallback.kt +++ b/app/src/main/java/com/nextcloud/talk/call/components/AvatarWithFallback.kt @@ -7,20 +7,18 @@ package com.nextcloud.talk.call.components -import androidx.compose.foundation.background +import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.nextcloud.talk.R @@ -57,6 +55,7 @@ fun AvatarWithFallback(participant: ParticipantUiState, displayName: String, mod val authHeader = LocalImageAuthHeader.current.takeIf { participant.actorType == ParticipantDto.ActorType.FEDERATED } + val fallback = painterResource(R.drawable.account_circle_96dp) AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(avatarUrl) @@ -64,37 +63,26 @@ fun AvatarWithFallback(participant: ParticipantUiState, displayName: String, mod .build(), contentDescription = stringResource(R.string.avatar), contentScale = ContentScale.Crop, + placeholder = fallback, + error = fallback, modifier = Modifier .fillMaxSize() .clip(CircleShape) ) } else { - FallbackAvatar(participant = participant) + FallbackAvatar() } } } } @Composable -private fun FallbackAvatar(participant: ParticipantUiState) { - val initials = participant.nick!! - .split(" ") - .mapNotNull { it.firstOrNull()?.uppercase() } - .take(2) - .joinToString("") - Box( - modifier = Modifier - .fillMaxSize() - .background(Color.White, CircleShape), - contentAlignment = Alignment.Center - ) { - Text( - text = initials.ifEmpty { "?" }, - color = Color.Black, - fontSize = 24.sp - ) - } -} +private fun FallbackAvatar() = + Image( + painter = painterResource(R.drawable.account_circle_96dp), + contentDescription = stringResource(R.string.avatar), + modifier = Modifier.fillMaxSize() + ) @Composable fun getUrlForAvatar(participant: ParticipantUiState): String = diff --git a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt index 50d0c1939fb..1779cd73a49 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt @@ -14,17 +14,16 @@ package com.nextcloud.talk.chat +import com.nextcloud.talk.mediaviewer.model.VideoAction import android.Manifest import android.annotation.SuppressLint import android.content.ClipData import android.content.ClipboardManager -import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.res.AssetFileDescriptor import android.database.Cursor -import android.media.MediaMetadataRetriever import android.net.Uri import android.os.Build import android.os.Bundle @@ -53,13 +52,11 @@ import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf @@ -68,7 +65,6 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalDensity -import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.core.content.PermissionChecker import androidx.core.content.PermissionChecker.PERMISSION_GRANTED @@ -82,11 +78,6 @@ import androidx.fragment.app.commit import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope -import androidx.media3.common.MediaItem -import androidx.media3.common.MediaMetadata -import androidx.media3.common.Player -import androidx.media3.session.MediaController -import androidx.media3.session.SessionToken import androidx.recyclerview.widget.LinearLayoutManager import androidx.work.Data import androidx.work.OneTimeWorkRequest @@ -97,10 +88,15 @@ import androidx.work.WorkManager import autodagger.AutoInjector import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar -import com.google.common.util.concurrent.ListenableFuture import com.nextcloud.android.common.ui.color.ColorUtil import com.nextcloud.talk.BuildConfig import com.nextcloud.talk.R +import com.nextcloud.talk.chat.data.io.MessageAudioController +import com.nextcloud.talk.chat.data.io.MessageAudioKey +import com.nextcloud.talk.chat.data.io.MessageAudioTrack +import com.nextcloud.talk.chat.ui.model.withMessageAudio +import com.nextcloud.talk.ui.MessageAudioBar +import com.nextcloud.talk.ui.openMessageAudioConversation import com.nextcloud.talk.activities.BaseActivity import com.nextcloud.talk.activities.CallActivity import com.nextcloud.talk.adapters.messages.CallStartedMessageInterface @@ -108,9 +104,8 @@ import com.nextcloud.talk.api.NcApi import com.nextcloud.talk.api.NcApiCoroutines import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.attachmentpreview.FileAttachmentPreviewFragment -import com.nextcloud.talk.chat.data.io.VoiceMessageMediaService import com.nextcloud.talk.chat.data.model.ChatMessage -import com.nextcloud.talk.chat.data.model.FileParameters +import com.nextcloud.talk.ui.chat.downloadingMessageKeys import com.nextcloud.talk.chat.ui.ChatEmptyState import com.nextcloud.talk.chat.ui.ChatEmptyStateType import com.nextcloud.talk.chat.ui.ChatToolbar @@ -238,7 +233,6 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach -import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.greenrobot.eventbus.Subscribe @@ -253,7 +247,6 @@ import java.time.ZonedDateTime import java.util.Date import java.util.Locale import java.util.UUID -import java.util.concurrent.CancellationException import java.util.concurrent.ExecutionException import javax.inject.Inject import kotlin.math.abs @@ -318,8 +311,8 @@ class ChatActivity : mutableStateOf(ChatViewModel.UpcomingEventUIState.None) private val overflowContainerHeightPx = mutableIntStateOf(0) - private var mediaControllerFuture: ListenableFuture? = null - private var mediaController: MediaController? = null + @Inject + lateinit var messageAudioController: MessageAudioController private val startSelectContactForResult = registerForActivityResult( ActivityResultContracts @@ -434,76 +427,6 @@ class ChatActivity : private lateinit var pickMultipleMedia: ActivityResultLauncher - private var progressJob: Job? = null - - private fun updateSeekbarUi() { - mediaController?.let { controller -> - val currentPosition = controller.currentPosition - val duration = controller.duration.takeIf { it > 0 } ?: 1 - - val progress = (currentPosition.toFloat() / duration) * FLOAT_100 - val secondsPlayed = (currentPosition / MILLIS_1000) - - val msg = chatViewModel.currentVoiceMessage?.apply { - voiceMessageSeekbarProgress = kotlin.math.ceil(progress).toInt() - voiceMessagePlayedSeconds = secondsPlayed.toInt() - if (controller.duration > 0) { - voiceMessageDuration = (controller.duration / MILLIS_1000).toInt() - } - } - - val currentMediaId = controller.currentMediaItem?.mediaId - if (currentMediaId != null && msg != null) { - chatViewModel.syncVoiceMessageUiState(msg) - } - } - } - - private fun startProgressPolling() { - progressJob?.cancel() - progressJob = lifecycleScope.launch { - while (isActive) { - updateSeekbarUi() - // Poll every 150ms for smooth seekbar updates - delay(MILLIS_150) - } - } - } - - private fun stopProgressPolling() { - progressJob?.cancel() - progressJob = null - } - - private val playerListener = object : Player.Listener { - override fun onIsPlayingChanged(isPlaying: Boolean) { - if (isPlaying) { - startProgressPolling() - } else { - stopProgressPolling() - updateSeekbarUi() - } - - chatViewModel.currentVoiceMessage?.apply { - isPlayingVoiceMessage = isPlaying - }?.let { chatViewModel.syncVoiceMessageUiState(it) } - } - - // Catches instant changes (e.g., manual seeks, skipping to the next track) - override fun onPositionDiscontinuity( - oldPosition: Player.PositionInfo, - newPosition: Player.PositionInfo, - reason: Int - ) { - updateSeekbarUi() - } - - override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { - // Ensures the UI resets immediately when transitioning to the next voice message - updateSeekbarUi() - } - } - private val onBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (chatViewModel.chatMode.value == ChatViewModel.ChatMode.SEARCH_MODE) { @@ -632,6 +555,11 @@ class ChatActivity : keepContentOutOfDisplayCutout() setupChatToolbarView() + binding.messageAudioBar.setContent { + MaterialTheme(colorScheme = viewThemeUtils.getColorScheme(this@ChatActivity)) { + MessageAudioBar(messageAudioController) { openMessageAudioConversation(it) } + } + } setupChatEmptyStateView() setupTypingIndicatorView() @@ -889,6 +817,7 @@ class ChatActivity : binding.messagesListViewCompose.setContent { MaterialTheme(colorScheme = viewThemeUtils.getColorScheme(this@ChatActivity)) { val uiState by chatViewModel.uiState.collectAsStateWithLifecycle() + val audioState by messageAudioController.state.collectAsStateWithLifecycle() val chatMode by chatViewModel.chatMode.collectAsStateWithLifecycle() val participantPermissions by participantPermissionsFlow.collectAsStateWithLifecycle() currentConversation = uiState.conversation @@ -939,9 +868,18 @@ class ChatActivity : // that if any of the messages that are present contain a fileId that is within downloadingFileState val openWhenDownloadState = remember { mutableStateOf(false) } - val visibleIds = listState.visibleItemsWithThreshold() - LaunchedEffect(visibleIds, downloadingFileState.value) { - openWhenDownloadState.value = (downloadingFileState.value.intersect(visibleIds).isNotEmpty()) + LaunchedEffect(listState, uiState.items, downloadingFileState.value) { + val downloadKeys = downloadingMessageKeys(uiState.items, downloadingFileState.value) + if (downloadKeys.isEmpty()) { + openWhenDownloadState.value = false + return@LaunchedEffect + } + snapshotFlow { + listState.layoutInfo.visibleItemsInfo.any { it.key in downloadKeys } + }.collect { openWhenDownloadState.value = it } + } + val audioItems = remember(uiState.items, audioState, conversationUserId, roomToken) { + uiState.items.withMessageAudio(audioState, conversationUserId, roomToken) } val overflowHeightDp = with(LocalDensity.current) { @@ -949,7 +887,7 @@ class ChatActivity : } ChatView( state = ChatViewState( - chatItems = uiState.items, + chatItems = audioItems, isOneToOneConversation = isOneToOneConversation, conversationThreadId = conversationThreadId, chatMode = chatMode, @@ -970,15 +908,13 @@ class ChatActivity : onLongClick = { openMessageActionsDialog(it) }, onSwipeReply = { handleSwipeToReply(it) }, onFileClick = { downloadAndOpenFile(it, openWhenDownloadState, downloadingFileState) }, + onVideoAction = { id, action -> + downloadAndOpenFile(id, openWhenDownloadState, downloadingFileState, action) + }, onPollClick = { pollId, pollName -> openPollDialog(pollId, pollName) }, onVoicePlayPauseClick = { onVoiceClick(it) }, onVoiceSeek = { id, progress -> - mediaController?.let { controller -> - if (id.toString() == controller.currentMediaItem?.mediaId) { - val pos = controller.duration * progress / 100f - controller.seekTo(pos.toLong()) - } - } + messageAudioController.playback.seek(audioKey(id), progress) }, onVoiceSpeedClick = { onVoiceSpeedClickCompose(it) }, onReactionClick = { messageId, emoji -> handleReactionClick(messageId, emoji) }, @@ -1107,169 +1043,54 @@ class ChatActivity : } } - @Suppress("ReturnCount", "CyclomaticComplexMethod") - private fun onVoiceClick(messageId: Int) { - fun getAudioDuration(audioFilePath: String): Long { - val retriever = MediaMetadataRetriever() - - return try { - retriever.setDataSource(audioFilePath) - val durationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) - val durationLong = durationString?.toLong() ?: 0L - - durationLong / ONE_SECOND_IN_MILLIS - } catch (e: IllegalArgumentException) { - logger.e(TAG, "Failed to read audio duration for $audioFilePath", e) - 0L - } finally { - retriever.release() - } - } - - fun setupAndPlay(controller: MediaController, message: ChatMessage, file: String) { - val avatarUrl = chatViewModel.getAvatarUrl(message) - - val artist = if (message.isVoiceMessage) { - "Voice Message" - } else { - message.fileParameters.name - } - val metadata = MediaMetadata.Builder() - .setTitle(message.actorDisplayName) - .setArtist(artist) - .setArtworkUri(avatarUrl.toUri()) - .build() - - val mediaItem = MediaItem.Builder() - .setMediaId(message.jsonMessageId.toString()) - .setMediaMetadata(metadata) - .setUri(file) - .build() - - controller.setMediaItem(mediaItem) - - controller.prepare() - controller.play() - } - - fun setUpWaveform(message: ChatMessage, file: File) { - if (message.voiceMessageFloatArray != null) return - - val filename = message.fileParameters.name - message.isDownloadingVoiceMessage = true - - chatViewModel.syncVoiceMessageUiState(message) - - CoroutineScope(Dispatchers.Default).launch { - val waveform = AudioUtils.audioFileToFloatArray(file) - appPreferences.saveWaveFormForFile(filename, waveform.toTypedArray()) - message.voiceMessageFloatArray = waveform - - withContext(Dispatchers.Main) { - message.isDownloadingVoiceMessage = false - chatViewModel.syncVoiceMessageUiState(message) - } - } - } + private fun audioKey(messageId: Int) = MessageAudioKey(conversationUserId, roomToken, messageId) - fun prepareVoiceMessage(controller: MediaController, message: ChatMessage): Boolean { - val currentMessageId = message.jsonMessageId.toString() - val filename = message.fileParameters.name - if (filename.isEmpty()) { - return true + private fun onVoiceClick(messageId: Int) { + val playback = messageAudioController.playback + val key = audioKey(messageId) + if (playback.toggle(key)) return + val request = playback.beginRequest(key) + lifecycleScope.launch { + if (!messageAudioController.connect()) { + Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_LONG).show() + return@launch } - - val file = FileUtils.resolveSharedAttachmentFile(context.cacheDir, filename) ?: return true - val fileURI = file.toUri() - val filePath = fileURI.toString() - - chatViewModel.syncVoiceMessageUiState( - message.apply { - voiceMessageDuration = getAudioDuration(file.absolutePath).toInt() - } + val message = chatViewModel.getMessageById(messageId.toLong()).first() + val file = FileUtils.resolveSharedAttachmentFile(context.cacheDir, message.fileParameters.name) + ?: return@launch + val track = MessageAudioTrack( + key = key, + uri = file.toUri().toString(), + title = message.actorDisplayName.orEmpty().ifEmpty { message.fileParameters.name }, + conversation = currentConversation?.displayName.orEmpty(), + isVoice = message.isVoiceMessage, + threadId = conversationThreadId ) - - fun finishPreparing() { - setupAndPlay(controller, message, filePath) - if (message.isVoiceMessage) { - setUpWaveform(message, file) - } else { - message.isDownloadingVoiceMessage = false - chatViewModel.syncVoiceMessageUiState(message) + fun playDownloaded() { + message.isDownloadingVoiceMessage = false + chatViewModel.syncVoiceMessageUiState(message) + if (playback.completeRequest(request, track, voiceMessagePlaybackSpeed(messageId).value)) { + prepareAudioWaveform(message, file) } } - - val alreadyLoaded = controller.currentMediaItem?.mediaId == currentMessageId - if (!alreadyLoaded || !file.exists()) { - if (!file.exists()) { - downloadFileToCache(message, true) { - chatViewModel.syncVoiceMessageUiState( - message.apply { - voiceMessageDuration = getAudioDuration(file.absolutePath).toInt() - } - ) - finishPreparing() - } - } else { - finishPreparing() - } - - return true + if (file.exists()) { + playDownloaded() + } else { + downloadFileToCache(message, true, reuseRunningDownload = true, ::playDownloaded) } - return false } + } + private fun prepareAudioWaveform(message: ChatMessage, file: File) { + if (!message.isVoiceMessage || message.voiceMessageFloatArray != null) return lifecycleScope.launch { - val message = chatViewModel.getMessageById(messageId.toLong()).first() - - mediaController?.let { controller -> - // If a message is still playing, it must be paused first before another can be loaded - val currentMessageId = message.jsonMessageId.toString() - if (controller.isPlaying && controller.currentMediaItem?.mediaId != currentMessageId) return@launch - - chatViewModel.currentVoiceMessage = message - - // If the controller is playing a new voice message, initialize - if (prepareVoiceMessage(controller, message)) return@launch - - // If the controller is playing the same voice message, pause/resume - if (controller.isPlaying) { - controller.pause() - } else { - controller.play() - } - } + val waveform = withContext(Dispatchers.Default) { AudioUtils.audioFileToFloatArray(file) } + appPreferences.saveWaveFormForFile(message.fileParameters.name, waveform.toTypedArray()) + message.voiceMessageFloatArray = waveform + chatViewModel.syncVoiceMessageUiState(message) } } - @Composable - private fun LazyListState.visibleItemsWithThreshold(): List = - remember(this) { - derivedStateOf { - val visibleItemsInfo = layoutInfo.visibleItemsInfo - if (layoutInfo.totalItemsCount == 0) { - emptyList() - } else { - visibleItemsInfo.mapNotNull { it.key as? String } - } - } - }.value.mapNotNull { key -> - val messageItem = chatViewModel.uiState.collectAsState().value.items.firstOrNull { it.stableKey() == key } - val message = messageItem?.messageOrNull() - var result: String? = null - message?.let { - if (message.messageParameters.isNotEmpty()) { - val normalizedParameters = HashMap>( - message.messageParameters.mapValues { (_, params) -> HashMap(params) } - ) - val fileParameters = FileParameters(normalizedParameters) - result = fileParameters.id - } - } - - result - } - private fun onLoadQuotedMessage(messageId: Int) { chatViewModel.jumpToQuotedMessage(messageId.toLong()) } @@ -1301,15 +1122,23 @@ class ChatActivity : } } - private fun onVoiceSpeedClickCompose(messageId: Int) { - val currentSpeed = chatViewModel.uiState.value.items + private fun voiceMessagePlaybackSpeed(messageId: Int): PlaybackSpeed = + chatViewModel.uiState.value.items .mapNotNull { (it as? ChatViewModel.ChatItem.MessageItem)?.uiMessage } .firstOrNull { it.id == messageId } ?.content ?.let { it as? MessageTypeContent.Voice } ?.playbackSpeed ?: PlaybackSpeed.NORMAL - val nextSpeed = currentSpeed.next() - chatViewModel.setPlayBack(nextSpeed) + + private fun onVoiceSpeedClickCompose(messageId: Int) { + val current = messageAudioController.state.value + val speed = if (current.belongsTo(audioKey(messageId))) { + PlaybackSpeed.entries.firstOrNull { it.value == current.speed } ?: PlaybackSpeed.NORMAL + } else { + voiceMessagePlaybackSpeed(messageId) + } + val nextSpeed = speed.next() + messageAudioController.playback.setSpeed(audioKey(messageId), nextSpeed.value) appPreferences.savePreferredPlayback(conversationUser!!.userId, nextSpeed) chatViewModel.setVoiceMessageSpeed(messageId, nextSpeed) } @@ -1317,7 +1146,8 @@ class ChatActivity : fun downloadAndOpenFile( messageId: Int, openWhenDownloadState: MutableState, - downloadState: MutableState> + downloadState: MutableState>, + videoAction: VideoAction = VideoAction.PLAY ) { lifecycleScope.launch { val chatMessage = chatViewModel.getMessageById(messageId.toLong()).first() @@ -1339,11 +1169,12 @@ class ChatActivity : conversationUserId, roomToken, seedItems, - messageId.toLong() + messageId.toLong(), + videoAction ) ) } else { - fileViewerUtils.openFile(chatMessage, openWhenDownloadState, downloadState) + fileViewerUtils.openFile(chatMessage, openWhenDownloadState, downloadState, videoAction) } } } @@ -1444,36 +1275,6 @@ class ChatActivity : active = true this.lifecycle.addObserver(AudioUtils) this.lifecycle.addObserver(chatViewModel) - - val sessionToken = SessionToken(this, ComponentName(this, VoiceMessageMediaService::class.java)) - val future = MediaController.Builder(this, sessionToken) - .setListener(object : MediaController.Listener { - override fun onDisconnected(controller: MediaController) { - mediaController?.removeListener(playerListener) - stopProgressPolling() - mediaController = null - } - }) - .buildAsync() - mediaControllerFuture = future - - future.addListener({ - if (future !== mediaControllerFuture) { - return@addListener - } - - mediaController = try { - future.get() - } catch (_: CancellationException) { - null - } - - mediaController?.addListener(playerListener) - - if (mediaController?.isPlaying == true) { - startProgressPolling() - } - }, ContextCompat.getMainExecutor(this)) } override fun onSaveInstanceState(outState: Bundle) { @@ -1488,12 +1289,6 @@ class ChatActivity : active = false this.lifecycle.removeObserver(AudioUtils) this.lifecycle.removeObserver(chatViewModel) - - mediaController?.removeListener(playerListener) - stopProgressPolling() - - mediaControllerFuture?.let { MediaController.releaseFuture(it) } - mediaController = null } @OptIn(FlowPreview::class) @@ -2459,6 +2254,7 @@ class ChatActivity : private fun downloadFileToCache( message: ChatMessage, openWhenDownloaded: Boolean, + reuseRunningDownload: Boolean = false, funToCallWhenDownloadSuccessful: (() -> Unit) ) { message.isDownloadingVoiceMessage = true @@ -2480,11 +2276,15 @@ class ChatActivity : context ).getWorkInfosByTag(fileId!!) try { - for (workInfo in workers.get()) { - if (workInfo.state == WorkInfo.State.RUNNING || workInfo.state == WorkInfo.State.ENQUEUED) { - Log.d(TAG, "Download worker for $fileId is already running or scheduled") - return + val runningWork = workers.get().firstOrNull { + it.state == WorkInfo.State.RUNNING || it.state == WorkInfo.State.ENQUEUED + } + if (runningWork != null) { + Log.d(TAG, "Download worker for $fileId is already running or scheduled") + if (reuseRunningDownload) { + observeAudioDownload(runningWork.id, message, funToCallWhenDownloadSuccessful) } + return } } catch (e: ExecutionException) { Log.e(TAG, "Error when checking if worker already exists", e) @@ -2508,6 +2308,11 @@ class ChatActivity : WorkManager.getInstance().enqueue(downloadWorker) + if (reuseRunningDownload) { + observeAudioDownload(downloadWorker.id, message, funToCallWhenDownloadSuccessful) + return + } + WorkManager.getInstance(context).getWorkInfoByIdLiveData(downloadWorker.id) .observeForever { workInfo: WorkInfo? -> if (workInfo?.state == WorkInfo.State.SUCCEEDED) { @@ -2516,6 +2321,19 @@ class ChatActivity : } } + private fun observeAudioDownload(id: UUID, message: ChatMessage, onSuccess: () -> Unit) { + val work = WorkManager.getInstance(context).getWorkInfoByIdLiveData(id) + work.observeForever(object : androidx.lifecycle.Observer { + override fun onChanged(value: WorkInfo?) { + if (value?.state?.isFinished != true) return + work.removeObserver(this) + message.isDownloadingVoiceMessage = false + chatViewModel.syncVoiceMessageUiState(message) + if (value.state == WorkInfo.State.SUCCEEDED) onSuccess() + } + }) + } + fun isRecordAudioPermissionGranted(): Boolean = PermissionChecker.checkSelfPermission( context, @@ -4328,9 +4146,6 @@ class ChatActivity : private const val GET_ROOM_INFO_DELAY_NORMAL: Long = 30000 private const val GET_ROOM_INFO_DELAY_LOBBY: Long = 5000 private const val MILLIS_250 = 250L - private const val MILLIS_150 = 150L - private const val MILLIS_1000 = 1000L - private const val FLOAT_100 = 100f private const val AGE_THRESHOLD_FOR_DELETE_MESSAGE: Int = 21600000 // (6 hours in millis = 6 * 3600 * 1000) private const val REQUEST_SHARE_FILE_PERMISSION: Int = 221 private const val REQUEST_RECORD_AUDIO_PERMISSION = 222 diff --git a/app/src/main/java/com/nextcloud/talk/chat/MessageInputFragment.kt b/app/src/main/java/com/nextcloud/talk/chat/MessageInputFragment.kt index f6feee6b71f..b6d7d8b49b3 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/MessageInputFragment.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/MessageInputFragment.kt @@ -1201,16 +1201,20 @@ class MessageInputFragment : Fragment() { } private fun themeMessageInputView() { - binding.messageInputContainer.apply { - viewThemeUtils.talk.themeCardView(this) - } + binding.messageInputContainer.setCardBackgroundColor( + resources.getColor(R.color.bg_message_input, null) + ) binding.fragmentMessageInputView.findViewById(R.id.microphoneEnabledInfoBackground)?.let { - viewThemeUtils.platform.themeViewBackground(it, ColorRole.SURFACE_VARIANT) + it.backgroundTintList = android.content.res.ColorStateList.valueOf( + resources.getColor(R.color.bg_message_input, null) + ) } binding.fragmentMessageInputView.findViewById(R.id.audioRecordDuration)?.let { - viewThemeUtils.platform.themeViewBackground(it, ColorRole.SURFACE_VARIANT) + it.backgroundTintList = android.content.res.ColorStateList.valueOf( + resources.getColor(R.color.bg_message_input, null) + ) } binding.fragmentMessageInputView.button?.let { viewThemeUtils.platform.colorImageView(it, ColorRole.PRIMARY) } diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/io/MediaRecorderManager.kt b/app/src/main/java/com/nextcloud/talk/chat/data/io/MediaRecorderManager.kt index a08ef504e6d..2792d17fa50 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/io/MediaRecorderManager.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/io/MediaRecorderManager.kt @@ -32,6 +32,10 @@ class MediaRecorderManager : LifecycleAwareManager { private const val FILE_DATE_PATTERN = "yyyy-MM-dd HH-mm-ss" private const val VOICE_MESSAGE_FILE_SUFFIX = ".mp3" private const val VOICE_MESSAGE_PREFIX_MAX_LENGTH = 146 + + @Volatile + var isRecording = false + private set } var currentVoiceRecordFile: String = "" @@ -97,6 +101,7 @@ class MediaRecorderManager : LifecycleAwareManager { prepare() _mediaRecorderState = MediaRecorderState.PREPARED } catch (e: IOException) { + isRecording = false _mediaRecorderState = MediaRecorderState.ERROR Log.e(TAG, "prepare for audio recording failed") } @@ -106,10 +111,12 @@ class MediaRecorderManager : LifecycleAwareManager { _mediaRecorderState = MediaRecorderState.RECORDING Log.d(TAG, "recording started") } catch (e: IllegalStateException) { + isRecording = false _mediaRecorderState = MediaRecorderState.ERROR Log.e(TAG, "start for audio recording failed") } } + isRecording = _mediaRecorderState == MediaRecorderState.RECORDING } @Suppress("TooGenericExceptionCaught") @@ -135,6 +142,7 @@ class MediaRecorderManager : LifecycleAwareManager { } } recorder = null + isRecording = false } @SuppressLint("SimpleDateFormat") diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioController.kt b/app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioController.kt new file mode 100644 index 00000000000..4845e108618 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioController.kt @@ -0,0 +1,144 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.chat.data.io + +import android.content.ComponentName +import android.content.Context +import android.media.AudioManager +import androidx.core.content.ContextCompat +import androidx.core.net.toUri +import androidx.media3.common.MediaItem +import androidx.media3.common.MediaMetadata +import androidx.media3.common.Player +import androidx.media3.session.MediaController +import androidx.media3.session.SessionToken +import com.google.common.util.concurrent.ListenableFuture +import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.util.concurrent.CancellationException +import java.util.concurrent.ExecutionException +import javax.inject.Inject +import javax.inject.Singleton + +object MessageAudioPolicy { + fun canPlay(context: Context): Boolean { + val call = ApplicationWideCurrentRoomHolder.getInstance() + val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + return !call.isInCall && + !call.isDialing && + !MediaRecorderManager.isRecording && + audio.mode != AudioManager.MODE_IN_COMMUNICATION && + audio.mode != AudioManager.MODE_IN_CALL + } +} + +@Singleton +class MessageAudioController @Inject constructor(private val context: Context) { + val playback = MessageAudioPlayback { MessageAudioPolicy.canPlay(context) } + val state = playback.state + private val scope = MainScope() + private var future: ListenableFuture? = null + private var connection: CompletableDeferred? = null + private var controller: MediaController? = null + + private val listener = object : Player.Listener { + override fun onEvents(player: Player, events: Player.Events) = playback.refresh() + } + + fun stop() { + playback.stop() + disconnect() + } + + suspend fun connect(): Boolean { + connection?.let { return it.await() } + val ready = CompletableDeferred() + connection = ready + val pending = MediaController.Builder( + context.applicationContext, + SessionToken(context, ComponentName(context, VoiceMessageMediaService::class.java)) + ).setListener(object : MediaController.Listener { + override fun onDisconnected(controller: MediaController) { + disconnect() + } + }).buildAsync() + future = pending + pending.addListener({ + if (future !== pending) return@addListener + try { + val player = pending.get() + controller = player + playback.attach(ControllerPort(player)) + player.addListener(listener) + ready.complete(true) + scope.launch { + while (controller === player) { + playback.refresh() + delay(PROGRESS_INTERVAL_MS) + } + } + } catch (_: ExecutionException) { + disconnect() + } catch (_: CancellationException) { + disconnect() + } + }, ContextCompat.getMainExecutor(context)) + return ready.await() + } + + private fun disconnect() { + controller?.removeListener(listener) + controller = null + playback.attach(null) + val previous = future + future = null + connection?.complete(false) + connection = null + previous?.let { MediaController.releaseFuture(it) } + } + + private class ControllerPort(private val player: MediaController) : MessageAudioPort { + override val mediaId: String? get() = player.currentMediaItem?.mediaId + + override fun snapshot(track: MessageAudioTrack) = + MessageAudioState( + track = track, + isPlaying = player.isPlaying, + playWhenReady = player.playWhenReady, + positionMs = player.currentPosition.coerceAtLeast(0), + durationMs = player.duration.coerceAtLeast(0), + speed = player.playbackParameters.speed, + ended = player.playbackState == Player.STATE_ENDED + ) + + override fun load(track: MessageAudioTrack, speed: Float) { + player.setMediaItem( + MediaItem.Builder().setMediaId(track.key.mediaId).setUri(track.uri.toUri()) + .setMediaMetadata( + MediaMetadata.Builder().setTitle(track.title).setArtist(track.conversation).build() + ).build() + ) + player.setPlaybackSpeed(speed) + player.prepare() + } + + override fun play() = player.play() + override fun pause() = player.pause() + override fun clear() { + player.stop() + player.clearMediaItems() + } + + override fun seekTo(positionMs: Long) = player.seekTo(positionMs) + override fun setSpeed(speed: Float) = player.setPlaybackSpeed(speed) + } + + companion object { + private const val PROGRESS_INTERVAL_MS = 250L + } +} diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioPlayback.kt b/app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioPlayback.kt new file mode 100644 index 00000000000..3fc3b8b830c --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/chat/data/io/MessageAudioPlayback.kt @@ -0,0 +1,146 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.chat.data.io + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow + +data class MessageAudioKey(val accountId: Long, val roomToken: String, val messageId: Int) { + val mediaId: String get() = "$accountId/$roomToken/$messageId" +} + +data class MessageAudioTrack( + val key: MessageAudioKey, + val uri: String, + val title: String, + val conversation: String, + val isVoice: Boolean, + val threadId: Long? = null +) + +data class MessageAudioState( + val track: MessageAudioTrack? = null, + val isPlaying: Boolean = false, + val playWhenReady: Boolean = false, + val positionMs: Long = 0, + val durationMs: Long = 0, + val speed: Float = 1f, + val ended: Boolean = false +) { + val progress: Int + get() = if (durationMs > 0) ((positionMs * PERCENT / durationMs).toInt()).coerceIn(0, PERCENT) else 0 + + fun belongsTo(key: MessageAudioKey): Boolean = track?.key == key + + companion object { + private const val PERCENT = 100 + } +} + +interface MessageAudioPort { + val mediaId: String? + fun snapshot(track: MessageAudioTrack): MessageAudioState + fun load(track: MessageAudioTrack, speed: Float) + fun play() + fun pause() + fun clear() + fun seekTo(positionMs: Long) + fun setSpeed(speed: Float) +} + +/** Main-thread state and commands for the single service-owned message player. */ +class MessageAudioPlayback(private val canPlay: () -> Boolean = { true }) { + private var port: MessageAudioPort? = null + private var track: MessageAudioTrack? = null + private var generation = 0L + private var pendingKey: MessageAudioKey? = null + private val mutableState = MutableStateFlow(MessageAudioState()) + val state = mutableState.asStateFlow() + + fun attach(player: MessageAudioPort?) { + port = player + if (player == null) { + generation++ + pendingKey = null + track = null + } + refresh() + } + + fun beginRequest(key: MessageAudioKey): Long { + generation++ + pendingKey = key + if (track?.key != key) port?.pause() + refresh() + return generation + } + + fun completeRequest(request: Long, newTrack: MessageAudioTrack, speed: Float): Boolean { + val player = port + if (player == null || request != generation || pendingKey != newTrack.key || !canPlay()) return false + pendingKey = null + track = newTrack + player.load(newTrack, if (newTrack.isVoice) speed else 1f) + player.play() + refresh() + return true + } + + fun toggle(key: MessageAudioKey): Boolean { + val player = port + val current = track + if (player == null || current == null || current.key != key || player.mediaId != key.mediaId) return false + generation++ + pendingKey = null + val snapshot = player.snapshot(current) + if (snapshot.playWhenReady && !snapshot.ended) { + player.pause() + } else if (canPlay()) { + if (snapshot.ended) player.seekTo(0) + player.play() + } + refresh() + return true + } + + fun stop() { + generation++ + pendingKey = null + track = null + port?.clear() + refresh() + } + + fun seek(key: MessageAudioKey, percent: Int) { + if (track?.key != key || state.value.durationMs <= 0) return + port?.seekTo(state.value.durationMs * percent.coerceIn(0, PERCENT) / PERCENT) + refresh() + } + + fun setSpeed(key: MessageAudioKey, speed: Float) { + if (track?.key != key || track?.isVoice != true) return + port?.setSpeed(speed) + refresh() + } + + fun refresh() { + val current = track + val player = port + if (!canPlay()) { + generation++ + pendingKey = null + if (current != null && player?.snapshot(current)?.playWhenReady == true) player.pause() + } + mutableState.value = if (current != null && player?.mediaId == current.key.mediaId) { + player.snapshot(current) + } else { + MessageAudioState() + } + } + + companion object { + private const val PERCENT = 100 + } +} diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/io/VoiceMessageMediaService.kt b/app/src/main/java/com/nextcloud/talk/chat/data/io/VoiceMessageMediaService.kt index 3deed37744b..631134bab7c 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/io/VoiceMessageMediaService.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/io/VoiceMessageMediaService.kt @@ -8,6 +8,9 @@ package com.nextcloud.talk.chat.data.io import androidx.annotation.OptIn +import androidx.media3.common.AudioAttributes +import androidx.media3.common.C +import androidx.media3.common.ForwardingPlayer import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.ExoPlayer import androidx.media3.session.MediaSession @@ -19,7 +22,24 @@ class VoiceMessageMediaService : MediaSessionService() { @OptIn(UnstableApi::class) override fun onCreate() { super.onCreate() - val player = ExoPlayer.Builder(this).build() + val exoPlayer = ExoPlayer.Builder(this) + .setAudioAttributes( + AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_SPEECH).build(), + true + ) + .setHandleAudioBecomingNoisy(true) + .build() + val player = object : ForwardingPlayer(exoPlayer) { + override fun play() { + if (MessageAudioPolicy.canPlay(this@VoiceMessageMediaService)) super.play() + } + + override fun setPlayWhenReady(playWhenReady: Boolean) { + if (!playWhenReady || MessageAudioPolicy.canPlay(this@VoiceMessageMediaService)) { + super.setPlayWhenReady(playWhenReady) + } + } + } mediaSession = MediaSession.Builder(this, player).build() } diff --git a/app/src/main/java/com/nextcloud/talk/chat/ui/model/MessageAudioProjection.kt b/app/src/main/java/com/nextcloud/talk/chat/ui/model/MessageAudioProjection.kt new file mode 100644 index 00000000000..02ede1bd9c7 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/chat/ui/model/MessageAudioProjection.kt @@ -0,0 +1,49 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.chat.ui.model + +import com.nextcloud.talk.chat.data.io.MessageAudioKey +import com.nextcloud.talk.chat.data.io.MessageAudioState +import com.nextcloud.talk.chat.viewmodels.ChatViewModel +import com.nextcloud.talk.ui.PlaybackSpeed + +private const val MILLIS_PER_SECOND = 1000L + +fun List.withMessageAudio( + state: MessageAudioState, + accountId: Long, + roomToken: String +): List = + map { item -> + if (item !is ChatViewModel.ChatItem.MessageItem) return@map item + val message = item.uiMessage + val active = state.belongsTo(MessageAudioKey(accountId, roomToken, message.id)) + val content = when (val content = message.content) { + is MessageTypeContent.Voice -> + if (active) content.withPlayback(state) else content.copy(isPlaying = false) + is MessageTypeContent.AudioFile -> + if (active) content.withPlayback(state) else content.copy(isPlaying = false) + else -> content + } + if (content == message.content) item else item.copy(uiMessage = message.copy(content = content)) + } + +private fun MessageTypeContent.Voice.withPlayback(state: MessageAudioState) = + copy( + isPlaying = state.isPlaying, + playedSeconds = (state.positionMs / MILLIS_PER_SECOND).toInt(), + durationSeconds = if (state.durationMs > 0) (state.durationMs / MILLIS_PER_SECOND).toInt() else durationSeconds, + seekbarProgress = state.progress, + wasPlayed = wasPlayed || state.positionMs > 0, + playbackSpeed = PlaybackSpeed.entries.firstOrNull { it.value == state.speed } ?: playbackSpeed + ) + +private fun MessageTypeContent.AudioFile.withPlayback(state: MessageAudioState) = + copy( + isPlaying = state.isPlaying, + playedSeconds = (state.positionMs / MILLIS_PER_SECOND).toInt(), + durationSeconds = if (state.durationMs > 0) (state.durationMs / MILLIS_PER_SECOND).toInt() else durationSeconds, + seekbarProgress = state.progress + ) diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt index 514c334e641..fc47679c5a9 100644 --- a/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt @@ -52,6 +52,9 @@ import com.nextcloud.talk.activities.MainActivity import com.nextcloud.talk.api.NcApiCoroutines import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.chat.ChatActivity +import com.nextcloud.talk.chat.data.io.MessageAudioController +import com.nextcloud.talk.ui.MessageAudioBar +import com.nextcloud.talk.ui.openMessageAudioConversation import com.nextcloud.talk.contacts.ContactsActivity import com.nextcloud.talk.contacts.ContactsViewModel import com.nextcloud.talk.conversation.RenameConversationDialogFragment @@ -140,6 +143,9 @@ import retrofit2.HttpException @Suppress("LargeClass", "TooManyFunctions", "NestedBlockDepth") class ConversationsListActivity : BaseActivity() { + @Inject + lateinit var messageAudioController: MessageAudioController + // Started without an account on app start, when sharing from other apps and after login. override val allowsDefaultAccount = true @@ -264,7 +270,10 @@ class ConversationsListActivity : BaseActivity() { viewModel = conversationsListViewModel, tagsViewModel = conversationTagsViewModel, state = buildScreenState(), - callbacks = buildScreenCallbacks() + callbacks = buildScreenCallbacks(), + audioBar = { + MessageAudioBar(messageAudioController) { openMessageAudioConversation(it) } + } ) } diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationList.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationList.kt index 1016ca49228..f4dc7d2b0bc 100644 --- a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationList.kt +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationList.kt @@ -34,6 +34,7 @@ import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.pulltorefresh.PullToRefreshBox @@ -102,6 +103,7 @@ import kotlin.math.abs import kotlin.math.roundToInt private const val MSG_KEY_EXCERPT_LENGTH = 20 +private const val CONVERSATION_DIVIDER_ALPHA = 0.65f private const val TAGS_REVEAL_PULL_RESISTANCE = 0.5f private const val TAGS_REVEAL_SNAP_THRESHOLD_FRACTION = 0.35f @@ -284,17 +286,13 @@ fun ConversationList( coroutineScope = tagsRevealCoroutineScope ) - var prevIndex by remember { mutableIntStateOf(listState.firstVisibleItemIndex) } - var prevOffset by remember { mutableIntStateOf(listState.firstVisibleItemScrollOffset) } + val currentOnScrollChanged by rememberUpdatedState(onScrollChanged) + val currentOnScrollStopped by rememberUpdatedState(onScrollStopped) LaunchedEffect(listState) { + val directionTracker = ScrollDirectionTracker() snapshotFlow { listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset } .collect { (index, offset) -> - if (index != prevIndex || offset != prevOffset) { - val scrolledDown = index > prevIndex || (index == prevIndex && offset > prevOffset) - onScrollChanged(scrolledDown) - prevIndex = index - prevOffset = offset - } + directionTracker.onPosition(index, offset)?.let(currentOnScrollChanged) } } @@ -303,20 +301,20 @@ fun ConversationList( .collect { isScrolling -> if (!isScrolling) { val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0 - onScrollStopped(lastVisible) + currentOnScrollStopped(lastVisible) } } } LaunchedEffect(entries) { if (entries.isEmpty()) { - onScrollStopped(0) + currentOnScrollStopped(0) return@LaunchedEffect } snapshotFlow { listState.layoutInfo.visibleItemsInfo } .first { it.isNotEmpty() } val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0 - onScrollStopped(lastVisible) + currentOnScrollStopped(lastVisible) } Column( @@ -357,6 +355,7 @@ fun ConversationList( ) { itemsIndexed( items = entries, + contentType = { _, entry -> entry.javaClass }, key = { index, entry -> when (entry) { is ConversationListEntry.Header -> @@ -380,26 +379,36 @@ fun ConversationList( "load_more" } } - ) { _, entry -> + ) { index, entry -> when (entry) { is ConversationListEntry.Header -> ConversationSectionHeader(title = entry.title) is ConversationListEntry.ConversationEntry -> - SwipeableConversationItem( - model = entry.model, - onSwipe = { action -> onSwipeConversation(action, entry.model) }, - enabled = isOnline - ) { - ConversationListItem( + Column { + SwipeableConversationItem( model = entry.model, - currentUser = currentUser, - callbacks = ConversationListItemCallbacks( - onClick = { onConversationClick(entry.model) }, - onLongClick = { onConversationLongClick(entry.model) } - ), - searchQuery = searchQuery - ) + onSwipe = { action -> onSwipeConversation(action, entry.model) }, + enabled = isOnline + ) { + ConversationListItem( + model = entry.model, + currentUser = currentUser, + callbacks = ConversationListItemCallbacks( + onClick = { onConversationClick(entry.model) }, + onLongClick = { onConversationLongClick(entry.model) } + ), + searchQuery = searchQuery + ) + } + if (entries.getOrNull(index + 1) is ConversationListEntry.ConversationEntry) { + HorizontalDivider( + modifier = Modifier.padding(start = 80.dp, end = 16.dp), + thickness = 0.5.dp, + color = MaterialTheme.colorScheme.outlineVariant + .copy(alpha = CONVERSATION_DIVIDER_ALPHA) + ) + } } is ConversationListEntry.MessageResultEntry -> diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationListItem.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationListItem.kt index 2e347f4009c..47cb3cbec91 100644 --- a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationListItem.kt +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationListItem.kt @@ -47,7 +47,6 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.painter.BitmapPainter -import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext @@ -85,11 +84,9 @@ import com.nextcloud.talk.models.domain.ConversationModel import com.nextcloud.talk.models.json.chat.ChatMessageDto import com.nextcloud.talk.models.json.conversations.ConversationEnums import com.nextcloud.talk.models.json.participants.ParticipantDto -import com.nextcloud.talk.ui.StatusDrawable import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.AvatarImageLoader import com.nextcloud.talk.utils.CapabilitiesUtil.hasSpreedFeatureCapability -import com.nextcloud.talk.utils.DisplayUtils import com.nextcloud.talk.utils.SpreedFeatures private const val AVATAR_SIZE_DP = 48 @@ -97,7 +94,6 @@ private const val FAVORITE_OVERLAY_SIZE_DP = 16 private const val STATUS_OVERLAY_SIZE_DP = 18 private const val BADGE_OVERLAY_SIZE_DP = 18 private const val CALL_OVERLAY_SIZE_DP = 16 -private const val STATUS_INTERNAL_SIZE_DP = 9f private const val ICON_MSG_SIZE_DP = 14 private const val ICON_MSG_SPACING_DP = 2 private const val THREAD_ICON_ID = "threadIcon" @@ -372,52 +368,27 @@ private fun ActiveCallOverlay(modifier: Modifier = Modifier) { @Composable private fun StatusOverlay(model: ConversationModel, modifier: Modifier = Modifier) { - val isInPreview = LocalInspectionMode.current - - if (isInPreview) { - if (model.statusIcon != null) { - Text( - text = model.statusIcon!!, - modifier = modifier, - style = MaterialTheme.typography.labelSmall - ) - } else { - val drawableRes = when (model.status) { - "online" -> R.drawable.online_status - "away" -> R.drawable.ic_user_status_away - "busy" -> R.drawable.ic_user_status_busy - "dnd" -> R.drawable.ic_user_status_dnd - else -> null - } - if (drawableRes != null) { - Icon( - painter = painterResource(drawableRes), - contentDescription = null, - tint = Color.Unspecified, - modifier = modifier - ) - } + val emoji = model.statusIcon?.takeIf { it.isNotEmpty() && model.status != "dnd" } + if (emoji != null) { + Box(modifier = modifier, contentAlignment = Alignment.Center) { + Text(text = emoji, fontSize = 14.sp, lineHeight = 18.sp) } } else { - val context = LocalContext.current - val surfaceArgb = MaterialTheme.colorScheme.surface.toArgb() - AndroidView( - factory = { ctx -> - ImageView(ctx).apply { - val sizePx = DisplayUtils.convertDpToPixel(STATUS_INTERNAL_SIZE_DP, ctx) - setImageDrawable( - StatusDrawable(model.status, model.statusIcon, sizePx, surfaceArgb, ctx) - ) - } - }, - update = { imageView -> - val sizePx = DisplayUtils.convertDpToPixel(STATUS_INTERNAL_SIZE_DP, context) - imageView.setImageDrawable( - StatusDrawable(model.status, model.statusIcon, sizePx, surfaceArgb, context) - ) - }, - modifier = modifier - ) + val drawableRes = when (model.status) { + "online" -> R.drawable.online_status + "away" -> R.drawable.ic_user_status_away + "busy" -> R.drawable.ic_user_status_busy + "dnd" -> R.drawable.ic_user_status_dnd + else -> null + } + if (drawableRes != null) { + Icon( + painter = painterResource(drawableRes), + contentDescription = null, + tint = Color.Unspecified, + modifier = modifier.background(MaterialTheme.colorScheme.surface, CircleShape) + ) + } } } @@ -637,7 +608,9 @@ private fun LastMessageContent( // Deleted comment if (chatMessage.isDeletedCommentMessage) { - val parsedText = ChatUtils.getParsedMessage(chatMessage.message, chatMessage.messageParameters) ?: "" + val parsedText = remember(chatMessage.message, chatMessage.messageParameters) { + ChatUtils.getParsedMessage(chatMessage.message, chatMessage.messageParameters).orEmpty() + } val youPrefix = stringResource(R.string.nc_formatted_message_you, parsedText) val groupFormat = stringResource(R.string.nc_formatted_message) val guestLabel = stringResource(R.string.nc_guest) @@ -672,7 +645,9 @@ private fun LastMessageContent( if (msgType == ChatMessage.MessageType.SYSTEM_MESSAGE || model.type == ConversationEnums.ConversationType.ROOM_SYSTEM ) { - val parsedText = ChatUtils.getParsedMessage(chatMessage.message, chatMessage.messageParameters) ?: "" + val parsedText = remember(chatMessage.message, chatMessage.messageParameters) { + ChatUtils.getParsedMessage(chatMessage.message, chatMessage.messageParameters).orEmpty() + } Text( text = buildLastMessageText(parsedText, parsedText, chatMessage.isThread, searchQuery, primaryColor), modifier = modifier, @@ -799,7 +774,9 @@ private fun LastMessageContent( } // Regular text message - val parsedText = ChatUtils.getParsedMessage(chatMessage.message, chatMessage.messageParameters) ?: "" + val parsedText = remember(chatMessage.message, chatMessage.messageParameters) { + ChatUtils.getParsedMessage(chatMessage.message, chatMessage.messageParameters).orEmpty() + } val youPrefix = stringResource(R.string.nc_formatted_message_you, parsedText) val groupFormat = stringResource(R.string.nc_formatted_message) val guestLabel = stringResource(R.string.nc_guest) diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt index c8e7bf5193b..597d1c2ec05 100644 --- a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt @@ -129,7 +129,8 @@ fun ConversationsListScreen( viewModel: ConversationsListViewModel, tagsViewModel: ConversationTagsViewModel, state: ConversationsListScreenState, - callbacks: ConversationsListScreenCallbacks + callbacks: ConversationsListScreenCallbacks, + audioBar: @Composable () -> Unit = {} ) { val context = LocalContext.current val activity = context as Activity @@ -268,6 +269,7 @@ fun ConversationsListScreen( onAccountChooserClick = callbacks.onAccountChooserClick ) ) + audioBar() } } ) { paddingValues -> diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTracker.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTracker.kt new file mode 100644 index 00000000000..4fdcf3de990 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTracker.kt @@ -0,0 +1,28 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.conversationlist.ui + +internal class ScrollDirectionTracker { + private var previousIndex: Int? = null + private var previousOffset = 0 + private var lastDirection: Boolean? = null + + fun onPosition(index: Int, offset: Int): Boolean? { + val oldIndex = previousIndex + val oldOffset = previousOffset + previousIndex = index + previousOffset = offset + if (oldIndex == null || (index == oldIndex && offset == oldOffset)) return null + val direction = index > oldIndex || (index == oldIndex && offset > oldOffset) + return if (direction != lastDirection) { + lastDirection = direction + direction + } else { + null + } + } +} diff --git a/app/src/main/java/com/nextcloud/talk/extensions/ImageViewExtensions.kt b/app/src/main/java/com/nextcloud/talk/extensions/ImageViewExtensions.kt index f0a47be0367..a5a35b9bfd4 100644 --- a/app/src/main/java/com/nextcloud/talk/extensions/ImageViewExtensions.kt +++ b/app/src/main/java/com/nextcloud/talk/extensions/ImageViewExtensions.kt @@ -75,13 +75,21 @@ fun ImageView.loadConversationAvatar( ignoreCache: Boolean, viewThemeUtils: ViewThemeUtils? ): io.reactivex.disposables.Disposable { - val imageRequestUri = ApiUtils.getUrlForConversationAvatarWithVersion( - 1, - user.baseUrl, - conversation.token, - DisplayUtils.isDarkModeOn(this.context), - conversation.avatarVersion - ) + val isDark = DisplayUtils.isDarkModeOn(this.context) + val imageRequestUri = if ( + conversation.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL && + conversation.remoteServer.isNullOrEmpty() + ) { + ApiUtils.getUrlForAvatar(user.baseUrl, conversation.name, true, isDark) + } else { + ApiUtils.getUrlForConversationAvatarWithVersion( + 1, + user.baseUrl, + conversation.token, + isDark, + conversation.avatarVersion + ) + } if (conversation.avatarVersion.isNullOrEmpty() && viewThemeUtils != null) { when (conversation.type) { diff --git a/app/src/main/java/com/nextcloud/talk/jobs/CacheFileWriter.kt b/app/src/main/java/com/nextcloud/talk/jobs/CacheFileWriter.kt new file mode 100644 index 00000000000..260e642daae --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/jobs/CacheFileWriter.kt @@ -0,0 +1,42 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.jobs + +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.io.InterruptedIOException + +internal object CacheFileWriter { + @Suppress("LongParameterList") + fun write( + input: InputStream, + target: File, + expectedLength: Long, + isStopped: () -> Boolean, + onTemporaryFile: (File) -> Unit = {}, + publish: (File, File) -> Boolean = { temporary, destination -> temporary.renameTo(destination) }, + onProgress: (Long) -> Unit + ) { + val temporary = File.createTempFile("download-", ".part", target.parentFile) + try { + onTemporaryFile(temporary) + val total = temporary.outputStream().use { output -> + CancellableStreamCopy.copy(input, output, isStopped, onProgress) + } + validateComplete(total, expectedLength, isStopped()) + if (!publish(temporary, target)) throw IOException("Cannot publish downloaded file") + } finally { + temporary.delete() + } + } + + private fun validateComplete(total: Long, expectedLength: Long, stopped: Boolean) { + if (expectedLength >= 0 && total != expectedLength) throw IOException("Incomplete download") + if (stopped) throw InterruptedIOException("Download cancelled") + } +} diff --git a/app/src/main/java/com/nextcloud/talk/jobs/CancellableStreamCopy.kt b/app/src/main/java/com/nextcloud/talk/jobs/CancellableStreamCopy.kt new file mode 100644 index 00000000000..842a1576364 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/jobs/CancellableStreamCopy.kt @@ -0,0 +1,32 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.jobs + +import java.io.InputStream +import java.io.InterruptedIOException +import java.io.OutputStream + +internal object CancellableStreamCopy { + fun copy( + input: InputStream, + output: OutputStream, + isStopped: () -> Boolean, + onProgress: (Long) -> Unit = {} + ): Long { + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + var total = 0L + while (true) { + if (isStopped()) throw InterruptedIOException("File copy cancelled") + val count = input.read(buffer) + if (count < 0) break + output.write(buffer, 0, count) + total += count + onProgress(total) + } + return total + } +} diff --git a/app/src/main/java/com/nextcloud/talk/jobs/DownloadFileToCacheWorker.kt b/app/src/main/java/com/nextcloud/talk/jobs/DownloadFileToCacheWorker.kt index 27542f3c3f6..41f43130cb6 100644 --- a/app/src/main/java/com/nextcloud/talk/jobs/DownloadFileToCacheWorker.kt +++ b/app/src/main/java/com/nextcloud/talk/jobs/DownloadFileToCacheWorker.kt @@ -17,17 +17,16 @@ import com.nextcloud.talk.api.NcApi import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.data.user.model.User import com.nextcloud.talk.users.UserManager +import com.nextcloud.talk.mediaviewer.stream.ProgressiveVideoFile +import com.nextcloud.talk.mediaviewer.stream.VideoDownloadRegistry import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.FileUtils import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_INTERNAL_USER_ID import com.nextcloud.talk.utils.preferences.AppPreferences import kotlinx.coroutines.runBlocking import okhttp3.ResponseBody -import java.io.BufferedInputStream -import java.io.File -import java.io.FileOutputStream -import java.io.InputStream -import java.io.OutputStream +import retrofit2.Call +import java.io.IOException import javax.inject.Inject @AutoInjector(NextcloudTalkApplication::class) @@ -35,6 +34,15 @@ class DownloadFileToCacheWorker(val context: Context, workerParameters: WorkerPa Worker(context, workerParameters) { private var totalFileSize: Long = -1 + private var stream: ProgressiveVideoFile? = null + + @Volatile + private var activeCall: Call? = null + + override fun onStopped() { + activeCall?.cancel() + super.onStopped() + } @Inject lateinit var ncApi: NcApi @@ -48,11 +56,7 @@ class DownloadFileToCacheWorker(val context: Context, workerParameters: WorkerPa override fun doWork(): Result { NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this) - if (totalFileSize > -1) { - setProgressAsync(Data.Builder().putInt(PROGRESS, 0).build()) - } - - try { + return try { val currentUser = runBlocking { userManager.getUserWithId(inputData.getLong(KEY_INTERNAL_USER_ID, 0L)) } val attachmentFolder = inputData.getString(KEY_ATTACHMENT_FOLDER) val fileId = inputData.getString(KEY_FILE_ID) @@ -69,10 +73,19 @@ class DownloadFileToCacheWorker(val context: Context, workerParameters: WorkerPa val url = ApiUtils.getUrlForFileDownload(baseUrl, userId, remotePath) - return downloadFile(currentUser, url, fileId, fileName) + downloadFile(currentUser, url, fileId, fileName) } catch (e: IllegalStateException) { Log.e(javaClass.simpleName, "Something went wrong when trying to download file", e) - return Result.failure() + Result.failure() + } catch (e: IOException) { + Log.e(TAG, "File download failed", e) + Result.failure() + } finally { + activeCall = null + stream?.let { download -> + download.fail() + inputData.getString(KEY_STREAM_KEY)?.let { VideoDownloadRegistry.remove(it, download) } + } } } @@ -82,60 +95,61 @@ class DownloadFileToCacheWorker(val context: Context, workerParameters: WorkerPa url ) - return executeDownload(downloadCall.execute().body(), fileId, fileName) + activeCall = downloadCall + if (isStopped) downloadCall.cancel() + val response = downloadCall.execute() + if (!response.isSuccessful) { + response.errorBody()?.close() + return Result.failure() + } + val validator = response.headers()["ETag"]?.takeUnless { it.startsWith("W/") } + ?: response.headers()["Last-Modified"] + return response.body()?.use { executeDownload(it, fileId, fileName, validator) } ?: Result.failure() } - private fun executeDownload(body: ResponseBody?, fileId: String?, fileName: String): Result { + private fun executeDownload(body: ResponseBody, fileId: String?, fileName: String, validator: String?): Result { val targetFile = FileUtils.resolveSharedAttachmentFile(context.cacheDir, fileId, fileName) - if (body == null || targetFile == null) { - if (body == null) { - Log.e(TAG, "Response body when downloading $fileName is null!") - } - if (targetFile == null) { - Log.e(TAG, "Refused to download file with unsafe name: $fileName") - } + if (targetFile == null) { + Log.e(TAG, "Refused to download file with unsafe name: $fileName") return Result.failure() } - - var count: Int - val data = ByteArray(BYTE_UNIT_DIVIDER * DATA_BYTES) - val bis: InputStream = BufferedInputStream(body.byteStream(), BYTE_UNIT_DIVIDER * DOWNLOAD_STREAM_SIZE) - val outputFile = File(targetFile.parentFile, targetFile.name + "_") - val output: OutputStream = FileOutputStream(outputFile) - var total: Long = 0 - val startTime = System.currentTimeMillis() - var timeCount = 1 - - count = bis.read(data) - - while (count != -1) { - if (totalFileSize > 0) { - total += count.toLong() - val progress = (total * COMPLETE_PERCENTAGE / totalFileSize).toInt() - val currentTime = System.currentTimeMillis() - startTime - if (currentTime > PROGRESS_THRESHOLD * timeCount) { - setProgressAsync(Data.Builder().putInt(PROGRESS, progress).build()) - timeCount++ - } + val expectedLength = body.contentLength().takeIf { it >= 0 } ?: totalFileSize.takeIf { it > 0 } ?: -1L + val key = inputData.getString(KEY_STREAM_KEY) + val download = key?.let { ProgressiveVideoFile(expectedLength, validator) } + stream = download + var lastProgressTime = 0L + CacheFileWriter.write( + body.byteStream(), + targetFile, + expectedLength, + { isStopped }, + onTemporaryFile = { temporary -> + download?.attach(temporary) + if (key != null && download != null) VideoDownloadRegistry.register(key, download) + reportProgress(0L, expectedLength) + }, + publish = { temporary, target -> + download?.publish(temporary, target) ?: temporary.renameTo(target) + } + ) { total -> + download?.advance(total) + val now = android.os.SystemClock.elapsedRealtime() + if (now - lastProgressTime >= PROGRESS_THRESHOLD) { + reportProgress(total, expectedLength) + lastProgressTime = now } - output.write(data, 0, count) - count = bis.read(data) } - - output.flush() - output.close() - bis.close() - - return onDownloadComplete(outputFile, targetFile) + return Result.success(Data.Builder().putBoolean(SUCCESS, true).putInt(PROGRESS, COMPLETE_PERCENTAGE).build()) } - private fun onDownloadComplete(tempFile: File, targetFile: File): Result = - if (tempFile.renameTo(targetFile)) { - setProgressAsync(Data.Builder().putBoolean(SUCCESS, true).build()) - Result.success() - } else { - Result.failure() - } + private fun reportProgress(bytes: Long, total: Long) { + setProgressAsync( + Data.Builder() + .putInt(PROGRESS, DownloadProgress.percent(bytes, total)) + .putBoolean(STREAM_READY, stream != null) + .build() + ) + } companion object { const val TAG = "DownloadFileToCache" @@ -144,12 +158,11 @@ class DownloadFileToCacheWorker(val context: Context, workerParameters: WorkerPa const val KEY_FILE_NAME = "KEY_FILE_NAME" const val KEY_FILE_PATH = "KEY_FILE_PATH" const val KEY_FILE_SIZE = "KEY_FILE_SIZE" + const val KEY_STREAM_KEY = "VIDEO_STREAM_KEY" + const val STREAM_READY = "VIDEO_STREAM_READY" const val PROGRESS = "PROGRESS" const val SUCCESS = "SUCCESS" - const val BYTE_UNIT_DIVIDER = 1024 - const val DATA_BYTES = 4 - const val DOWNLOAD_STREAM_SIZE = 8 const val COMPLETE_PERCENTAGE = 100 - const val PROGRESS_THRESHOLD = 50 + const val PROGRESS_THRESHOLD = 250 } } diff --git a/app/src/main/java/com/nextcloud/talk/jobs/DownloadProgress.kt b/app/src/main/java/com/nextcloud/talk/jobs/DownloadProgress.kt new file mode 100644 index 00000000000..6a500921cbf --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/jobs/DownloadProgress.kt @@ -0,0 +1,14 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.jobs + +internal object DownloadProgress { + fun percent(bytes: Long, total: Long): Int = + if (total > 0) ((bytes.toDouble() / total) * COMPLETE).toInt().coerceIn(0, COMPLETE - 1) else -1 + + private const val COMPLETE = 100 +} diff --git a/app/src/main/java/com/nextcloud/talk/jobs/ExportVideoWorker.kt b/app/src/main/java/com/nextcloud/talk/jobs/ExportVideoWorker.kt new file mode 100644 index 00000000000..5550e8422a1 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/jobs/ExportVideoWorker.kt @@ -0,0 +1,85 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.jobs + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.DocumentsContract +import android.util.Log +import android.widget.Toast +import androidx.core.net.toUri +import androidx.work.Worker +import androidx.work.WorkerParameters +import com.nextcloud.talk.R +import com.nextcloud.talk.utils.FileUtils +import java.io.File +import java.io.IOException + +class ExportVideoWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) { + override fun doWork(): Result { + val destination = inputData.getString(DESTINATION)?.toUri() ?: return Result.failure() + val resolver = applicationContext.contentResolver + var success = false + try { + copyFile(destination) + success = true + } catch (exception: IOException) { + Log.e(TAG, "Video export failed", exception) + } catch (exception: SecurityException) { + Log.e(TAG, "Video export permission denied", exception) + } finally { + if (!success) removeIncompleteDocument(destination) + try { + resolver.releasePersistableUriPermission(destination, Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + } catch (exception: SecurityException) { + Log.w(TAG, "Video export permission already released", exception) + } + } + val message = if (success) R.string.nc_save_success else R.string.nc_common_error_sorry + Handler(Looper.getMainLooper()).post { + Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show() + } + return if (success) Result.success() else Result.failure() + } + + private fun copyFile(destination: Uri) { + sourceFile().inputStream().use { input -> + val output = applicationContext.contentResolver.openOutputStream(destination) + ?: throw IOException("Cannot open destination") + output.use { CancellableStreamCopy.copy(input, it, { isStopped }) } + } + } + + private fun sourceFile(): File { + val name = inputData.getString(FILE_NAME) ?: throw IOException("Missing source name") + return FileUtils.resolveSharedAttachmentFile( + applicationContext.cacheDir, + inputData.getString(FILE_ID), + name + ) ?: throw IOException("Invalid source file") + } + + private fun removeIncompleteDocument(destination: Uri) { + try { + DocumentsContract.deleteDocument(applicationContext.contentResolver, destination) + } catch (exception: IOException) { + Log.w(TAG, "Unable to remove incomplete export", exception) + } catch (exception: SecurityException) { + Log.w(TAG, "Unable to remove incomplete export", exception) + } + } + + companion object { + private const val TAG = "ExportVideoWorker" + const val FILE_ID = "fileId" + const val FILE_NAME = "fileName" + const val DESTINATION = "destination" + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerActivity.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerActivity.kt index 5314119ceaa..eec9cecdb14 100644 --- a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerActivity.kt @@ -8,6 +8,7 @@ package com.nextcloud.talk.mediaviewer.activities import android.content.Context import android.content.Intent +import android.content.res.Configuration import android.os.Bundle import android.util.Log import androidx.activity.SystemBarStyle @@ -41,6 +42,10 @@ import javax.inject.Inject import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.ui.LocalImageAuthHeader import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.nextcloud.talk.mediaviewer.model.VideoAction /** * Swipeable, group-aware media viewer - the entry point for every image/video tap in chat. See @@ -54,11 +59,16 @@ class MediaViewerActivity : BaseActivity() { private lateinit var viewModel: MediaViewerViewModel private lateinit var windowInsetsController: WindowInsetsControllerCompat + private lateinit var videoPlayback: VideoPlaybackController + private lateinit var videoExporter: VideoExporter + private var inPictureInPicture by mutableStateOf(false) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this) val user = setUpBoundUserOrFinish() ?: return + videoPlayback = VideoPlaybackController(this) + videoExporter = VideoExporter(this) val imageAuthHeader = ApiUtils.getCredentials(user.username, user.token) val roomToken = intent.getStringExtra(KEY_ROOM_TOKEN) @@ -81,7 +91,11 @@ class MediaViewerActivity : BaseActivity() { windowInsetsController = WindowCompat.getInsetsController(window, window.decorView) windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE - val composeView = ComposeView(this).apply { + setContentView(createContentView(imageAuthHeader)) + } + + private fun createContentView(imageAuthHeader: String?) = + ComposeView(this).apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { val colorScheme = viewThemeUtils.getColorScheme(this@MediaViewerActivity) @@ -91,6 +105,13 @@ class MediaViewerActivity : BaseActivity() { viewModel = viewModel, onShare = ::shareFile, onSave = ::showSaveDialog, + exoPlayer = videoPlayback.player, + inPictureInPicture = inPictureInPicture, + initialAction = VideoAction.entries.firstOrNull { + it.name == intent.getStringExtra(EXTRA_VIDEO_ACTION) + } ?: VideoAction.PLAY, + onInitialActionConsumed = { intent.removeExtra(EXTRA_VIDEO_ACTION) }, + onPictureInPicture = ::openPictureInPicture, onControlsVisibilityChanged = { visible -> if (visible) exitImmersiveMode() else enterImmersiveMode() } @@ -100,7 +121,27 @@ class MediaViewerActivity : BaseActivity() { } } - setContentView(composeView) + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + if (::videoPlayback.isInitialized) videoPlayback.player.pause() + setIntent(intent) + viewModelStore.clear() + recreate() + } + + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) + inPictureInPicture = isInPictureInPictureMode + } + + private fun openPictureInPicture() { + if (!videoPlayback.canPlay()) { + Snackbar.make(window.decorView, R.string.video_playback_blocked, Snackbar.LENGTH_LONG).show() + return + } + if (!videoPlayback.enterPictureInPicture()) { + Snackbar.make(window.decorView, R.string.video_pip_unavailable, Snackbar.LENGTH_LONG).show() + } } private fun enterImmersiveMode() { @@ -125,6 +166,10 @@ class MediaViewerActivity : BaseActivity() { } private fun showSaveDialog(item: MediaViewerItem, localPath: String) { + if (item.mimeType.startsWith("video/")) { + videoExporter.save(item) + return + } val safeFile = FileUtils.resolveSharedAttachmentFile(cacheDir, item.fileId, File(localPath).name) if (safeFile == null) { logger.e(TAG, "Refused to save file with unsafe name: ${File(localPath).name}") @@ -139,19 +184,23 @@ class MediaViewerActivity : BaseActivity() { private val TAG = MediaViewerActivity::class.java.simpleName private const val EXTRA_SEED_ITEMS = "MEDIA_VIEWER_SEED_ITEMS" private const val EXTRA_START_MESSAGE_ID = "MEDIA_VIEWER_START_MESSAGE_ID" + private const val EXTRA_VIDEO_ACTION = "MEDIA_VIEWER_VIDEO_ACTION" + @Suppress("LongParameterList") fun newIntent( context: Context, userId: Long, roomToken: String, seedItems: List, - startMessageId: Long + startMessageId: Long, + videoAction: VideoAction = VideoAction.PLAY ): Intent = Intent(context, MediaViewerActivity::class.java).apply { putExtra(BundleKeys.KEY_INTERNAL_USER_ID, userId) putExtra(KEY_ROOM_TOKEN, roomToken) putParcelableArrayListExtra(EXTRA_SEED_ITEMS, ArrayList(seedItems)) putExtra(EXTRA_START_MESSAGE_ID, startMessageId) + putExtra(EXTRA_VIDEO_ACTION, videoAction.name) } } } diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerScreen.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerScreen.kt index b79155536ac..3c896acfd95 100644 --- a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerScreen.kt +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/MediaViewerScreen.kt @@ -49,6 +49,10 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.ui.layout.onSizeChanged +import androidx.media3.common.PlaybackException +import androidx.compose.ui.text.style.TextAlign import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -70,7 +74,14 @@ import androidx.core.net.toUri import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.media3.common.AudioAttributes +import androidx.media3.common.Player +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import com.nextcloud.talk.chat.data.io.MessageAudioPolicy +import com.nextcloud.talk.mediaviewer.model.VideoAction +import com.nextcloud.talk.ui.chat.VideoActions import androidx.media3.common.MediaItem import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.ExoPlayer @@ -105,13 +116,18 @@ private val thumbnailSpacing = 4.dp private val thumbnailStripVerticalPadding = 12.dp private val controlsSlideDistance = 24.dp -@Suppress("Detekt.LongMethod", "CyclomaticComplexMethod") -@OptIn(ExperimentalMaterial3Api::class) +@Suppress("Detekt.LongMethod", "CyclomaticComplexMethod", "LongParameterList") +@OptIn(ExperimentalMaterial3Api::class, UnstableApi::class) @Composable fun MediaViewerScreen( viewModel: MediaViewerViewModel, onShare: (MediaViewerItem, String) -> Unit, onSave: (MediaViewerItem, String) -> Unit, + exoPlayer: ExoPlayer, + inPictureInPicture: Boolean, + initialAction: VideoAction, + onInitialActionConsumed: () -> Unit, + onPictureInPicture: () -> Unit, onControlsVisibilityChanged: (Boolean) -> Unit = {} ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() @@ -142,20 +158,78 @@ fun MediaViewerScreen( } } - val exoPlayer = rememberViewerExoPlayer() val currentItem = uiState.currentItem val currentLocalPath = currentItem?.let { uiState.cachedFilePaths[it.messageId] } + val currentStream = currentItem?.let { uiState.videoStreams[it.messageId] } + val currentPlaybackSource = currentStream ?: currentLocalPath + // Autoplay only the item the viewer was directly opened on from chat - once the user has // swiped to any other item, nothing autoplays again, even swiping back to this one. val initialMessageId = remember { items.getOrNull(uiState.currentGlobalIndex)?.messageId } var hasAutoPlayed by remember { mutableStateOf(false) } + val openingAction = remember { initialAction } + var pendingAction by remember { mutableStateOf(initialAction) } + var playerReady by remember { mutableStateOf(false) } + var hasVideoFrame by remember(currentItem?.messageId) { mutableStateOf(false) } + var playbackFailed by remember(currentItem?.messageId) { mutableStateOf(false) } + + DisposableEffect(exoPlayer, currentItem?.messageId) { + val listener = object : Player.Listener { + override fun onPlaybackStateChanged(playbackState: Int) { + playerReady = playbackState == Player.STATE_READY + } + + override fun onPlayerError(error: PlaybackException) { + playbackFailed = true + } + + override fun onRenderedFirstFrame() { + hasVideoFrame = true + if (pendingAction == VideoAction.PICTURE_IN_PICTURE && + currentItem?.messageId == initialMessageId && + MessageAudioPolicy.canPlay(context) + ) { + pendingAction = VideoAction.PLAY + onInitialActionConsumed() + onPictureInPicture() + } + } + } + exoPlayer.addListener(listener) + onDispose { exoPlayer.removeListener(listener) } + } LaunchedEffect(currentItem?.messageId, currentLocalPath) { + if (currentItem?.messageId != initialMessageId) { + pendingAction = VideoAction.PLAY + onInitialActionConsumed() + } else if (pendingAction == VideoAction.DOWNLOAD && currentLocalPath != null && currentItem != null) { + pendingAction = VideoAction.PLAY + onInitialActionConsumed() + onSave(currentItem, currentLocalPath) + } + } + + LaunchedEffect(currentItem?.messageId, currentPlaybackSource) { + playerReady = false + playbackFailed = false val isVideo = currentItem?.mimeType?.startsWith(Mimetype.VIDEO_PREFIX) == true - if (isVideo && currentLocalPath != null) { - exoPlayer.setMediaItem(MediaItem.fromUri(currentLocalPath.toUri())) - val shouldAutoPlay = !hasAutoPlayed && currentItem.messageId == initialMessageId + if (isVideo && currentItem != null && currentPlaybackSource != null) { + val media = MediaItem.Builder() + .setUri(currentLocalPath?.toUri() ?: "video://${currentItem.messageId}".toUri()) + .setMediaId(currentItem.messageId.toString()) + .setMimeType(currentItem.mimeType) + .build() + if (currentStream != null) { + exoPlayer.setMediaSource(currentStream.mediaSource(media)) + } else { + exoPlayer.setMediaItem(media) + } + val shouldAutoPlay = !hasAutoPlayed && + currentItem.messageId == initialMessageId && + openingAction != VideoAction.DOWNLOAD && + MessageAudioPolicy.canPlay(context) exoPlayer.playWhenReady = shouldAutoPlay if (shouldAutoPlay) hasAutoPlayed = true exoPlayer.prepare() @@ -172,8 +246,8 @@ fun MediaViewerScreen( // The status/nav bars toggle together with the top bar and thumbnail strip - one tap hides all // of it. - LaunchedEffect(showControls) { - onControlsVisibilityChanged(showControls) + LaunchedEffect(showControls, inPictureInPicture) { + onControlsVisibilityChanged(showControls && !inPictureInPicture) } // Hoisted here (rather than inside ThumbnailStrip) so its scroll position survives showControls @@ -193,10 +267,20 @@ fun MediaViewerScreen( val thumbnailStripHeightPx = with(density) { (thumbnailSize + thumbnailStripVerticalPadding * 2).roundToPx() } - val controllerExtraBottomInsetPx = if (hasThumbnailStrip) thumbnailStripHeightPx else 0 + val isCurrentVideo = currentItem?.mimeType?.startsWith(Mimetype.VIDEO_PREFIX) == true + var videoActionsHeightPx by remember { mutableIntStateOf(0) } + val controllerExtraBottomInsetPx = if (inPictureInPicture) { + 0 + } else { + (if (hasThumbnailStrip) thumbnailStripHeightPx else 0) + (if (isCurrentVideo) videoActionsHeightPx else 0) + } Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { - HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page -> + HorizontalPager( + state = pagerState, + userScrollEnabled = !inPictureInPicture, + modifier = Modifier.fillMaxSize() + ) { page -> val item = items.getOrNull(page) ?: return@HorizontalPager MediaPage( item = item, @@ -206,15 +290,17 @@ fun MediaViewerScreen( // on currentItem below), so mounting VideoPlayerView any earlier would attach it // to a page whose video hasn't been loaded into the player yet. isCurrentPage = page == pagerState.settledPage, + canStream = item.messageId in uiState.videoStreams, exoPlayer = exoPlayer, onToggleControls = { showControls = !showControls }, onControlsVisibilityChanged = { showControls = it }, - controllerExtraBottomInsetPx = controllerExtraBottomInsetPx + controllerExtraBottomInsetPx = controllerExtraBottomInsetPx, + inPictureInPicture = inPictureInPicture ) } AnimatedVisibility( - visible = showControls, + visible = showControls && !inPictureInPicture, enter = fadeIn() + slideInVertically(initialOffsetY = { -slideOffsetPx }), exit = fadeOut() + slideOutVertically(targetOffsetY = { -slideOffsetPx }), modifier = Modifier.align(Alignment.TopCenter) @@ -247,52 +333,92 @@ fun MediaViewerScreen( // spinner for the page the user had already left rather than the one on screen. val livePageItem = items.getOrNull(pagerState.currentPage) val livePageLocalPath = livePageItem?.let { uiState.cachedFilePaths[it.messageId] } - if (livePageItem != null && livePageLocalPath == null) { - CircularProgressIndicator( - modifier = Modifier.align(Alignment.Center).size(48.dp), - color = Color.White - ) + if (livePageItem != null && livePageLocalPath == null && !inPictureInPicture) { + val playing = livePageItem.messageId == currentItem?.messageId && hasVideoFrame && !playbackFailed + val placement = if (playing) { + Modifier.align(Alignment.TopEnd).statusBarsPadding().padding(top = 64.dp, end = 16.dp) + .background(Color.Black.copy(alpha = TOOLBAR_ALPHA), RoundedCornerShape(8.dp)).padding(8.dp) + } else { + Modifier.align(Alignment.Center) + } + Column(modifier = placement, horizontalAlignment = Alignment.CenterHorizontally) { + if (livePageItem.messageId in uiState.failedMessageIds) { + Text(stringResource(R.string.video_download_failed), color = Color.White) + TextButton(onClick = { viewModel.retryDownload(livePageItem.messageId) }) { + Text(stringResource(R.string.nc_retry), color = Color.White) + } + } else { + val percent = uiState.downloadProgress[livePageItem.messageId]?.takeIf { it >= 0 } + val indicator = Modifier.size(if (playing) 24.dp else 48.dp) + if (percent != null) { + CircularProgressIndicator( + progress = { percent / 100f }, + modifier = indicator, + color = Color.White + ) + Text("$percent%", color = Color.White) + } else { + CircularProgressIndicator(modifier = indicator, color = Color.White) + } + } + } + } + + if (playbackFailed && !inPictureInPicture) { + Column( + modifier = Modifier.align(Alignment.Center).padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text(stringResource(R.string.video_playback_failed), color = Color.White, textAlign = TextAlign.Center) + TextButton(onClick = { + playbackFailed = false + exoPlayer.prepare() + if (MessageAudioPolicy.canPlay(context)) exoPlayer.play() + }) { + Text(stringResource(R.string.nc_retry), color = Color.White) + } + } } AnimatedVisibility( - visible = showControls && hasThumbnailStrip, + visible = showControls && !inPictureInPicture && (hasThumbnailStrip || isCurrentVideo), enter = fadeIn() + slideInVertically(initialOffsetY = { slideOffsetPx }), exit = fadeOut() + slideOutVertically(targetOffsetY = { slideOffsetPx }), modifier = Modifier.align(Alignment.BottomCenter) ) { - if (group != null) { - ThumbnailStrip( - group = group, - currentItem = currentItem, - listState = thumbnailListState, - onThumbnailClick = { clickedItem -> - val globalIndex = items.indexOfFirst { it.messageId == clickedItem.messageId } - if (globalIndex >= 0) { - coroutineScope.launch { pagerState.animateScrollToPage(globalIndex) } + Column(modifier = Modifier.background(Color.Black.copy(alpha = TOOLBAR_ALPHA)).navigationBarsPadding()) { + if (isCurrentVideo && currentItem != null) { + VideoActions( + onAction = { action -> + when (action) { + VideoAction.DOWNLOAD -> currentLocalPath?.let { onSave(currentItem, it) } + VideoAction.PICTURE_IN_PICTURE -> if (playerReady) onPictureInPicture() + VideoAction.PLAY -> Unit + } + }, + modifier = Modifier.fillMaxWidth().onSizeChanged { videoActionsHeightPx = it.height }, + enabled = currentLocalPath != null, + pipEnabled = playerReady && !playbackFailed + ) + } + if (hasThumbnailStrip && group != null) { + ThumbnailStrip( + group = group, + currentItem = currentItem, + listState = thumbnailListState, + onThumbnailClick = { clickedItem -> + val globalIndex = items.indexOfFirst { it.messageId == clickedItem.messageId } + if (globalIndex >= 0) { + coroutineScope.launch { pagerState.animateScrollToPage(globalIndex) } + } } - } - ) + ) + } } } } } -@OptIn(UnstableApi::class) -@Composable -private fun rememberViewerExoPlayer(): ExoPlayer { - val context = LocalContext.current - val player = remember { - ExoPlayer.Builder(context) - .setAudioAttributes(AudioAttributes.DEFAULT, true) - .setHandleAudioBecomingNoisy(true) - .build() - } - DisposableEffect(Unit) { - onDispose { player.release() } - } - return player -} - @Suppress("LongParameterList") @OptIn(UnstableApi::class) @Composable @@ -300,26 +426,29 @@ private fun MediaPage( item: MediaViewerItem, localPath: String?, isCurrentPage: Boolean, + canStream: Boolean, exoPlayer: ExoPlayer, onToggleControls: () -> Unit, onControlsVisibilityChanged: (Boolean) -> Unit, - controllerExtraBottomInsetPx: Int + controllerExtraBottomInsetPx: Int, + inPictureInPicture: Boolean ) { val isVideo = item.mimeType.startsWith(Mimetype.VIDEO_PREFIX) Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { when { - localPath == null -> PreviewPlaceholder(item, onToggleControls = onToggleControls) + localPath == null && !canStream -> PreviewPlaceholder(item, onToggleControls = onToggleControls) isVideo -> if (isCurrentPage) { VideoPlayerView( exoPlayer = exoPlayer, onControlsVisibilityChanged = onControlsVisibilityChanged, - extraBottomInsetPx = controllerExtraBottomInsetPx + extraBottomInsetPx = controllerExtraBottomInsetPx, + inPictureInPicture = inPictureInPicture ) } else { PreviewPlaceholder(item, onToggleControls = onToggleControls) } - else -> ImagePage(localPath = localPath, onToggleControls = onToggleControls) + else -> localPath?.let { ImagePage(localPath = it, onToggleControls = onToggleControls) } } } } @@ -389,7 +518,8 @@ private fun ImagePage(localPath: String, onToggleControls: () -> Unit) { private fun VideoPlayerView( exoPlayer: ExoPlayer, onControlsVisibilityChanged: (Boolean) -> Unit, - extraBottomInsetPx: Int + extraBottomInsetPx: Int, + inPictureInPicture: Boolean ) { val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current @@ -407,7 +537,7 @@ private fun VideoPlayerView( factory = { ctx -> PlayerView(ctx).apply { player = exoPlayer - useController = true + useController = !inPictureInPicture controllerShowTimeoutMs = CONTROLLER_SHOW_TIMEOUT_MS showController() setControllerVisibilityListener( @@ -418,6 +548,8 @@ private fun VideoPlayerView( } }, update = { playerView -> + playerView.useController = !inPictureInPicture + if (inPictureInPicture) playerView.hideController() val exoControls = playerView.findViewById(R.id.exo_bottom_bar) val exoProgress = playerView.findViewById(R.id.exo_progress) exoControls?.apply { @@ -457,7 +589,6 @@ private fun ThumbnailStrip( modifier = modifier .fillMaxWidth() .background(Color.Black.copy(alpha = TOOLBAR_ALPHA)) - .navigationBarsPadding() .padding(vertical = thumbnailStripVerticalPadding) ) { // Side padding equal to half the leftover viewport width, so the row can scroll any item - diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoExporter.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoExporter.kt new file mode 100644 index 00000000000..90ae8a59d80 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoExporter.kt @@ -0,0 +1,71 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.activities + +import android.content.Intent +import android.content.Context +import android.net.Uri +import android.os.Bundle +import androidx.activity.result.contract.ActivityResultContracts +import androidx.work.Data +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import com.google.android.material.snackbar.Snackbar +import com.nextcloud.talk.R +import com.nextcloud.talk.jobs.ExportVideoWorker +import com.nextcloud.talk.mediaviewer.model.MediaViewerItem + +internal class VideoExporter(private val activity: MediaViewerActivity) { + private var pending = activity.savedStateRegistry.consumeRestoredStateForKey(STATE_KEY) + private val launcher = activity.registerForActivityResult( + object : ActivityResultContracts.CreateDocument("application/octet-stream") { + override fun createIntent(context: Context, input: String): Intent = + super.createIntent(context, input).setType(pending?.getString(MIME_TYPE) ?: "application/octet-stream") + }, + ::onDestinationSelected + ) + + private fun onDestinationSelected(uri: Uri?) { + val item = pending + pending = null + if (uri != null && item != null) { + try { + activity.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + val data = Data.Builder() + .putString(ExportVideoWorker.FILE_ID, item.getString(ExportVideoWorker.FILE_ID)) + .putString(ExportVideoWorker.FILE_NAME, item.getString(ExportVideoWorker.FILE_NAME)) + .putString(ExportVideoWorker.DESTINATION, uri.toString()) + .build() + WorkManager.getInstance(activity).enqueue( + OneTimeWorkRequestBuilder().setInputData(data).build() + ) + Snackbar.make(activity.window.decorView, R.string.video_saving, Snackbar.LENGTH_LONG).show() + } catch (_: SecurityException) { + Snackbar.make(activity.window.decorView, R.string.nc_common_error_sorry, Snackbar.LENGTH_LONG).show() + } + } + } + + init { + activity.savedStateRegistry.registerSavedStateProvider(STATE_KEY) { pending ?: Bundle() } + } + + fun save(item: MediaViewerItem) { + if (pending?.containsKey(ExportVideoWorker.FILE_NAME) == true) return + pending = Bundle().apply { + putString(ExportVideoWorker.FILE_ID, item.fileId) + putString(ExportVideoWorker.FILE_NAME, item.fileName) + putString(MIME_TYPE, item.mimeType) + } + launcher.launch(item.fileName) + } + + companion object { + private const val STATE_KEY = "video-export" + private const val MIME_TYPE = "mimeType" + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackController.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackController.kt new file mode 100644 index 00000000000..6faa61ccf02 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackController.kt @@ -0,0 +1,125 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.activities + +import android.app.PendingIntent +import android.app.PictureInPictureParams +import android.app.RemoteAction +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.PackageManager +import android.graphics.drawable.Icon +import android.os.Handler +import android.os.Looper +import android.util.Rational +import androidx.annotation.OptIn +import androidx.core.content.ContextCompat +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.media3.common.AudioAttributes +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.ExoPlayer +import com.nextcloud.talk.R +import com.nextcloud.talk.chat.data.io.MessageAudioPolicy + +@OptIn(UnstableApi::class) +internal class VideoPlaybackController(private val activity: MediaViewerActivity) : DefaultLifecycleObserver { + val player: ExoPlayer = ExoPlayer.Builder(activity) + .setAudioAttributes(AudioAttributes.DEFAULT, true) + .setHandleAudioBecomingNoisy(true) + .build() + + private val handler = Handler(Looper.getMainLooper()) + private val playbackGuard = VideoPlaybackGuard(player, ::canPlay) + private val action = "${activity.packageName}.VIDEO_PIP_TOGGLE" + private val monitor = object : Runnable { + override fun run() { + playbackGuard.enforcePolicy() + handler.postDelayed(this, POLICY_CHECK_INTERVAL_MS) + } + } + private val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == action && activity.isInPictureInPictureMode) { + playbackGuard.toggle() + } + } + } + + init { + activity.lifecycle.addObserver(this) + ContextCompat.registerReceiver(activity, receiver, IntentFilter(action), ContextCompat.RECEIVER_NOT_EXPORTED) + player.addListener(playbackGuard) + player.addListener(object : Player.Listener { + override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { + if (activity.isInPictureInPictureMode) activity.setPictureInPictureParams(parameters()) + } + }) + } + + fun canPlay(): Boolean = MessageAudioPolicy.canPlay(activity) + + fun enterPictureInPicture(): Boolean { + if (!activity.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) || + !canPlay() || + player.playbackState != Player.STATE_READY + ) { + return false + } + return try { + activity.enterPictureInPictureMode(parameters()) + } catch (_: IllegalStateException) { + false + } catch (_: IllegalArgumentException) { + false + } + } + + private fun parameters(): PictureInPictureParams { + val video = player.videoSize + val ratio = VideoPlaybackPolicy.pictureInPictureRatio(video.width, video.height, video.pixelWidthHeightRatio) + val drawable = if (player.playWhenReady) { + R.drawable.ic_baseline_pause_voice_message_24 + } else { + R.drawable.ic_baseline_play_arrow_voice_message_24 + } + val title = activity.getString(R.string.play_pause_audio_file) + val toggle = PendingIntent.getBroadcast( + activity, + 0, + Intent(action).setPackage(activity.packageName), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + return PictureInPictureParams.Builder() + .setAspectRatio(Rational((ratio * RATIO_SCALE).toInt(), RATIO_SCALE)) + .setActions(listOf(RemoteAction(Icon.createWithResource(activity, drawable), title, title, toggle))) + .build() + } + + override fun onStart(owner: LifecycleOwner) { + handler.post(monitor) + } + + override fun onStop(owner: LifecycleOwner) { + player.pause() + handler.removeCallbacks(monitor) + } + + override fun onDestroy(owner: LifecycleOwner) { + handler.removeCallbacksAndMessages(null) + activity.unregisterReceiver(receiver) + player.release() + } + + companion object { + private const val POLICY_CHECK_INTERVAL_MS = 250L + private const val RATIO_SCALE = 1000 + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuard.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuard.kt new file mode 100644 index 00000000000..e8bea8f1b23 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuard.kt @@ -0,0 +1,27 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.activities + +import androidx.media3.common.Player + +internal class VideoPlaybackGuard(private val player: Player, private val canPlay: () -> Boolean) : Player.Listener { + fun enforcePolicy() { + if (!canPlay()) player.pause() + } + + fun toggle() { + if (player.playWhenReady) { + player.pause() + } else if (canPlay()) { + player.play() + } + } + + override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { + if (playWhenReady) enforcePolicy() + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicy.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicy.kt new file mode 100644 index 00000000000..c331b142e05 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicy.kt @@ -0,0 +1,18 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.activities + +internal object VideoPlaybackPolicy { + private const val DEFAULT_RATIO = 16f / 9f + private const val MAX_RATIO = 2.38f + private const val MIN_RATIO = 0.42f + + fun pictureInPictureRatio(width: Int, height: Int, pixelRatio: Float): Float { + if (width <= 0 || height <= 0 || !pixelRatio.isFinite() || pixelRatio <= 0) return DEFAULT_RATIO + return (width.toFloat() * pixelRatio / height).coerceIn(MIN_RATIO, MAX_RATIO) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/model/VideoAction.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/model/VideoAction.kt new file mode 100644 index 00000000000..dd3915a3217 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/model/VideoAction.kt @@ -0,0 +1,9 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.model + +enum class VideoAction { PLAY, DOWNLOAD, PICTURE_IN_PICTURE } diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSource.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSource.kt new file mode 100644 index 00000000000..02ce6f1df35 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSource.kt @@ -0,0 +1,128 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import android.net.Uri +import androidx.annotation.OptIn +import androidx.media3.common.C +import androidx.media3.common.util.UnstableApi +import androidx.media3.datasource.BaseDataSource +import androidx.media3.datasource.DataSpec +import okhttp3.ResponseBody +import retrofit2.Call +import retrofit2.Response +import java.io.EOFException +import java.io.IOException + +@OptIn(UnstableApi::class) +internal class ProgressiveVideoDataSource( + private val download: ProgressiveVideoFile, + private val requestRange: (Long, String) -> Call +) : BaseDataSource(false) { + private var uri: Uri? = null + private var position = 0L + private var remaining = C.LENGTH_UNSET.toLong() + private var opened = false + private var rangeBody: ResponseBody? = null + + @Volatile private var rangeCall: Call? = null + + @Volatile private var closed = false + + override fun open(dataSpec: DataSpec): Long { + closed = false + transferInitializing(dataSpec) + uri = dataSpec.uri + position = dataSpec.position + remaining = if (dataSpec.length != C.LENGTH_UNSET.toLong()) { + dataSpec.length + } else if (download.length >= 0) { + (download.length - position).coerceAtLeast(0) + } else { + C.LENGTH_UNSET.toLong() + } + download.acquire() + opened = true + transferStarted(dataSpec) + if (download.needsRange(position)) openRange() + return remaining + } + + private fun openRange() { + val call = requestRange(position, checkNotNull(download.validator)) + rangeCall = call + val response = call.execute() + if (response.code() == HTTP_OK) { + // Servers without range support continue through the original sequential download. + response.body()?.close() + return + } + if (response.code() != HTTP_PARTIAL) { + response.errorBody()?.close() + response.body()?.close() + throw IOException("Video range request failed: ${response.code()}") + } + val body = requireBody(response) + try { + val size = VideoRangeResponse.validate(response.headers()["Content-Range"], position, download.length) + validateLength(body.contentLength(), size) + rangeBody = body + } catch (exception: IOException) { + body.close() + throw exception + } + } + + private fun requireBody(response: Response): ResponseBody = + response.body() ?: throw IOException("Empty video response") + + private fun validateLength(actual: Long, expected: Long) { + if (actual >= 0 && actual != expected) throw IOException("Invalid video length") + } + + override fun read(buffer: ByteArray, offset: Int, length: Int): Int = + when { + length == 0 -> 0 + remaining == 0L -> C.RESULT_END_OF_INPUT + else -> readAvailable(buffer, offset, length) + } + + private fun readAvailable(buffer: ByteArray, offset: Int, length: Int): Int { + val count = if (remaining < 0) length else minOf(length.toLong(), remaining).toInt() + val read = rangeBody?.byteStream()?.read(buffer, offset, count) + ?: download.read(position, buffer, offset, count) { closed } + if (read < 0) { + if (remaining > 0) throw EOFException("Incomplete video stream") + return C.RESULT_END_OF_INPUT + } + position += read + if (remaining >= 0) remaining -= read + bytesTransferred(read) + return read + } + + override fun getUri(): Uri? = uri + + override fun close() { + closed = true + rangeCall?.cancel() + rangeCall = null + rangeBody?.close() + rangeBody = null + uri = null + if (opened) { + opened = false + download.release() + transferEnded() + } + } + + companion object { + private const val HTTP_OK = 200 + private const val HTTP_PARTIAL = 206 + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFile.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFile.kt new file mode 100644 index 00000000000..b08ad6f047b --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFile.kt @@ -0,0 +1,94 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import java.io.File +import java.io.IOException +import java.io.InterruptedIOException +import java.io.RandomAccessFile + +/** A reader of the committed prefix of a download; an incomplete file is never reported as EOF. */ +class ProgressiveVideoFile(val length: Long, val validator: String?) { + private val monitor = Object() + private var file: File? = null + private var reader: RandomAccessFile? = null + private var readers = 0 + private var available = 0L + private var complete = false + private var failure: IOException? = null + + fun attach(temporary: File) = synchronized(monitor) { file = temporary } + + fun advance(bytes: Long) = + synchronized(monitor) { + available = bytes + monitor.notifyAll() + } + + fun publish(temporary: File, target: File): Boolean = + synchronized(monitor) { + reader?.close() + reader = null + val published = temporary.renameTo(target) + if (published) { + file = target + complete = true + monitor.notifyAll() + } + published + } + + fun fail() = + synchronized(monitor) { + if (!complete) failure = IOException("Video download did not complete") + monitor.notifyAll() + } + + fun acquire() = synchronized(monitor) { readers++ } + + fun release() = + synchronized(monitor) { + readers-- + if (readers == 0) { + reader?.close() + reader = null + } + } + + fun needsRange(position: Long): Boolean = + synchronized(monitor) { + position > available && position < length && !complete && validator != null + } + + @Suppress("LongParameterList") + fun read(position: Long, buffer: ByteArray, offset: Int, count: Int, cancelled: () -> Boolean): Int = + synchronized(monitor) { + while (true) { + if (cancelled() || Thread.currentThread().isInterrupted) throw InterruptedIOException("Read cancelled") + failure?.let { throw it } + if (count == 0) return@synchronized 0 + if (position < available) { + val input = reader ?: RandomAccessFile(checkNotNull(file), "r").also { reader = it } + input.seek(position) + return@synchronized input.read(buffer, offset, minOf(count.toLong(), available - position).toInt()) + } + if (complete || (length >= 0 && position >= length)) return@synchronized -1 + try { + monitor.wait(WAIT_INTERVAL_MS) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + throw InterruptedIOException("Read cancelled") + } + } + @Suppress("UNREACHABLE_CODE") + -1 + } + + companion object { + private const val WAIT_INTERVAL_MS = 100L + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoDownloadRegistry.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoDownloadRegistry.kt new file mode 100644 index 00000000000..588d4bb10ff --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoDownloadRegistry.kt @@ -0,0 +1,23 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import java.util.concurrent.ConcurrentHashMap + +object VideoDownloadRegistry { + private val downloads = ConcurrentHashMap() + + fun find(key: String): ProgressiveVideoFile? = downloads[key] + + fun register(key: String, download: ProgressiveVideoFile) { + downloads[key] = download + } + + fun remove(key: String, download: ProgressiveVideoFile) { + downloads.remove(key, download) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponse.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponse.kt new file mode 100644 index 00000000000..a2b063edee3 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponse.kt @@ -0,0 +1,27 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import java.io.IOException + +internal object VideoRangeResponse { + fun validate(header: String?, start: Long, total: Long): Long { + val values = Regex("bytes (\\d+)-(\\d+)/(\\d+)").matchEntire(header.orEmpty()) + ?.groupValues?.drop(1)?.mapNotNull { it.toLongOrNull() } + if (values == null || values.size != RANGE_VALUES) throw IOException("Invalid video byte range") + if (values[0] != start || + values[2] != total || + values[1] != total - 1 || + start >= total + ) { + throw IOException("Unexpected video byte range") + } + return total - start + } + + private const val RANGE_VALUES = 3 +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoStreamSource.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoStreamSource.kt new file mode 100644 index 00000000000..54ced9ab1e7 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/stream/VideoStreamSource.kt @@ -0,0 +1,23 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import androidx.annotation.OptIn +import androidx.media3.common.MediaItem +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.source.ProgressiveMediaSource +import okhttp3.ResponseBody +import retrofit2.Call + +class VideoStreamSource( + private val download: ProgressiveVideoFile, + private val requestRange: (Long, String) -> Call +) { + @OptIn(UnstableApi::class) + fun mediaSource(item: MediaItem): ProgressiveMediaSource = + ProgressiveMediaSource.Factory { ProgressiveVideoDataSource(download, requestRange) }.createMediaSource(item) +} diff --git a/app/src/main/java/com/nextcloud/talk/mediaviewer/viewmodels/MediaViewerViewModel.kt b/app/src/main/java/com/nextcloud/talk/mediaviewer/viewmodels/MediaViewerViewModel.kt index 694c6f7e544..193ffb8d9f5 100644 --- a/app/src/main/java/com/nextcloud/talk/mediaviewer/viewmodels/MediaViewerViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/mediaviewer/viewmodels/MediaViewerViewModel.kt @@ -7,6 +7,9 @@ package com.nextcloud.talk.mediaviewer.viewmodels import android.util.Log +import android.content.Context +import androidx.work.ExistingWorkPolicy +import androidx.work.await import androidx.lifecycle.ViewModel import androidx.lifecycle.asFlow import androidx.lifecycle.viewModelScope @@ -17,6 +20,10 @@ import com.nextcloud.talk.utils.setExpeditedIfSupported import androidx.work.WorkInfo import androidx.work.WorkManager import com.nextcloud.talk.application.NextcloudTalkApplication +import com.nextcloud.talk.api.NcApi +import com.nextcloud.talk.utils.ApiUtils +import com.nextcloud.talk.mediaviewer.stream.VideoDownloadRegistry +import com.nextcloud.talk.mediaviewer.stream.VideoStreamSource import com.nextcloud.talk.data.user.model.User import com.nextcloud.talk.jobs.DownloadFileToCacheWorker import com.nextcloud.talk.mediaviewer.model.MediaViewerGroup @@ -33,7 +40,9 @@ import com.nextcloud.talk.utils.FileUtils import io.reactivex.Observable import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine @@ -49,8 +58,10 @@ import kotlin.coroutines.resumeWithException * why "older" does). "Older" navigation pages further back through conversation history via * [SharedItemsRepository] once the locally seeded items run out. */ -class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository: SharedItemsRepository) : - ViewModel() { +class MediaViewerViewModel @Inject constructor( + private val sharedItemsRepository: SharedItemsRepository, + private val ncApi: NcApi +) : ViewModel() { data class PendingShift(val id: Long, val amount: Int) @@ -61,6 +72,9 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository val canLoadOlder: Boolean = true, val cachedFilePaths: Map = emptyMap(), val downloadingMessageIds: Set = emptySet(), + val failedMessageIds: Set = emptySet(), + val downloadProgress: Map = emptyMap(), + val videoStreams: Map = emptyMap(), val pendingShift: PendingShift? = null ) { val flattenedItems: List get() = groups.flatMap { it.items } @@ -81,6 +95,7 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository private var oldestKnownMessageId: Long? = null fun initialize(user: User, roomToken: String, seedItems: List, startMessageId: Long) { + viewModelScope.coroutineContext.cancelChildren() this.user = user repositoryParameters = SharedItemsRepository.Parameters( // The login name, as it authenticates the requests. The user id can differ from it. @@ -94,12 +109,12 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository oldestKnownMessageId = seedItems.minOfOrNull { it.messageId } _uiState.value = UiState(groups = groups, currentGlobalIndex = startIndex) - ensureCachedAround(startIndex) + ensureCurrentCached(startIndex) } fun onPageSettled(globalIndex: Int) { _uiState.update { it.copy(currentGlobalIndex = globalIndex) } - ensureCachedAround(globalIndex) + ensureCurrentCached(globalIndex) if (globalIndex <= EDGE_LOAD_THRESHOLD) { loadOlderGroups() } @@ -113,11 +128,12 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository _uiState.update { if (it.pendingShift?.id == id) it.copy(pendingShift = null) else it } } - private fun ensureCachedAround(globalIndex: Int) { - val items = _uiState.value.flattenedItems - for (index in (globalIndex - PREFETCH_RADIUS)..(globalIndex + PREFETCH_RADIUS)) { - items.getOrNull(index)?.let(::ensureCached) - } + private fun ensureCurrentCached(globalIndex: Int) { + _uiState.value.flattenedItems.getOrNull(globalIndex)?.let(::ensureCached) + } + + fun retryDownload(messageId: Long) { + _uiState.value.flattenedItems.firstOrNull { it.messageId == messageId }?.let(::ensureCached) } private fun ensureCached(item: MediaViewerItem) { @@ -136,9 +152,17 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository return } - _uiState.update { it.copy(downloadingMessageIds = it.downloadingMessageIds + item.messageId) } + _uiState.update { + it.copy( + downloadingMessageIds = it.downloadingMessageIds + item.messageId, + failedMessageIds = it.failedMessageIds - item.messageId, + downloadProgress = it.downloadProgress - item.messageId + ) + } + val workName = "media-download-${user.id}-${item.fileId}-${item.fileName}" val data = Data.Builder() + .putString(DownloadFileToCacheWorker.KEY_STREAM_KEY, workName.takeIf { item.mimeType.startsWith("video/") }) .putLong(BundleKeys.KEY_INTERNAL_USER_ID, user.id!!) .putString( DownloadFileToCacheWorker.KEY_ATTACHMENT_FOLDER, @@ -155,33 +179,88 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository .addTag(item.fileId) .setExpeditedIfSupported() .build() - WorkManager.getInstance(context).enqueue(request) + observeDownload(context, workName, request, item) + } + @Suppress("TooGenericExceptionCaught") + private fun observeDownload( + context: Context, + workName: String, + request: OneTimeWorkRequest, + item: MediaViewerItem + ) { viewModelScope.launch { - WorkManager.getInstance(context).getWorkInfoByIdLiveData(request.id).asFlow().collect { workInfo -> - if (workInfo == null) return@collect - when (workInfo.state) { - WorkInfo.State.SUCCEEDED -> { - val downloaded = FileUtils.resolveSharedAttachmentFile( - context.cacheDir, - item.fileId, - item.fileName - ) - _uiState.update { - it.copy( - downloadingMessageIds = it.downloadingMessageIds - item.messageId, - cachedFilePaths = downloaded?.let { file -> - it.cachedFilePaths + (item.messageId to file.absolutePath) - } ?: it.cachedFilePaths - ) - } - } - WorkInfo.State.FAILED, WorkInfo.State.CANCELLED -> { - _uiState.update { it.copy(downloadingMessageIds = it.downloadingMessageIds - item.messageId) } - } - else -> Unit + try { + val manager = WorkManager.getInstance(context) + manager.enqueueUniqueWork(workName, ExistingWorkPolicy.KEEP, request).await() + manager.getWorkInfosForUniqueWorkLiveData(workName).asFlow().first { workInfos -> + val workInfo = workInfos.firstOrNull { it.id == request.id } ?: workInfos.singleOrNull() + if (workInfo == null) return@first false + updateDownload(context, item, workInfo, workName) + workInfo.state.isFinished + } + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + Log.e(TAG, "Unable to observe media download", exception) + markDownloadFailed(item.messageId) + } + } + } + + private fun updateDownload(context: Context, item: MediaViewerItem, workInfo: WorkInfo, workName: String) { + when (workInfo.state) { + WorkInfo.State.SUCCEEDED -> { + val downloaded = FileUtils.resolveSharedAttachmentFile(context.cacheDir, item.fileId, item.fileName) + ?.takeIf { it.isFile } + _uiState.update { + it.copy( + downloadingMessageIds = it.downloadingMessageIds - item.messageId, + downloadProgress = it.downloadProgress + (item.messageId to 100), + failedMessageIds = if (downloaded != null) { + it.failedMessageIds - item.messageId + } else { + it.failedMessageIds + item.messageId + }, + cachedFilePaths = downloaded?.let { file -> + it.cachedFilePaths + (item.messageId to file.absolutePath) + } ?: it.cachedFilePaths + ) } } + WorkInfo.State.FAILED, WorkInfo.State.CANCELLED -> markDownloadFailed(item.messageId) + WorkInfo.State.RUNNING -> updateRunningDownload(item, workInfo, workName) + else -> Unit + } + } + + private fun updateRunningDownload(item: MediaViewerItem, workInfo: WorkInfo, workName: String) { + val source = if (item.messageId !in _uiState.value.videoStreams) createVideoStream(item, workName) else null + _uiState.update { + it.copy( + downloadProgress = it.downloadProgress + + (item.messageId to workInfo.progress.getInt(DownloadFileToCacheWorker.PROGRESS, -1)), + videoStreams = source?.let { stream -> it.videoStreams + (item.messageId to stream) } ?: it.videoStreams + ) + } + } + + private fun createVideoStream(item: MediaViewerItem, workName: String): VideoStreamSource? { + val download = VideoDownloadRegistry.find(workName) ?: return null + val credentials = ApiUtils.getCredentials(user.username, user.token) + val url = ApiUtils.getUrlForFileDownload(user.baseUrl!!, user.userId!!, item.path) + return VideoStreamSource(download) { position, validator -> + ncApi.downloadVideoRange(credentials, url, "bytes=$position-", validator) + } + } + + private fun markDownloadFailed(messageId: Long) { + _uiState.update { + it.copy( + downloadingMessageIds = it.downloadingMessageIds - messageId, + failedMessageIds = it.failedMessageIds + messageId, + videoStreams = it.videoStreams - messageId + ) } } @@ -198,6 +277,8 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository viewModelScope.launch { val sharedItems = try { sharedItemsRepository.media(repositoryParameters, SharedItemType.MEDIA, cursor.toInt())?.awaitFirst() + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Failed to load older shared items", e) null @@ -239,7 +320,6 @@ class MediaViewerViewModel @Inject constructor(private val sharedItemsRepository companion object { private val TAG = MediaViewerViewModel::class.simpleName - private const val PREFETCH_RADIUS = 1 private const val EDGE_LOAD_THRESHOLD = 1 } } diff --git a/app/src/main/java/com/nextcloud/talk/ui/ComposeWaveformSeekbar.kt b/app/src/main/java/com/nextcloud/talk/ui/ComposeWaveformSeekbar.kt index 2765aee7b68..187def33adb 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/ComposeWaveformSeekbar.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/ComposeWaveformSeekbar.kt @@ -7,13 +7,9 @@ package com.nextcloud.talk.ui -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider @@ -23,15 +19,12 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -const val WAVEFORM_THUMB_SIZE = 20 const val WAVEFORM_SIZE = 30 -const val MAX_HEIGHT = 100 -const val OVERLAP = 0.025 -const val PROGRESS = 0.97f +private const val INACTIVE_WAVEFORM_ALPHA = 0.4f +private const val PREVIEW_PROGRESS = 0.4f @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -42,39 +35,33 @@ fun ComposeWaveformSeekBar( waveData: FloatArray, enabled: Boolean ) { - val barWidth = Stroke.DefaultMiter - val thumbSize = WAVEFORM_THUMB_SIZE.dp - val inversePrimary = MaterialTheme.colorScheme.inversePrimary - val onPrimaryContainer = MaterialTheme.colorScheme.onPrimaryContainer - + val activeColor = MaterialTheme.colorScheme.primary + val inactiveColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = INACTIVE_WAVEFORM_ALPHA) Slider( value = value, enabled = enabled, onValueChange = onValueChange, + modifier = modifier, track = { Box( - modifier = modifier + modifier = Modifier + .fillMaxWidth() + .height(32.dp) .drawWithCache { + val barWidth = 3.dp.toPx() + val midpoint = size.height / 2f + val halfBar = barWidth / 2f + val barGap = (size.width - barWidth) / (waveData.size - 1).coerceAtLeast(1) onDrawBehind { - val height = this.size.height - val width = this.size.width + 8.dp.value - val midpoint = (this.size.height / 2f) - - val barGap = (width - waveData.size * barWidth) / (waveData.size - 1).toFloat() + 1 for (i in waveData.indices) { - val x: Float = i * (barWidth + barGap) - - if (x < 0f || x > size.width) continue - - val y: Float = (waveData[i] * height).coerceIn(0f, midpoint) - - val isXBeforeThumb = x <= value * width - + val x = halfBar + i * barGap + val amplitude = waveData[i].takeIf { it.isFinite() } ?: 0f + val y = (amplitude * size.height).coerceIn(halfBar, midpoint) drawLine( - if (isXBeforeThumb) inversePrimary else onPrimaryContainer, + color = if (i < value * waveData.size) activeColor else inactiveColor, start = Offset(x, midpoint - y), end = Offset(x, midpoint + y), - strokeWidth = Stroke.DefaultMiter, + strokeWidth = barWidth, cap = StrokeCap.Round ) } @@ -82,30 +69,19 @@ fun ComposeWaveformSeekBar( } ) }, - thumb = { - Box( - modifier = Modifier - .size(thumbSize) - .background(inversePrimary, shape = CircleShape) - ) - } + thumb = {} ) } -@OptIn(ExperimentalMaterial3Api::class) @Composable @Preview fun Preview() { val waveData = remember { FloatArray(WAVEFORM_SIZE) { (Math.random() % 1).toFloat() } } - ComposeWaveformSeekBar( - PROGRESS, - {}, - modifier = Modifier - .height(MAX_HEIGHT.dp) - .fillMaxWidth() - .padding(8.dp), - waveData, - true + value = PREVIEW_PROGRESS, + onValueChange = {}, + modifier = Modifier.fillMaxWidth(), + waveData = waveData, + enabled = true ) } diff --git a/app/src/main/java/com/nextcloud/talk/ui/MessageAudioBar.kt b/app/src/main/java/com/nextcloud/talk/ui/MessageAudioBar.kt new file mode 100644 index 00000000000..6591210daab --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/MessageAudioBar.kt @@ -0,0 +1,202 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui + +import android.os.Bundle +import android.text.format.DateUtils +import androidx.appcompat.app.AppCompatActivity +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDirection +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.text.BidiFormatter +import androidx.core.text.TextDirectionHeuristicsCompat +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.nextcloud.talk.R +import com.nextcloud.talk.chat.ChatActivity +import com.nextcloud.talk.chat.data.io.MessageAudioController +import com.nextcloud.talk.chat.data.io.MessageAudioState +import com.nextcloud.talk.chat.data.io.MessageAudioTrack +import com.nextcloud.talk.ui.chat.ChatFontFamily +import com.nextcloud.talk.utils.bundle.BundleKeys + +private const val MILLIS_PER_SECOND = 1000L +private const val PROGRESS_MAX = 100f + +fun AppCompatActivity.openMessageAudioConversation(track: MessageAudioTrack) { + val extras = Bundle().apply { + putLong(BundleKeys.KEY_MESSAGE_ID, track.key.messageId.toLong()) + track.threadId?.let { putLong(BundleKeys.KEY_THREAD_ID, it) } + } + startActivity(ChatActivity.createIntent(this, track.key.accountId, track.key.roomToken, extras)) +} + +@Composable +fun MessageAudioBar(controller: MessageAudioController, onOpen: (MessageAudioTrack) -> Unit) { + val state by controller.state.collectAsStateWithLifecycle() + val track = state.track ?: return + if (state.ended) return + val speed = PlaybackSpeed.entries.firstOrNull { it.value == state.speed } ?: PlaybackSpeed.NORMAL + MessageAudioBarContent( + state = state, + onToggle = { controller.playback.toggle(track.key) }, + onSpeed = { controller.playback.setSpeed(track.key, speed.next().value) }, + onStop = { controller.stop() }, + onOpen = { onOpen(track) } + ) +} + +@Suppress("LongMethod") +@Composable +private fun MessageAudioBarContent( + state: MessageAudioState, + onToggle: () -> Unit, + onSpeed: () -> Unit, + onStop: () -> Unit, + onOpen: () -> Unit +) { + val track = state.track ?: return + val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl + val progress = state.progress / PROGRESS_MAX + val accent = MaterialTheme.colorScheme.primary + val speed = PlaybackSpeed.entries.firstOrNull { it.value == state.speed } ?: PlaybackSpeed.NORMAL + Surface(color = MaterialTheme.colorScheme.surface) { + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) { + Column { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp).padding(horizontal = 4.dp) + ) { + IconButton(onClick = onToggle, modifier = Modifier.size(48.dp)) { + Icon( + painterResource( + if (state.playWhenReady) { + R.drawable.ic_baseline_pause_voice_message_24 + } else { + R.drawable.ic_baseline_play_arrow_voice_message_24 + } + ), + contentDescription = stringResource( + if (track.isVoice) R.string.play_pause_voice_message else R.string.play_pause_audio_file + ), + tint = accent, + modifier = Modifier.size(26.dp) + ) + } + MessageAudioBarDetails( + state = state, + isRtl = isRtl, + onOpen = onOpen, + modifier = Modifier.weight(1f) + ) + if (track.isVoice) { + MessageAudioSpeedButton(label = speed.label, onClick = onSpeed) + } + IconButton(onClick = onStop, modifier = Modifier.size(48.dp)) { + Icon( + painterResource(R.drawable.ic_baseline_close_24), + contentDescription = stringResource(R.string.nc_stop_message_audio), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + } + Box( + modifier = Modifier + .fillMaxWidth() + .height(2.dp) + .background(MaterialTheme.colorScheme.outlineVariant) + .drawBehind { drawRect(accent, size = size.copy(width = size.width * progress)) } + .semantics { progressBarRangeInfo = ProgressBarRangeInfo(progress, 0f..1f) } + ) + } + } + } +} + +@Composable +private fun MessageAudioBarDetails( + state: MessageAudioState, + isRtl: Boolean, + onOpen: () -> Unit, + modifier: Modifier = Modifier +) { + val track = state.track ?: return + val elapsed = DateUtils.formatElapsedTime(state.positionMs / MILLIS_PER_SECOND) + val duration = DateUtils.formatElapsedTime(state.durationMs / MILLIS_PER_SECOND) + val time = BidiFormatter.getInstance(isRtl).unicodeWrap("$elapsed / $duration", TextDirectionHeuristicsCompat.LTR) + val textAlign = if (isRtl) TextAlign.Right else TextAlign.Left + Column( + modifier = modifier + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onOpen) + .padding(horizontal = 6.dp, vertical = 4.dp) + ) { + Text( + text = track.title, + style = TextStyle( + fontFamily = ChatFontFamily, + fontSize = 14.sp, + lineHeight = 22.sp, + fontWeight = FontWeight.Medium, + textDirection = TextDirection.Content, + textAlign = textAlign + ), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.fillMaxWidth() + ) + Text( + text = "${track.conversation} · $time", + style = TextStyle( + fontFamily = ChatFontFamily, + fontSize = 11.sp, + lineHeight = 17.sp, + textDirection = TextDirection.Content, + textAlign = textAlign + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.fillMaxWidth() + ) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/MessageAudioControls.kt b/app/src/main/java/com/nextcloud/talk/ui/MessageAudioControls.kt new file mode 100644 index 00000000000..ca8408ab0bf --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/MessageAudioControls.kt @@ -0,0 +1,129 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui + +import android.text.format.DateUtils +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +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.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.nextcloud.talk.R +import com.nextcloud.talk.ui.chat.ChatFontFamily + +private const val SPEED_BACKGROUND_ALPHA = 0.12f + +@Composable +internal fun MessageAudioPlayButton( + isPlaying: Boolean, + isDownloading: Boolean, + description: String, + onClick: () -> Unit +) { + Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) { + if (isDownloading) { + CircularProgressIndicator(modifier = Modifier.size(36.dp), strokeWidth = 2.dp) + } else { + IconButton(onClick = onClick, modifier = Modifier.size(48.dp)) { + Box( + modifier = Modifier.size(44.dp).background(MaterialTheme.colorScheme.primary, CircleShape), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow, + contentDescription = description, + tint = MaterialTheme.colorScheme.onPrimary, + modifier = Modifier.size(26.dp) + ) + } + } + } + } +} + +@Composable +internal fun MessageAudioSpeedButton(label: String, onClick: () -> Unit, modifier: Modifier = Modifier) { + val description = stringResource(R.string.playback_speed_control) + Box( + modifier = modifier + .sizeIn(minWidth = 48.dp, minHeight = 48.dp) + .clip(RoundedCornerShape(8.dp)) + .clickable(role = Role.Button, onClick = onClick) + .semantics { + contentDescription = description + stateDescription = label + } + .padding(horizontal = 4.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = label, + style = TextStyle( + fontFamily = ChatFontFamily, + fontSize = 13.sp, + lineHeight = 18.sp, + fontWeight = FontWeight.Medium, + textDirection = TextDirection.Ltr + ), + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .background( + MaterialTheme.colorScheme.primary.copy(alpha = SPEED_BACKGROUND_ALPHA), + RoundedCornerShape(8.dp) + ) + .padding(horizontal = 6.dp, vertical = 4.dp) + ) + } +} + +@Composable +internal fun MessageAudioTime( + playedSeconds: Int, + durationSeconds: Int, + isPlaying: Boolean, + modifier: Modifier = Modifier +) { + val elapsed = DateUtils.formatElapsedTime(playedSeconds.coerceAtLeast(0).toLong()) + val duration = DateUtils.formatElapsedTime(durationSeconds.coerceAtLeast(0).toLong()) + Text( + text = if (isPlaying || playedSeconds > 0) "$elapsed / $duration" else duration, + style = TextStyle( + fontFamily = ChatFontFamily, + fontSize = 11.sp, + lineHeight = 16.sp, + textDirection = TextDirection.Ltr + ), + color = if (isPlaying) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = modifier + ) +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/AttachmentDetails.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/AttachmentDetails.kt new file mode 100644 index 00000000000..21acd80050e --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/AttachmentDetails.kt @@ -0,0 +1,51 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.ui.chat + +import android.text.format.Formatter +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextDirection +import androidx.compose.ui.unit.dp +import com.nextcloud.talk.R +import com.nextcloud.talk.chat.data.model.FileParameters +import com.nextcloud.talk.chat.ui.model.ChatMessageUi +import java.util.Locale + +@Composable +fun AttachmentDetails(message: ChatMessageUi, modifier: Modifier = Modifier, fallbackFileName: String? = null) { + val file = remember(message.messageParameters) { + FileParameters(HashMap(message.messageParameters.mapValues { (_, params) -> HashMap(params) })) + } + val name = file.name.ifBlank { fallbackFileName.orEmpty() } + val extension = name.substringAfterLast('.', "") + .takeIf { name.lastIndexOf('.') > 0 && it.isNotBlank() } + ?.uppercase(Locale.ROOT) + val size = file.size?.takeIf { it >= 0 }?.let { Formatter.formatShortFileSize(LocalContext.current, it) } + ?: stringResource(R.string.nc_attachment_size_unknown) + val details = listOfNotNull(extension, size).joinToString(" · ") + + Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + text = name.ifBlank { stringResource(R.string.shared_items_file) }, + style = MaterialTheme.typography.bodyMedium.copy(textDirection = TextDirection.Content), + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = details, + style = MaterialTheme.typography.bodySmall.copy(textDirection = TextDirection.Content), + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/AudioFileMessage.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/AudioFileMessage.kt index 2c85897e1bf..9fa71a7143c 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/AudioFileMessage.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/AudioFileMessage.kt @@ -7,43 +7,40 @@ package com.nextcloud.talk.ui.chat -import android.text.format.DateUtils +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Pause -import androidx.compose.material.icons.filled.PlayArrow -import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.Slider -import androidx.compose.material3.SliderDefaults -import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.nextcloud.talk.R import com.nextcloud.talk.chat.ui.model.ChatMessageUi import com.nextcloud.talk.chat.ui.model.MessageTypeContent +import com.nextcloud.talk.ui.MessageAudioPlayButton +import com.nextcloud.talk.ui.MessageAudioTime -private const val SEEKBAR_MAX = 100 +private const val SEEKBAR_MAX = 100f private const val INACTIVE_TRACK_ALPHA = 0.4f -@OptIn(ExperimentalMaterial3Api::class) -@Suppress("Detekt.LongMethod") +@Suppress("LongMethod") @Composable fun AudioFileMessage( typeContent: MessageTypeContent.AudioFile, @@ -59,103 +56,86 @@ fun AudioFileMessage( conversationThreadId = conversationThreadId, forceTimeBelow = true, content = { - val remainingSeconds = (typeContent.durationSeconds - typeContent.playedSeconds) - val icon = if (typeContent.isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow - Column { + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth().padding(top = 4.dp) + ) { + MessageAudioPlayButton( + isPlaying = typeContent.isPlaying, + isDownloading = typeContent.isDownloading, + description = stringResource(R.string.play_pause_audio_file), + onClick = { onPlayPauseClick(message.id) } + ) + Column(modifier = Modifier.weight(1f)) { + AudioFileSeekBar( + progress = typeContent.seekbarProgress / SEEKBAR_MAX, + onSeek = { onSeek(message.id, (it * SEEKBAR_MAX).toInt()) } + ) + MessageAudioTime( + playedSeconds = typeContent.playedSeconds, + durationSeconds = typeContent.durationSeconds, + isPlaying = typeContent.isPlaying + ) + } + } + } Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth() + modifier = Modifier.fillMaxWidth().padding(top = 4.dp) ) { Icon( painter = painterResource(R.drawable.ic_mimetype_audio), contentDescription = null, - modifier = Modifier - .padding(end = 4.dp) - .size(24.dp) + tint = colorScheme.onSurfaceVariant, + modifier = Modifier.padding(end = 8.dp).size(20.dp) ) - - Text( - text = typeContent.fileName, - color = colorScheme.onPrimaryContainer, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f) + AttachmentDetails( + message, + modifier = Modifier.weight(1f), + fallbackFileName = typeContent.fileName ) } - - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth() - ) { - if (typeContent.isDownloading) { - CircularProgressIndicator(modifier = Modifier.size(48.dp), strokeWidth = 2.dp) - } else { - IconButton( - onClick = { onPlayPauseClick(message.id) }, - modifier = Modifier.size(48.dp) - ) { - Icon( - imageVector = icon, - contentDescription = stringResource(R.string.play_pause_audio_file), - modifier = Modifier.size(40.dp) - ) - } - } - - var sliderValue by remember { mutableFloatStateOf(0f) } - sliderValue = typeContent.seekbarProgress * 1f / SEEKBAR_MAX - - Slider( - value = sliderValue, - onValueChange = { - val progressI = (it * SEEKBAR_MAX).toInt() - onSeek(message.id, progressI) - }, - colors = SliderDefaults.colors( - thumbColor = colorScheme.primary, - activeTrackColor = colorScheme.primary, - inactiveTrackColor = colorScheme.onPrimaryContainer.copy(alpha = INACTIVE_TRACK_ALPHA) - ), - modifier = Modifier - .fillMaxWidth() - .padding(8.dp) - ) - } - - Text( - text = DateUtils.formatElapsedTime(remainingSeconds.toLong()), - color = colorScheme.onPrimaryContainer, - modifier = Modifier.padding(start = 4.dp) - ) } } ) } +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AudioFileSeekBar(progress: Float, onSeek: (Float) -> Unit) { + val accent = colorScheme.primary + Slider( + value = progress, + onValueChange = onSeek, + modifier = Modifier.fillMaxWidth(), + track = { + Box( + modifier = Modifier + .fillMaxWidth() + .height(3.dp) + .background(colorScheme.onSurfaceVariant.copy(alpha = INACTIVE_TRACK_ALPHA), CircleShape) + .drawBehind { drawRect(accent, size = size.copy(width = size.width * progress)) } + ) + }, + thumb = { Box(Modifier.size(8.dp).background(accent, CircleShape)) } + ) +} + @ChatMessagePreviews @Composable private fun AudioFileMessagePreview() { PreviewContainer { - AudioFileMessage( - typeContent = MessageTypeContent.AudioFile( - fileName = "podcast-episode-42.mp3", - isPlaying = false, - isDownloading = false, - durationSeconds = 245, - playedSeconds = 60, - seekbarProgress = 24 - ), - message = createBaseMessageWithoutCaption( - MessageTypeContent.AudioFile( - fileName = "podcast-episode-42.mp3", - isPlaying = false, - isDownloading = false, - durationSeconds = 245, - playedSeconds = 60, - seekbarProgress = 24 - ) - ) + val audio = MessageTypeContent.AudioFile( + fileName = "podcast-episode-42.mp3", + isPlaying = false, + isDownloading = false, + durationSeconds = 245, + playedSeconds = 60, + seekbarProgress = 24 ) + AudioFileMessage(typeContent = audio, message = createBaseMessageWithoutCaption(audio)) } } diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageScaffold.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageScaffold.kt index da1ad4b7c77..fe6b8b77bf5 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageScaffold.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageScaffold.kt @@ -199,8 +199,8 @@ fun MessageScaffold( val context = LocalContext.current val viewThemeUtils = LocalViewThemeUtils.current val isInspectionMode = LocalInspectionMode.current - val primaryContainer = colorScheme.primaryContainer - val resolvedBubbleColor = remember(bubbleColor, incoming, uiMessage.isDeleted, isInspectionMode, primaryContainer) { + val outgoingColor = colorResource(R.color.bg_message_list_outgoing_bubble) + val resolvedBubbleColor = remember(bubbleColor, incoming, uiMessage.isDeleted, isInspectionMode, outgoingColor) { bubbleColor ?: if (incoming) { val colorRes = if (uiMessage.isDeleted) { R.color.bg_message_list_incoming_bubble_deleted @@ -210,7 +210,7 @@ fun MessageScaffold( Color(getColorFromTheme(context, colorRes)) } else { if (isInspectionMode) { - primaryContainer + outgoingColor } else { val colorInt = viewThemeUtils.talk .getOutgoingMessageBubbleColor(context, uiMessage.isDeleted, false) @@ -898,6 +898,7 @@ private fun QuoteTextContent(message: ChatMessageUi, onClick: () -> Unit) { message = message, modifier = Modifier.padding(end = 4.dp), textStyle = TextStyle( + fontFamily = ChatFontFamily, fontSize = fontSize, color = colorScheme.onSurface, lineHeight = fontSize * LINE_SPACING @@ -1128,6 +1129,7 @@ fun EnrichedText( message = message, modifier = modifier, textStyle = TextStyle( + fontFamily = ChatFontFamily, fontSize = fontSize, color = colorScheme.onSurface, lineHeight = fontSize * LINE_SPACING diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageView.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageView.kt index 95cb0549711..361715bee37 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageView.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatMessageView.kt @@ -7,6 +7,7 @@ package com.nextcloud.talk.ui.chat +import com.nextcloud.talk.mediaviewer.model.VideoAction import android.util.Log import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween @@ -63,6 +64,7 @@ data class ChatMessageCallbacks( val onLongClick: ((Int) -> Unit?)? = null, val onSwipeReply: ((Int) -> Unit)? = null, val onFileClick: (Int) -> Unit = {}, + val onVideoAction: ((Int, VideoAction) -> Unit)? = null, val onPollClick: (String, String) -> Unit = { _, _ -> }, val onVoicePlayPauseClick: (Int) -> Unit = {}, val onVoiceSeek: (Int, Int) -> Unit = { _, _ -> }, @@ -154,7 +156,8 @@ fun ChatMessageView( isOneToOneConversation = context.isOneToOneConversation, conversationThreadId = context.conversationThreadId, chatViewDownloadingFileState = context.downloadingFileState, - onImageClick = callbacks.onFileClick + onImageClick = callbacks.onFileClick, + onVideoAction = callbacks.onVideoAction ) } diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatScrollPolicy.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatScrollPolicy.kt new file mode 100644 index 00000000000..5d91720053f --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatScrollPolicy.kt @@ -0,0 +1,13 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui.chat + +internal fun isNewerMessage(previousId: Int?, newestId: Int?): Boolean = + previousId != null && newestId != null && newestId > 0 && newestId > previousId + +internal fun shouldFollowNewMessage(isNearNewest: Boolean, isScrolling: Boolean): Boolean = isNearNewest && !isScrolling diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatTypography.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatTypography.kt new file mode 100644 index 00000000000..6994689e95a --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatTypography.kt @@ -0,0 +1,13 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui.chat + +import androidx.compose.ui.text.font.FontFamily + +// Chat uses the system family, including the device's fallback fonts for Persian and Arabic. +internal val ChatFontFamily = FontFamily.Default diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatView.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatView.kt index 472087614bd..682d7b289cb 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/ChatView.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/ChatView.kt @@ -17,6 +17,7 @@ import androidx.compose.animation.scaleOut import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.gestures.animateScrollBy +import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues @@ -52,7 +53,7 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.pluralStringResource @@ -84,7 +85,6 @@ import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter -private const val LONG_1000 = 1000L private const val LOAD_MORE_BUFFER_ITEMS = 5 private const val STICKY_HEADER_HIDE_DELAY_MILLIS = 1200L private const val UNREAD_MARKER_LAYOUT_TIMEOUT_MS = 500L @@ -168,6 +168,12 @@ fun ChatView( mutableStateOf(state.chatMode == ChatViewModel.ChatMode.DEFAULT_MODE) } var didScrollToUnreadMarker by remember { mutableStateOf(false) } + var hasUserDragged by remember { mutableStateOf(false) } + LaunchedEffect(listState) { + listState.interactionSource.interactions.collect { interaction -> + if (interaction is DragInteraction.Start) hasUserDragged = true + } + } var hadUnreadMarker by remember { mutableStateOf(false) } val handleQuotedMessageClick: (Int) -> Unit = remember(coroutineScope, listState) { @@ -200,18 +206,11 @@ fun ChatView( it is ChatViewModel.ChatItem.UnreadMessagesMarkerItem } - if (markerIndex < 0) { - didScrollToUnreadMarker = false - return@LaunchedEffect - } - - if (didScrollToUnreadMarker) return@LaunchedEffect + if (markerIndex < 0 || didScrollToUnreadMarker) return@LaunchedEffect - if (state.markedAsUnreadByUser) { - // the user placed this marker themselves and is looking at it already - didScrollToUnreadMarker = true - return@LaunchedEffect - } + // Consume the initial jump before suspending; new message updates may cancel this effect. + didScrollToUnreadMarker = true + if (state.markedAsUnreadByUser || hasUserDragged || listState.isScrollInProgress) return@LaunchedEffect // While marker exists, keep popup hidden and reset unread popup count once. showUnreadPopup.value = false @@ -223,8 +222,9 @@ fun ChatView( listState.layoutInfo.visibleItemsInfo.firstOrNull { it.index == markerIndex } }.filterNotNull().first() } - listState.centerItemInViewportIfVisible(markerIndex) - didScrollToUnreadMarker = true + if (!hasUserDragged && !listState.isScrollInProgress) { + listState.centerItemInViewportIfVisible(markerIndex) + } } // Track newest message and show unread popup. @@ -241,18 +241,11 @@ fun ChatView( val newestId = state.chatItems.firstNotNullOfOrNull { it.messageOrNull()?.id } val previousNewestId = lastNewestIdRef.value - - if (previousNewestId == null) { - lastNewestIdRef.value = newestId - return@LaunchedEffect - } + lastNewestIdRef.value = newestId val isNearBottom = listState.firstVisibleItemIndex <= 2 - val hasNewMessage = newestId != previousNewestId && - state.chatMode == ChatViewModel.ChatMode.DEFAULT_MODE - - if (hasNewMessage) { - if (isNearBottom) { + if (isNewerMessage(previousNewestId, newestId)) { + if (shouldFollowNewMessage(isNearBottom, listState.isScrollInProgress)) { listState.animateScrollToItem(0) unreadCount = 0 } else { @@ -260,8 +253,6 @@ fun ChatView( showUnreadPopup.value = true } } - - lastNewestIdRef.value = newestId } // Hide unread popup when user scrolls to newest @@ -324,7 +315,7 @@ fun ChatView( val density = LocalDensity.current val overflowPx = with(density) { state.stickyHeaderTopOffset.roundToPx() } - val stickyDateHeaderText by remember(listState, state.chatItems, overflowPx) { + val stickyDateHeaderDate by remember(listState, state.chatItems, overflowPx) { derivedStateOf { val visibleItems = listState.layoutInfo.visibleItemsInfo val viewportEnd = listState.layoutInfo.viewportEndOffset @@ -332,18 +323,20 @@ fun ChatView( // An item's bottom edge is at screen Y = viewportEnd - offset; it is visible when that // is >= overflowPx, i.e. offset <= viewportEnd - overflowPx. val targetItem = if (overflowPx > 0) { - visibleItems.filter { it.offset <= viewportEnd - overflowPx }.lastOrNull() + visibleItems.lastOrNull { it.offset <= viewportEnd - overflowPx } } else { visibleItems.lastOrNull() } targetItem?.let { itemInfo -> state.chatItems.getOrNull(itemInfo.index)?.let { item -> - item.dateOrNull()?.let { formatTime(it) } - ?: item.messageOrNull()?.let { formatTime(it.timestamp * LONG_1000) } - } ?: "" - } ?: "" + item.dateOrNull() ?: item.messageOrNull()?.date + } + } } } + val stickyDateHeaderText = remember(stickyDateHeaderDate) { + stickyDateHeaderDate?.let { formatTime(it) }.orEmpty() + } var stickyDateHeader by remember { mutableStateOf(false) } @@ -397,13 +390,23 @@ fun ChatView( ) { items( items = state.chatItems, - key = { it.stableKey() } + key = { it.stableKey() }, + contentType = { + when (it) { + is ChatViewModel.ChatItem.MessageItem -> it.uiMessage.content?.javaClass ?: it.javaClass + else -> it.javaClass + } + } ) { chatItem -> when (chatItem) { is ChatViewModel.ChatItem.MessageItem -> { Box( modifier = Modifier.padding( - top = if (!chatItem.uiMessage.isGrouped) 4.dp else 0.dp + top = when { + chatItem.uiMessage.content == MessageTypeContent.SystemMessage -> 0.dp + !chatItem.uiMessage.isGrouped -> 4.dp + else -> 0.dp + } ) ) { ChatMessageView( @@ -423,6 +426,7 @@ fun ChatView( onLongClick = callbacks.messageCallbacks.onLongClick, onSwipeReply = callbacks.messageCallbacks.onSwipeReply, onFileClick = callbacks.messageCallbacks.onFileClick, + onVideoAction = callbacks.messageCallbacks.onVideoAction, onPollClick = callbacks.messageCallbacks.onPollClick, onVoicePlayPauseClick = callbacks.messageCallbacks.onVoicePlayPauseClick, onVoiceSeek = callbacks.messageCallbacks.onVoiceSeek, @@ -457,6 +461,7 @@ fun ChatView( onLongClick = callbacks.messageCallbacks.onLongClick, onSwipeReply = callbacks.messageCallbacks.onSwipeReply, onFileClick = callbacks.messageCallbacks.onFileClick, + onVideoAction = callbacks.messageCallbacks.onVideoAction, onReactionClick = callbacks.messageCallbacks.onReactionClick, onReactionLongClick = callbacks.messageCallbacks.onReactionLongClick, onOpenThreadClick = callbacks.messageCallbacks.onOpenThreadClick, @@ -495,7 +500,7 @@ fun ChatView( modifier = Modifier .align(Alignment.TopCenter) .padding(top = state.stickyHeaderTopOffset + 2.dp) - .alpha(stickyDateHeaderAlpha) + .graphicsLayer { alpha = stickyDateHeaderAlpha } ) // Unread messages popup diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/CompactFileMessage.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/CompactFileMessage.kt new file mode 100644 index 00000000000..9128f0b618f --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/CompactFileMessage.kt @@ -0,0 +1,157 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.ui.chat + +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.nextcloud.talk.R +import com.nextcloud.talk.chat.data.model.FileParameters +import com.nextcloud.talk.chat.ui.model.ChatMessageUi +import com.nextcloud.talk.chat.ui.model.MessageStatusIcon +import com.nextcloud.talk.chat.ui.model.MessageTypeContent +import com.nextcloud.talk.ui.theme.mimetypeIconTint +import com.nextcloud.talk.utils.DrawableUtils +import com.nextcloud.talk.utils.Mimetype + +private const val UPLOAD_PERCENT_MAX = 100f + +internal fun ChatMessageUi.isUploadingFile(): Boolean = + statusIcon != MessageStatusIcon.SENT && statusIcon != MessageStatusIcon.FAILED + +internal fun isPreviewableMimeType(mimeType: String?): Boolean = + mimeType?.startsWith(Mimetype.IMAGE_PREFIX) == true || mimeType?.startsWith(Mimetype.VIDEO_PREFIX) == true + +@Composable +internal fun CompactFileMessage( + message: ChatMessageUi, + isOneToOneConversation: Boolean, + conversationThreadId: Long?, + caption: String? = message.message.takeIf { message.plainMessage != "{file}" }, + content: @Composable () -> Unit +) { + MessageScaffold( + uiMessage = message, + isOneToOneConversation = isOneToOneConversation, + conversationThreadId = conversationThreadId, + captionText = caption, + forceTimeBelow = true, + content = content + ) +} + +@Composable +internal fun SyncedFileRow(message: ChatMessageUi, downloadingFiles: List, onClick: () -> Unit) { + val file = remember(message.messageParameters) { + FileParameters(HashMap(message.messageParameters.mapValues { (_, params) -> HashMap(params) })) + } + val icon = DrawableUtils.getDrawableResourceIdForMimeType(file.mimetype) + val onLongClick = LocalMessageLongClickHandler.current + Row( + modifier = Modifier + .fillMaxWidth() + .combinedClickable(onClick = onClick, onLongClick = { onLongClick(message.id) }) + .padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + modifier = Modifier.size(32.dp), + tint = mimetypeIconTint(icon) + ) + AttachmentDetails(message, Modifier.weight(1f)) + if (file.id in downloadingFiles) { + CircularProgressIndicator(modifier = Modifier.size(24.dp), strokeWidth = 2.dp) + } else { + Icon( + painter = painterResource(R.drawable.baseline_download_24), + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +@Composable +internal fun UploadingFileRow( + message: ChatMessageUi, + typeContent: MessageTypeContent.UploadingMedia, + onCancelUpload: (String) -> Unit +) { + val onLongClick = LocalMessageLongClickHandler.current + val isFailed = message.statusIcon == MessageStatusIcon.FAILED + val isUploading = message.isUploadingFile() + val progress = LocalUploadProgressProvider.current(message.referenceId.orEmpty()) + Column { + Row( + modifier = Modifier + .fillMaxWidth() + .combinedClickable(onClick = {}, onLongClick = { onLongClick(message.id) }) + .padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon( + painter = painterResource(typeContent.drawableResourceId), + contentDescription = null, + modifier = Modifier.size(32.dp), + tint = mimetypeIconTint(typeContent.drawableResourceId) + ) + AttachmentDetails(message, Modifier.weight(1f), fallbackFileName = typeContent.fileName) + if (message.statusIcon != MessageStatusIcon.SENT) { + Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) { + if (isUploading) FileUploadProgress(progress) + IconButton(onClick = { onCancelUpload(message.referenceId.orEmpty()) }) { + Icon(imageVector = Icons.Default.Close, contentDescription = stringResource(R.string.nc_cancel)) + } + } + } + } + if (isFailed) { + Text( + text = stringResource(R.string.nc_upload_failed_notification_title), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall + ) + } + } +} + +@Composable +private fun FileUploadProgress(progress: Int?) { + if (progress == null) { + CircularProgressIndicator(modifier = Modifier.size(36.dp), strokeWidth = 2.dp) + } else { + CircularProgressIndicator( + progress = { (progress / UPLOAD_PERCENT_MAX).coerceIn(0f, 1f) }, + modifier = Modifier.size(36.dp), + strokeWidth = 2.dp + ) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/MediaGroupMessage.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/MediaGroupMessage.kt index 285ba26466d..5bfb052e199 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/MediaGroupMessage.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/MediaGroupMessage.kt @@ -18,14 +18,12 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons @@ -53,7 +51,6 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri @@ -68,7 +65,6 @@ import com.nextcloud.talk.chat.ui.model.MessageStatusIcon import com.nextcloud.talk.chat.ui.model.MessageTypeContent import com.nextcloud.talk.contacts.load import com.nextcloud.talk.ui.theme.mimetypeIconTint -import com.nextcloud.talk.utils.DrawableUtils import com.nextcloud.talk.utils.Mimetype import com.nextcloud.talk.utils.MimetypeUtils import com.nextcloud.talk.utils.VideoThumbnailCache @@ -105,7 +101,7 @@ private val gridPlayIconSize = 20.dp /** * Renders a run of file-share messages uploaded together in one batch (see * ChatViewModel.MediaGroupItem) as a single WhatsApp-style "album" bubble: image/video attachments - * as an adaptive thumbnail grid, any other file types as a stacked list of rows below it. The + * as an adaptive thumbnail grid, with each attachment's details in a stacked list below it. The * bubble itself is anchored on the group's last (newest) message, same as a single MediaMessage - * its timestamp, reactions, read status, reply target and long-press/swipe-reply all target that * representative message, same as web bases its combined message on the group's last real message. @@ -119,7 +115,6 @@ fun MediaGroupMessage( ) { val representative = messages.last() val mediaItems = messages.filter { it.isPreviewableMedia() } - val fileItems = messages.filterNot { it.isPreviewableMedia() } val hasExplicitCaption = representative.plainMessage != FILE_PLACEHOLDER_MESSAGE val captionText = if (hasExplicitCaption) representative.message else null @@ -161,7 +156,7 @@ fun MediaGroupMessage( conversationThreadId = context.conversationThreadId, includePadding = mediaItems.isEmpty(), captionText = captionText, - forceTimeOverlay = captionText == null && fileItems.isEmpty(), + forceTimeBelow = true, content = { Column { if (mediaItems.isNotEmpty()) { @@ -178,18 +173,26 @@ fun MediaGroupMessage( ) } } - if (fileItems.isNotEmpty()) { - Column( - modifier = Modifier.padding( - horizontal = 8.dp, - vertical = if (mediaItems.isNotEmpty()) 4.dp else 0.dp + Column( + modifier = Modifier.padding( + horizontal = 8.dp, + vertical = if (mediaItems.isNotEmpty()) 4.dp else 0.dp + ) + ) { + messages.forEach { message -> + GroupedFileRow( + message = message, + downloadingFiles = context.downloadingFileState, + onClick = { callbacks.onFileClick(message.id) }, + onCancelUpload = callbacks.onCancelUpload ) - ) { - fileItems.forEach { message -> - GroupedFileRow( - message = message, - onClick = { callbacks.onFileClick(message.id) }, - onCancelUpload = callbacks.onCancelUpload + val media = message.content as? MessageTypeContent.Media + if (media?.mimeType?.startsWith("video/") == true && + callbacks.onVideoAction != null + ) { + VideoActions( + onAction = { callbacks.onVideoAction(message.id, it) }, + modifier = Modifier.fillMaxWidth() ) } } @@ -209,7 +212,7 @@ private fun ChatMessageUi.isPreviewableMedia(): Boolean { is MessageTypeContent.UploadingMedia -> currentContent.mimeType.orEmpty() else -> "" } - return mimeType.startsWith(Mimetype.IMAGE_PREFIX) || mimeType.startsWith(Mimetype.VIDEO_PREFIX) + return isPreviewableMimeType(mimeType) } @Suppress("Detekt.LongMethod", "LongParameterList") @@ -377,7 +380,7 @@ private fun SyncedMediaTileContent( chatViewDownloadingFileState: List ) { val context = LocalContext.current - val fileParameters = remember(message.id) { + val fileParameters = remember(message.messageParameters) { FileParameters(HashMap(message.messageParameters.mapValues { (_, params) -> HashMap(params) })) } val isVideo = typeContent.mimeType.startsWith(Mimetype.VIDEO_PREFIX) @@ -579,85 +582,15 @@ private fun UploadingMediaTileContent( } @Composable -private fun GroupedFileRow(message: ChatMessageUi, onClick: () -> Unit, onCancelUpload: (String) -> Unit) { - when (val content = message.content) { - is MessageTypeContent.Media -> SyncedFileRow(message, onClick) - is MessageTypeContent.UploadingMedia -> UploadingFileRow(message, content, onCancelUpload) - else -> Unit - } -} - -@Composable -private fun SyncedFileRow(message: ChatMessageUi, onClick: () -> Unit) { - val fileParameters = remember(message.id) { - FileParameters(HashMap(message.messageParameters.mapValues { (_, params) -> HashMap(params) })) - } - val drawableResourceId = DrawableUtils.getDrawableResourceIdForMimeType(fileParameters.mimetype) - val messageLongClickHandler = LocalMessageLongClickHandler.current - - Row( - modifier = Modifier - .fillMaxWidth() - .combinedClickable( - onClick = onClick, - onLongClick = { messageLongClickHandler(message.id) } - ) - .padding(vertical = 6.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Icon( - painter = painterResource(drawableResourceId), - contentDescription = null, - modifier = Modifier.size(32.dp), - tint = mimetypeIconTint(drawableResourceId) - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = fileParameters.name.orEmpty(), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - style = MaterialTheme.typography.bodyMedium - ) - } -} - -@Composable -private fun UploadingFileRow( +private fun GroupedFileRow( message: ChatMessageUi, - typeContent: MessageTypeContent.UploadingMedia, + downloadingFiles: List, + onClick: () -> Unit, onCancelUpload: (String) -> Unit ) { - val messageLongClickHandler = LocalMessageLongClickHandler.current - val isSent = message.statusIcon == MessageStatusIcon.SENT - - Row( - modifier = Modifier - .fillMaxWidth() - .combinedClickable( - onClick = {}, - onLongClick = { messageLongClickHandler(message.id) } - ) - .padding(vertical = 6.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Icon( - painter = painterResource(typeContent.drawableResourceId), - contentDescription = null, - modifier = Modifier.size(32.dp), - tint = mimetypeIconTint(typeContent.drawableResourceId) - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = typeContent.fileName, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.weight(1f) - ) - if (!isSent) { - IconButton(onClick = { onCancelUpload(message.referenceId.orEmpty()) }) { - Icon(imageVector = Icons.Default.Close, contentDescription = stringResource(R.string.nc_cancel)) - } - } + when (val content = message.content) { + is MessageTypeContent.Media -> SyncedFileRow(message, downloadingFiles, onClick) + is MessageTypeContent.UploadingMedia -> UploadingFileRow(message, content, onCancelUpload) + else -> Unit } } diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/MediaMessage.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/MediaMessage.kt index c3c77649e82..c83a47baeb0 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/MediaMessage.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/MediaMessage.kt @@ -7,6 +7,7 @@ package com.nextcloud.talk.ui.chat +import com.nextcloud.talk.mediaviewer.model.VideoAction import android.graphics.Bitmap import android.util.Log import androidx.compose.animation.core.animateFloatAsState @@ -173,10 +174,18 @@ fun MediaMessage( isOneToOneConversation: Boolean = false, conversationThreadId: Long? = null, chatViewDownloadingFileState: List, - onImageClick: (Int) -> Unit + onImageClick: (Int) -> Unit, + onVideoAction: ((Int, VideoAction) -> Unit)? ) { + if (!isPreviewableMimeType(typeContent.mimeType)) { + CompactFileMessage(message, isOneToOneConversation, conversationThreadId) { + SyncedFileRow(message, chatViewDownloadingFileState) { onImageClick(message.id) } + } + return + } + val fileParameters = - remember { + remember(message.messageParameters) { FileParameters( HashMap( message.messageParameters.mapValues { (_, params) -> HashMap(params) } @@ -224,16 +233,8 @@ fun MediaMessage( null } - // A video shown via its local first frame counts as "has a preview" too, so the filename caption - // stays suppressed just like it would once the server's own preview becomes available. - val hasPreview = hasServerPreview || localVideoFramePainter != null val hasExplicitCaption = message.plainMessage != FILE_PLACEHOLDER_MESSAGE - val captionText = when { - hasExplicitCaption -> message.message - !hasPreview -> message.message - else -> null - } - val hasCaption = captionText != null + val captionText = message.message.takeIf { hasExplicitCaption } val mediaInset = 4.dp val mediaShape = remember(message.incoming, message.isGrouped, message.isGroupedWithNext) { shape(message.incoming, message.isGrouped, message.isGroupedWithNext) @@ -316,7 +317,7 @@ fun MediaMessage( conversationThreadId = conversationThreadId, includePadding = false, captionText = captionText, - forceTimeOverlay = !hasCaption, + forceTimeBelow = true, contentWidthFraction = { availableWidth -> mediaContentWidthFraction(availableWidth, aspectRatio, mediaMaxHeight) }, @@ -478,6 +479,10 @@ fun MediaMessage( ) } } + AttachmentDetails(message, Modifier.padding(horizontal = 8.dp, vertical = 6.dp)) + if (isVideo && onVideoAction != null) { + VideoActions(onAction = { onVideoAction(message.id, it) }, modifier = Modifier.fillMaxWidth()) + } } } ) @@ -496,10 +501,15 @@ fun UploadingMediaMessage( val getProgress = LocalUploadProgressProvider.current val progress = getProgress(message.referenceId.orEmpty()) val isFailed = message.statusIcon == MessageStatusIcon.FAILED - val isSent = message.statusIcon == MessageStatusIcon.SENT - val hasCaption = typeContent.caption != null + val isUploading = message.isUploadingFile() val isImage = typeContent.mimeType?.startsWith(Mimetype.IMAGE_PREFIX) == true val isVideo = typeContent.mimeType?.startsWith(Mimetype.VIDEO_PREFIX) == true + if (!isPreviewableMimeType(typeContent.mimeType)) { + CompactFileMessage(message, isOneToOneConversation, conversationThreadId, typeContent.caption) { + UploadingFileRow(message, typeContent, onCancelUpload) + } + return + } val mediaInset = 4.dp val mediaShape = remember(message.incoming, message.isGrouped, message.isGroupedWithNext) { @@ -526,7 +536,7 @@ fun UploadingMediaMessage( conversationThreadId = conversationThreadId, includePadding = false, captionText = typeContent.caption, - forceTimeOverlay = !hasCaption, + forceTimeBelow = true, contentWidthFraction = { availableWidth -> mediaContentWidthFraction(availableWidth, imageAspectRatio, mediaMaxHeight) }, @@ -587,7 +597,7 @@ fun UploadingMediaMessage( ) } - if (!isSent && !isFailed) { + if (isUploading) { Box( modifier = Modifier .matchParentSize() @@ -628,6 +638,11 @@ fun UploadingMediaMessage( } } + AttachmentDetails( + message, + Modifier.padding(horizontal = 8.dp, vertical = 6.dp), + fallbackFileName = typeContent.fileName + ) if (isFailed) { Text( text = stringResource(R.string.nc_upload_failed_notification_title), diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/SystemMessage.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/SystemMessage.kt index 276314d5bfc..278abdb3af8 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/SystemMessage.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/SystemMessage.kt @@ -16,7 +16,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.InlineTextContent import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf @@ -24,6 +23,7 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.text.SpanStyle @@ -38,26 +38,34 @@ import com.nextcloud.talk.chat.ui.model.ChatMessageUi import com.nextcloud.talk.utils.DateUtils import com.nextcloud.talk.utils.DisplayUtils -private const val TIME_TEXT_SIZE = 12 +private const val TIME_TEXT_SIZE = 11 +private const val TIME_LINE_HEIGHT = 14 private val systemMessageTextStyle - @Composable get() = MaterialTheme.typography.bodyMedium + @Composable get() = MaterialTheme.typography.bodySmall + +private val systemMessageTimeStyle + @Composable get() = MaterialTheme.typography.bodySmall.copy( + fontSize = TIME_TEXT_SIZE.sp, + lineHeight = TIME_LINE_HEIGHT.sp + ) @Composable fun SystemMessage(message: ChatMessageUi) { val timeString = DateUtils(LocalContext.current).getLocalTimeStringFromTimestamp(message.timestamp) val highlightSearchTerm = LocalHighlightSearchTerm.current + val logColor = colorResource(R.color.chat_system_log_text) if (message.isExpandableParent) { Box(modifier = Modifier.fillMaxWidth()) { ExpandableSystemMessage(message = message, highlightSearchTerm = highlightSearchTerm) Text( timeString, - fontSize = TIME_TEXT_SIZE.sp, - color = colorScheme.onSurfaceVariant, + style = systemMessageTimeStyle, + color = logColor, textAlign = TextAlign.End, modifier = Modifier .align(Alignment.BottomEnd) - .padding(end = 8.dp, bottom = 4.dp) + .padding(end = 8.dp, bottom = 1.dp) ) } } else { @@ -77,12 +85,12 @@ fun SystemMessage(message: ChatMessageUi) { Text( highlightedAnnotated, style = resolvedTextStyle, - color = colorScheme.onSurface, + color = logColor, inlineContent = inlineContent, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() - .padding(horizontal = 64.dp, vertical = 4.dp) + .padding(horizontal = 64.dp, vertical = 1.dp) .align(Alignment.Center), onTextLayout = { result -> if (!addLineBreaks.value && result.lineCount > 1) { @@ -92,11 +100,11 @@ fun SystemMessage(message: ChatMessageUi) { ) Text( timeString, - fontSize = TIME_TEXT_SIZE.sp, - color = colorScheme.onSurfaceVariant, + style = systemMessageTimeStyle, + color = logColor, modifier = Modifier .align(Alignment.BottomEnd) - .padding(end = 8.dp, bottom = 4.dp) + .padding(end = 8.dp, bottom = 1.dp) ) } } @@ -107,6 +115,7 @@ private fun ExpandableSystemMessage(message: ChatMessageUi, highlightSearchTerm: val chevronRes = if (message.isExpanded) R.drawable.ic_keyboard_arrow_up else R.drawable.ic_keyboard_arrow_down val textStyle = systemMessageTextStyle val (annotated, inlineContent) = rememberSystemMessageContent(message, textStyle) + val logColor = colorResource(R.color.chat_system_log_text) val highlightedAnnotated = remember(annotated, highlightSearchTerm) { annotated.withSearchHighlight(highlightSearchTerm) } @@ -114,7 +123,7 @@ private fun ExpandableSystemMessage(message: ChatMessageUi, highlightSearchTerm: Column( modifier = Modifier .fillMaxWidth() - .padding(start = 8.dp, top = 8.dp, bottom = 8.dp, end = 56.dp), + .padding(start = 8.dp, top = 2.dp, bottom = 2.dp, end = 56.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Row(verticalAlignment = Alignment.CenterVertically) { @@ -124,12 +133,12 @@ private fun ExpandableSystemMessage(message: ChatMessageUi, highlightSearchTerm: modifier = Modifier .padding(end = 4.dp) .size(16.dp), - tint = colorScheme.onSurfaceVariant + tint = logColor ) Text( highlightedAnnotated, style = textStyle, - color = colorScheme.onSurface, + color = logColor, inlineContent = inlineContent ) } @@ -140,8 +149,8 @@ private fun ExpandableSystemMessage(message: ChatMessageUi, highlightSearchTerm: message.expandableChildrenAmount, message.expandableChildrenAmount ), - style = MaterialTheme.typography.bodyMedium, - color = colorScheme.onSurfaceVariant + style = textStyle, + color = logColor ) } } diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/VideoActions.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/VideoActions.kt new file mode 100644 index 00000000000..32a8dbdc026 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/VideoActions.kt @@ -0,0 +1,57 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.ui.chat + +import android.content.pm.PackageManager +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.nextcloud.talk.R +import com.nextcloud.talk.mediaviewer.model.VideoAction + +@Composable +fun VideoActions( + onAction: (VideoAction) -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + pipEnabled: Boolean = enabled +) { + val context = LocalContext.current + val supportsPip = remember(context) { + context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) + } + Row(modifier = modifier, horizontalArrangement = Arrangement.End) { + IconButton(onClick = { onAction(VideoAction.DOWNLOAD) }, enabled = enabled) { + Icon( + painterResource(R.drawable.baseline_download_24), + stringResource(R.string.video_download), + Modifier.size(24.dp) + ) + } + if (supportsPip) { + IconButton( + onClick = { onAction(VideoAction.PICTURE_IN_PICTURE) }, + enabled = pipEnabled + ) { + Icon( + painterResource(R.drawable.ic_baseline_picture_in_picture_alt_24), + stringResource(R.string.video_picture_in_picture), + Modifier.size(24.dp) + ) + } + } + } +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/VisibleFileDownloads.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/VisibleFileDownloads.kt new file mode 100644 index 00000000000..e289b2de435 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/VisibleFileDownloads.kt @@ -0,0 +1,19 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui.chat + +import com.nextcloud.talk.chat.viewmodels.ChatViewModel.ChatItem + +internal fun downloadingMessageKeys(items: List, downloadingFileIds: List): Set { + if (downloadingFileIds.isEmpty()) return emptySet() + val fileIds = downloadingFileIds.toHashSet() + return items.mapNotNull { item -> + val fileId = item.messageOrNull()?.messageParameters?.get("file")?.get("id") + item.stableKey().takeIf { fileId in fileIds } + }.toSet() +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/chat/VoiceMessage.kt b/app/src/main/java/com/nextcloud/talk/ui/chat/VoiceMessage.kt index 7f40a8a0301..9cc8070fcae 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/chat/VoiceMessage.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/chat/VoiceMessage.kt @@ -7,47 +7,33 @@ package com.nextcloud.talk.ui.chat -import android.text.format.DateUtils -import androidx.compose.animation.core.animateIntAsState +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Pause -import androidx.compose.material.icons.filled.PlayArrow -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme.colorScheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.nextcloud.talk.R import com.nextcloud.talk.chat.ui.model.ChatMessageUi import com.nextcloud.talk.chat.ui.model.MessageTypeContent import com.nextcloud.talk.ui.ComposeWaveformSeekBar +import com.nextcloud.talk.ui.MessageAudioPlayButton +import com.nextcloud.talk.ui.MessageAudioSpeedButton +import com.nextcloud.talk.ui.MessageAudioTime import com.nextcloud.talk.ui.WAVEFORM_SIZE import com.nextcloud.talk.utils.AudioUtils -private const val SEEKBAR_MAX = 100 -private const val START_WAVE_FORM_HEIGHT = 10 -private const val END_WAVE_FORM_HEIGHT = 56 +private const val SEEKBAR_MAX = 100f -@OptIn(ExperimentalMaterial3Api::class) -@Suppress("Detekt.LongMethod", "LongParameterList") +@Suppress("LongMethod", "LongParameterList") @Composable fun VoiceMessage( typeContent: MessageTypeContent.Voice, @@ -64,11 +50,6 @@ fun VoiceMessage( conversationThreadId = conversationThreadId, forceTimeBelow = true, content = { - val inversePrimaryColor = colorScheme.inversePrimary - remember(inversePrimaryColor) { inversePrimaryColor.toArgb() } - val onPrimaryContainerColor = colorScheme.onPrimaryContainer - remember(onPrimaryContainerColor) { onPrimaryContainerColor.toArgb() } - val remainingSeconds = (typeContent.durationSeconds - typeContent.playedSeconds) val waveformData = remember(typeContent.waveform) { val floatArr = typeContent.waveform.toFloatArray() if (floatArr.size < WAVEFORM_SIZE) { @@ -77,68 +58,56 @@ fun VoiceMessage( AudioUtils.shrinkFloatArray(floatArr, WAVEFORM_SIZE) } } - - val animValue by animateIntAsState( - if (waveformData.average() > 0) END_WAVE_FORM_HEIGHT else START_WAVE_FORM_HEIGHT, - label = "size" - ) - - val icon = if (typeContent.isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow - - Column { + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) { Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth() + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth().padding(top = 4.dp) ) { - if (typeContent.isDownloading) { - CircularProgressIndicator(modifier = Modifier.size(48.dp), strokeWidth = 2.dp) - } else { - IconButton( - onClick = { onPlayPauseClick(message.id) }, - modifier = Modifier.size(48.dp) - ) { - Icon( - imageVector = icon, - contentDescription = stringResource(R.string.play_pause_voice_message), - modifier = Modifier.size(40.dp) - ) - } - } - - var sliderValue by remember { mutableFloatStateOf(0f) } - sliderValue = typeContent.seekbarProgress * 1f / SEEKBAR_MAX - - ComposeWaveformSeekBar( - sliderValue, - { - val progressI = (it * SEEKBAR_MAX).toInt() - onSeek(message.id, progressI) - }, - modifier = Modifier - .height(animValue.dp) - .fillMaxWidth() - .padding(8.dp), // or weight(1f), - waveformData, - enabled = true + MessageAudioPlayButton( + isPlaying = typeContent.isPlaying, + isDownloading = typeContent.isDownloading, + description = stringResource(R.string.play_pause_voice_message), + onClick = { onPlayPauseClick(message.id) } ) - - TextButton( - onClick = { onSpeedClick(message.id) }, - modifier = Modifier.padding(start = 4.dp) - ) { - Text( - text = typeContent.playbackSpeed.label, - color = colorScheme.onPrimaryContainer + Column(modifier = Modifier.weight(1f)) { + ComposeWaveformSeekBar( + value = typeContent.seekbarProgress / SEEKBAR_MAX, + onValueChange = { onSeek(message.id, (it * SEEKBAR_MAX).toInt()) }, + modifier = Modifier.fillMaxWidth(), + waveData = waveformData, + enabled = true + ) + MessageAudioTime( + playedSeconds = typeContent.playedSeconds, + durationSeconds = typeContent.durationSeconds, + isPlaying = typeContent.isPlaying ) } + MessageAudioSpeedButton( + label = typeContent.playbackSpeed.label, + onClick = { onSpeedClick(message.id) } + ) } - - Text( - text = DateUtils.formatElapsedTime(remainingSeconds.toLong()), - color = colorScheme.onPrimaryContainer, - modifier = Modifier.padding(start = 4.dp) - ) } } ) } + +@ChatMessagePreviews +@Composable +private fun VoiceMessagePreview() { + PreviewContainer { + val voice = MessageTypeContent.Voice( + actorId = null, + isPlaying = true, + wasPlayed = false, + isDownloading = false, + durationSeconds = 50, + playedSeconds = 18, + seekbarProgress = 36, + waveform = List(WAVEFORM_SIZE) { (it % 5 + 1) / 10f } + ) + VoiceMessage(typeContent = voice, message = createBaseMessageWithoutCaption(voice)) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/theme/TalkSpecificViewThemeUtils.kt b/app/src/main/java/com/nextcloud/talk/ui/theme/TalkSpecificViewThemeUtils.kt index 774a1270894..41cf9c457f2 100644 --- a/app/src/main/java/com/nextcloud/talk/ui/theme/TalkSpecificViewThemeUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/ui/theme/TalkSpecificViewThemeUtils.kt @@ -102,41 +102,23 @@ class TalkSpecificViewThemeUtils @Inject constructor( } fun themeOutgoingMessageBubble(bubble: View, grouped: Boolean, deleted: Boolean, isPlayed: Boolean = false) { - withScheme(bubble) { scheme -> - val bgBubbleColor = if (deleted) { - ColorUtils.setAlphaComponent(dynamicColor.surfaceVariant().getArgb(scheme), HALF_ALPHA_INT) - } else if (isPlayed) { - ContextCompat.getColor(bubble.context, R.color.bg_message_list_outgoing_bubble_audio_played) - } else { - dynamicColor.surfaceVariant().getArgb(scheme) - } - - val layout = if (grouped) { - R.drawable.shape_grouped_outcoming_message - } else { - R.drawable.shape_outcoming_message - } - val bubbleDrawable = DisplayUtils.getMessageSelector( - bgBubbleColor, - ResourcesCompat.getColor(bubble.resources, R.color.transparent, null), - bgBubbleColor, - layout - ) - ViewCompat.setBackground(bubble, bubbleDrawable) - } + val bgBubbleColor = getOutgoingMessageBubbleColor(bubble.context, deleted, isPlayed) + val layout = if (grouped) R.drawable.shape_grouped_outcoming_message else R.drawable.shape_outcoming_message + val bubbleDrawable = DisplayUtils.getMessageSelector( + bgBubbleColor, + ResourcesCompat.getColor(bubble.resources, R.color.transparent, null), + bgBubbleColor, + layout + ) + ViewCompat.setBackground(bubble, bubbleDrawable) } fun getOutgoingMessageBubbleColor(context: Context, deleted: Boolean, isPlayed: Boolean): Int { - return withScheme(context) { scheme -> - val bgBubbleColor = if (deleted) { - ColorUtils.setAlphaComponent(dynamicColor.surfaceVariant().getArgb(scheme), HALF_ALPHA_INT) - } else if (isPlayed) { - ContextCompat.getColor(context, R.color.bg_message_list_outgoing_bubble_audio_played) - } else { - dynamicColor.surfaceVariant().getArgb(scheme) - } - - return@withScheme bgBubbleColor + val bubbleColor = ContextCompat.getColor(context, R.color.bg_message_list_outgoing_bubble) + return when { + deleted -> ColorUtils.setAlphaComponent(bubbleColor, HALF_ALPHA_INT) + isPlayed -> ContextCompat.getColor(context, R.color.bg_message_list_outgoing_bubble_audio_played) + else -> bubbleColor } } diff --git a/app/src/main/java/com/nextcloud/talk/utils/CharacterAvatarUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/CharacterAvatarUtils.kt index c66e08783fe..7b6e6134098 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/CharacterAvatarUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/CharacterAvatarUtils.kt @@ -8,7 +8,6 @@ package com.nextcloud.talk.utils import androidx.annotation.ColorRes import com.nextcloud.talk.R -import java.util.Locale /** * The avatar of an actor the server has no avatar for, drawn by the client instead of being @@ -19,8 +18,7 @@ import java.util.Locale sealed interface ActorAvatar { /** - * A character on a coloured circle: the first character of a guest's name, or the shell prompt - * of a bot. Both colours are theme-aware resources, as the web client's are. + * A bot's shell prompt on a coloured circle. Both colours are theme-aware resources. */ data class Character(val character: String, @ColorRes val backgroundColor: Int, @ColorRes val textColor: Int) : ActorAvatar @@ -31,7 +29,7 @@ sealed interface ActorAvatar { object AppIcon : ActorAvatar /** - * The generic person icon, for guests who did not tell us their name. + * The generic person icon for people without a server-provided avatar. */ object PersonIcon : ActorAvatar } @@ -39,14 +37,8 @@ sealed interface ActorAvatar { /** * Decides what to draw for actors the server has no avatar for. * - * Guests, email participants and bots have no avatar on the server, so theirs is rendered on the - * client instead of being requested: a guest who told us their name gets the first character of it, - * a bot gets a shell prompt. This mirrors the web client's AvatarWrapper, so both clients show the - * same avatar for the same actor. - * - * A guest without a name is not represented by a character at all - they get the generic person - * icon, because the placeholder name ("Guest") is the same for everyone in the conversation and its - * initial would tell the reader nothing. + * Guests and email participants use the generic person icon. Bots retain their shell prompt or + * bundled app icon. Registered and federated users are left to the server's avatar response. */ object CharacterAvatarUtils { @@ -80,8 +72,8 @@ object CharacterAvatarUtils { * * @param actorType the actor type as the API reports it, e.g. "guests" or "bots" * @param actorId the actor's id, only used to spot the bots shipping their own avatar - * @param displayName the actor's display name, a guest's character is derived from it - * @param guestLabel the localized placeholder name for unnamed guests, null to accept any name + * @param displayName the actor's display name; does not affect a guest's person icon + * @param guestLabel the localized placeholder name; does not affect a guest's person icon */ fun avatarFor(actorType: String?, actorId: String?, displayName: String?, guestLabel: String?): ActorAvatar? = when (actorType) { @@ -92,19 +84,10 @@ object CharacterAvatarUtils { } /** - * The avatar of a guest or email participant, for callers whose actor type is already narrowed - * down to those - the name is all that is left to decide. + * The avatar of a guest or email participant, independent of their display name. */ - fun guestAvatar(displayName: String?, guestLabel: String?): ActorAvatar = - guestCharacter(displayName, guestLabel) - ?.let { - ActorAvatar.Character( - character = it, - backgroundColor = R.color.character_avatar_background_guest, - textColor = R.color.character_avatar_text_guest - ) - } - ?: ActorAvatar.PersonIcon + @Suppress("UNUSED_PARAMETER") + fun guestAvatar(displayName: String?, guestLabel: String?): ActorAvatar = ActorAvatar.PersonIcon /** * The avatar of a bot: the shell prompt, or the app's icon for the bots shipping their own. @@ -131,21 +114,4 @@ object CharacterAvatarUtils { val name = displayName?.trim() return !name.isNullOrEmpty() && name != guestLabel?.trim() } - - /** - * The character to draw for a guest or email actor, or null when there is no name to derive it - * from and the generic person icon should be used instead. - */ - private fun guestCharacter(displayName: String?, guestLabel: String?): String? { - if (!hasCustomName(displayName, guestLabel)) { - return null - } - return firstCharacterOf(displayName!!.trim().uppercase(Locale.getDefault())) - } - - /** - * First character as a whole code point, so names starting with an emoji or any other - * character outside the basic plane do not get cut in half into an unrenderable fragment. - */ - private fun firstCharacterOf(name: String): String = String(Character.toChars(name.codePointAt(0))) } diff --git a/app/src/main/java/com/nextcloud/talk/utils/DefaultUserAvatarImage.kt b/app/src/main/java/com/nextcloud/talk/utils/DefaultUserAvatarImage.kt new file mode 100644 index 00000000000..598f8bdfec4 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/utils/DefaultUserAvatarImage.kt @@ -0,0 +1,40 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.utils + +import android.content.Context +import android.content.res.Configuration +import android.graphics.Bitmap +import androidx.core.content.ContextCompat +import androidx.core.graphics.drawable.toBitmap +import com.nextcloud.talk.R +import java.io.ByteArrayOutputStream + +class DefaultUserAvatarImage(private val context: Context) { + private val images = mutableMapOf() + + @Synchronized + fun bytes(dark: Boolean): ByteArray = + images.getOrPut(dark) { + val configuration = Configuration(context.resources.configuration) + val night = if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO + configuration.uiMode = (configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or night + val themedContext = context.createConfigurationContext(configuration) + val drawable = requireNotNull(ContextCompat.getDrawable(themedContext, R.drawable.account_circle_96dp)) + val bitmap = drawable.toBitmap(AVATAR_PIXELS, AVATAR_PIXELS) + ByteArrayOutputStream().use { output -> + bitmap.compress(Bitmap.CompressFormat.PNG, PNG_QUALITY, output) + bitmap.recycle() + output.toByteArray() + } + } + + companion object { + private const val AVATAR_PIXELS = 256 + private const val PNG_QUALITY = 100 + } +} diff --git a/app/src/main/java/com/nextcloud/talk/utils/FileViewerUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/FileViewerUtils.kt index b10ca7dfd68..d485c5b86ee 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/FileViewerUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/FileViewerUtils.kt @@ -6,6 +6,7 @@ */ package com.nextcloud.talk.utils +import com.nextcloud.talk.mediaviewer.model.VideoAction import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context @@ -64,13 +65,14 @@ class FileViewerUtils(private val context: Context, private val user: User) { fun openFile( message: ChatMessage, openWhenDownloadState: MutableState, - downloadState: MutableState> + downloadState: MutableState>, + videoAction: VideoAction = VideoAction.PLAY ) { val mimetype = message.fileParameters.mimetype val isViewableMedia = mimetype.startsWith(IMAGE_PREFIX) || mimetype.startsWith(VIDEO_PREFIX) if (isViewableMedia) { - openInMediaViewer(message) + openInMediaViewer(message, videoAction) return } @@ -89,7 +91,7 @@ class FileViewerUtils(private val context: Context, private val user: User) { ) } - private fun openInMediaViewer(message: ChatMessage) { + private fun openInMediaViewer(message: ChatMessage, videoAction: VideoAction) { val fileParameters = message.fileParameters val fileId = fileParameters.id val roomToken = message.token @@ -119,7 +121,7 @@ class FileViewerUtils(private val context: Context, private val user: User) { timestamp = message.timestamp ) context.startActivity( - MediaViewerActivity.newIntent(context, user.id!!, roomToken, listOf(item), item.messageId) + MediaViewerActivity.newIntent(context, user.id!!, roomToken, listOf(item), item.messageId, videoAction) ) } diff --git a/app/src/main/java/com/nextcloud/talk/utils/UserAvatarRequestInterceptor.kt b/app/src/main/java/com/nextcloud/talk/utils/UserAvatarRequestInterceptor.kt new file mode 100644 index 00000000000..08364c4189a --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/utils/UserAvatarRequestInterceptor.kt @@ -0,0 +1,32 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.utils + +import coil.intercept.Interceptor +import coil.request.ImageResult +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okio.ByteString.Companion.encodeUtf8 + +/** Keeps old generated avatars and the other theme out of the avatar cache. */ +class UserAvatarRequestInterceptor : Interceptor { + override suspend fun intercept(chain: Interceptor.Chain): ImageResult { + val request = chain.request + val url = request.data.toString().toHttpUrlOrNull() + if (url == null || !UserAvatarPolicy.appliesTo(url)) return chain.proceed(request) + val dark = DisplayUtils.isDarkModeOn(request.context) + val identity = request.headers["Authorization"].orEmpty().encodeUtf8().sha256().hex() + val policyKey = UserAvatarPolicy.cacheKey(identity, dark) + val builder = request.newBuilder() + .tag(UserAvatarAppearance::class.java, UserAvatarAppearance(dark)) + .setParameter("talkPersonAvatar", policyKey, policyKey) + .diskCacheKey(UserAvatarPolicy.cacheKey("${request.diskCacheKey ?: url}-$identity", dark)) + request.memoryCacheKey?.let { key -> + builder.memoryCacheKey(key.copy(key = UserAvatarPolicy.cacheKey("${key.key}-$identity", dark))) + } + return chain.proceed(builder.build()) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptor.kt b/app/src/main/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptor.kt new file mode 100644 index 00000000000..6f254c3b1bb --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptor.kt @@ -0,0 +1,49 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.utils + +import okhttp3.HttpUrl +import okhttp3.Interceptor +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody + +data class UserAvatarAppearance(val dark: Boolean) + +object UserAvatarPolicy { + private val userPath = Regex("(?:^|/)avatar/[^/]+/[0-9]+(?:/dark)?$") + private val proxyPath = Regex("/ocs/v[12]\\.php/apps/spreed/api/v[0-9]+/proxy/[^/]+/user-avatar/[0-9]+(?:/dark)?$") + + fun appliesTo(url: HttpUrl): Boolean = + !url.encodedPath.contains("/remote.php/") && + (userPath.containsMatchIn(url.encodedPath) || proxyPath.containsMatchIn(url.encodedPath)) + + fun cacheKey(key: String, dark: Boolean): String = "$key#talk-person-avatar-v2-${if (dark) "dark" else "light"}" +} + +/** Replaces only avatars explicitly identified as generated by the server. */ +class UserAvatarResponseInterceptor(private val fallbackImage: (Boolean) -> ByteArray) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + val response = chain.proceed(request) + if (!UserAvatarPolicy.appliesTo(request.url) || + !response.isSuccessful || + response.header("X-NC-IsCustomAvatar")?.trim() != "0" + ) { + return response + } + val dark = request.tag(UserAvatarAppearance::class.java)?.dark ?: request.url.encodedPath.endsWith("/dark") + val image = fallbackImage(dark) + response.body.close() + return response.newBuilder() + .removeHeader("Content-Encoding") + .header("Content-Type", "image/png") + .header("Content-Length", image.size.toString()) + .body(image.toResponseBody("image/png".toMediaType())) + .build() + } +} diff --git a/app/src/main/res/drawable-night/account_circle_48dp.xml b/app/src/main/res/drawable-night/account_circle_48dp.xml index 97bce5e38c0..b976b2470d9 100644 --- a/app/src/main/res/drawable-night/account_circle_48dp.xml +++ b/app/src/main/res/drawable-night/account_circle_48dp.xml @@ -2,16 +2,18 @@ ~ Nextcloud Talk - Android Client ~ ~ SPDX-FileCopyrightText: 2018-2024 Google LLC + ~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors ~ SPDX-License-Identifier: Apache-2.0 --> + android:viewportWidth="24" + android:viewportHeight="24"> + android:fillColor="@color/avatar_default_background" + android:pathData="M12,0 A12,12 0,1 1,12,24 A12,12 0,1 1,12,0" /> + diff --git a/app/src/main/res/drawable-night/account_circle_96dp.xml b/app/src/main/res/drawable-night/account_circle_96dp.xml index 48636b3f670..29ce61bf9b6 100644 --- a/app/src/main/res/drawable-night/account_circle_96dp.xml +++ b/app/src/main/res/drawable-night/account_circle_96dp.xml @@ -2,15 +2,18 @@ ~ Nextcloud Talk - Android Client ~ ~ SPDX-FileCopyrightText: 2018-2024 Google LLC + ~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors ~ SPDX-License-Identifier: Apache-2.0 --> + android:viewportWidth="24" + android:viewportHeight="24"> + android:fillColor="@color/avatar_default_background" + android:pathData="M12,0 A12,12 0,1 1,12,24 A12,12 0,1 1,12,0" /> + diff --git a/app/src/main/res/drawable/account_circle_48dp.xml b/app/src/main/res/drawable/account_circle_48dp.xml index d90f59f4f32..b976b2470d9 100644 --- a/app/src/main/res/drawable/account_circle_48dp.xml +++ b/app/src/main/res/drawable/account_circle_48dp.xml @@ -2,16 +2,18 @@ ~ Nextcloud Talk - Android Client ~ ~ SPDX-FileCopyrightText: 2018-2024 Google LLC + ~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors ~ SPDX-License-Identifier: Apache-2.0 --> + android:viewportWidth="24" + android:viewportHeight="24"> + android:fillColor="@color/avatar_default_background" + android:pathData="M12,0 A12,12 0,1 1,12,24 A12,12 0,1 1,12,0" /> + diff --git a/app/src/main/res/drawable/account_circle_96dp.xml b/app/src/main/res/drawable/account_circle_96dp.xml index 7a6126ca32a..29ce61bf9b6 100644 --- a/app/src/main/res/drawable/account_circle_96dp.xml +++ b/app/src/main/res/drawable/account_circle_96dp.xml @@ -2,15 +2,18 @@ ~ Nextcloud Talk - Android Client ~ ~ SPDX-FileCopyrightText: 2018-2024 Google LLC + ~ SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors ~ SPDX-License-Identifier: Apache-2.0 --> + android:viewportWidth="24" + android:viewportHeight="24"> + android:fillColor="@color/avatar_default_background" + android:pathData="M12,0 A12,12 0,1 1,12,24 A12,12 0,1 1,12,0" /> + diff --git a/app/src/main/res/layout/activity_chat.xml b/app/src/main/res/layout/activity_chat.xml index 16a10d70a5b..05e2ffb5b07 100644 --- a/app/src/main/res/layout/activity_chat.xml +++ b/app/src/main/res/layout/activity_chat.xml @@ -22,6 +22,11 @@ android:layout_width="match_parent" android:layout_height="wrap_content" /> + + - \ No newline at end of file + diff --git a/app/src/main/res/values-night/avatar_colors.xml b/app/src/main/res/values-night/avatar_colors.xml new file mode 100644 index 00000000000..1b4c4b850f9 --- /dev/null +++ b/app/src/main/res/values-night/avatar_colors.xml @@ -0,0 +1,11 @@ + + + + #2C2C2C + #FFFFFF + diff --git a/app/src/main/res/values-night/chat_system_log_colors.xml b/app/src/main/res/values-night/chat_system_log_colors.xml new file mode 100644 index 00000000000..dc31c0fdb3e --- /dev/null +++ b/app/src/main/res/values-night/chat_system_log_colors.xml @@ -0,0 +1,10 @@ + + + + #898B93 + diff --git a/app/src/main/res/values-night/colors.xml b/app/src/main/res/values-night/colors.xml index 4dd49cc3dca..aad60ab5d94 100644 --- a/app/src/main/res/values-night/colors.xml +++ b/app/src/main/res/values-night/colors.xml @@ -59,4 +59,6 @@ #99FFFFFF + #202B33 + #32363B diff --git a/app/src/main/res/values/avatar_colors.xml b/app/src/main/res/values/avatar_colors.xml new file mode 100644 index 00000000000..7a55b075151 --- /dev/null +++ b/app/src/main/res/values/avatar_colors.xml @@ -0,0 +1,11 @@ + + + + #DBDBDB + #FFFFFF + diff --git a/app/src/main/res/values/chat_system_log_colors.xml b/app/src/main/res/values/chat_system_log_colors.xml new file mode 100644 index 00000000000..0e940979478 --- /dev/null +++ b/app/src/main/res/values/chat_system_log_colors.xml @@ -0,0 +1,10 @@ + + + + #73757D + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 3c80902ce09..7f88672cb4a 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -101,4 +101,6 @@ #EF3B02 #DBE2E9 + #DCE1E5 + #F5F5F5 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c2106b82432..17d7489b0d9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -882,6 +882,7 @@ How to translate with transifex: No shared items Media File + Size unknown Call recording Audio Voice @@ -1088,6 +1089,7 @@ How to translate with transifex: Local time: %1$s Open Notes Cancel Login + Stop audio playback Scan QR Code QR code could not be read Are you sure you want to delete this message? @@ -1129,4 +1131,11 @@ How to translate with transifex: Turn off background blur Account not found Password is secure + Download + Picture-in-picture + Download failed. Check your connection and free storage, then retry. + Picture-in-picture is unavailable. Check the app permission in Android settings. + Saving video… + Unable to play this video. You can download it and try another video player. + Video playback is paused during calls and voice recording. diff --git a/app/src/qa/AndroidManifest.xml b/app/src/qa/AndroidManifest.xml new file mode 100644 index 00000000000..b13e418b423 --- /dev/null +++ b/app/src/qa/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + diff --git a/app/src/qa/ic_launcher-web.png b/app/src/qa/ic_launcher-web.png index 9bde487a33852cf9a3f4aa34a19877bb64a003ca..d9a9f2a0ecb0fc6fb73e037deacc33a164f1d1ab 100644 GIT binary patch literal 14892 zcmeHuc{J4R|MxXBYN$ISDoU72N*gLsjG2@|wonpT5-QoU8_QT)NRcI5mTbwACHp!m zYnCXxLCMaHeH&(;&se&BzvuTn=lS;zdGGJ{^}b%0mx|KW9ozP80|4xh zlfA48037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Tj47@@;BW*Q`g z2&d8gqvXdNSVj7Jct{E6cbA}m%6muIt})be!2YX?a(+ONSRYm#Y-3!^HHKdg6&Nr( zeg{gP-xR5NYz&d0Fn&bPZAJRb8)P&}L~V=UV2N8rrGUdsVJW6z7@mCGH3l^)u|>u( zOdyHcPb5!~9HWwsl7O2Ko${f_FvWCH&JtAaLaBr|G>F_WXbif?2}3Bia4gmpzz4u; z#2h{hTKz?+251bbOb7e0xY0#)jCzS`s*11RqJepI3C&FYd=8ShMUWQYM&wA;GlbFj%P=YU zB?NM__9GAj!`qWEmmNii*ii|q2eG%Wu^;6-I|vkv2Q}Cmb4+}~Ffy>fD5J);qZLGa z#XjsS+f)YBvd}%_;Pltlp|XJ%!ZZfJP{=N#9O57lbQhgz2U#(qkp9E_blCs>ep9c| zARBU48%E^78qYG-W}>D8Q=#s{F=I)u;9X4eN1XP*IRu*zJ^_|WUvv2K=!tVME5<}b z3w}6FoB|!vU>Xo;gUh{{0>4GztfGUf#bha1YB>YXs@hJyL8CqL9<22@y8;e@;|s0T zDacX*PEC(xMEQJ|dP>OWkWmiY2RcmBW%E^Tmfe;NfJqocb;@a4o-BGfKa z`{6aV9kWetMumQf4%CH&>=*!eT^%aR{^vqFS=h53(;)xe@plAHMSkS0KK`EbX~cvv z8V=9P=6tx?Z~8 zGq}+?gG%Z`b_6zz0|9s#({yn0z`Kj6Q}v@*p#N-b==;H9+lB6*{C9y-gs6y((qmY! zF$B_3E%1xxI#h$-unt%m9+W`fI%qF~>Ch&-2!d46L&b^#qqSdKP=cZbgN#RCKArwQ zjZ|t&$tQJ)VDuj7ag|APol%VmH2I%hE&%5-qQC=k`9 zBFnA-G?1}i$GdRw$SJ54S`-q*?I;U%NdZTd4WTk1p0-IEdc?}V=L(J~!} GsQ&|^KBDyi diff --git a/app/src/qa/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.java b/app/src/qa/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.java deleted file mode 100644 index 94778d81763..00000000000 --- a/app/src/qa/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Nextcloud Talk - Android Client - * - * SPDX-FileCopyrightText: 2022 Marcel Hibbe - * SPDX-FileCopyrightText: 2017-2018 Mario Danic - * SPDX-License-Identifier: GPL-3.0-or-later - */ -package com.nextcloud.talk.utils; - - -import com.nextcloud.talk.interfaces.ClosedInterface; - -public class ClosedInterfaceImpl implements ClosedInterface { - @Override - public void providerInstallerInstallIfNeededAsync() { - // does absolutely nothing :) - } - - @Override - public boolean isGooglePlayServicesAvailable() { - return false; - } - - @Override - public void setUpPushTokenRegistration() { - // no push notifications for qa build flavour :( - } -} diff --git a/app/src/qa/res/drawable/ic_launcher_background.xml b/app/src/qa/res/drawable/ic_launcher_background.xml index 72e525962d1..c0ae928622f 100644 --- a/app/src/qa/res/drawable/ic_launcher_background.xml +++ b/app/src/qa/res/drawable/ic_launcher_background.xml @@ -1,32 +1,17 @@ + - - - - - - - - - + android:fillColor="#FF0082C9" + android:pathData="M0,0 H108 V108 H0 Z" /> diff --git a/app/src/qa/res/drawable/ic_launcher_foreground.xml b/app/src/qa/res/drawable/ic_launcher_foreground.xml index e7047a228b7..c3bbb3fa6d2 100644 --- a/app/src/qa/res/drawable/ic_launcher_foreground.xml +++ b/app/src/qa/res/drawable/ic_launcher_foreground.xml @@ -1,7 +1,9 @@ + - - + android:fillColor="#FFFFFFFF" + android:fillType="evenOdd" + android:pathData="M42.9393,34.3444 L64.9198,34.3444 C70.2106,34.3444,74.501,38.6348,74.501,43.9256 L74.501,63.0881 C74.501,68.3789,70.2106,72.6693,64.9198,72.6693 L43.2211,72.6693 L35.4012,77.1781 C34.908,77.4599,34.4853,77.6008,33.9922,77.2485 C33.5695,76.9667,33.4286,76.544,33.6399,75.8395 L35.7534,69.2172 C34.2035,67.456,33.3581,65.3425,33.3581,63.0881 L33.3581,43.9256 C33.3581,38.6348,37.6485,34.3444,42.9393,34.3444 Z M45.4403,49.4207 C46.8216,49.4207,47.9413,50.5405,47.9413,51.9217 L47.9413,57.2759 C47.9413,58.6572,46.8216,59.7769,45.4403,59.7769 C44.0591,59.7769,42.9393,58.6572,42.9393,57.2759 L42.9393,51.9217 C42.9393,50.5405,44.0591,49.4207,45.4403,49.4207 Z M53.8591,42.3757 C55.182,42.3757,56.2544,43.4481,56.2544,44.771 L56.2544,62.3836 C56.2544,63.7065,55.182,64.7789,53.8591,64.7789 C52.5362,64.7789,51.4638,63.7065,51.4638,62.3836 L51.4638,44.771 C51.4638,43.4481,52.5362,42.3757,53.8591,42.3757 Z M62.0665,47.2368 C63.4478,47.2368,64.5675,48.3565,64.5675,49.7378 L64.5675,58.4031 C64.5675,59.7844,63.4478,60.9041,62.0665,60.9041 C60.6853,60.9041,59.5656,59.7844,59.5656,58.4031 L59.5656,49.7378 C59.5656,48.3565,60.6853,47.2368,62.0665,47.2368 Z" /> diff --git a/app/src/qa/res/mipmap-anydpi/ic_launcher.xml b/app/src/qa/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 00000000000..9d0bf699387 --- /dev/null +++ b/app/src/qa/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/app/src/qa/res/mipmap-hdpi/ic_launcher.png b/app/src/qa/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index 99024db8ebd23bbb5638ed52cea41fac902a102c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5184 zcmV-G6u;|7rO5S zd=&JltYs-eK@pWwftIdxN!z4bO1jX}q-W0g-`=k%s+a&!OR{?7TI zbN>HSBKai`fNPj7hha|5`uqPk2MsnGhU4J9*jemB&ppJy=3fpNrv@)}c6LOS%9RPG zKy7OC_3HH2@xf^HSh>X%I3Wt;F0Xk=;F`aR!>SaULz$rq@K0%+p-FA}pMccHENxoT zF>P97Ii8!esf`_Y?$)L^bqAz1bp+7Q(woZzGFpzIWd&xmyb+jToT1Dx1=zjMArIAf z6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(~eR!tt>E|7TSbVH#?S?x)tpib81kt@Hr}BCI^KCSC$((GNyQOEJ z;g7xjp!}1cfP-|l*Eys@myop4#qi;=#w)h6>MYj1c&JIl%1KSH8iTYdq7b|veC2WG zUQXkW?J;W!eMakA`FjTr%EQhOBr^}nBS>TfNvx8F+Nfh-&AJ63nMp-{@9fFLF^}ZO zE^7OWa`?mV&XIq7ic?Y8nO?Dw6a$n*?nW`me1!qkwq1g|x7G=)oK*MHCj?XxXF&1L z(kE%ml0^w3cfN-HU4dUm$==xUrF`9KKb$#>rr7=?z?n5t)`CR$1L)glRcafo%+x{(v`~{VDi~=(YYH({MZWWI44^KW2-GHbS>qY?@V5|&YZ!< z8oJ!WeTp2>YrPgkFPE+Pk(<#NAbUu14uC*G zm6sX2A^pq+c=W3}xG}lXq0s%)_F728-DL9%uO{Gzz_Ei-<_qhCPxkG%CNjX`qrJ({6}V?BmRZn&8)JWe|Eg@w}h z4_@G6(pi^~#O6v)-AxcunVXGWJe-(HwgKLEWu8g?z+zI)ILUR>wQMYx=@=%NJdOVI z!C3k2vmchdv9m(9HlH9_P)!z3l_Vy3d$P;KW`?u)#hkbJ(evNkTOqsSk;mws`Fp?Y zpMoAH31NSQ8znxfyQD8@K=`f|h^_mD9g_K^0#yJ@>M5zRTY6eoSB)e zy{#uJv?vf9TSei`I~nOBdlio_d*5sHq#3+o#`~N&Wb=zQP-o< zj;))$g0BBJY3Nf6(rPABc?xI0^jh%YGeB$qBkA~U1M^fUS$2jdqDxc>y>^ diff --git a/app/src/qa/res/mipmap-mdpi/ic_launcher.png b/app/src/qa/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index 2b6d24b1c0984fcea6fb0296eaf17e702a866cbd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3229 zcmV;O3}W+%P)yiD5x3oXy|Tn{D;d3> zTxL;-u5%dIptXKY$K&#>(^Wdlf*74OH@3iXB&NXJqAs+U)jDgxy3p1iTVyq(wZs0Y8{z{v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vdU0Szz9;Eu}a^eEExAYYu9 zL_UT3PA>Rxcm8~m=!WpucI}iTeNPbX@gM@nk1K;vWYTeFr#lMYBVWFIH~GSRy5w(d zxO^a~Zj~%A+s`Y3;Z*OsdxsNS;q#FIoGgUYbZC)U_KyN=|EV6epvRoCZQPw!`xp?YHUB zfE}Q>hNlpXJ{W7HPxzkh(4`LN#0R_YG^LEB2I!CmeT3 zDbW#z3nvPrCbVW|a!h17UA=1H`yvvn9kSJ*mCK&nw1(DVYqC18{TaUK9<2s<6FJ%x zwBJp<_sJ(E&n2ysEZebLvg)%+>3c_7Wbaq>$~K;`$u?HmWC<0$()jWg*_wluve$R* zmOY=mjy{8*ox!gmXKTjC|I+_6!4iyMqIpLs@$Lvy#@!z_?e~vNy64fym`(fRBkXtd zH|{-C_|Js1HGa{5_7GEqIZ-Cz^TewT{r^K0Z;|}(!r6Oh7f7GE3UU5_nhN<#O}c{1 P00000NkvXXu0mjf$`ckF diff --git a/app/src/qa/res/mipmap-xhdpi/ic_launcher.png b/app/src/qa/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index a0528c11be638a176148ea733b196de14cb6cc33..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7299 zcmV-}9DL)6P)1V>#8fYcta3D zMFI!`71XKNs;jLRT3hQ~sfyeLxrQVJ0w`X{<=ykV=L7;t;3NU1UGw=opA$kz&iQ@M zb9tZlJqI4|hsO_(P9KEy;)N3*YP(494$byH{F@&h9zGZmeW{_So<8tzv*9zc>1X-; zAZ$lxIEtkr{Eh_gr_xA5)3qV;WaE#5w$uz)s%uA~;d6Wqe~0hs5QyzNe((@h5IoD< zi?NFc0+S3Q<*9}j15@-%l_`3)GPUNYQf;^lR-sHa)Pdauy9EGl1*&Urg4KbQgIx|x zt33*)4pbYL2BsTd3`{qS#Lskqp6#WFeTPGg!-2zD+z*7FsYuZ!C{pwn!EPv0YKUTs zo+xdWqGL_p)>8E(Ftw(g83@2&EUoSa*ac-;T|#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+49}n+&S)r|$wuixAH$h&{ zX;>n5WSa<4ca3hKb3Np*qfT`Ul7GLcMn`#1{8CByn?UKAI=_Yg$U-b3@^Is2QEy|S z|3S`$D{fAf5A4C`(gF*CvQ_=Jm@U_8IcqzrXkLdn!KIhk{-R(+d58I&Y&r3cHI9MvY zM`H4^J#=E|W-OEf6L6#?w}Q!=%I2>p|+E30>jxQ<~@V QdU!xtUR|zS#w_Un06%TK^#A|> diff --git a/app/src/test/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModelTest.kt b/app/src/test/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModelTest.kt index 6401bfb13a6..3e483de2f1d 100644 --- a/app/src/test/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModelTest.kt +++ b/app/src/test/java/com/nextcloud/talk/account/viewmodels/BrowserLoginActivityViewModelTest.kt @@ -9,9 +9,14 @@ package com.nextcloud.talk.account.viewmodels import com.nextcloud.talk.account.data.LoginRepository import com.nextcloud.talk.account.data.model.LoginCompletion import com.nextcloud.talk.account.data.model.LoginResponse +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After @@ -20,11 +25,12 @@ import org.junit.Before import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verifyBlocking -import org.mockito.kotlin.wheneverBlocking +import org.mockito.kotlin.whenever @OptIn(ExperimentalCoroutinesApi::class) class BrowserLoginActivityViewModelTest { @@ -47,7 +53,7 @@ class BrowserLoginActivityViewModelTest { @Test fun `starting the login again continues the started login`() { - wheneverBlocking { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) viewModel.startWebBrowserLogin(BASE_URL) viewModel.startWebBrowserLogin(BASE_URL) @@ -61,7 +67,7 @@ class BrowserLoginActivityViewModelTest { @Test fun `a QR code login is not started twice either`() { - wheneverBlocking { repository.startOTPLoginFlow(any(), any(), anyOrNull()) }.thenReturn(null) + whenever { repository.startOTPLoginFlow(any(), any(), anyOrNull()) }.thenReturn(null) viewModel.loginWithOTPQR("qr") viewModel.loginWithOTPQR("qr") @@ -69,9 +75,37 @@ class BrowserLoginActivityViewModelTest { verifyBlocking(repository, times(1)) { startOTPLoginFlow(any(), any(), anyOrNull()) } } + @Test + fun `browser login starts polling without waiting for an activity restart`() { + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + whenever { repository.pollLogin(loginResponse) }.thenReturn(null) + + viewModel.startWebBrowserLogin(BASE_URL) + + verifyBlocking(repository, times(1)) { pollLogin(loginResponse) } + } + + @Test + fun `returning from the browser repeatedly does not consume credentials twice`() { + val completion = LoginCompletion(200, BASE_URL, "user", "app-password") + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + whenever { repository.pollLogin(loginResponse) }.thenReturn(completion) + whenever { repository.parseAndLogin(completion) }.thenReturn(LoginRepository.LoginResult.ExistingAccount) + + viewModel.startWebBrowserLogin(BASE_URL) + repeat(3) { viewModel.handleWebBrowserLogin() } + + verifyBlocking(repository, times(1)) { pollLogin(loginResponse) } + verifyBlocking(repository, times(1)) { parseAndLogin(completion) } + assertEquals( + BrowserLoginActivityViewModel.PostLoginViewState.PostLoginRestartApp, + viewModel.postLoginState.value + ) + } + @Test fun `a login refused because of too many failed logins is reported as such`() { - wheneverBlocking { repository.startOTPLoginFlow(any(), any(), anyOrNull()) } + whenever { repository.startOTPLoginFlow(any(), any(), anyOrNull()) } .thenReturn(LoginCompletion(LoginRepository.HTTP_TOO_MANY_REQUESTS, BASE_URL, "user", "")) viewModel.loginWithOTPQR("qr") @@ -83,6 +117,95 @@ class BrowserLoginActivityViewModelTest { verifyBlocking(repository, never()) { parseAndLogin(any()) } } + @Test + fun `the browser launch is not replayed when the activity resumes`() { + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + + viewModel.startWebBrowserLogin(BASE_URL) + viewModel.onBrowserOpened() + viewModel.startWebBrowserLogin(BASE_URL) + + assertEquals( + BrowserLoginActivityViewModel.InitialLoginViewState.None, + viewModel.initialLoginRequestState.value + ) + verifyBlocking(repository, times(1)) { startLoginFlow(any(), any(), anyOrNull()) } + } + + @Test + fun `cancelled polling cannot complete the login`() { + val result = CompletableDeferred() + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + whenever { repository.pollLogin(loginResponse) }.doSuspendableAnswer { result.await() } + + viewModel.startWebBrowserLogin(BASE_URL) + verifyBlocking(repository, times(1)) { pollLogin(loginResponse) } + viewModel.cancelLogin() + result.complete(LoginCompletion(200, BASE_URL, "user", "app-password")) + + verifyBlocking(repository, never()) { parseAndLogin(any()) } + assertEquals(BrowserLoginActivityViewModel.PostLoginViewState.None, viewModel.postLoginState.value) + } + + @Test + fun `returning after a failed poll retries the same login session`() { + val completion = LoginCompletion(200, BASE_URL, "user", "app-password") + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + whenever { repository.pollLogin(loginResponse) }.thenReturn(null, completion) + whenever { repository.parseAndLogin(completion) }.thenReturn(LoginRepository.LoginResult.ExistingAccount) + + viewModel.startWebBrowserLogin(BASE_URL) + assertEquals(BrowserLoginActivityViewModel.PostLoginViewState.PostLoginError, viewModel.postLoginState.value) + viewModel.onBrowserOpened() + viewModel.handleWebBrowserLogin() + + verifyBlocking(repository, times(1)) { startLoginFlow(any(), any(), anyOrNull()) } + verifyBlocking(repository, times(2)) { pollLogin(loginResponse) } + assertEquals( + BrowserLoginActivityViewModel.PostLoginViewState.PostLoginRestartApp, + viewModel.postLoginState.value + ) + assertEquals( + BrowserLoginActivityViewModel.InitialLoginViewState.None, + viewModel.initialLoginRequestState.value + ) + } + + @Test + fun `pending login stops polling after twenty minutes`() = + runTest { + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.thenReturn(loginResponse) + whenever { repository.pollLogin(loginResponse) }.doSuspendableAnswer { awaitCancellation() } + + viewModel.startWebBrowserLogin(BASE_URL) + repeat(3) { viewModel.handleWebBrowserLogin() } + verifyBlocking(repository, times(1)) { pollLogin(loginResponse) } + advanceTimeBy(20 * 60 * 1000L) + runCurrent() + + assertEquals( + BrowserLoginActivityViewModel.PostLoginViewState.PostLoginError, + viewModel.postLoginState.value + ) + verifyBlocking(repository, never()) { parseAndLogin(any()) } + } + + @Test + fun `cancelling an initial request does not open the browser later`() { + val result = CompletableDeferred() + whenever { repository.startLoginFlow(any(), any(), anyOrNull()) }.doSuspendableAnswer { result.await() } + + viewModel.startWebBrowserLogin(BASE_URL) + viewModel.cancelLogin() + result.complete(loginResponse) + + assertEquals( + BrowserLoginActivityViewModel.InitialLoginViewState.None, + viewModel.initialLoginRequestState.value + ) + verifyBlocking(repository, never()) { pollLogin(any()) } + } + companion object { private const val BASE_URL = "https://example.com" private const val URL = "https://example.com/login" diff --git a/app/src/test/java/com/nextcloud/talk/api/FileDownloadStreamingTest.kt b/app/src/test/java/com/nextcloud/talk/api/FileDownloadStreamingTest.kt new file mode 100644 index 00000000000..86abfc7503d --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/api/FileDownloadStreamingTest.kt @@ -0,0 +1,102 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.api + +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Protocol +import okhttp3.Response +import okhttp3.ResponseBody +import okio.Buffer +import okio.Source +import okio.Timeout +import okio.buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import retrofit2.Retrofit +import java.io.IOException +import com.nextcloud.talk.logger.Level +import com.nextcloud.talk.logger.Logger +import com.nextcloud.talk.logger.LogsRepository +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class FileDownloadStreamingTest { + @Test + fun `large download returns before reading the file body into memory`() { + assertStreaming(advancedLogging = false) + } + + @Test + fun `advanced logging does not buffer a large file body`() { + assertStreaming(advancedLogging = true) + } + + @Test + fun `video range response stays streaming with authentication and advanced logging`() { + assertStreaming(advancedLogging = true, range = true) + } + + private fun assertStreaming(advancedLogging: Boolean, range: Boolean = false) { + var bytesRead = 0L + var closed = false + val source = object : Source { + override fun read(sink: Buffer, byteCount: Long): Long { + if (bytesRead >= READ_LIMIT) throw IOException("File body buffered before the caller could save it") + val count = minOf(byteCount, READ_LIMIT - bytesRead) + sink.write(ByteArray(count.toInt())) + bytesRead += count + return count + } + + override fun timeout(): Timeout = Timeout.NONE + override fun close() { + closed = true + } + }.buffer() + val body = object : ResponseBody() { + override fun contentType() = "video/mp4".toMediaType() + override fun contentLength() = LARGE_FILE_SIZE + override fun source() = source + } + val builder = OkHttpClient.Builder() + if (advancedLogging) { + val logs = mock() + whenever(logs.minimumLevel).thenReturn(Level.DEBUG) + builder.addInterceptor(LoggingHttpInterceptor(mock(), logs)) + } + val client = builder.addInterceptor { chain -> + if (range) { + assertEquals("bytes=100-", chain.request().header("Range")) + assertEquals("version-one", chain.request().header("If-Range")) + assertEquals("test", chain.request().header("Authorization")) + } + Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1) + .code(200).message("OK").body(body).build() + }.build() + val api = Retrofit.Builder().baseUrl("https://download.test/").client(client).build().create(NcApi::class.java) + + val call = if (range) { + api.downloadVideoRange("test", "https://download.test/video.mp4", "bytes=100-", "version-one") + } else { + api.downloadFile("test", "https://download.test/video.mp4") + } + call.execute().body()!!.use { response -> + assertEquals(LARGE_FILE_SIZE, response.contentLength()) + assertEquals(0L, bytesRead) + assertEquals(0, response.byteStream().read()) + assertTrue(bytesRead in 1..READ_LIMIT) + } + assertTrue(closed) + } + + companion object { + private const val READ_LIMIT = 64L * 1024 + private const val LARGE_FILE_SIZE = 750L * 1024 * 1024 + } +} diff --git a/app/src/test/java/com/nextcloud/talk/chat/VoiceMessageSpeedTest.kt b/app/src/test/java/com/nextcloud/talk/chat/VoiceMessageSpeedTest.kt new file mode 100644 index 00000000000..0e30da109b6 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/chat/VoiceMessageSpeedTest.kt @@ -0,0 +1,67 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.chat + +import com.nextcloud.talk.chat.data.io.MessageAudioKey +import com.nextcloud.talk.chat.data.io.MessageAudioState +import com.nextcloud.talk.chat.data.io.MessageAudioTrack +import com.nextcloud.talk.chat.ui.model.MessageTypeContent +import com.nextcloud.talk.chat.ui.model.withMessageAudio +import com.nextcloud.talk.chat.viewmodels.ChatViewModel +import com.nextcloud.talk.ui.PlaybackSpeed +import com.nextcloud.talk.ui.chat.createBaseMessageWithoutCaption +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class VoiceMessageSpeedTest { + private val voice = MessageTypeContent.Voice("sender", false, false, false, 30, 0, 0, emptyList()) + private val message = createBaseMessageWithoutCaption(voice) + private val items = listOf(ChatViewModel.ChatItem.MessageItem(message)) + private val track = MessageAudioTrack(MessageAudioKey(1, "room", message.id), "file.m4a", "Sender", "Room", true) + + private fun projected(state: MessageAudioState, account: Long = 1, room: String = "room") = + (items.withMessageAudio(state, account, room).first() as ChatViewModel.ChatItem.MessageItem) + .uiMessage.content as MessageTypeContent.Voice + + @Test + fun `recreated chat rows restore real progress and one and a half speed`() { + val state = MessageAudioState(track, true, true, 12_000, 30_000, 1.5f) + val result = projected(state) + assertTrue(result.isPlaying) + assertEquals(12, result.playedSeconds) + assertEquals(40, result.seekbarProgress) + assertEquals(PlaybackSpeed.FASTER, result.playbackSpeed) + } + + @Test + fun `paused double speed is reflected when returning to the chat`() { + val result = projected(MessageAudioState(track, false, false, 12_000, 30_000, 2f)) + assertFalse(result.isPlaying) + assertEquals(PlaybackSpeed.FASTEST, result.playbackSpeed) + assertEquals(12, result.playedSeconds) + } + + @Test + fun `another account or room cannot inherit playing state or speed`() { + val state = MessageAudioState(track, true, true, 12_000, 30_000, 2f) + for (result in listOf(projected(state, account = 2), projected(state, room = "other"))) { + assertFalse(result.isPlaying) + assertEquals(PlaybackSpeed.NORMAL, result.playbackSpeed) + assertEquals(0, result.playedSeconds) + } + } + + @Test + fun `stopping clears a stale playing icon`() { + val stale = listOf(ChatViewModel.ChatItem.MessageItem(message.copy(content = voice.copy(isPlaying = true)))) + val result = stale.withMessageAudio(MessageAudioState(), 1, "room").first() + as ChatViewModel.ChatItem.MessageItem + assertFalse((result.uiMessage.content as MessageTypeContent.Voice).isPlaying) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPlaybackTest.kt b/app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPlaybackTest.kt new file mode 100644 index 00000000000..13e0fdd273d --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPlaybackTest.kt @@ -0,0 +1,204 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.chat.data.io + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class MessageAudioPlaybackTest { + private val port = FakeMessageAudioPort() + private var allowed = true + private val playback = MessageAudioPlayback { allowed } + private val first = MessageAudioTrack(MessageAudioKey(1, "first", 1), "first.m4a", "Sender", "First", true) + private val second = first.copy(key = MessageAudioKey(1, "second", 1), uri = "second.m4a") + + @Before + fun attach() = playback.attach(port) + + private fun play(track: MessageAudioTrack = first, speed: Float = 1f) { + assertTrue(playback.completeRequest(playback.beginRequest(track.key), track, speed)) + } + + @Test + fun `playing another room replaces the current audio even when message ids match`() { + play() + play(second) + assertEquals(listOf(first.key.mediaId, second.key.mediaId), port.loads) + assertEquals(second, playback.state.value.track) + assertTrue(playback.state.value.isPlaying) + assertEquals(1, port.pauses) + } + + @Test + fun `accounts on the same server never share playback identity`() { + play() + val otherAccount = first.copy(key = first.key.copy(accountId = 2)) + assertFalse(playback.toggle(otherAccount.key)) + play(otherAccount) + assertEquals(otherAccount, playback.state.value.track) + } + + @Test + fun `returning to a conversation restores position pause and speed without reloading`() { + play(speed = 1.5f) + port.position = 12_000 + playback.refresh() + assertEquals(12_000L, playback.state.value.positionMs) + assertEquals(40, playback.state.value.progress) + playback.toggle(first.key) + playback.refresh() + assertFalse(playback.state.value.isPlaying) + assertEquals(1.5f, playback.state.value.speed) + playback.toggle(first.key) + assertTrue(playback.state.value.isPlaying) + assertEquals(12_000L, playback.state.value.positionMs) + assertEquals(1, port.loads.size) + } + + @Test + fun `a late download cannot replace a newer selection`() { + val oldRequest = playback.beginRequest(first.key) + val latestRequest = playback.beginRequest(second.key) + assertTrue(playback.completeRequest(latestRequest, second, 1f)) + assertFalse(playback.completeRequest(oldRequest, first, 1f)) + assertEquals(second, playback.state.value.track) + assertEquals(1, port.loads.size) + } + + @Test + fun `closing the bar invalidates pending downloads and clears playback`() { + play() + val request = playback.beginRequest(second.key) + playback.stop() + assertFalse(playback.completeRequest(request, second, 1f)) + assertNull(playback.state.value.track) + assertNull(port.mediaId) + } + + @Test + fun `seeking another room cannot move the active audio`() { + play() + playback.seek(second.key, 80) + assertEquals(0L, port.position) + playback.seek(first.key, 50) + assertEquals(15_000L, port.position) + } + + @Test + fun `speed changes are scoped to the active voice message`() { + play() + playback.setSpeed(second.key, 2f) + assertEquals(1f, playback.state.value.speed) + playback.setSpeed(first.key, 1.5f) + playback.toggle(first.key) + playback.setSpeed(first.key, 2f) + assertFalse(playback.state.value.isPlaying) + assertEquals(2f, playback.state.value.speed) + } + + @Test + fun `ordinary audio starts at normal speed after a fast voice message`() { + play(speed = 2f) + play(second.copy(isVoice = false), speed = 2f) + assertEquals(1f, playback.state.value.speed) + } + + @Test + fun `calls and recording block starting or resuming message audio`() { + play() + allowed = false + playback.refresh() + assertFalse(port.playing) + playback.toggle(first.key) + assertFalse(port.playing) + val request = playback.beginRequest(second.key) + assertFalse(playback.completeRequest(request, second, 1f)) + allowed = true + playback.refresh() + assertFalse(port.playing) + } + + @Test + fun `a call invalidates a download selected before the call`() { + val request = playback.beginRequest(first.key) + allowed = false + playback.refresh() + allowed = true + assertFalse(playback.completeRequest(request, first, 1f)) + assertTrue(port.loads.isEmpty()) + } + + @Test + fun `external pause and playback completion are reflected by the shared state`() { + play() + port.playing = false + playback.refresh() + assertFalse(playback.state.value.isPlaying) + port.ended = true + port.position = 30_000 + playback.refresh() + assertTrue(playback.state.value.ended) + playback.toggle(first.key) + assertEquals(0L, port.position) + assertTrue(port.playing) + } + + @Test + fun `service disconnection clears stale state`() { + play() + playback.attach(null) + assertNull(playback.state.value.track) + assertFalse(playback.toggle(first.key)) + } +} + +class FakeMessageAudioPort : MessageAudioPort { + override var mediaId: String? = null + val loads = mutableListOf() + var playing = false + var position = 0L + var playbackSpeed = 1f + var ended = false + var pauses = 0 + + override fun snapshot(track: MessageAudioTrack) = + MessageAudioState(track, playing, playing, position, 30_000, playbackSpeed, ended) + + override fun load(track: MessageAudioTrack, speed: Float) { + mediaId = track.key.mediaId + loads.add(track.key.mediaId) + playbackSpeed = speed + position = 0 + ended = false + } + + override fun play() { + playing = true + ended = false + } + + override fun pause() { + if (playing) pauses++ + playing = false + } + + override fun clear() { + playing = false + mediaId = null + } + + override fun seekTo(positionMs: Long) { + position = positionMs + ended = false + } + + override fun setSpeed(speed: Float) { + playbackSpeed = speed + } +} diff --git a/app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPolicyTest.kt b/app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPolicyTest.kt new file mode 100644 index 00000000000..4bf24d130d5 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/chat/data/io/MessageAudioPolicyTest.kt @@ -0,0 +1,50 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.chat.data.io + +import android.content.Context +import android.media.AudioManager +import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder +import org.junit.After +import org.junit.Before +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class MessageAudioPolicyTest { + private val context: Context = mock() + private val audio: AudioManager = mock() + private val call = ApplicationWideCurrentRoomHolder.getInstance() + + init { + whenever(context.getSystemService(Context.AUDIO_SERVICE)).thenReturn(audio) + } + + @After + fun resetCall() = call.clear() + + @Before + fun clearCall() = call.clear() + + @Test + fun `dialing and connected calls forbid message playback`() { + assertTrue(MessageAudioPolicy.canPlay(context)) + call.isDialing = true + assertFalse(MessageAudioPolicy.canPlay(context)) + call.isDialing = false + call.isInCall = true + assertFalse(MessageAudioPolicy.canPlay(context)) + } + + @Test + fun `communication audio mode blocks playback before call state is published`() { + whenever(audio.mode).thenReturn(AudioManager.MODE_IN_COMMUNICATION) + assertFalse(MessageAudioPolicy.canPlay(context)) + whenever(audio.mode).thenReturn(AudioManager.MODE_IN_CALL) + assertFalse(MessageAudioPolicy.canPlay(context)) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTrackerTest.kt b/app/src/test/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTrackerTest.kt new file mode 100644 index 00000000000..fe81b1b5d72 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/conversationlist/ui/ScrollDirectionTrackerTest.kt @@ -0,0 +1,39 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.conversationlist.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ScrollDirectionTrackerTest { + @Test + fun `initial position and unchanged position do not move the controls`() { + val tracker = ScrollDirectionTracker() + assertNull(tracker.onPosition(3, 80)) + assertNull(tracker.onPosition(3, 80)) + } + + @Test + fun `a long scroll updates controls only once per direction`() { + val tracker = ScrollDirectionTracker() + val events = (0..500).mapNotNull { tracker.onPosition(0, it) } + assertEquals(listOf(true), events) + } + + @Test + fun `crossing rows does not reverse the direction when the offset resets`() { + val tracker = ScrollDirectionTracker() + val positions = listOf(0 to 80, 0 to 90, 1 to 0, 1 to 30, 1 to 20, 0 to 90) + assertEquals(listOf(true, false), positions.mapNotNull { tracker.onPosition(it.first, it.second) }) + } + + @Test + fun `direction changes respond immediately after a pause`() { + val tracker = ScrollDirectionTracker() + val positions = listOf(0, 10, 10, 9, 9, 10) + assertEquals(listOf(true, false, true), positions.mapNotNull { tracker.onPosition(0, it) }) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/jobs/CacheFileWriterTest.kt b/app/src/test/java/com/nextcloud/talk/jobs/CacheFileWriterTest.kt new file mode 100644 index 00000000000..e21d7022d8e --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/jobs/CacheFileWriterTest.kt @@ -0,0 +1,105 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.jobs + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.io.InterruptedIOException +import java.io.RandomAccessFile + +class CacheFileWriterTest { + @get:Rule + val folder = TemporaryFolder() + + @Test + fun `750 MiB file uses bounded reads and is published only when complete`() { + val target = File(folder.root, "video.mp4") + var remaining = LARGE_FILE_SIZE + var lastProgress = 0L + val input = object : InputStream() { + override fun read(): Int = error("Bulk reads required") + override fun read(buffer: ByteArray, offset: Int, length: Int): Int { + assertTrue(length <= DEFAULT_BUFFER_SIZE) + if (remaining == 0L) return -1 + val count = minOf(length.toLong(), remaining).toInt() + buffer.fill(CONTENT_BYTE, offset, offset + count) + remaining -= count + return count + } + } + CacheFileWriter.write(input, target, LARGE_FILE_SIZE, { false }) { + assertFalse(target.exists()) + assertTrue(it > lastProgress) + lastProgress = it + } + assertEquals(LARGE_FILE_SIZE, target.length()) + assertEquals(LARGE_FILE_SIZE, lastProgress) + RandomAccessFile(target, "r").use { + assertEquals(CONTENT_BYTE.toInt(), it.read()) + it.seek(LARGE_FILE_SIZE - 1) + assertEquals(CONTENT_BYTE.toInt(), it.read()) + } + assertEquals(listOf("video.mp4"), folder.root.list()!!.toList()) + } + + @Test + fun `truncated response removes partial file and preserves existing cache`() { + val target = folder.newFile("existing") + target.writeText("original") + assertThrows(IOException::class.java) { + CacheFileWriter.write(byteArrayOf(1, 2).inputStream(), target, 3, { false }) {} + } + assertEquals("original", target.readText()) + assertEquals(listOf("existing"), folder.root.list()!!.toList()) + } + + @Test + fun `cancellation removes partial output`() { + val target = File(folder.root, "cancelled") + var stopped = false + assertThrows(InterruptedIOException::class.java) { + CacheFileWriter.write(ByteArray(DEFAULT_BUFFER_SIZE * 2).inputStream(), target, -1, { stopped }) { + stopped = true + } + } + assertTrue(folder.root.list()!!.isEmpty()) + } + + @Test + fun `network read failure removes partial output`() { + val target = File(folder.root, "failed") + val input = object : InputStream() { + override fun read(): Int = throw IOException("Connection interrupted") + } + assertThrows(IOException::class.java) { + CacheFileWriter.write(input, target, -1, { false }) {} + } + assertTrue(folder.root.list()!!.isEmpty()) + } + + @Test + fun `unknown length response preserves exact bytes`() { + val target = File(folder.root, "chunked") + val bytes = byteArrayOf(0, 1, -1, 5) + CacheFileWriter.write(bytes.inputStream(), target, -1, { false }) {} + assertArrayEquals(bytes, target.readBytes()) + } + + companion object { + private const val LARGE_FILE_SIZE = 750L * 1024 * 1024 + private const val CONTENT_BYTE: Byte = 37 + } +} diff --git a/app/src/test/java/com/nextcloud/talk/jobs/DownloadProgressTest.kt b/app/src/test/java/com/nextcloud/talk/jobs/DownloadProgressTest.kt new file mode 100644 index 00000000000..eda5315edb1 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/jobs/DownloadProgressTest.kt @@ -0,0 +1,27 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.jobs + +import org.junit.Assert.assertEquals +import org.junit.Test + +class DownloadProgressTest { + @Test + fun `percentage uses bytes and reserves completion for a published file`() { + assertEquals(0, DownloadProgress.percent(0, 1000)) + assertEquals(37, DownloadProgress.percent(375, 1000)) + assertEquals(99, DownloadProgress.percent(1000, 1000)) + assertEquals(99, DownloadProgress.percent(1100, 1000)) + } + + @Test + fun `unknown length stays indeterminate and large sizes do not overflow`() { + assertEquals(-1, DownloadProgress.percent(100, -1)) + assertEquals(-1, DownloadProgress.percent(100, 0)) + assertEquals(50, DownloadProgress.percent(Long.MAX_VALUE / 2, Long.MAX_VALUE)) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuardTest.kt b/app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuardTest.kt new file mode 100644 index 00000000000..de9aca0dfee --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackGuardTest.kt @@ -0,0 +1,55 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.activities + +import androidx.media3.common.Player +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class VideoPlaybackGuardTest { + private val player: Player = mock() + private var allowed = true + private val guard = VideoPlaybackGuard(player) { allowed } + + @Test + fun `call or recording stops video and ending it never resumes automatically`() { + allowed = false + guard.enforcePolicy() + verify(player).pause() + allowed = true + guard.enforcePolicy() + verify(player, never()).play() + } + + @Test + fun `PiP play command during a call cannot start video`() { + allowed = false + whenever(player.playWhenReady).thenReturn(false) + guard.toggle() + verify(player, never()).play() + } + + @Test + fun `player UI play request during a call is immediately paused`() { + allowed = false + guard.onPlayWhenReadyChanged(true, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST) + verify(player).pause() + } + + @Test + fun `PiP controls pause playing video and resume only on user request`() { + whenever(player.playWhenReady).thenReturn(true) + guard.toggle() + verify(player).pause() + whenever(player.playWhenReady).thenReturn(false) + guard.toggle() + verify(player).play() + } +} diff --git a/app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicyTest.kt b/app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicyTest.kt new file mode 100644 index 00000000000..08ab24e5cc7 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/mediaviewer/activities/VideoPlaybackPolicyTest.kt @@ -0,0 +1,35 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.activities + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class VideoPlaybackPolicyTest { + @Test + fun `normal video retains aspect ratio`() { + assertEquals(16f / 9, VideoPlaybackPolicy.pictureInPictureRatio(1920, 1080, 1f), 0.001f) + assertEquals(9f / 16, VideoPlaybackPolicy.pictureInPictureRatio(1080, 1920, 1f), 0.001f) + } + + @Test + fun `extreme dimensions and pixel shapes stay within Android PiP limits after rounding`() { + for ((width, height, pixel) in listOf(Triple(1, 10000, 1f), Triple(10000, 1, 1f), Triple(1920, 1080, 2f))) { + val ratio = VideoPlaybackPolicy.pictureInPictureRatio(width, height, pixel) + val rounded = (ratio * 1000).toInt() / 1000f + assertTrue(rounded >= 1f / 2.39f && rounded <= 2.39f) + } + } + + @Test + fun `unknown and invalid video dimensions use safe default`() { + for ((width, height, pixel) in listOf(Triple(0, 0, 1f), Triple(10, 0, 1f), Triple(10, 10, Float.NaN))) { + assertEquals(16f / 9, VideoPlaybackPolicy.pictureInPictureRatio(width, height, pixel), 0.001f) + } + } +} diff --git a/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSourceTest.kt b/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSourceTest.kt new file mode 100644 index 00000000000..0948e32e88a --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoDataSourceTest.kt @@ -0,0 +1,111 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import android.net.Uri +import androidx.media3.datasource.DataSpec +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.ResponseBody +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import retrofit2.Call +import retrofit2.Response +import java.io.IOException + +class ProgressiveVideoDataSourceTest { + @get:Rule val folder = TemporaryFolder() + private val uri = mock() + + @Test + fun `player reads the downloaded prefix without another network request`() { + val file = folder.newFile().apply { writeBytes(byteArrayOf(1, 2, 3)) } + val download = ProgressiveVideoFile(100, "etag") + download.attach(file) + download.advance(3) + val source = ProgressiveVideoDataSource(download) { _, _ -> error("Unexpected network read") } + try { + assertEquals(100L, source.open(DataSpec.Builder().setUri(uri).build())) + val bytes = ByteArray(10) + assertEquals(3, source.read(bytes, 0, bytes.size)) + assertArrayEquals(byteArrayOf(1, 2, 3), bytes.copyOf(3)) + } finally { + source.close() + } + } + + @Test + fun `player can fetch tail metadata before the sequential download completes`() { + val download = ProgressiveVideoFile(100, "etag") + val call = response(206, "bytes 97-99/100") + val source = ProgressiveVideoDataSource(download) { start, validator -> + assertEquals(97L, start) + assertEquals("etag", validator) + call + } + try { + assertEquals(3L, source.open(DataSpec.Builder().setUri(uri).setPosition(97).build())) + val bytes = ByteArray(3) + assertEquals(3, source.read(bytes, 0, 3)) + assertArrayEquals(byteArrayOf(7, 8, 9), bytes) + assertEquals(-1, source.read(bytes, 0, 3)) + } finally { + source.close() + } + verify(call).cancel() + } + + @Test + fun `server ignoring range falls back to the original download`() { + val file = folder.newFile().apply { writeBytes(ByteArray(100) { 4 }) } + val download = ProgressiveVideoFile(100, "etag") + download.attach(file) + val call = response(200, null) + val source = ProgressiveVideoDataSource(download) { _, _ -> call } + try { + source.open(DataSpec.Builder().setUri(uri).setPosition(97).build()) + download.advance(100) + val bytes = ByteArray(3) + assertEquals(3, source.read(bytes, 0, 3)) + assertArrayEquals(byteArrayOf(4, 4, 4), bytes) + } finally { + source.close() + } + } + + @Test + fun `invalid range fails and still releases the request`() { + val call = response(206, "bytes 0-2/100") + val source = ProgressiveVideoDataSource(ProgressiveVideoFile(100, "etag")) { _, _ -> call } + try { + assertThrows(IOException::class.java) { + source.open(DataSpec.Builder().setUri(uri).setPosition(97).build()) + } + } finally { + source.close() + } + verify(call).cancel() + } + + private fun response(code: Int, range: String?): Call { + val raw = okhttp3.Response.Builder() + .request(Request.Builder().url("https://video.test/file").build()) + .protocol(Protocol.HTTP_1_1).code(code).message("test") + if (range != null) raw.header("Content-Range", range) + val call = mock>() + whenever(call.execute()).thenReturn(Response.success(byteArrayOf(7, 8, 9).toResponseBody(), raw.build())) + return call + } +} diff --git a/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFileTest.kt b/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFileTest.kt new file mode 100644 index 00000000000..7954f905d71 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/ProgressiveVideoFileTest.kt @@ -0,0 +1,99 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.IOException +import java.io.InterruptedIOException +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException + +class ProgressiveVideoFileTest { + @get:Rule val folder = TemporaryFolder() + + @Test + fun `downloaded prefix can play before the remaining bytes arrive`() { + val file = folder.newFile().apply { writeBytes(byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8)) } + val stream = ProgressiveVideoFile(8, "version-one") + stream.attach(file) + stream.acquire() + stream.advance(4) + val executor = Executors.newSingleThreadExecutor() + try { + val bytes = ByteArray(8) + val first = executor.submit { stream.read(0, bytes, 0, bytes.size) { false } } + assertEquals(4, first.get(1, TimeUnit.SECONDS)) + assertArrayEquals(byteArrayOf(1, 2, 3, 4, 0, 0, 0, 0), bytes) + val next = executor.submit { stream.read(4, bytes, 0, bytes.size) { false } } + assertThrows(TimeoutException::class.java) { next.get(100, TimeUnit.MILLISECONDS) } + stream.advance(8) + assertEquals(4, next.get(1, TimeUnit.SECONDS)) + assertArrayEquals(byteArrayOf(5, 6, 7, 8), bytes.copyOf(4)) + } finally { + executor.shutdownNow() + executor.awaitTermination(1, TimeUnit.SECONDS) + stream.release() + } + } + + @Test(timeout = 5000) + fun `reader survives atomic publication and can reopen the finished file`() { + val temporary = folder.newFile().apply { writeBytes(byteArrayOf(1, 2, 3)) } + val target = folder.root.resolve("complete.mp4") + val stream = ProgressiveVideoFile(3, null) + stream.attach(temporary) + stream.advance(3) + stream.acquire() + try { + val bytes = ByteArray(3) + assertEquals(1, stream.read(0, bytes, 0, 1) { false }) + assertTrue(stream.publish(temporary, target)) + assertEquals(3, stream.read(0, bytes, 0, 3) { false }) + assertArrayEquals(byteArrayOf(1, 2, 3), bytes) + assertEquals(-1, stream.read(3, bytes, 0, 3) { false }) + } finally { + stream.release() + } + } + + @Test + fun `unknown length only ends after download completion`() { + val file = folder.newFile() + val stream = ProgressiveVideoFile(-1, null) + stream.attach(file) + assertTrue(stream.publish(file, folder.root.resolve("unknown.mp4"))) + assertEquals(-1, stream.read(0, ByteArray(1), 0, 1) { false }) + } + + @Test + fun `failed or cancelled download cannot wait forever`() { + val stream = ProgressiveVideoFile(100, null) + stream.fail() + assertThrows(IOException::class.java) { stream.read(0, ByteArray(1), 0, 1) { false } } + val cancelled = ProgressiveVideoFile(100, null) + assertThrows(InterruptedIOException::class.java) { cancelled.read(0, ByteArray(1), 0, 1) { true } } + } + + @Test + fun `seeking needs a range only outside available bytes with a validator`() { + val stream = ProgressiveVideoFile(100, "version-one") + stream.advance(10) + assertFalse(stream.needsRange(0)) + assertFalse(stream.needsRange(10)) + assertTrue(stream.needsRange(90)) + assertFalse(ProgressiveVideoFile(100, null).needsRange(90)) + assertFalse(ProgressiveVideoFile(-1, "version-one").needsRange(90)) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponseTest.kt b/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponseTest.kt new file mode 100644 index 00000000000..3fbc4f0863b --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/mediaviewer/stream/VideoRangeResponseTest.kt @@ -0,0 +1,26 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.mediaviewer.stream + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.IOException + +class VideoRangeResponseTest { + @Test + fun `valid tail request has the exact remaining length`() { + assertEquals(10L, VideoRangeResponse.validate("bytes 90-99/100", 90, 100)) + } + + @Test + fun `changed file or wrong position cannot be combined with downloaded bytes`() { + for (header in listOf("bytes 0-99/100", "bytes 90-100/101", "bytes 90-98/100", "bytes 90-99/*", null)) { + assertThrows(IOException::class.java) { VideoRangeResponse.validate(header, 90, 100) } + } + } +} diff --git a/app/src/test/java/com/nextcloud/talk/ui/chat/ChatScrollPolicyTest.kt b/app/src/test/java/com/nextcloud/talk/ui/chat/ChatScrollPolicyTest.kt new file mode 100644 index 00000000000..2d27d47d183 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/ui/chat/ChatScrollPolicyTest.kt @@ -0,0 +1,48 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui.chat + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ChatScrollPolicyTest { + @Test + fun `receiving a message must not cancel a drag or fling near the bottom`() { + assertFalse(shouldFollowNewMessage(isNearNewest = true, isScrolling = true)) + } + + @Test + fun `follow a new message when resting at the bottom`() { + assertTrue(shouldFollowNewMessage(isNearNewest = true, isScrolling = false)) + } + + @Test + fun `keep the reading position when browsing older messages`() { + assertFalse(shouldFollowNewMessage(isNearNewest = false, isScrolling = false)) + assertFalse(shouldFollowNewMessage(isNearNewest = false, isScrolling = true)) + } + + @Test + fun `removing the newest message must not count as an incoming message`() { + assertFalse(isNewerMessage(previousId = 120, newestId = 119)) + } + + @Test + fun `an unsent local message must not trigger incoming auto scroll`() { + assertFalse(isNewerMessage(previousId = 120, newestId = -1)) + } + + @Test + fun `initial load and read receipt updates must not trigger incoming auto scroll`() { + assertFalse(isNewerMessage(previousId = null, newestId = 120)) + assertFalse(isNewerMessage(previousId = 120, newestId = null)) + assertFalse(isNewerMessage(previousId = 120, newestId = 120)) + assertTrue(isNewerMessage(previousId = 120, newestId = 121)) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/ui/chat/VisibleFileDownloadsTest.kt b/app/src/test/java/com/nextcloud/talk/ui/chat/VisibleFileDownloadsTest.kt new file mode 100644 index 00000000000..6d574e27a82 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/ui/chat/VisibleFileDownloadsTest.kt @@ -0,0 +1,56 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.ui.chat + +import com.nextcloud.talk.chat.ui.model.ChatMessageUi +import com.nextcloud.talk.chat.ui.model.MessageStatusIcon +import com.nextcloud.talk.chat.viewmodels.ChatViewModel.ChatItem +import org.junit.Assert.assertEquals +import org.junit.Test +import java.time.LocalDate + +class VisibleFileDownloadsTest { + @Test + fun `scrolling without downloads must not inspect the message list`() { + val unreadableItems = object : AbstractList() { + override val size: Int = 100 + override fun get(index: Int): ChatItem = error("Unnecessary message lookup") + } + assertEquals(emptySet(), downloadingMessageKeys(unreadableItems, emptyList())) + } + + @Test + fun `only rows for active file downloads are tracked`() { + val first = message(10, "file-a") + val second = message(11, "file-b") + val items = listOf(first, second, ChatItem.DateHeaderItem(LocalDate.of(2026, 11, 19))) + assertEquals(setOf(first.stableKey()), downloadingMessageKeys(items, listOf("file-a", "missing"))) + assertEquals(emptySet(), downloadingMessageKeys(items, listOf("missing"))) + } + + private fun message(id: Int, fileId: String) = + ChatItem.MessageItem( + ChatMessageUi( + id = id, + message = "{file}", + renderMarkdown = false, + actorDisplayName = "Sender", + isThread = false, + threadTitle = "", + threadReplies = 0, + incoming = true, + isDeleted = false, + avatarUrl = null, + statusIcon = MessageStatusIcon.SENT, + timestamp = 1, + date = LocalDate.of(2026, 11, 19), + content = null, + messageParameters = mapOf("file" to mapOf("id" to fileId)) + ) + ) +} diff --git a/app/src/test/java/com/nextcloud/talk/utils/CharacterAvatarUtilsTest.kt b/app/src/test/java/com/nextcloud/talk/utils/CharacterAvatarUtilsTest.kt index 0e43fe6bec3..6adced51ec6 100644 --- a/app/src/test/java/com/nextcloud/talk/utils/CharacterAvatarUtilsTest.kt +++ b/app/src/test/java/com/nextcloud/talk/utils/CharacterAvatarUtilsTest.kt @@ -9,7 +9,6 @@ package com.nextcloud.talk.utils import com.nextcloud.talk.R import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse -import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Assert.assertTrue @@ -24,13 +23,16 @@ class CharacterAvatarUtilsTest { ?.character @Test - fun `named guest is drawn from the first character of their name`() { - assertEquals("A", characterOf("guests", "guest-hash", "alice")) + fun `named guest gets the person icon instead of initials`() { + assertSame( + ActorAvatar.PersonIcon, + CharacterAvatarUtils.avatarFor("guests", "guest-hash", "Alice Smith", guestLabel) + ) } @Test fun `surrounding whitespace is ignored`() { - assertEquals("B", characterOf("guests", "guest-hash", " bob ")) + assertSame(ActorAvatar.PersonIcon, CharacterAvatarUtils.guestAvatar(" bob ", guestLabel)) } @Test @@ -47,23 +49,21 @@ class CharacterAvatarUtilsTest { } @Test - fun `any name counts as custom when no placeholder name is given`() { - val avatar = CharacterAvatarUtils.guestAvatar("Guest", null) - assertEquals("G", (avatar as ActorAvatar.Character).character) + fun `a missing placeholder label cannot bring back guest initials`() { + assertSame(ActorAvatar.PersonIcon, CharacterAvatarUtils.guestAvatar("Guest", null)) } @Test - fun `first character outside the basic plane stays whole`() { - val name = "😀 party" - assertEquals(name.substring(0, 2), characterOf("guests", "guest-hash", name)) + fun `Persian and emoji guest names use the same person icon`() { + assertSame(ActorAvatar.PersonIcon, CharacterAvatarUtils.guestAvatar("مریم احمدی", guestLabel)) + assertSame(ActorAvatar.PersonIcon, CharacterAvatarUtils.guestAvatar("😀 party", guestLabel)) } @Test fun `both the plural and the singular spelling of an actor type are understood`() { - assertEquals("T", characterOf("guests", "guest-hash", "Test")) - assertEquals("T", characterOf("guest", "guest-hash", "Test")) - assertEquals("T", characterOf("emails", "email-hash", "Test")) - assertEquals("T", characterOf("email", "email-hash", "Test")) + for (type in listOf("guests", "guest", "emails", "email")) { + assertSame(ActorAvatar.PersonIcon, CharacterAvatarUtils.avatarFor(type, "guest-hash", "Test", guestLabel)) + } assertEquals(">_", characterOf("bots", "weather-bot", "Weather")) assertEquals(">_", characterOf("bot", "weather-bot", "Weather")) } @@ -77,18 +77,17 @@ class CharacterAvatarUtilsTest { } @Test - fun `guests are drawn in the guest colours`() { - val avatar = CharacterAvatarUtils.guestAvatar("alice", guestLabel) as ActorAvatar.Character - assertEquals(R.color.character_avatar_background_guest, avatar.backgroundColor) - assertEquals(R.color.character_avatar_text_guest, avatar.textColor) + fun `deleted users keep the generic person icon`() { + assertSame( + ActorAvatar.PersonIcon, + CharacterAvatarUtils.avatarFor("deleted_users", "deleted_users", "Alice", guestLabel) + ) } @Test - fun `bots and guests do not share a colour pair`() { - val bot = CharacterAvatarUtils.botAvatar("weather-bot") as ActorAvatar.Character - val guest = CharacterAvatarUtils.guestAvatar("alice", guestLabel) as ActorAvatar.Character - assertNotEquals(bot.backgroundColor, guest.backgroundColor) - assertNotEquals(bot.textColor, guest.textColor) + fun `the new person icon does not replace bot characters`() { + assertTrue(CharacterAvatarUtils.botAvatar("weather-bot") is ActorAvatar.Character) + assertSame(ActorAvatar.PersonIcon, CharacterAvatarUtils.guestAvatar("alice", guestLabel)) } @Test diff --git a/app/src/test/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptorTest.kt b/app/src/test/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptorTest.kt new file mode 100644 index 00000000000..c76f29728a3 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/utils/UserAvatarResponseInterceptorTest.kt @@ -0,0 +1,264 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.utils + +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.Interceptor +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import java.util.Base64 + +@Suppress("TooManyFunctions") +class UserAvatarResponseInterceptorTest { + + @Test + fun `generated avatar becomes a light PNG with matching content headers`() { + val result = intercept() + + assertEquals(listOf(false), result.fallbackThemes) + assertArrayEquals(LIGHT_IMAGE, result.response.body.bytes()) + assertEquals("image/png", result.response.header("Content-Type")) + assertEquals("image/png", result.response.body.contentType().toString()) + assertEquals(LIGHT_IMAGE.size.toLong(), result.response.body.contentLength()) + assertEquals(LIGHT_IMAGE.size.toString(), result.response.header("Content-Length")) + assertNull(result.response.header("Content-Encoding")) + } + + @Test + fun `dark appearance tag selects the dark fallback`() { + val result = intercept(request = request(dark = true)) + + assertEquals(listOf(true), result.fallbackThemes) + assertArrayEquals(DARK_IMAGE, result.response.body.bytes()) + } + + @Test + fun `dark avatar path selects the dark fallback without a tag`() { + val result = intercept(request = request("$AVATAR_URL/dark")) + + assertEquals(listOf(true), result.fallbackThemes) + assertArrayEquals(DARK_IMAGE, result.response.body.bytes()) + } + + @Test + fun `explicit light appearance takes precedence over the dark path`() { + val result = intercept(request = request("$AVATAR_URL/dark", dark = false)) + + assertEquals(listOf(false), result.fallbackThemes) + assertArrayEquals(LIGHT_IMAGE, result.response.body.bytes()) + } + + @Test + fun `generated avatar marker tolerates surrounding whitespace`() { + val result = intercept(marker = " 0 ") + + assertEquals(listOf(false), result.fallbackThemes) + assertArrayEquals(LIGHT_IMAGE, result.response.body.bytes()) + } + + @Test + fun `custom user photos are returned unchanged`() { + assertUntouched(intercept(marker = "1")) + } + + @Test + fun `missing custom avatar marker preserves the server image`() { + assertUntouched(intercept(marker = null)) + } + + @Test + fun `unrecognized custom avatar markers preserve the server image`() { + listOf("", "false", "00", "1, 0", "unknown").forEach { marker -> + assertUntouched(intercept(marker = marker)) + } + } + + @Test + fun `ordinary photos and WebDAV files are not replaced even with a generated marker`() { + listOf( + "$SERVER/remote.php/dav/files/alice/photo.png", + "$SERVER/remote.php/dav/files/alice/avatar/bob/96", + "$SERVER/index.php/core/preview?fileId=123" + ).forEach { url -> + assertUntouched(intercept(request = request(url))) + } + } + + @Test + fun `conversation avatars are not replaced even with a generated marker`() { + val url = "$SERVER/ocs/v2.php/apps/spreed/api/v1/room/room-token/avatar" + + assertUntouched(intercept(request = request(url))) + } + + @Test + fun `failed HTTP responses are preserved`() { + listOf(HTTP_UNAUTHORIZED, HTTP_NOT_FOUND, HTTP_SERVICE_UNAVAILABLE).forEach { code -> + assertUntouched(intercept(code = code)) + } + } + + @Test + fun `avatar replacement preserves the original request URL and authentication`() { + val originalRequest = request("$AVATAR_URL?v=7&account=alice").newBuilder() + .header("Authorization", "Basic test-credentials") + .header("Accept-Language", "fa") + .build() + val result = intercept(request = originalRequest) + + assertSame(originalRequest, result.proceededRequest) + assertSame(originalRequest, result.response.request) + assertEquals(originalRequest.url, result.proceededRequest.url) + assertEquals(originalRequest.headers, result.proceededRequest.headers) + assertEquals(1, result.requestCount) + } + + @Test + fun `policy recognizes subdirectory installations encoded user names and federated proxies`() { + listOf( + AVATAR_URL, + "$SERVER/nextcloud/index.php/avatar/alice/96/dark", + "$SERVER/nextcloud/avatar/Alice%20Smith/128", + "$SERVER/index.php/avatar/alice%2Fteam/96", + "$SERVER/index.php/avatar/%D8%B9%D9%84%DB%8C/96", + "$SERVER/ocs/v2.php/apps/spreed/api/v1/proxy/alice%40remote.example/user-avatar/96", + "$SERVER/nextcloud/ocs/v1.php/apps/spreed/api/v2/proxy/alice/user-avatar/128" + ).forEach { url -> + assertTrue(url, UserAvatarPolicy.appliesTo(url.toHttpUrl())) + val result = intercept(request = request(url)) + assertEquals(url, 1, result.fallbackThemes.size) + } + } + + @Test + fun `policy rejects unrelated and incomplete avatar paths`() { + listOf( + "$SERVER/avatar/alice", + "$SERVER/avatar/alice/original", + "$SERVER/avatar/alice/-1", + "$SERVER/avatar/alice/96/photo.png", + "$SERVER/files/avatar.png", + "$SERVER/ocs/v2.php/apps/spreed/api/v1/proxy/alice/room-avatar/96" + ).forEach { url -> + assertFalse(url, UserAvatarPolicy.appliesTo(url.toHttpUrl())) + } + } + + @Test + fun `light and dark cache entries cannot reuse each other`() { + assertNotEquals(UserAvatarPolicy.cacheKey(AVATAR_URL, false), UserAvatarPolicy.cacheKey(AVATAR_URL, true)) + } + + @Test + fun `cache keys retain the original account server and avatar version identity`() { + val originalKeys = listOf( + "$AVATAR_URL?v=1", + "$AVATAR_URL?v=2", + "$SERVER/avatar/bob/96?v=1", + "https://other.example.com/avatar/alice/96?v=1" + ) + val updatedKeys = originalKeys.map { UserAvatarPolicy.cacheKey(it, false) } + + assertEquals(originalKeys.size, updatedKeys.toSet().size) + originalKeys.zip(updatedKeys).forEach { (original, updated) -> + assertTrue(updated.startsWith("$original#")) + } + } + + @Test + fun `cache policy version prevents reuse of original and older fallback entries`() { + val key = UserAvatarPolicy.cacheKey(AVATAR_URL, false) + + assertEquals("$AVATAR_URL#talk-person-avatar-v2-light", key) + assertNotEquals(AVATAR_URL, key) + assertNotEquals("$AVATAR_URL#talk-person-avatar-v1-light", key) + } + + private fun assertUntouched(result: Result) { + assertSame(result.originalResponse, result.response) + assertArrayEquals(SERVER_IMAGE, result.response.body.bytes()) + assertEquals("image/jpeg", result.response.header("Content-Type")) + assertEquals("gzip", result.response.header("Content-Encoding")) + assertTrue(result.fallbackThemes.isEmpty()) + assertEquals(1, result.requestCount) + } + + private fun request(url: String = AVATAR_URL, dark: Boolean? = null): Request = + Request.Builder() + .url(url) + .apply { dark?.let { tag(UserAvatarAppearance::class.java, UserAvatarAppearance(it)) } } + .build() + + private fun intercept(request: Request = request(), marker: String? = "0", code: Int = HTTP_OK): Result { + val originalResponse = Response.Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(code) + .message("") + .header("Content-Type", "image/jpeg") + .header("Content-Length", SERVER_IMAGE.size.toString()) + .header("Content-Encoding", "gzip") + .apply { marker?.let { header("x-nc-iscustomavatar", it) } } + .body(SERVER_IMAGE.toResponseBody("image/jpeg".toMediaType())) + .build() + val fallbackThemes = mutableListOf() + var proceededRequest = request + var requestCount = 0 + val chain = mock { + on { request() } doReturn request + on { proceed(any()) } doAnswer { invocation -> + proceededRequest = invocation.getArgument(0) + requestCount++ + originalResponse + } + } + val response = UserAvatarResponseInterceptor { dark -> + fallbackThemes.add(dark) + if (dark) DARK_IMAGE else LIGHT_IMAGE + }.intercept(chain) + return Result(originalResponse, response, fallbackThemes, proceededRequest, requestCount) + } + + private data class Result( + val originalResponse: Response, + val response: Response, + val fallbackThemes: List, + val proceededRequest: Request, + val requestCount: Int + ) + + companion object { + private const val SERVER = "https://cloud.example.com" + private const val AVATAR_URL = "$SERVER/index.php/avatar/alice/96" + private const val HTTP_OK = 200 + private const val HTTP_UNAUTHORIZED = 401 + private const val HTTP_NOT_FOUND = 404 + private const val HTTP_SERVICE_UNAVAILABLE = 503 + private val SERVER_IMAGE = "server-avatar".toByteArray() + private val LIGHT_IMAGE = Base64.getDecoder().decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jF1sAAAAASUVORK5CYII=" + ) + private val DARK_IMAGE = Base64.getDecoder().decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" + ) + } +} diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index b41ab0e7bfc..de6c1a5dc0d 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -27361,6 +27361,14 @@ + + + + + + + + @@ -34135,5 +34143,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +