Skip to content

Commit

Permalink
Implement image saving from media gallery
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandarIlic committed Feb 1, 2024
1 parent c4bc6dc commit fb9849b
Show file tree
Hide file tree
Showing 11 changed files with 383 additions and 50 deletions.
4 changes: 4 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
<uses-permission android:name="android.permission.READ_CLIPBOARD" />
<uses-permission android:name="android.permission.CAMERA"/>

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />

<uses-feature android:name="android.hardware.camera.any" android:required="false" />

<application
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ interface MediaGalleryContract {
val noteId: String,
val loading: Boolean = true,
val initialAttachmentIndex: Int = 0,
val error: MediaGalleryError? = null,
val attachments: List<NoteAttachmentUi> = emptyList(),
)
) {
sealed class MediaGalleryError {
data class FailedToSaveMedia(val cause: Throwable) : MediaGalleryError()
}
}

sealed class UiEvent {
data class SaveMedia(val remoteUrl: String) : UiEvent()
data object DismissError : UiEvent()
}

sealed class SideEffect {
data object MediaSaved : SideEffect()
}
}
Original file line number Diff line number Diff line change
@@ -1,84 +1,134 @@
package net.primal.android.attachments.gallery

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FileDownload
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import coil.imageLoader
import coil.memory.MemoryCache
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.SuccessResult
import kotlinx.coroutines.launch
import me.saket.telephoto.zoomable.ZoomSpec
import me.saket.telephoto.zoomable.coil.ZoomableAsyncImage
import me.saket.telephoto.zoomable.rememberZoomableImageState
import me.saket.telephoto.zoomable.rememberZoomableState
import net.primal.android.R
import net.primal.android.core.compose.AppBarIcon
import net.primal.android.core.compose.HorizontalPagerIndicator
import net.primal.android.core.compose.SnackbarErrorHandler
import net.primal.android.core.compose.attachment.model.NoteAttachmentUi
import net.primal.android.core.compose.dropdown.DropdownPrimalMenu
import net.primal.android.core.compose.dropdown.DropdownPrimalMenuItem
import net.primal.android.core.compose.icons.PrimalIcons
import net.primal.android.core.compose.icons.primaliconpack.ArrowBack
import net.primal.android.core.compose.icons.primaliconpack.More
import net.primal.android.theme.AppTheme

