[go: nahoru, domu]

Skip to content

Commit

Permalink
Feature/mms (#6)
Browse files Browse the repository at this point in the history
* Add initial MMS support

* Bump versions

* Ensure conversations updated upon receiving an MMS

* Update gitignore
  • Loading branch information
oblakr24 committed May 5, 2023
1 parent 1b1ca33 commit c35b0c2
Show file tree
Hide file tree
Showing 11 changed files with 290 additions and 61 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ captures/
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/deploymentTargetDropdown.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
Expand Down
11 changes: 7 additions & 4 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ android {
applicationId "com.rokoblak.chatbackup"
minSdk 29
targetSdk 33
versionCode 5
versionName "1.0.2"
versionCode 6
versionName "1.0.3"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
Expand Down Expand Up @@ -72,7 +72,7 @@ dependencies {
// Compose
implementation "androidx.compose.ui:ui:$compose_ui_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"
implementation 'androidx.compose.material:material:1.4.2'
implementation 'androidx.compose.material:material:1.4.3'
// Compose constraint layout
implementation "androidx.constraintlayout:constraintlayout-compose:1.0.1"
// Compose tooling
Expand All @@ -84,7 +84,7 @@ dependencies {
// Compose permissions
implementation "com.google.accompanist:accompanist-permissions:0.29.1-alpha"
// Compose extended material icons
implementation "androidx.compose.material:material-icons-extended:1.4.2"
implementation "androidx.compose.material:material-icons-extended:1.4.3"
// Coil
implementation "io.coil-kt:coil-compose:2.2.2"

Expand All @@ -107,6 +107,9 @@ dependencies {
// SimpleXML parser
implementation group: 'org.simpleframework', name: 'simple-xml', version: '2.7.1'

// SMS-MMS parsing lib, used for MMS
implementation 'com.klinkerapps:android-smsmms:5.2.6'

// Test dependencies
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
Expand Down
26 changes: 24 additions & 2 deletions app/src/main/java/com/rokoblak/chatbackup/commonui/ChatDisplay.kt
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
package com.rokoblak.chatbackup.commonui

import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.rokoblak.chatbackup.ui.theme.ChatBackupTheme
import com.rokoblak.chatbackup.ui.theme.LocalTypography

Expand All @@ -19,6 +27,7 @@ data class ChatDisplayData(
val date: String,
val alignedLeft: Boolean,
val avatar: AvatarData?,
val imageUri: String?,
)

@Composable
Expand Down Expand Up @@ -55,15 +64,26 @@ fun ChatDisplay(modifier: Modifier = Modifier, data: ChatDisplayData) {
style = LocalTypography.current.bodyRegular,
color = textColor,
)
if (data.imageUri != null) {
Surface(
modifier = modifier
.size(220.dp)
.padding(vertical = 8.dp)
.border(1.dp, MaterialTheme.colors.background, CircleShape),
color = MaterialTheme.colors.background,
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
AsyncImage(model = Uri.parse(data.imageUri), contentDescription = null)
}
}
}
Text(
modifier = Modifier.padding(2.dp),
text = data.date,
style = LocalTypography.current.subheadRegular
)
}
}


}
}

Expand All @@ -79,6 +99,7 @@ fun ChatDisplayOtherPreview() {
date = "Sun 14th Dec 2022, 13:44:55",
alignedLeft = true,
avatar = AvatarData.Initials("AB", Color.Blue),
imageUri = null,
)
)
}
Expand All @@ -96,6 +117,7 @@ fun ChatDisplayMinePreview() {
date = "Sun 14th Dec 2022, 13:44:55",
alignedLeft = false,
avatar = null,
imageUri = null,
)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ object PreviewDataUtils {
content = content,
date = dateFormatted,
alignedLeft = isMine.not(),
avatar = avatar
avatar = avatar,
imageUri = null,
)
}.toImmutableList()

Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/rokoblak/chatbackup/data/Message.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package com.rokoblak.chatbackup.data

import android.net.Uri
import java.time.Instant

data class Message(
val id: String,
val content: String,
val contact: MinimalContact,
val imageUri: Uri?,
val timestamp: Instant,
val incoming: Boolean
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ class ConversationUIMapper @Inject constructor() {
contact.avatar()
} else {
null
}
},
imageUri = message.imageUri?.toString(),
)
}

