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 9bde487a338..d9a9f2a0ecb 100644 Binary files a/app/src/qa/ic_launcher-web.png and b/app/src/qa/ic_launcher-web.png differ 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 99024db8ebd..00000000000 Binary files a/app/src/qa/res/mipmap-hdpi/ic_launcher.png and /dev/null differ 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 2b6d24b1c09..00000000000 Binary files a/app/src/qa/res/mipmap-mdpi/ic_launcher.png and /dev/null differ 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 a0528c11be6..00000000000 Binary files a/app/src/qa/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/qa/res/mipmap-xxhdpi/ic_launcher.png b/app/src/qa/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index a2a2f273103..00000000000 Binary files a/app/src/qa/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/qa/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/qa/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 677ffdd258a..00000000000 Binary files a/app/src/qa/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ 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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +