Skip to content

Commit

Permalink
[AND-12] Improve media storage permission handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
PetarVelikov committed Dec 12, 2024
1 parent 2ebf4a9 commit 0b1a3b9
Show file tree
Hide file tree
Showing 11 changed files with 752 additions and 88 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,7 @@ public final class io/getstream/chat/android/compose/ui/components/attachments/f
}

public final class io/getstream/chat/android/compose/ui/components/attachments/images/ImagesPickerKt {
public static final fun ImagesPicker (Ljava/util/List;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/Modifier;Lkotlin/jvm/functions/Function3;Landroidx/compose/runtime/Composer;II)V
public static final fun ImagesPicker (Ljava/util/List;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/Modifier;Lkotlin/jvm/functions/Function3;ZLkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;II)V
}

public final class io/getstream/chat/android/compose/ui/components/audio/ComposableSingletons$PlaybackTimerKt {
Expand Down Expand Up @@ -1635,6 +1635,13 @@ public final class io/getstream/chat/android/compose/ui/messages/attachments/fac
public final fun getLambda-1$stream_chat_android_compose_release ()Lkotlin/jvm/functions/Function3;
}

public final class io/getstream/chat/android/compose/ui/messages/attachments/factory/ComposableSingletons$NoStorageAccessContentKt {
public static final field INSTANCE Lio/getstream/chat/android/compose/ui/messages/attachments/factory/ComposableSingletons$NoStorageAccessContentKt;
public static field lambda-1 Lkotlin/jvm/functions/Function3;
public fun <init> ()V
public final fun getLambda-1$stream_chat_android_compose_release ()Lkotlin/jvm/functions/Function3;
}

public final class io/getstream/chat/android/compose/ui/messages/attachments/poll/ComposableSingletons$PollCreationDiscardDialogKt {
public static final field INSTANCE Lio/getstream/chat/android/compose/ui/messages/attachments/poll/ComposableSingletons$PollCreationDiscardDialogKt;
public static field lambda-1 Lkotlin/jvm/functions/Function2;
Expand Down
2 changes: 2 additions & 0 deletions stream-chat-android-compose/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- Needed to properly handle media re-selection on android 14+, otherwise we run the app in compatibility mode -->
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />

<application>
<activity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
Expand All @@ -43,11 +45,13 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil.decode.VideoFrameDecoder
import coil.request.ImageRequest
Expand All @@ -71,6 +75,10 @@ private const val DefaultNumberOfPicturesPerRow = 3
* @param images The images the user can pick, to be rendered in a list.
* @param onImageSelected Handler when the user clicks on any image item.
* @param modifier Modifier for styling.
* @param itemContent Composable rendering an image/video item in the picker.
* @param showAddMore Flag indicating the the "Add more" item should be shown at the beginning of the picker.
* @param onAddMoreClick Action to be invoked when the user clicks on the "Add more" item.
* @param addMoreContent Composable rendering the "Add more" item.
*/
@Composable
public fun ImagesPicker(
Expand All @@ -83,12 +91,20 @@ public fun ImagesPicker(
onImageSelected = onImageSelected,
)
},
showAddMore: Boolean = false,
onAddMoreClick: () -> Unit = {},
addMoreContent: @Composable () -> Unit = {
DefaultAddMoreItem(onAddMoreClick)
},
) {
LazyVerticalGrid(
modifier = modifier,
columns = GridCells.Fixed(DefaultNumberOfPicturesPerRow),
contentPadding = PaddingValues(1.dp),
) {
if (showAddMore) {
item { addMoreContent() }
}
items(images) { imageItem -> itemContent(imageItem) }
}
}
Expand Down Expand Up @@ -210,6 +226,46 @@ private fun BoxScope.VideoThumbnailOverlay(
}
}

