Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,16 @@ private fun ContactBubblePreview() {
}
}
}

@PreviewLightDark
@Composable
private fun ContactCardDialogPreview() {
MessagesTheme(mode = "system") {
com.anindra.messages.ui.ContactCardDialog(
uri = "content://preview/contact",
onAddToContacts = { _, _ -> },
onSaveFile = {},
onDismiss = {}
)
}
}
9 changes: 9 additions & 0 deletions app/src/main/java/com/anindra/messages/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -802,10 +802,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
var saved = 0
var allAudio = true
var allVideo = true
var allContact = true
for (msg in messages) {
val target = MmsSupport.saveTargetFor(msg.mediaType)
if (target != MmsSupport.SaveTarget.AUDIO) allAudio = false
if (target != MmsSupport.SaveTarget.VIDEO) allVideo = false
if (target != MmsSupport.SaveTarget.FILE) allContact = false
val uri = Uri.parse(msg.mediaUri)
val bytes = runCatching {
resolver.openInputStream(uri)?.use { it.readBytes() }
Expand All @@ -821,16 +823,23 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
)
val ok = bytes != null && bytes.isNotEmpty() &&
DownloadsStore.writeMedia(app, name, mime, bytes, target)
if (ok) saved++
// The toast is the only evidence a user gets, so the same outcome
// names itself for the regression script.
android.util.Log.d(
"AttachmentSave",
"target=$target mime=$mime name=$name ok=$ok"
)
}
// How many of the selection were written: the toast is chosen from
// this, and the regression script reads it back instead of a toast
// it cannot see.
android.util.Log.d("AttachmentSave", "saved=$saved/${messages.size} contact=$allContact")
withContext(Dispatchers.Main) {
val savedAll = saved == messages.size
val message = when {
allContact && savedAll -> R.string.chat_contact_saved
allContact -> R.string.chat_contact_save_failed
allAudio && savedAll -> R.string.chat_voice_saved
allAudio -> R.string.chat_voice_save_failed
allVideo && savedAll -> R.string.chat_video_saved
Expand Down
27 changes: 21 additions & 6 deletions app/src/main/java/com/anindra/messages/data/MmsSupport.kt
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,30 @@ object MmsSupport {
/** The clips of this MMS; a clip is never folded into a picture album. */
val videoIds: List<Long> = emptyList(),
val audioId: Long? = null,
val audioMime: String = ""
val audioMime: String = "",
/** The contact cards this MMS carries. A card is a `text/x-vcard` part,
* which is what a phone sends when someone shares a contact. */
val contactIds: List<Long> = emptyList()
) {
val mediaType: String
get() = when {
imageId != null -> "image"
videoIds.isNotEmpty() -> "video"
audioId != null -> "audio"
contactIds.isNotEmpty() -> KIND_CONTACT
else -> "text"
}

val mediaId: Long?
get() = imageId ?: videoIds.firstOrNull() ?: audioId
get() = imageId ?: videoIds.firstOrNull() ?: audioId ?: contactIds.firstOrNull()

/** Every attachment this MMS carries, in the order it should be shown, as
* (mediaType, partId). Empty for a text-only MMS. */
fun mediaRows(): List<Pair<String, Long>> = buildList {
imageId?.let { add("image" to it) }
extraImageIds.forEach { add("image" to it) }
videoIds.forEach { add("video" to it) }
contactIds.forEach { add(KIND_CONTACT to it) }
}
}
data class InboundMms(
Expand All @@ -124,6 +129,9 @@ object MmsSupport {
val imageUri: String? = null,
/** The voice note of a voice MMS, or null. */
val audioUri: String? = null,
/** The contact card of a card MMS, or null. Like a picture, a card-only
* MMS has a blank body and needs a label to be shown at all. */
val contactUri: String? = null,
/**
* The conversation the import filed this message under (#448).
*
Expand All @@ -134,6 +142,7 @@ object MmsSupport {
val conversationId: Long = 0
) {
val isAudio: Boolean get() = audioUri != null
val isContact: Boolean get() = contactUri != null
}
/** [subscriptionId] is the line the announcement was filed under, or -1 when the
* provider does not record one. The downloaded message keeps it. */
Expand Down Expand Up @@ -302,6 +311,9 @@ object MmsSupport {
* received voice note can arrive as AMR, MP3 or OGG. */
fun isAudio(raw: String): Boolean = mime(raw).startsWith("audio/")

/** A contact card: the one part type a phone turns into a savable contact. */
fun isVCard(raw: String): Boolean = mime(raw) == VCARD_MIME

/** The MIME the app labels a clip with when the provider does not say. */
const val DEFAULT_VIDEO_MIME = "video/mp4"

Expand All @@ -310,12 +322,13 @@ object MmsSupport {
)

/** The message `media_type` for an attachment of this type: pictures get the
* album layout, a clip its own bubble, a voice note its waveform, and
* everything else is a plain file. */
* album layout, a clip its own bubble, a voice note its waveform, a contact
* card its card, and everything else is a plain file. */
fun mediaKind(rawMime: String): String = when {
isImage(rawMime) -> "image"
isVideo(rawMime) -> "video"
isAudio(rawMime) -> "audio"
isVCard(rawMime) -> KIND_CONTACT
else -> "file"
}

Expand Down Expand Up @@ -365,9 +378,10 @@ object MmsSupport {
val audio = parts.firstOrNull { it.id > 0 && isAudio(it.mime) }
?.takeIf { images.isEmpty() }
val videos = parts.filter { it.id > 0 && isVideo(it.mime) }
val contacts = parts.filter { it.id > 0 && isVCard(it.mime) }
val text = parts.filter { mime(it.mime) == "text/plain" }.mapNotNull { it.text }
.filter { it.isNotBlank() }.joinToString("\n")
val shownIds = (images + videos).map { it.id }.toSet()
val shownIds = (images + videos + contacts).map { it.id }.toSet()
val omitted = parts.count {
mime(it.mime) !in setOf("text/plain", "application/smil") &&
it.id !in shownIds && it !== audio
Expand All @@ -380,7 +394,8 @@ object MmsSupport {
extraImageIds = images.drop(1).map { it.id },
videoIds = videos.map { it.id },
audioId = audio?.id,
audioMime = audio?.let { mime(it.mime) } ?: ""
audioMime = audio?.let { mime(it.mime) } ?: "",
contactIds = contacts.map { it.id }
)
}

Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/anindra/messages/data/Repository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5164,6 +5164,8 @@ class Repository(private val context: Context) {
message.timestamp,
imageUri = message.content.imageId?.let { "content://mms/part/$it" },
audioUri = message.content.audioId?.let { "content://mms/part/$it" },
contactUri = message.content.contactIds.firstOrNull()
?.let { "content://mms/part/$it" },
conversationId = cid
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class MmsDownloadReceiver : BroadcastReceiver() {
for (mms in repo.importDownloadedMms()) {
NotificationHelper.show(
context, mms.address, mms.body, mms.imageUri, audio = mms.isAudio,
contact = mms.isContact,
conversationId = mms.conversationId
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ data class NotificationLine(
val imageUri: String? = null,
/** True when the message carries a voice note. Like a picture, a voice MMS
* has a blank body and is dropped unless it says what it is. */
val isAudio: Boolean = false
val isAudio: Boolean = false,
/** True when the message carries a contact card, which is also blank-bodied. */
val isContact: Boolean = false
)

/**
Expand Down
14 changes: 10 additions & 4 deletions app/src/main/java/com/anindra/messages/sms/SmsSupport.kt
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ object NotificationHelper {
imageUri: String? = null,
privacyMode: Boolean = false,
senderIcon: IconCompat? = null,
audio: Boolean = false
audio: Boolean = false,
contact: Boolean = false
): NotificationCompat.Style {
val hideLinks = app.repository.settings.hideLinks
val person = Person.Builder().setName(senderName)
Expand All @@ -125,12 +126,14 @@ object NotificationHelper {
// empty row, and the picture itself rides along as message data.
val photoLabel = context.getString(R.string.notif_photo)
val voiceLabel = context.getString(R.string.notif_voice)
val contactLabel = context.getString(R.string.notif_contact)
val lines = NotificationHistory.window(
if (history.isEmpty()) {
listOf(
NotificationLine(
fallbackText, System.currentTimeMillis(), false,
isImage = imageUri != null, imageUri = imageUri, isAudio = audio
isImage = imageUri != null, imageUri = imageUri, isAudio = audio,
isContact = contact
)
)
} else history.map {
Expand All @@ -140,7 +143,8 @@ object NotificationHelper {
fromMe = false,
isImage = it.isImage,
imageUri = it.imageUri,
isAudio = it.isAudio
isAudio = it.isAudio,
isContact = it.isContact
)
}
)
Expand All @@ -152,6 +156,7 @@ object NotificationHelper {
it.text.isNotBlank() -> it.text
it.isImage -> photoLabel
it.isAudio -> voiceLabel
it.isContact -> contactLabel
else -> it.text
}
val message = NotificationCompat.MessagingStyle.Message(
Expand Down Expand Up @@ -401,6 +406,7 @@ object NotificationHelper {
imageUri: String? = null,
silentRepost: Boolean = false,
audio: Boolean = false,
contact: Boolean = false,
/**
* The chat the import filed this message under (#448). A group has no
* single address, so looking it up by [from] would post the group on the
Expand Down Expand Up @@ -573,7 +579,7 @@ object NotificationHelper {
.setStyle(
groupedStyle(
context, app, convoId, senderName, text, imageUri, privacyMode,
senderIcon = avatar?.icon, audio = audio
senderIcon = avatar?.icon, audio = audio, contact = contact
)
)
avatar?.let { builder.setLargeIcon(it.bitmap) }
Expand Down
36 changes: 35 additions & 1 deletion app/src/main/java/com/anindra/messages/ui/ChatScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ internal fun ChatBubble(
onTap: () -> Unit,
onImageTap: (Message) -> Unit = {},
onVideoTap: (Message) -> Unit = {},
onContactTap: (Message) -> Unit = {},
deliveryReports: Boolean,
highlightLinks: Boolean,
linkWarningEnabled: Boolean,
Expand Down Expand Up @@ -544,7 +545,8 @@ internal fun ChatBubble(
uri = msg.mediaUri,
isMe = msg.isMe,
isSelected = isSelected,
onLongPress = onLongPress
onLongPress = onLongPress,
onClick = { onContactTap(msg) }
)
} else if (msg.mediaType == "audio" && msg.mediaUri.isNotBlank()) {
VoiceBubble(
Expand Down Expand Up @@ -1012,6 +1014,8 @@ fun ChatScreen(
// chat, so opening it dismisses the IME and closing it gives the field back.
var attachOpen by remember { mutableStateOf(false) }
var showLocationDialog by remember { mutableStateOf(false) }
// The contact card the user tapped, if any: it offers "add to contacts".
var contactCard by remember { mutableStateOf<Message?>(null) }
val fieldFocus = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
Expand Down Expand Up @@ -2214,6 +2218,10 @@ fun ChatScreen(
if (selectionActive) toggleRowSelection(rowIds)
else playingVideo = clip
},
onContactTap = { card ->
if (selectionActive) toggleRowSelection(rowIds)
else contactCard = card
},
deliveryReports = deliveryReports,
highlightLinks = vm.settings.highlightLinks,
linkWarningEnabled = vm.settings.linkOpenWarningEnabled,
Expand Down Expand Up @@ -2339,6 +2347,32 @@ fun ChatScreen(
)
}

contactCard?.let { card ->
ContactCardDialog(
uri = card.mediaUri,
onAddToContacts = { name, number ->
contactCard = null
val intent = ContactActions.addIntent(name, number)
if (intent != null) {
launchOrExplain(R.string.chat_contact_save_failed) {
context.startActivity(intent)
}
} else {
Toast.makeText(
context,
context.getString(R.string.chat_contact_unavailable),
Toast.LENGTH_SHORT
).show()
}
},
onSaveFile = {
contactCard = null
vm.saveMessageImage(card.id)
},
onDismiss = { contactCard = null }
)
}

// A device without a camera app, a photo picker, a document picker or a
// contact picker throws instead of opening anything: an unhandled
// ActivityNotFoundException crashed the chat the moment that tile was
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/com/anindra/messages/ui/ContactActions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.anindra.messages.ui

import android.content.Intent
import android.provider.ContactsContract

/**
* What a contact card in the conversation can do.
*
* A card is only worth sending if the person who receives it can keep it, so a
* tap offers the two things a phone does with a vCard: add it to the contacts
* app, or write the file somewhere it can be opened later.
*/
object ContactActions {

/** The name and number the insert intent carries, or null when the card has
* no number — there is nothing a contact could be created from. */
fun insertValues(name: String?, number: String?): Pair<String, String>? {
val phone = number?.trim().orEmpty()
if (phone.isEmpty()) return null
return name?.trim().orEmpty() to phone
}

/** The contacts app's "new contact" intent, prefilled from the card. */
fun addIntent(name: String?, number: String?): Intent? {
val (safeName, phone) = insertValues(name, number) ?: return null
return Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI).apply {
type = ContactsContract.Contacts.CONTENT_TYPE
putExtra(ContactsContract.Intents.Insert.NAME, safeName)
putExtra(ContactsContract.Intents.Insert.PHONE, phone)
}
}
}
11 changes: 7 additions & 4 deletions app/src/main/java/com/anindra/messages/ui/ContactBubble.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ internal fun ContactBubble(
uri: String,
isMe: Boolean,
isSelected: Boolean = false,
onLongPress: () -> Unit = {}
onLongPress: () -> Unit = {},
onClick: () -> Unit = {}
) {
val context = LocalContext.current
val card = remember(uri) { ContactShare.readCard(context, Uri.parse(uri)) }
Expand All @@ -54,7 +55,8 @@ internal fun ContactBubble(
number = card?.second,
isMe = isMe,
isSelected = isSelected,
onLongPress = onLongPress
onLongPress = onLongPress,
onClick = onClick
)
}

Expand All @@ -66,7 +68,8 @@ internal fun ContactCardBubble(
number: String?,
isMe: Boolean,
isSelected: Boolean = false,
onLongPress: () -> Unit = {}
onLongPress: () -> Unit = {},
onClick: () -> Unit = {}
) {
val cs = MaterialTheme.colorScheme
val label = stringResource(R.string.chat_media_contact)
Expand All @@ -76,7 +79,7 @@ internal fun ContactCardBubble(
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.widthIn(max = 260.dp)
.combinedClickable(onClick = {}, onLongClick = onLongPress)
.combinedClickable(onClick = onClick, onLongClick = onLongPress)
) {
Row(
Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
Expand Down
Loading