Expand Down
173 changes: 156 additions & 17 deletions app/src/main/java/com/rokoblak/chatbackup/services/MessagesRetriever.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.rokoblak.chatbackup.services

import android.content.ContentProviderOperation
import android.content.ContentResolver
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
Expand All @@ -16,6 +18,7 @@ import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.File
import java.time.Instant
import javax.inject.Inject

Expand All @@ -27,31 +30,123 @@ class MessagesRetriever @Inject constructor(
) {

suspend fun retrieveMessages(): Conversations = withContext(Dispatchers.IO) {
val cr = appScope.appContext.contentResolver
val c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null)

if (c != null) {
val totalSMS = c.count
if (totalSMS == 0) return@withContext Conversations(emptyMap(), emptyList())

val messages = if (c.moveToFirst()) {
(0 until totalSMS).mapNotNull {
c.readMessage().also { c.moveToNext() }
}
} else {
return@withContext Conversations(emptyMap(), emptyList())
}
c.close()
val messages = retrieveSMSMessages() + retrieveMMSMessages()

if (messages.isNotEmpty()) {
builder.groupMessages(messages, contactRetriever = { num ->
contactsRepo.resolveContact(num)
})
} else {
Timber.e("Content SMS query returned null")
Conversations(emptyMap(), emptyList())
}
}

private fun retrieveSMSMessages(): List<Message> {
val cr = appScope.appContext.contentResolver
val c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null) ?: return emptyList()

val totalSMS = c.count
if (totalSMS == 0) return emptyList()

val messages = if (c.moveToFirst()) {
(0 until totalSMS).mapNotNull {
c.readMessage().also { c.moveToNext() }
}
} else {
return emptyList()
}
c.close()

return messages
}

private fun retrieveMMSMessages(): List<Message> {
val context = appScope.appContext
val cr = appScope.appContext.contentResolver
val c = cr.query(Telephony.Mms.CONTENT_URI, null, null, null, null) ?: return emptyList()

val totalSMS = c.count
if (totalSMS == 0) return emptyList()

val messages = if (c.moveToFirst()) {
(0 until totalSMS).mapNotNull {
c.readMMSMessage(context, cr).also { c.moveToNext() }
}
} else {
return emptyList()
}
c.close()

return messages
}

private fun getAddress(context: Context, messageId: Long): String? {
val contentResolver = context.contentResolver
val uri = ContentUris.withAppendedId(Telephony.Mms.CONTENT_URI, messageId).buildUpon()
.appendPath("addr").build()
val selection = "${Telephony.Mms.Addr.MSG_ID} = ? AND ${Telephony.Mms.Addr.TYPE} = ?"
val selectionArgs = arrayOf(messageId.toString(), Telephony_Mms_Addr_TYPE_FROM)
val cursor = contentResolver.query(uri, null, selection, selectionArgs, null)

var address: String? = null
if (cursor?.moveToFirst() == true) {
address = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Mms.Addr.ADDRESS))
}
cursor?.close()

return address
}

private fun Cursor.readMMSMessage(context: Context, cr: ContentResolver): Message? {
val messageId = getLong(getColumnIndexOrThrow(Telephony.Mms._ID))
val timestampMillis = getLong(getColumnIndexOrThrow(Telephony.Mms.DATE)) * 1000L

val incoming = when (getInt(getColumnIndexOrThrow(Telephony.Mms.MESSAGE_BOX))) {
Telephony.Mms.MESSAGE_BOX_INBOX -> true
Telephony.Mms.MESSAGE_BOX_SENT -> false
else -> { // Other message box types (e.g., drafts, outbox, etc.)
false
}
}

val address = getAddress(context, messageId) ?: return null

val partSelection = "${Telephony.Mms.Part.MSG_ID}=?"
val partSelectionArgs = arrayOf(messageId.toString())
val partCursor =
cr.query(Telephony.Mms.Part.CONTENT_URI, null, partSelection, partSelectionArgs, null)

var imageFileUri: Uri? = null
var content: String? = null
// TODO: Read other metadata, properties, image-related info
while (partCursor?.moveToNext() == true) {
val contentType =
partCursor.getString(partCursor.getColumnIndexOrThrow(Telephony.Mms.Part.CONTENT_TYPE))

if (contentType == "text/plain") {
content =
partCursor.getString(partCursor.getColumnIndexOrThrow(Telephony.Mms.Part.TEXT))
// Handle text content
} else if (contentType.startsWith("image/")) {
val imageFilePath =
partCursor.getString(partCursor.getColumnIndexOrThrow(Telephony.Mms.Part._DATA))
val fileName = imageFilePath.substringAfterLast('/')
imageFileUri = Uri.withAppendedPath(Telephony.Mms.Part.CONTENT_URI, fileName)
// TODO: path not accessible or invalid?
}
}
partCursor?.close()

return Message(
id = messageId.toString(),
content = content ?: "MMS Message",
contact = MinimalContact(address),
imageUri = imageFileUri,
timestamp = Instant.ofEpochMilli(timestampMillis),
incoming = incoming,
)
}