/**
* Default 'pick more' tile to be shown if the user can pick more images.
*
* @param onPickMoreClick Action invoked when the user clicks on the 'pick more' tile.
*/
@Composable
internal fun DefaultAddMoreItem(onPickMoreClick: () -> Unit) {
Column(
modifier = Modifier
.height(125.dp)
.padding(2.dp)
.clip(RoundedCornerShape(8.dp))
.border(
width = 1.dp,
color = ChatTheme.colors.borders,
shape = RoundedCornerShape(8.dp),
)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = ripple(),
onClick = onPickMoreClick,
)
.testTag("Stream_AttachmentPickerPickMore"),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Icon(
painter = painterResource(id = R.drawable.stream_compose_ic_add),
contentDescription = null,
tint = ChatTheme.colors.textLowEmphasis,
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.stream_ui_message_composer_permissions_visual_media_add_more),
style = ChatTheme.typography.body,
color = ChatTheme.colors.textLowEmphasis,
)
}
}

/**
* The time code of the frame to extract from a video.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,33 @@

package io.getstream.chat.android.compose.ui.messages.attachments.factory

import android.Manifest
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.StringRes
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.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.SnackbarHostState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LocalLifecycleOwner
import io.getstream.chat.android.compose.R
import io.getstream.chat.android.compose.state.messages.attachments.AttachmentPickerItemState
import io.getstream.chat.android.compose.state.messages.attachments.AttachmentsPickerMode
Expand All @@ -44,6 +53,7 @@ import io.getstream.chat.android.compose.ui.util.StorageHelperWrapper
import io.getstream.chat.android.ui.common.helper.internal.AttachmentFilter
import io.getstream.chat.android.ui.common.helper.internal.StorageHelper
import io.getstream.chat.android.ui.common.state.messages.composer.AttachmentMetaData
import io.getstream.chat.android.uiutils.util.openSystemSettings

/**
* Holds the information required to add support for "files" tab in the attachment picker.
Expand Down Expand Up @@ -85,7 +95,6 @@ public class AttachmentsPickerFilesTabFactory : AttachmentsPickerTabFactory {
* @param onAttachmentItemSelected Handler when the item selection state changes.
* @param onAttachmentsSubmitted Handler to submit the selected attachments to the message composer.
*/
@OptIn(ExperimentalPermissionsApi::class)
@Composable
override fun PickerTabContent(
onAttachmentPickerAction: (AttachmentPickerAction) -> Unit,
Expand All @@ -94,36 +103,38 @@ public class AttachmentsPickerFilesTabFactory : AttachmentsPickerTabFactory {
onAttachmentItemSelected: (AttachmentPickerItemState) -> Unit,
onAttachmentsSubmitted: (List<AttachmentMetaData>) -> Unit,
) {
var storagePermissionRequested by rememberSaveable { mutableStateOf(false) }
val storagePermissionState = rememberMultiplePermissionsState(
permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
listOf(
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_VIDEO,
Manifest.permission.READ_MEDIA_AUDIO,
)
} else {
listOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
)
},
) {
storagePermissionRequested = true
}

val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val storageHelper: StorageHelperWrapper = remember {
StorageHelperWrapper(context, StorageHelper(), AttachmentFilter())
}
var showPermanentlyDeniedSnackBar by remember { mutableStateOf(false) }
val permissionLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
if (isPermanentlyDenied(context, result)) {
showPermanentlyDeniedSnackBar = true
}
}
val filesAccess by filesAccessAsState(context, lifecycleOwner) { value ->
if (value != FilesAccess.DENIED) {
onAttachmentsChanged(
storageHelper.getFiles().map { AttachmentPickerItemState(it, false) },
)
}
}

