Adds a server and compression selection screen when uploading images on DMs

This commit is contained in:
Vitor Pamplona 2025-01-02 18:06:41 -05:00
parent ff9509b649
commit dbe593db98
5 changed files with 466 additions and 84 deletions

View File

@ -53,7 +53,6 @@ import com.vitorpamplona.amethyst.ui.components.Split
import com.vitorpamplona.amethyst.ui.screen.loggedIn.AccountViewModel
import com.vitorpamplona.amethyst.ui.stringRes
import com.vitorpamplona.ammolite.relays.RelaySetupInfo
import com.vitorpamplona.quartz.crypto.nip17.AESGCM
import com.vitorpamplona.quartz.encoders.Hex
import com.vitorpamplona.quartz.encoders.HexKey
import com.vitorpamplona.quartz.encoders.IMetaTag
@ -858,70 +857,6 @@ open class NewPostViewModel : ViewModel() {
}
}
fun uploadAsSeparatePrivateEvent(
toUsers: Set<HexKey>,
alt: String?,
sensitiveContent: Boolean,
mediaQuality: Int,
server: ServerName,
onError: (title: String, message: String) -> Unit,
context: Context,
) {
val myAccount = account ?: return
viewModelScope.launch(Dispatchers.Default) {
isUploadingImage = true
val cipher = AESGCM()
val myMultiOrchestrator = multiOrchestrator ?: return@launch
val results =
myMultiOrchestrator.uploadEncrypted(
viewModelScope,
alt,
sensitiveContent,
MediaCompressor.intToCompressorQuality(mediaQuality),
cipher,
server,
myAccount,
context,
)
if (results.allGood) {
results.successful.forEach { state ->
if (state.result is UploadOrchestrator.OrchestratorResult.ServerResult) {
account?.sendNIP17EncryptedFile(
url = state.result.url,
toUsers = toUsers.toList(),
replyingTo = originalNote,
contentType = state.result.mimeTypeBeforeEncryption,
algo = cipher.name(),
key = cipher.keyBytes,
nonce = cipher.nonce,
originalHash = state.result.hashBeforeEncryption,
hash = state.result.fileHeader.hash,
size = state.result.fileHeader.size,
dimensions = state.result.fileHeader.dim,
blurhash =
state.result.fileHeader.blurHash
?.blurhash,
alt = alt,
sensitiveContent = sensitiveContent,
)
}
}
multiOrchestrator = null
} else {
val errorMessages = results.errors.map { stringRes(context, it.errorResource, *it.params) }.distinct()
onError(stringRes(context, R.string.failed_to_upload_media_no_details), errorMessages.joinToString(".\n"))
}
isUploadingImage = false
}
}
fun upload(
alt: String?,
sensitiveContent: Boolean,

View File

@ -0,0 +1,170 @@
/**
* Copyright (c) 2024 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.ui.screen.loggedIn.chatrooms
import android.content.Context
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.commons.richtext.RichTextParser
import com.vitorpamplona.amethyst.model.Account
import com.vitorpamplona.amethyst.model.LocalCache.users
import com.vitorpamplona.amethyst.service.uploads.MediaCompressor
import com.vitorpamplona.amethyst.service.uploads.MultiOrchestrator
import com.vitorpamplona.amethyst.service.uploads.UploadOrchestrator
import com.vitorpamplona.amethyst.ui.actions.mediaServers.DEFAULT_MEDIA_SERVERS
import com.vitorpamplona.amethyst.ui.actions.mediaServers.ServerName
import com.vitorpamplona.amethyst.ui.actions.uploads.SelectedMedia
import com.vitorpamplona.amethyst.ui.actions.uploads.SelectedMediaProcessing
import com.vitorpamplona.amethyst.ui.stringRes
import com.vitorpamplona.quartz.crypto.nip17.AESGCM
import com.vitorpamplona.quartz.events.ChatroomKey
import kotlinx.collections.immutable.ImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Stable
open class ChatFileUploadModel : ViewModel() {
var account: Account? = null
var chatroom: ChatroomKey? = null
var isUploadingImage by mutableStateOf(false)
var selectedServer by mutableStateOf<ServerName?>(null)
var caption by mutableStateOf("")
var sensitiveContent by mutableStateOf(false)
// Images and Videos
var multiOrchestrator by mutableStateOf<MultiOrchestrator?>(null)
var onceUploaded: () -> Unit = {}
// 0 = Low, 1 = Medium, 2 = High, 3=UNCOMPRESSED
var mediaQualitySlider by mutableIntStateOf(1)
open fun load(
uris: ImmutableList<SelectedMedia>,
chatroom: ChatroomKey,
account: Account,
) {
this.chatroom = chatroom
this.caption = ""
this.account = account
this.multiOrchestrator = MultiOrchestrator(uris)
this.selectedServer = defaultServer()
}
fun isImage(
url: String,
mimeType: String?,
): Boolean = mimeType?.startsWith("image/") == true || RichTextParser.isImageUrl(url)
fun upload(
onError: (title: String, message: String) -> Unit,
context: Context,
) {
println("AABBCC uploading $account $selectedServer $chatroom $multiOrchestrator")
val myAccount = account ?: return
val mySelectedServer = selectedServer ?: return
val myChatroom = chatroom ?: return
val myMultiOrchestrator = multiOrchestrator ?: return
viewModelScope.launch(Dispatchers.Default) {
isUploadingImage = true
println("AABBCC uploading")
val cipher = AESGCM()
val results =
myMultiOrchestrator.uploadEncrypted(
viewModelScope,
caption,
sensitiveContent,
MediaCompressor.intToCompressorQuality(mediaQualitySlider),
cipher,
mySelectedServer,
myAccount,
context,
)
println("AABBCC uploading")
if (results.allGood) {
results.successful.forEach { state ->
if (state.result is UploadOrchestrator.OrchestratorResult.ServerResult) {
account?.sendNIP17EncryptedFile(
url = state.result.url,
toUsers = myChatroom.users.toList(),
replyingTo = null,
contentType = state.result.mimeTypeBeforeEncryption,
algo = cipher.name(),
key = cipher.keyBytes,
nonce = cipher.nonce,
originalHash = state.result.hashBeforeEncryption,
hash = state.result.fileHeader.hash,
size = state.result.fileHeader.size,
dimensions = state.result.fileHeader.dim,
blurhash =
state.result.fileHeader.blurHash
?.blurhash,
alt = caption,
sensitiveContent = sensitiveContent,
)
}
}
onceUploaded()
cancelModel()
} else {
val errorMessages = results.errors.map { stringRes(context, it.errorResource, *it.params) }.distinct()
onError(stringRes(context, R.string.failed_to_upload_media_no_details), errorMessages.joinToString(".\n"))
}
isUploadingImage = false
}
}
open fun cancelModel() {
multiOrchestrator = null
isUploadingImage = false
caption = ""
selectedServer = defaultServer()
}
fun deleteMediaToUpload(selected: SelectedMediaProcessing) {
multiOrchestrator?.remove(selected)
}
fun canPost(): Boolean = !isUploadingImage && multiOrchestrator != null && selectedServer != null
fun defaultServer() = account?.settings?.defaultFileServer ?: DEFAULT_MEDIA_SERVERS[0]
fun onceUploaded(onceUploaded: () -> Unit) {
this.onceUploaded = onceUploaded
}
}

View File

@ -0,0 +1,281 @@
/**
* Copyright (c) 2024 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.ui.screen.loggedIn.chatrooms
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.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.ui.actions.mediaServers.ServerType
import com.vitorpamplona.amethyst.ui.actions.uploads.ShowImageUploadGallery
import com.vitorpamplona.amethyst.ui.components.SetDialogToEdgeToEdge
import com.vitorpamplona.amethyst.ui.navigation.INav
import com.vitorpamplona.amethyst.ui.screen.loggedIn.AccountViewModel
import com.vitorpamplona.amethyst.ui.screen.loggedIn.CloseButton
import com.vitorpamplona.amethyst.ui.screen.loggedIn.PostButton
import com.vitorpamplona.amethyst.ui.screen.loggedIn.SettingSwitchItem
import com.vitorpamplona.amethyst.ui.screen.loggedIn.TextSpinner
import com.vitorpamplona.amethyst.ui.screen.loggedIn.TitleExplainer
import com.vitorpamplona.amethyst.ui.screen.loggedIn.settings.SettingsRow
import com.vitorpamplona.amethyst.ui.stringRes
import com.vitorpamplona.amethyst.ui.theme.Size5dp
import com.vitorpamplona.amethyst.ui.theme.StdHorzSpacer
import com.vitorpamplona.amethyst.ui.theme.placeholderText
import kotlinx.collections.immutable.toImmutableList
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatFileUploadView(
postViewModel: ChatFileUploadModel,
onClose: () -> Unit,
accountViewModel: AccountViewModel,
nav: INav,
) {
val account = accountViewModel.account
val context = LocalContext.current
val scrollState = rememberScrollState()
Dialog(
onDismissRequest = { onClose() },
properties =
DialogProperties(
usePlatformDefaultWidth = false,
dismissOnClickOutside = false,
decorFitsSystemWindows = false,
),
) {
SetDialogToEdgeToEdge()
Scaffold(
topBar = {
TopAppBar(
title = {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(modifier = StdHorzSpacer)
Text(
text = stringRes(R.string.dm_upload),
modifier = Modifier.weight(1f),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.titleLarge,
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
PostButton(
onPost = {
postViewModel.upload(
onError = accountViewModel::toast,
context = context,
)
postViewModel.selectedServer?.let {
if (it.type != ServerType.NIP95) {
account.settings.changeDefaultFileServer(it)
}
}
onClose()
},
isActive = postViewModel.canPost(),
)
}
},
navigationIcon = {
Row {
Spacer(modifier = StdHorzSpacer)
CloseButton(
onPress = {
postViewModel.cancelModel()
onClose()
},
)
}
},
colors =
TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.surface,
),
)
},
) { pad ->
Surface(
modifier =
Modifier
.padding(pad)
.consumeWindowInsets(pad)
.imePadding(),
) {
Column(Modifier.fillMaxSize().padding(start = 10.dp, end = 10.dp, bottom = 10.dp)) {
Column(Modifier.fillMaxWidth().verticalScroll(scrollState)) {
ImageVideoPostChat(postViewModel, accountViewModel)
}
}
}
}
}
}
@Composable
private fun ImageVideoPostChat(
postViewModel: ChatFileUploadModel,
accountViewModel: AccountViewModel,
) {
val fileServers by accountViewModel.account.liveServerList.collectAsState()
val fileServerOptions =
remember(fileServers) {
fileServers
.mapNotNull {
if (it.type != ServerType.NIP95) {
TitleExplainer(it.name, it.baseUrl)
} else {
null
}
}.toImmutableList()
}
postViewModel.multiOrchestrator?.let {
ShowImageUploadGallery(
it,
postViewModel::deleteMediaToUpload,
accountViewModel,
)
}
OutlinedTextField(
label = { Text(text = stringRes(R.string.content_description)) },
modifier = Modifier.fillMaxWidth().padding(top = 3.dp).height(150.dp),
maxLines = 10,
value = postViewModel.caption,
onValueChange = { postViewModel.caption = it },
placeholder = {
Text(
text = stringRes(R.string.content_description_example),
color = MaterialTheme.colorScheme.placeholderText,
)
},
keyboardOptions =
KeyboardOptions.Default.copy(
capitalization = KeyboardCapitalization.Sentences,
),
)
SettingSwitchItem(
title = R.string.add_sensitive_content_label,
description = R.string.add_sensitive_content_description,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
checked = postViewModel.sensitiveContent,
onCheckedChange = { postViewModel.sensitiveContent = it },
)
SettingsRow(R.string.file_server, R.string.file_server_description) {
TextSpinner(
label = "",
placeholder =
fileServers
.firstOrNull { it == accountViewModel.account.settings.defaultFileServer }
?.name
?: fileServers[0].name,
options = fileServerOptions,
onSelect = { postViewModel.selectedServer = fileServers[it] },
)
}
Column(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(Size5dp),
) {
Text(
text = stringRes(R.string.media_compression_quality_label),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = stringRes(R.string.media_compression_quality_explainer),
style = MaterialTheme.typography.bodySmall,
color = Color.Gray,
maxLines = 5,
overflow = TextOverflow.Ellipsis,
)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Box(modifier = Modifier.fillMaxWidth()) {
Text(
text =
when (postViewModel.mediaQualitySlider) {
0 -> stringRes(R.string.media_compression_quality_low)
1 -> stringRes(R.string.media_compression_quality_medium)
2 -> stringRes(R.string.media_compression_quality_high)
3 -> stringRes(R.string.media_compression_quality_uncompressed)
else -> stringRes(R.string.media_compression_quality_medium)
},
modifier = Modifier.align(Alignment.Center),
)
}
Slider(
value = postViewModel.mediaQualitySlider.toFloat(),
onValueChange = { postViewModel.mediaQualitySlider = it.toInt() },
valueRange = 0f..3f,
steps = 2,
)
}
}

View File

@ -23,13 +23,11 @@ package com.vitorpamplona.amethyst.ui.screen.loggedIn.chatrooms
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
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.fillMaxHeight
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.foundation.layout.width
@ -65,7 +63,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardCapitalization
@ -85,8 +82,6 @@ import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.model.Note
import com.vitorpamplona.amethyst.model.User
import com.vitorpamplona.amethyst.service.NostrChatroomDataSource
import com.vitorpamplona.amethyst.service.uploads.CompressorQuality
import com.vitorpamplona.amethyst.service.uploads.MediaCompressor
import com.vitorpamplona.amethyst.ui.actions.CrossfadeIfEnabled
import com.vitorpamplona.amethyst.ui.actions.NewPostViewModel
import com.vitorpamplona.amethyst.ui.actions.UrlUserTagTransformation
@ -387,6 +382,8 @@ fun PrepareChatroomViewModels(
}
}
val imageUpload: ChatFileUploadModel = viewModel()
if (draftMessage != null) {
LaunchedEffect(key1 = draftMessage) { newPostModel.updateMessage(TextFieldValue(draftMessage)) }
}
@ -395,6 +392,7 @@ fun PrepareChatroomViewModels(
room = room,
feedViewModel = feedViewModel,
newPostModel = newPostModel,
fileUpload = imageUpload,
accountViewModel = accountViewModel,
nav = nav,
)
@ -405,11 +403,10 @@ fun ChatroomScreen(
room: ChatroomKey,
feedViewModel: NostrChatroomFeedViewModel,
newPostModel: NewPostViewModel,
fileUpload: ChatFileUploadModel,
accountViewModel: AccountViewModel,
nav: INav,
) {
val context = LocalContext.current
NostrChatroomDataSource.loadMessagesBetween(accountViewModel.account, room)
val lifeCycleOwner = LocalLifecycleOwner.current
@ -483,6 +480,15 @@ fun ChatroomScreen(
}
}
fileUpload.multiOrchestrator?.let {
ChatFileUploadView(
fileUpload,
onClose = fileUpload::cancelModel,
accountViewModel,
nav,
)
}
// LAST ROW
PrivateMessageEditFieldRow(
newPostModel,
@ -500,16 +506,7 @@ fun ChatroomScreen(
}
},
onSendNewMedia = {
newPostModel.selectImage(it)
newPostModel.uploadAsSeparatePrivateEvent(
toUsers = room.users,
alt = null,
sensitiveContent = false,
mediaQuality = MediaCompressor.compressorQualityToInt(CompressorQuality.MEDIUM),
server = accountViewModel.account.settings.defaultFileServer,
onError = accountViewModel::toast,
context = context,
)
fileUpload.load(it, room, accountViewModel.account)
},
)
}
@ -558,8 +555,6 @@ fun PrivateMessageEditFieldRow(
Column(
modifier = EditFieldModifier,
) {
val context = LocalContext.current
ShowUserSuggestionList(
channelScreenModel.userSuggestions,
channelScreenModel::autocompleteWithUser,

View File

@ -978,6 +978,7 @@
<string name="search_relays_not_found_editing">Insert between 13 relays to use when searching for content or tagging users. Make sure your chosen relays implement NIP-50</string>
<string name="search_relays_not_found_examples">Good options are:\n - nostr.wine\n - relay.nostr.band\n - relay.noswhere.com</string>
<string name="dm_upload">DM Upload</string>
<string name="relay_settings">Relay Settings</string>
<string name="public_home_section">Public Outbox/Home Relays</string>
<string name="public_home_section_explainer">This relay type stores all your content. Amethyst will send your posts here and others will use these relays to find your content. Insert between 13 relays. They can be personal relays, paid relays or public relays.</string>