diff --git a/app/src/debug/java/com/anindra/messages/ui/previews/ContactPreviews.kt b/app/src/debug/java/com/anindra/messages/ui/previews/ContactPreviews.kt new file mode 100644 index 00000000..8de3adfb --- /dev/null +++ b/app/src/debug/java/com/anindra/messages/ui/previews/ContactPreviews.kt @@ -0,0 +1,42 @@ +package com.anindra.messages.ui.previews + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.PreviewLightDark +import androidx.compose.ui.unit.dp +import com.anindra.messages.ui.ContactBubble +import com.anindra.messages.ui.ContactCardBubble +import com.anindra.messages.ui.theme.MessagesTheme + +@PreviewLightDark +@Composable +private fun IncomingContactCardPreview() { + MessagesTheme(mode = "system") { + Column(Modifier.width(300.dp).padding(12.dp)) { + ContactCardBubble(name = "Alex Rivera", number = "+1 555 333 4444", isMe = false) + } + } +} + +@PreviewLightDark +@Composable +private fun OutgoingContactCardPreview() { + MessagesTheme(mode = "system") { + Column(Modifier.width(300.dp).padding(12.dp)) { + ContactCardBubble(name = "Priya Raman", number = "+1 555 775 010", isMe = true) + } + } +} + +@PreviewLightDark +@Composable +private fun ContactBubblePreview() { + MessagesTheme(mode = "system") { + Column(Modifier.width(300.dp).padding(12.dp)) { + ContactBubble(uri = "content://preview/contact", isMe = false) + } + } +} diff --git a/app/src/main/java/com/anindra/messages/MainActivity.kt b/app/src/main/java/com/anindra/messages/MainActivity.kt index c459fc46..cd8b2f88 100644 --- a/app/src/main/java/com/anindra/messages/MainActivity.kt +++ b/app/src/main/java/com/anindra/messages/MainActivity.kt @@ -770,7 +770,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) { val handedOff = SmsSender.sendMms( getApplication(), stored.map { it.id }, recipients, uris, settings.simSubscriptionId, stored.first().body, - kinds.map { if (it == "audio") "audio/mp4" else null } + kinds.map { MmsSupport.outgoingMime(it) } ) if (!handedOff) { stored.forEach { repo.markMessageStatusSuspend(it.id, "failed") } diff --git a/app/src/main/java/com/anindra/messages/data/MmsSupport.kt b/app/src/main/java/com/anindra/messages/data/MmsSupport.kt index 25183b70..579c45b6 100644 --- a/app/src/main/java/com/anindra/messages/data/MmsSupport.kt +++ b/app/src/main/java/com/anindra/messages/data/MmsSupport.kt @@ -319,6 +319,35 @@ object MmsSupport { else -> "file" } + /** The kind a contact card is stored as, for its own bubble. */ + const val KIND_CONTACT = "contact" + + /** What a contact card is declared as on the wire; the receiving phone + * turns a part of this type into a contact rather than into a file. */ + const val VCARD_MIME = com.anindra.messages.mms.pdu.ContentTypes.VCARD + + /** The MIME an outgoing attachment of this kind is sent with, or null when + * the picked file's own type is the right one. + * + * The recorder writes an MPEG-4 alias the carriers do not name, and a + * contact is a cache file whose type has to be declared as the vCard the + * receiving phone looks for. */ + fun outgoingMime(kind: String): String? = when (kind) { + KIND_CONTACT -> VCARD_MIME + "audio" -> "audio/mp4" + else -> null + } + + /** What the conversation list shows for an attachment just sent or received: + * the preview line the thread gets when the message carries no text. */ + fun previewFor(kind: String): String = when (kind) { + "image" -> "Photo" + "video" -> "Video" + "audio" -> "Voice message" + KIND_CONTACT -> "Contact" + else -> "Attachment" + } + /** The sentence [content] writes when it could not show every attachment. * Only the provider's parts can say whether it is still true. */ private const val NOTICE_MARKER = "additional/unsupported attachment(s) not displayed" @@ -410,7 +439,7 @@ object MmsSupport { "audio/mp4" to "m4a", "audio/m4a" to "m4a", "audio/x-m4a" to "m4a", "audio/mp4a-latm" to "m4a", "audio/aac" to "aac", "audio/3gpp" to "3gp", "audio/amr" to "amr", "audio/mpeg" to "mp3", "audio/ogg" to "ogg", - "audio/wav" to "wav", "audio/x-wav" to "wav" + "audio/wav" to "wav", "audio/x-wav" to "wav", "text/x-vcard" to "vcf" ) /** The fallback a saved attachment gets when neither the resolver nor the diff --git a/app/src/main/java/com/anindra/messages/data/Repository.kt b/app/src/main/java/com/anindra/messages/data/Repository.kt index 95c1d9af..3e87ca22 100644 --- a/app/src/main/java/com/anindra/messages/data/Repository.kt +++ b/app/src/main/java/com/anindra/messages/data/Repository.kt @@ -1753,7 +1753,7 @@ class Repository(private val context: Context) { database.endTransaction() } val firstKind = mediaTypes.firstOrNull() ?: "image" - touchConversation(conversationId, if (firstKind == "image") "Photo" else "Voice message", now, isMe = true) + touchConversation(conversationId, MmsSupport.previewFor(firstKind), now, isMe = true) return out } diff --git a/app/src/main/java/com/anindra/messages/ui/ChatScreen.kt b/app/src/main/java/com/anindra/messages/ui/ChatScreen.kt index 1c708b8e..82582548 100644 --- a/app/src/main/java/com/anindra/messages/ui/ChatScreen.kt +++ b/app/src/main/java/com/anindra/messages/ui/ChatScreen.kt @@ -539,6 +539,13 @@ internal fun ChatBubble( } } } + } else if (msg.mediaType == MmsSupport.KIND_CONTACT && msg.mediaUri.isNotBlank()) { + ContactBubble( + uri = msg.mediaUri, + isMe = msg.isMe, + isSelected = isSelected, + onLongPress = onLongPress + ) } else if (msg.mediaType == "audio" && msg.mediaUri.isNotBlank()) { VoiceBubble( uri = msg.mediaUri, @@ -1229,16 +1236,23 @@ fun ChatScreen( if (uri != null && uri !in pendingMedia) pendingMedia.add(uri) } - // A contact is sent as a vCard body, so the picker only has to hand back an - // id. + // A contact leaves as a vCard attachment, so the receiving phone shows a + // contact it can save. The picker only has to hand back a contact id. val contactLauncher = rememberLauncherForActivityResult( ActivityResultContracts.PickContact() ) { uri -> if (uri != null) { - ContactShare.read(context, uri)?.let { (name, number) -> - if (ContactShare.isSendable(number)) { - vm.send(conversationId, ContactShare.vCard(name, number), currentSimId) - } + val picked = ContactShare.read(context, uri) + val card = picked?.takeIf { ContactShare.isSendable(it.second) } + ?.let { (name, number) -> ContactShare.writeCard(context, name, number) } + if (card != null) { + vm.sendMediaMessage(conversationId, card, "", MmsSupport.KIND_CONTACT) + } else { + Toast.makeText( + context, + context.getString(R.string.chat_contact_unavailable), + Toast.LENGTH_SHORT + ).show() } } } @@ -3416,6 +3430,13 @@ fun MessageRow( } } } + } else if (msg.mediaType == MmsSupport.KIND_CONTACT && msg.mediaUri.isNotBlank()) { + ContactBubble( + uri = msg.mediaUri, + isMe = msg.isMe, + isSelected = isSelected, + onLongPress = { onLongPress() } + ) } else if (msg.mediaType == "audio" && msg.mediaUri.isNotBlank()) { VoiceBubble( uri = msg.mediaUri, diff --git a/app/src/main/java/com/anindra/messages/ui/ContactBubble.kt b/app/src/main/java/com/anindra/messages/ui/ContactBubble.kt new file mode 100644 index 00000000..8c818cb3 --- /dev/null +++ b/app/src/main/java/com/anindra/messages/ui/ContactBubble.kt @@ -0,0 +1,112 @@ +package com.anindra.messages.ui + +import android.net.Uri +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Person +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +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.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.anindra.messages.R +import com.anindra.messages.ui.theme.incomingBubble +import com.anindra.messages.ui.theme.outgoingBubble +import com.anindra.messages.ui.theme.selectedBubble + +/** + * A contact card in the conversation: the name and number the card carries, not + * the properties it is made of. + * + * The card is read back from the attachment itself rather than kept in the + * message body, so it stays right after the provider holds the part and the + * original cache file is gone. + */ +@Composable +internal fun ContactBubble( + uri: String, + isMe: Boolean, + isSelected: Boolean = false, + onLongPress: () -> Unit = {} +) { + val context = LocalContext.current + val card = remember(uri) { ContactShare.readCard(context, Uri.parse(uri)) } + ContactCardBubble( + name = card?.first, + number = card?.second, + isMe = isMe, + isSelected = isSelected, + onLongPress = onLongPress + ) +} + +/** The card itself, without the attachment behind it. */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun ContactCardBubble( + name: String?, + number: String?, + isMe: Boolean, + isSelected: Boolean = false, + onLongPress: () -> Unit = {} +) { + val cs = MaterialTheme.colorScheme + val label = stringResource(R.string.chat_media_contact) + + Surface( + color = if (isSelected) cs.selectedBubble else if (isMe) cs.outgoingBubble else cs.incomingBubble, + shape = RoundedCornerShape(16.dp), + modifier = Modifier + .widthIn(max = 260.dp) + .combinedClickable(onClick = {}, onLongClick = onLongPress) + ) { + Row( + Modifier.padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + Icons.Rounded.Person, + contentDescription = label, + tint = cs.onPrimaryContainer, + modifier = Modifier + .size(36.dp) + .background(cs.primaryContainer, CircleShape) + .padding(6.dp) + ) + Spacer(Modifier.width(10.dp)) + Column { + Text( + text = name ?: label, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = if (isMe) cs.onPrimaryContainer else cs.onSurface + ) + if (number != null) { + Text( + text = number, + style = MaterialTheme.typography.bodyMedium, + color = if (isMe) cs.onPrimaryContainer else cs.onSurfaceVariant + ) + } + } + } + } +} diff --git a/app/src/main/java/com/anindra/messages/ui/ContactCard.kt b/app/src/main/java/com/anindra/messages/ui/ContactCard.kt deleted file mode 100644 index ee2494ad..00000000 --- a/app/src/main/java/com/anindra/messages/ui/ContactCard.kt +++ /dev/null @@ -1,51 +0,0 @@ -package com.anindra.messages.ui - -import java.util.Locale - -/** - * A contact as it travels over SMS: the name and one number, wrapped in the - * smallest vCard an incoming phone can read. - * - * Kept free of Android types so the rule for "is this contact sendable" and the - * card's own shape can be tested without a device. - */ -internal object ContactCard { - - /** Shortest thing a network will dial: 7 digits, as ContactsShare's callers do. */ - const val MIN_DIGITS = 7 - - /** True when the number has enough digits to be worth sending. */ - fun isSendable(number: String): Boolean = number.count { it.isDigit() } >= MIN_DIGITS - - /** The label a card carries when the contact has no name saved. */ - fun nameOf(name: String?, number: String): String { - val trimmed = name?.trim().orEmpty() - return trimmed.ifEmpty { number.trim() } - } - - /** - * vCard 3.0 text, the version every stock dialer imports. Newlines inside - * the name are folded away: a line break in the middle of a property ends - * it, so a two-line contact name would produce a broken card. - */ - fun vCard(name: String?, number: String): String { - val safeName = nameOf(name, number).replace(Regex("[\\r\\n]+"), " ").replace(";", " ") - val safeNumber = number.replace("\n", "").replace("\r", "").trim() - return buildString { - appendLine("BEGIN:VCARD") - appendLine("VERSION:3.0") - appendLine("FN:$safeName") - appendLine("TEL;TYPE=CELL:$safeNumber") - appendLine("END:VCARD") - } - } - - /** Coordinates as a maps link, with a full stop as the decimal separator. */ - fun geoLink(latitude: Double, longitude: Double): String = - String.format(Locale.US, "https://maps.google.com/?q=%.6f,%.6f", latitude, longitude) - - /** A fix is usable when it is a real point on Earth. */ - fun isUsable(latitude: Double, longitude: Double): Boolean = - latitude in -90.0..90.0 && longitude in -180.0..180.0 && - !(latitude == 0.0 && longitude == 0.0) -} diff --git a/app/src/main/java/com/anindra/messages/ui/ContactShare.kt b/app/src/main/java/com/anindra/messages/ui/ContactShare.kt index 65993919..968f5670 100644 --- a/app/src/main/java/com/anindra/messages/ui/ContactShare.kt +++ b/app/src/main/java/com/anindra/messages/ui/ContactShare.kt @@ -3,23 +3,43 @@ package com.anindra.messages.ui import android.content.Context import android.net.Uri import android.provider.ContactsContract +import androidx.core.content.FileProvider +import java.io.File import java.util.Locale /** * A contact sent as a vCard. * - * The card travels as the message body rather than as an MMS part: the SMS path - * is what works on every carrier, and a `text/vcard` part that the recipient's - * app ignores leaves them with an empty bubble. Most messaging apps detect the - * BEGIN:VCARD block and offer to save it, and anything that does not still shows - * a readable card with the name and number. + * The card leaves as an MMS part — `text/x-vCard`, named `contact.vcf` — so the + * receiving phone gets a contact it can save, which a vCard pasted into the text + * of an SMS does not give it: most apps show that as a wall of `BEGIN:VCARD` + * properties rather than as a card. */ object ContactShare { - /** vCard 3.0, which is the version every Android contacts app imports. */ + /** What the attachment is declared as on the wire. */ + const val MIME = com.anindra.messages.data.MmsSupport.VCARD_MIME + + /** The name the receiving app sees; its extension is what makes a contact + * app treat the part as a card rather than as an unnamed file. */ + const val FILE_NAME = "contact.vcf" + + /** Shortest thing a network will dial. */ + const val MIN_DIGITS = 7 + + /** + * vCard 3.0, which is the version every Android contacts app imports. + * + * A line break inside a property ends it, so a two-line contact name is + * folded to one line and semicolons (the property separator) are dropped: + * either would leave the receiving app a malformed card. + */ fun vCard(name: String, number: String): String { - val cleanName = name.trim().ifEmpty { number.trim() } - val cleanNumber = number.trim() + val cleanNumber = number.replace("\n", "").replace("\r", "").trim() + val cleanName = name.trim() + .replace(Regex("[\\r\\n]+"), " ") + .replace(";", " ") + .ifEmpty { cleanNumber } return buildString { appendLine("BEGIN:VCARD") appendLine("VERSION:3.0") @@ -30,6 +50,49 @@ object ContactShare { } } + /** + * Writes the card to a file and hands back the uri MMS reads it from. + * + * The picker's own uri cannot travel: its grant ends with the process, and + * the send path reads the bytes after the composer has moved on. A file in + * this app's cache is readable for as long as the message needs it. + */ + fun writeCard(context: Context, name: String, number: String): Uri? = try { + val dir = File(context.cacheDir, "vcard").apply { mkdirs() } + val file = File(dir, "contact_${System.currentTimeMillis()}.vcf") + file.writeText(vCard(name, number)) + FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file) + } catch (_: Exception) { + null + } + + /** The name and number a card carries, or null when it has no number. */ + fun parse(vCard: String): Pair? { + var name: String? = null + var number: String? = null + for (line in vCard.lineSequence()) { + val trimmed = line.trim() + when { + trimmed.startsWith("FN:", ignoreCase = true) && name == null -> + name = trimmed.substringAfter(':').trim() + trimmed.startsWith("TEL", ignoreCase = true) && number == null -> + number = trimmed.substringAfter(':').trim() + } + } + val cleanNumber = number?.takeIf { it.isNotBlank() } ?: return null + val cleanName = name?.takeIf { it.isNotBlank() } ?: cleanNumber + return cleanName to cleanNumber + } + + /** The card behind an attachment uri, for drawing it as a card. */ + fun readCard(context: Context, uri: Uri): Pair? = try { + context.contentResolver.openInputStream(uri)?.use { input -> + parse(input.readBytes().toString(Charsets.UTF_8)) + } + } catch (_: Exception) { + null + } + /** The name and first phone number behind a contact uri, or null. */ fun read(context: Context, uri: Uri): Pair? = try { val name = context.contentResolver.query( @@ -54,7 +117,7 @@ object ContactShare { /** Whether a number looks like something a vCard can carry. */ fun isSendable(number: String): Boolean = - number.count { it.isDigit() } >= 3 && number.none { it.isISOControl() } + number.count { it.isDigit() } >= MIN_DIGITS && number.none { it.isISOControl() } @Suppress("unused") private fun Locale.isRightToLeft(): Boolean = diff --git a/app/src/test/java/com/anindra/messages/data/MmsSupportTest.kt b/app/src/test/java/com/anindra/messages/data/MmsSupportTest.kt index 6d303a81..fae70788 100644 --- a/app/src/test/java/com/anindra/messages/data/MmsSupportTest.kt +++ b/app/src/test/java/com/anindra/messages/data/MmsSupportTest.kt @@ -481,4 +481,36 @@ class MmsSupportTest { // The picture the upgrade backfills belongs to a message already shown. assertFalse(MmsSupport.countsAsNewUnread(isMe = false, read = false, alreadyStored = true)) } + + @Test + fun aContactIsSentAsAVCard() { + // The receiving phone turns a text/x-vcard part into a contact; sent as + // text in the body it shows the BEGIN:VCARD properties instead. + assertEquals("text/x-vcard", MmsSupport.outgoingMime(MmsSupport.KIND_CONTACT)) + } + + @Test + fun aVoiceNoteKeepsItsOwnTypeOnTheWire() { + // The recorder writes an MPEG-4 alias carriers do not name. + assertEquals("audio/mp4", MmsSupport.outgoingMime("audio")) + assertNull(MmsSupport.outgoingMime("image")) + assertNull(MmsSupport.outgoingMime("video")) + } + + @Test + fun theConversationPreviewNamesTheAttachment() { + assertEquals("Photo", MmsSupport.previewFor("image")) + assertEquals("Video", MmsSupport.previewFor("video")) + assertEquals("Voice message", MmsSupport.previewFor("audio")) + assertEquals("Contact", MmsSupport.previewFor(MmsSupport.KIND_CONTACT)) + assertEquals("Attachment", MmsSupport.previewFor("file")) + } + + @Test + fun aSavedContactKeepsTheVcfExtension() { + assertEquals( + "Alex_1000.vcf", + MmsSupport.savedAttachmentName("Alex", 1000L, "text/x-vcard", MmsSupport.SaveTarget.FILE) + ) + } } diff --git a/app/src/test/java/com/anindra/messages/ui/ContactCardTest.kt b/app/src/test/java/com/anindra/messages/ui/ContactCardTest.kt deleted file mode 100644 index 02963a43..00000000 --- a/app/src/test/java/com/anindra/messages/ui/ContactCardTest.kt +++ /dev/null @@ -1,96 +0,0 @@ -package com.anindra.messages.ui - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test -import java.util.Locale - -/** - * The two things an attached contact and an attached location turn into before - * they reach the network: a vCard and a maps link. - */ -class ContactCardTest { - - @Test - fun aShortOrEmptyNumberIsNotSendable() { - assertFalse(ContactCard.isSendable("")) - assertFalse(ContactCard.isSendable("12345")) - assertFalse(ContactCard.isSendable("no digits here")) - } - - @Test - fun aDialableNumberIsSendable() { - assertTrue(ContactCard.isSendable("+1 555 333 4444")) - assertTrue(ContactCard.isSendable("5550100")) - } - - @Test - fun theCardIsVersionThreeWithOneCellNumber() { - val card = ContactCard.vCard("Alex Rivera", "+15553334444") - - assertTrue(card.startsWith("BEGIN:VCARD\n")) - assertTrue(card.trimEnd().endsWith("END:VCARD")) - assertTrue(card.contains("VERSION:3.0")) - assertTrue(card.contains("FN:Alex Rivera")) - assertTrue(card.contains("TEL;TYPE=CELL:+15553334444")) - } - - @Test - fun aNamelessContactFallsBackToItsNumber() { - val card = ContactCard.vCard(" ", "+15553334444") - - assertTrue(card.contains("FN:+15553334444")) - } - - @Test - fun aLineBreakInTheNameCannotBreakTheCard() { - // A newline inside a property ends it, so a two-line name would leave a - // malformed card behind. - val card = ContactCard.vCard("Alex\nRivera", "+15553334444") - - assertEquals(5, card.trimEnd().lines().size) - assertTrue(card.contains("FN:Alex Rivera")) - } - - @Test - fun theGeoLinkCarriesBothCoordinates() { - assertEquals( - "https://maps.google.com/?q=28.613939,77.209023", - ContactCard.geoLink(28.613939, 77.209023) - ) - } - - @Test - fun negativeCoordinatesSurviveFormatting() { - assertEquals( - "https://maps.google.com/?q=-33.868820,151.209290", - ContactCard.geoLink(-33.86882, 151.20929) - ) - } - - @Test - fun theLinkDoesNotFollowACommaDecimalLocale() { - // A German phone must not produce "28,613939" — the link would land in - // the wrong place, or nowhere. - val original = Locale.getDefault() - try { - Locale.setDefault(Locale.GERMANY) - assertEquals( - "https://maps.google.com/?q=28.613939,77.209023", - ContactCard.geoLink(28.613939, 77.209023) - ) - } finally { - Locale.setDefault(original) - } - } - - @Test - fun aFixIsUsableOnlyOnEarthAndNotAtNullIsland() { - assertTrue(ContactCard.isUsable(28.6, 77.2)) - assertTrue(ContactCard.isUsable(-33.8, 151.2)) - assertFalse("latitude out of range", ContactCard.isUsable(91.0, 0.0)) - assertFalse("longitude out of range", ContactCard.isUsable(0.0, 181.0)) - assertFalse("no fix at all", ContactCard.isUsable(0.0, 0.0)) - } -} diff --git a/app/src/test/java/com/anindra/messages/ui/ContactCardWiringTest.kt b/app/src/test/java/com/anindra/messages/ui/ContactCardWiringTest.kt new file mode 100644 index 00000000..0d93fc6f --- /dev/null +++ b/app/src/test/java/com/anindra/messages/ui/ContactCardWiringTest.kt @@ -0,0 +1,73 @@ +package com.anindra.messages.ui + +import java.io.File +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The Contact tile sends a card, and the chat draws it as a card. + * + * Picking a contact used to paste its vCard into the body of an SMS, so the + * receiving phone showed text. The tile has to write the card to a file, send it + * as the contact kind (which the send path declares `text/x-vcard`), and the + * bubble has to stop drawing the raw properties. + */ +class ContactCardWiringTest { + + private fun source(relative: String): String { + val app = generateSequence(File("").absoluteFile) { it.parentFile } + .map { File(it, "app") } + .firstOrNull { File(it, "src").isDirectory } + ?: error("app/src not found") + return File(app, "src/main/java/com/anindra/messages/$relative").readText() + } + + private val chat: String by lazy { source("ui/ChatScreen.kt") } + + @Test + fun theContactTileSendsACardFile() { + val launcher = chat.substringAfter("val contactLauncher").substringBefore("fun launchOrExplain") + assertTrue( + "the picked contact must be written out as a card file", + launcher.contains("ContactShare.writeCard(") + ) + assertTrue( + "and sent as the contact kind, which is what declares text/x-vcard", + launcher.contains("vm.sendMediaMessage(conversationId, card, \"\", MmsSupport.KIND_CONTACT)") + ) + } + + @Test + fun aContactThatCannotBeReadExplainsItself() { + val launcher = chat.substringAfter("val contactLauncher").substringBefore("fun launchOrExplain") + assertTrue( + "a denied contacts permission used to make the tile do nothing at all", + launcher.contains("R.string.chat_contact_unavailable") + ) + } + + @Test + fun theChatDrawsAContactAsACard() { + assertTrue( + "a contact row must render the card, not the raw vCard body", + chat.contains("msg.mediaType == MmsSupport.KIND_CONTACT") + ) + assertTrue(chat.contains("ContactBubble(")) + } + + @Test + fun theCardBubbleShowsTheNameAndNumber() { + val bubble = source("ui/ContactBubble.kt") + assertTrue("the name", bubble.contains("name")) + assertTrue("the number", bubble.contains("number")) + assertTrue( + "read back from the attachment, so it survives the cache file", + bubble.contains("ContactShare.readCard(") + ) + assertFalse( + "no raw card properties in the bubble", + bubble.contains("VERSION:3.0") || bubble.contains("TEL;TYPE") + ) + } +} diff --git a/app/src/test/java/com/anindra/messages/ui/ContactShareTest.kt b/app/src/test/java/com/anindra/messages/ui/ContactShareTest.kt index 24a2fc93..43c30a04 100644 --- a/app/src/test/java/com/anindra/messages/ui/ContactShareTest.kt +++ b/app/src/test/java/com/anindra/messages/ui/ContactShareTest.kt @@ -2,10 +2,18 @@ package com.anindra.messages.ui import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test -/** Issue #480: a contact leaves as a vCard body the receiving app can import. */ +/** + * A contact leaves as a vCard card, attached to an MMS. + * + * It used to leave as the card's text pasted into the message body, which the + * receiving phone showed as a wall of `BEGIN:VCARD` properties: a text message, + * not a contact. The card is now a file the send path reads, so its shape and + * the name/number the bubble reads back out of it both matter. + */ class ContactShareTest { @Test @@ -28,9 +36,10 @@ class ContactShareTest { fun numbersThatCannotBeSentAreRefused() { assertTrue(ContactShare.isSendable("+1555771010")) assertTrue(ContactShare.isSendable("555 7710")) + assertFalse("fewer than seven digits", ContactShare.isSendable("12345")) assertFalse(ContactShare.isSendable("")) assertFalse(ContactShare.isSendable("12")) - assertFalse(ContactShare.isSendable("555\n7710")) + assertFalse("a line break would split the property", ContactShare.isSendable("555\n7710")) } @Test @@ -39,4 +48,43 @@ class ContactShareTest { val card = ContactShare.vCard("Dad", "+1555771010") assertEquals(0, Regex("\n\n").findAll(card).count()) } + + @Test + fun aLineBreakInTheNameCannotBreakTheCard() { + // A newline inside a property ends it, so a two-line name would leave a + // malformed card behind. + val card = ContactShare.vCard("Alex\nRivera", "+15553334444") + assertEquals(6, card.trimEnd().lines().size) + assertTrue(card.contains("FN:Alex Rivera")) + } + + @Test + fun aSemicolonInTheNameCannotSplitTheProperty() { + val card = ContactShare.vCard("Rivera; Alex", "+15553334444") + assertTrue(card.contains("FN:Rivera Alex")) + } + + @Test + fun theCardIsDeclaredAsAVCardOnTheWire() { + assertEquals("text/x-vcard", ContactShare.MIME) + assertEquals("contact.vcf", ContactShare.FILE_NAME) + } + + @Test + fun theCardReadsBackAsTheNameAndNumber() { + val parsed = ContactShare.parse(ContactShare.vCard("Dad", "+1555771010")) + assertEquals("Dad" to "+1555771010", parsed) + } + + @Test + fun aCardWithNoNumberReadsBackAsNothing() { + assertNull(ContactShare.parse("BEGIN:VCARD\nVERSION:3.0\nFN:Dad\nEND:VCARD")) + assertNull(ContactShare.parse("")) + } + + @Test + fun aNamelessCardIsNamedByItsNumber() { + val card = "BEGIN:VCARD\nVERSION:3.0\nTEL;TYPE=CELL:+1555771010\nEND:VCARD" + assertEquals("+1555771010" to "+1555771010", ContactShare.parse(card)) + } } diff --git a/mms/src/main/java/com/anindra/messages/mms/Mms.kt b/mms/src/main/java/com/anindra/messages/mms/Mms.kt index 00ccf7f6..877f3289 100644 --- a/mms/src/main/java/com/anindra/messages/mms/Mms.kt +++ b/mms/src/main/java/com/anindra/messages/mms/Mms.kt @@ -292,6 +292,7 @@ object SendReqBuilder { * generic placeholder. */ private fun mediaPartName(contentType: String): String = when { + contentType == ContentTypes.VCARD -> "contact.vcf" ContentTypes.isImage(contentType) -> "image" ContentTypes.isVideo(contentType) -> "video" ContentTypes.isAudio(contentType) -> "audio" diff --git a/mms/src/main/java/com/anindra/messages/mms/pdu/ContentTypes.kt b/mms/src/main/java/com/anindra/messages/mms/pdu/ContentTypes.kt index 02ac4409..cbf7f3c4 100644 --- a/mms/src/main/java/com/anindra/messages/mms/pdu/ContentTypes.kt +++ b/mms/src/main/java/com/anindra/messages/mms/pdu/ContentTypes.kt @@ -100,6 +100,11 @@ object ContentTypes { private val INDEX = TABLE.withIndex().associate { (i, name) -> name to i } + /** A contact card. In the WSP table as `text/x-vCard`, but a type outside + * the table is written as a text-string and parses the same, so the + * lowercase spelling is the one to compare against. */ + const val VCARD = "text/x-vcard" + const val MULTIPART_RELATED = "application/vnd.wap.multipart.related" const val MULTIPART_MIXED = "multipart/mixed" const val MULTIPART_ALTERNATIVE = "multipart/alternative" diff --git a/mms/src/test/java/com/anindra/messages/mms/SendReqBuilderTest.kt b/mms/src/test/java/com/anindra/messages/mms/SendReqBuilderTest.kt index 9a2295d1..c93ffa18 100644 --- a/mms/src/test/java/com/anindra/messages/mms/SendReqBuilderTest.kt +++ b/mms/src/test/java/com/anindra/messages/mms/SendReqBuilderTest.kt @@ -106,6 +106,23 @@ class SendReqBuilderTest { assertEquals(Smil, String(body.partAt(0)!!.data!!)) } + @Test + fun aContactCardIsAVCardPartNamedWithItsExtension() { + // The receiving phone turns a text/x-vcard part into a contact. Named + // without the .vcf extension the part arrives as a nameless file. + val outcome = SendReqBuilder.build( + request(caption = "").copy( + attachments = listOf(FittedAttachment("text/x-vcard", ByteArray(64))) + ), + noSender, + now, + ) + assertTrue("expected a built PDU, got $outcome", outcome is SendReqOutcome.Built) + val part = (outcome as SendReqOutcome.Built).pdu.body!!.partAt(1)!! + assertEquals(ContentTypes.VCARD, ContentTypes.normalize(part.contentType!!)) + assertEquals("contact.vcf", part.name) + } + @Test fun aMessageWithoutACaptionHasNoTextPart() { val body = built(caption = " ").body!! diff --git a/scripts b/scripts index 0649647a..c39aefe1 160000 --- a/scripts +++ b/scripts @@ -1 +1 @@ -Subproject commit 0649647ae59623f2f23b4d2fdc107506e6551424 +Subproject commit c39aefe1553e5a67078457b7f71a3cbc1a154076