@Composable
fun MediaGalleryScreen(onClose: () -> Unit, viewModel: MediaGalleryViewModel) {
fun MediaGalleryScreen(viewModel: MediaGalleryViewModel, onClose: () -> Unit) {
val uiState = viewModel.state.collectAsState()

val uiScope = rememberCoroutineScope()
val context = LocalContext.current
LaunchedEffect(viewModel) {
viewModel.effects.collect {
when (it) {
MediaGalleryContract.SideEffect.MediaSaved -> uiScope.launch {
Toast.makeText(
context,
context.getString(R.string.media_gallery_toast_photo_saved),
Toast.LENGTH_SHORT,
).show()
}
}
}
}

MediaGalleryScreen(
state = uiState.value,
onClose = onClose,
eventPublisher = { viewModel.setEvent(it) },
)
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MediaGalleryScreen(state: MediaGalleryContract.UiState, onClose: () -> Unit) {
Surface(color = AppTheme.colorScheme.background) {
Box(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding(),
contentAlignment = Alignment.TopStart,
) {
val imageAttachments = state.attachments
val imagesCount = imageAttachments.size

val pagerState = rememberPagerState { imagesCount }
if (imageAttachments.isNotEmpty()) {
AttachmentsHorizontalPager(
modifier = Modifier.fillMaxSize(),
imageAttachments = imageAttachments,
pagerState = pagerState,
initialIndex = state.initialAttachmentIndex,
)
fun MediaGalleryScreen(
state: MediaGalleryContract.UiState,
onClose: () -> Unit,
eventPublisher: (MediaGalleryContract.UiEvent) -> Unit,
) {
val imageAttachments = state.attachments
val imagesCount = imageAttachments.size
val pagerState = rememberPagerState { imagesCount }

fun currentImage() = imageAttachments.getOrNull(pagerState.currentPage)

val context = LocalContext.current
val snackbarHostState = remember { SnackbarHostState() }
SnackbarErrorHandler(
error = state.error,
snackbarHostState = snackbarHostState,
errorMessageResolver = {
when (it) {
is MediaGalleryContract.UiState.MediaGalleryError.FailedToSaveMedia ->
context.getString(R.string.media_gallery_error_photo_not_saved)
}
},
actionLabel = stringResource(id = R.string.media_gallery_retry_save),
onErrorDismiss = {
eventPublisher(MediaGalleryContract.UiEvent.DismissError)
},
onActionPerformed = {
currentImage()?.let { eventPublisher(MediaGalleryContract.UiEvent.SaveMedia(it.url)) }
},
)

Scaffold(
contentColor = AppTheme.colorScheme.background,
topBar = {
CenterAlignedTopAppBar(
title = {},
navigationIcon = {
Expand All @@ -88,20 +138,97 @@ fun MediaGalleryScreen(state: MediaGalleryContract.UiState, onClose: () -> Unit)
containerColor = AppTheme.colorScheme.surface.copy(alpha = 0.2f),
scrolledContainerColor = AppTheme.colorScheme.surface.copy(alpha = 0.2f),
),
actions = {
GalleryDropdownMenu(
onSaveClick = {
currentImage()?.let { eventPublisher(MediaGalleryContract.UiEvent.SaveMedia(it.url)) }
},
)
},
)
},
content = { paddingValues ->
Box(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize()
.systemBarsPadding(),
contentAlignment = Alignment.TopStart,
) {
if (imageAttachments.isNotEmpty()) {
AttachmentsHorizontalPager(
modifier = Modifier.fillMaxSize(),
imageAttachments = imageAttachments,
pagerState = pagerState,
initialIndex = state.initialAttachmentIndex,
)
}

if (imagesCount > 1) {
HorizontalPagerIndicator(
modifier = Modifier
.height(32.dp)
.fillMaxWidth()
.align(Alignment.BottomCenter),
imagesCount = imagesCount,
currentPage = pagerState.currentPage,
)
if (imagesCount > 1) {
HorizontalPagerIndicator(
modifier = Modifier
.height(32.dp)
.fillMaxWidth()
.align(Alignment.BottomCenter),
imagesCount = imagesCount,
currentPage = pagerState.currentPage,
)
}
}
}
},
snackbarHost = {
SnackbarHost(hostState = snackbarHostState)
},
)
}

@Composable
private fun GalleryDropdownMenu(onSaveClick: () -> Unit) {
var menuVisible by remember { mutableStateOf(false) }

AppBarIcon(
icon = PrimalIcons.More,
onClick = { menuVisible = true },
)

DropdownPrimalMenu(
expanded = menuVisible,
onDismissRequest = { menuVisible = false },
) {
SaveMediaMenuItem(
onSaveClick = {
menuVisible = false
onSaveClick()
},
)
}
}

@Composable
private fun SaveMediaMenuItem(onSaveClick: () -> Unit) {
val context = LocalContext.current

val hasExternalStoragePermission by remember {
val permission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
mutableStateOf(permission == PackageManager.PERMISSION_GRANTED)
}

val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
onResult = { granted -> if (granted) onSaveClick() },
)

DropdownPrimalMenuItem(
trailingIconVector = Icons.Default.FileDownload,
text = stringResource(id = R.string.media_gallery_context_save),
onClick = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q || hasExternalStoragePermission) {
onSaveClick()
} else {
launcher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
},
)
}

@ExperimentalFoundationApi
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,32 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.getAndUpdate
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.primal.android.attachments.domain.NoteAttachmentType
import net.primal.android.attachments.gallery.MediaGalleryContract.UiEvent
import net.primal.android.attachments.gallery.MediaGalleryContract.UiState
import net.primal.android.attachments.repository.AttachmentsRepository
import net.primal.android.core.compose.attachment.model.asNoteAttachmentUi
import net.primal.android.core.coroutines.CoroutineDispatcherProvider
import net.primal.android.core.files.MediaDownloader
import net.primal.android.core.files.error.UnableToSaveContent
import net.primal.android.core.files.error.UnsuccessfulFileDownload
import net.primal.android.navigation.mediaUrl
import net.primal.android.navigation.noteIdOrThrow
import timber.log.Timber

@HiltViewModel
class MediaGalleryViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val dispatcherProvider: CoroutineDispatcherProvider,
private val mediaDownloader: MediaDownloader,
private val repository: AttachmentsRepository,
) : ViewModel() {

Expand All @@ -29,13 +41,33 @@ class MediaGalleryViewModel @Inject constructor(
val state = _state.asStateFlow()
private fun setState(reducer: UiState.() -> UiState) = _state.getAndUpdate { it.reducer() }

private val events = MutableSharedFlow<UiEvent>()
fun setEvent(event: UiEvent) = viewModelScope.launch { events.emit(event) }

private val _effects = Channel<MediaGalleryContract.SideEffect>()
val effects = _effects.receiveAsFlow()
private fun setEffect(effect: MediaGalleryContract.SideEffect) = viewModelScope.launch { _effects.send(effect) }

init {
observeEvents()
loadAttachments()
}

private fun observeEvents() =
viewModelScope.launch {
events.collect {
when (it) {
is UiEvent.SaveMedia -> saveMedia(remoteUrl = it.remoteUrl)
UiEvent.DismissError -> setState { copy(error = null) }
}
}
}

private fun loadAttachments() =
viewModelScope.launch {
val attachments = repository.loadAttachments(noteId = noteId, types = listOf(NoteAttachmentType.Image))
val attachments = withContext(dispatcherProvider.io()) {
repository.loadAttachments(noteId = noteId, types = listOf(NoteAttachmentType.Image))
}
setState {
copy(
loading = false,
Expand All @@ -44,4 +76,20 @@ class MediaGalleryViewModel @Inject constructor(
)
}
}

private fun saveMedia(remoteUrl: String) =
viewModelScope.launch {
withContext(dispatcherProvider.io()) {
try {
mediaDownloader.downloadToMediaGallery(url = remoteUrl)
setEffect(MediaGalleryContract.SideEffect.MediaSaved)
} catch (error: UnsuccessfulFileDownload) {
Timber.w(error)
setState { copy(error = UiState.MediaGalleryError.FailedToSaveMedia(error)) }
} catch (error: UnableToSaveContent) {
Timber.w(error)
setState { copy(error = UiState.MediaGalleryError.FailedToSaveMedia(error)) }
}
}
}
}
Loading

0 comments on commit fb9849b

Please sign in to comment.