when (storagePermissionState.allPermissionsGranted) {
true -> {
// Content
FilesAccessContent(
filesAccess = filesAccess,
onRequestFilesAccess = { permissionLauncher.launch(filesPermissions()) },
onRequestVisualMediaAccess = { permissionLauncher.launch(visualMediaPermissions()) },
onRequestAudioAccess = { permissionLauncher.launch(audioPermissions()) },
filePicker = {
FilesPicker(
files = attachments,
onItemSelected = onAttachmentItemSelected,
onBrowseFilesResult = { uris ->
val attachments = storageHelper.getAttachmentsMetadataFromUris(uris)

// Check if some of the files were filtered out due to upload config
if (uris.size != attachments.size) {
Toast.makeText(
Expand All @@ -136,28 +147,129 @@ public class AttachmentsPickerFilesTabFactory : AttachmentsPickerTabFactory {
onAttachmentsSubmitted(attachments)
},
)
}
},
)

else -> {
val revokedPermissionState = storagePermissionState.revokedPermissions.first()
MissingPermissionContent(revokedPermissionState)
// Access permanently denied snackbar
val snackBarHostState = remember { SnackbarHostState() }
PermissionPermanentlyDeniedSnackBar(snackBarHostState) {
context.openSystemSettings()
}
val snackbarMessage = stringResource(id = R.string.stream_ui_message_composer_permission_setting_message)
val snackbarAction = stringResource(id = R.string.stream_ui_message_composer_permissions_setting_button)
LaunchedEffect(showPermanentlyDeniedSnackBar) {
if (showPermanentlyDeniedSnackBar) {
snackBarHostState.showSnackbar(snackbarMessage, snackbarAction)
showPermanentlyDeniedSnackBar = false
}
}
}

val hasPermission = storagePermissionState.allPermissionsGranted
@Composable
private fun FilesAccessContent(
filesAccess: FilesAccess,
filePicker: @Composable () -> Unit,
onRequestFilesAccess: () -> Unit,
onRequestVisualMediaAccess: () -> Unit,
onRequestAudioAccess: () -> Unit,
) {
when (filesAccess) {
FilesAccess.DENIED -> {
NoStorageAccessContent(onRequestAccessClick = onRequestFilesAccess)
}

LaunchedEffect(storagePermissionState.allPermissionsGranted) {
if (storagePermissionState.allPermissionsGranted) {
onAttachmentsChanged(
storageHelper.getFiles().map { AttachmentPickerItemState(it, false) },
)
FilesAccess.PARTIAL_VISUAL -> {
Column {
GrantAudioAccessButton(onClick = onRequestAudioAccess)
AllowMoreVisualMediaButton(onClick = onRequestVisualMediaAccess)
filePicker()
}
}
}

LaunchedEffect(Unit) {
if (!hasPermission && !storagePermissionRequested) {
storagePermissionState.launchMultiplePermissionRequest()
FilesAccess.FULL_VISUAL -> {
Column {
GrantAudioAccessButton(onClick = onRequestAudioAccess)
filePicker()
}
}

FilesAccess.AUDIO -> {
Column {
GrantVisualMediaAccessButton(onClick = onRequestVisualMediaAccess)
filePicker()
}
}

FilesAccess.AUDIO_AND_PARTIAL_VISUAL -> {
Column {
AllowMoreVisualMediaButton(onClick = onRequestVisualMediaAccess)
filePicker()
}
}

FilesAccess.AUDIO_AND_FULL_VISUAL -> {
filePicker()
}
}
}

@Composable
private fun GrantVisualMediaAccessButton(onClick: () -> Unit) {
RequestAdditionalAccessButton(
textId = R.string.stream_ui_message_composer_permissions_files_allow_visual_media_access,
contentDescriptionId = R.string.stream_ui_message_composer_permissions_files_allow_visual_media_access,
onClick = onClick,
)
}

@Composable
private fun AllowMoreVisualMediaButton(onClick: () -> Unit) {
RequestAdditionalAccessButton(
textId = R.string.stream_ui_message_composer_permissions_files_allow_more_visual_media,
contentDescriptionId = R.string.stream_ui_message_composer_permissions_files_allow_more_visual_media,
onClick = onClick,
)
}

@Composable
private fun GrantAudioAccessButton(onClick: () -> Unit) {
RequestAdditionalAccessButton(
textId = R.string.stream_ui_message_composer_permissions_files_allow_audio_access,
contentDescriptionId = R.string.stream_ui_message_composer_permissions_files_allow_audio_access,
onClick = onClick,
)
}

@Composable
private fun RequestAdditionalAccessButton(
@StringRes textId: Int,
@StringRes contentDescriptionId: Int,
onClick: () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
modifier = Modifier
.padding(16.dp)
.weight(1f),
text = stringResource(id = textId),
style = ChatTheme.typography.bodyBold,
color = ChatTheme.colors.textHighEmphasis,
)

IconButton(
content = {
Icon(
painter = painterResource(id = R.drawable.stream_compose_ic_more_files),
contentDescription = stringResource(id = contentDescriptionId),
tint = ChatTheme.colors.primaryAccent,
)
},
onClick = onClick,
)
}
}
}
Loading

0 comments on commit 0b1a3b9

Please sign in to comment.