private fun Cursor.readMessage(): Message? {
val id = getString(getColumnIndexOrThrow("_id"))
val smsDateStr = getString(getColumnIndexOrThrow(Telephony.Sms.DATE))
Expand All @@ -71,7 +166,8 @@ class MessagesRetriever @Inject constructor(
content = body,
contact = MinimalContact(orgNumber = number),
timestamp = timestamp,
incoming = isInbox
incoming = isInbox,
imageUri = null,
)
}

Expand Down Expand Up @@ -142,6 +238,8 @@ class MessagesRetriever @Inject constructor(
companion object {
const val CHUNK_SIZE = 250

private const val Telephony_Mms_Addr_TYPE_FROM = "137" // Magic number

fun saveSingle(context: Context, incoming: Boolean, body: String, address: String) {
val cr = context.contentResolver
val values =
Expand All @@ -152,6 +250,47 @@ class MessagesRetriever @Inject constructor(
cr.insert(uri, values)
}

fun saveSingleMms(
context: Context,
imageData: ByteArray?,
incoming: Boolean,
body: String,
address: String
) {
val cr = context.contentResolver
val timestamp = Instant.now()

// TODO: Use incoming for MESSAGE_BOX

val imgPath = imageData?.let { bytes ->
val imageFileName =
"temp_image${timestamp.toEpochMilli()}.jpg" // Use a unique and appropriate file name
val imageFile = File(context.cacheDir, imageFileName)
imageFile.writeBytes(bytes)
imageFile.absolutePath
}

val messageUri = cr.insert(Telephony.Mms.CONTENT_URI, ContentValues().apply {
put(Telephony.Mms.Addr.ADDRESS, address)
put("read", "1") // 1 = read, 0 = not read
put("date", timestamp.toEpochMilli())
}) ?: return

val messageId = ContentUris.parseId(messageUri)

cr.insert(Telephony.Mms.Part.CONTENT_URI, ContentValues().apply {
put(Telephony.Mms.Part.MSG_ID, messageId)
put(Telephony.Mms.Part.CONTENT_TYPE, "text/plain")
put(Telephony.Mms.Part.TEXT, body)
})

cr.insert(Telephony.Mms.Part.CONTENT_URI, ContentValues().apply {
put(Telephony.Mms.Part.MSG_ID, messageId)
put(Telephony.Mms.Part.CONTENT_TYPE, "image/jpeg")
put(Telephony.Mms.Part._DATA, imgPath)
})
}

private fun createMsgValues(number: String, content: String, timestamp: Instant) =
ContentValues().apply {
put("address", number)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ class ConversationsImporter @Inject constructor(
content = body,
contact = MinimalContact(conv.contactNumber),
timestamp = Instant.ofEpochMilli(timestampMs),
incoming = msg.incoming
incoming = msg.incoming,
imageUri = null,
)
}
Conversation(contact, messages = messages)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class XMLParser @Inject constructor(private val builder: ConversationBuilder, pr
contact = MinimalContact(num),
timestamp = Instant.ofEpochMilli(timestampMs),
incoming = it.type == "1",
imageUri = null,
)
}

Expand Down
Loading

0 comments on commit c35b0c2

Please sign in to comment.