Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
Add ability to receive MMS attachments
Acho Arnold14b718ee2d1c
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 24c3eb18..86ca0a51 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -48,10 +48,10 @@<activity android:name=".SettingsActivity" android:screenOrientation="portrait"tools:ignore="LockedOrientationActivity" /><activity- android:name="com.journeyapps.barcodescanner.CaptureActivity"- android:screenOrientation="fullSensor"- tools:replace="screenOrientation"- tools:ignore="DiscouragedApi" />+ android:name="com.journeyapps.barcodescanner.CaptureActivity"+ android:screenOrientation="fullSensor"+ tools:replace="screenOrientation"+ tools:ignore="DiscouragedApi" /><serviceandroid:name=".services.StickyNotificationService"@@ -74,6 +74,10 @@<intent-filter android:priority="999"><action android:name="android.provider.Telephony.SMS_RECEIVED"/></intent-filter>+ <intent-filter android:priority="999">+ <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />+ <data android:mimeType="application/vnd.wap.mms-message" />+ </intent-filter></receiver><receiver android:enabled="true" android:exported="true" android:name=".receivers.PhoneStateReceiver" android:permission="android.permission.READ_PHONE_STATE">diff --git a/android/app/src/main/java/com/httpsms/Constants.kt b/android/app/src/main/java/com/httpsms/Constants.ktindex 542f78d7..ba3e1584 100644--- a/android/app/src/main/java/com/httpsms/Constants.kt+++ b/android/app/src/main/java/com/httpsms/Constants.kt@@ -10,6 +10,7 @@ class Constants {const val KEY_MESSAGE_TIMESTAMP = "KEY_MESSAGE_TIMESTAMP"const val KEY_MESSAGE_REASON = "KEY_MESSAGE_REASON"const val KEY_MESSAGE_ENCRYPTED = "KEY_MESSAGE_ENCRYPTED"+ const val KEY_MESSAGE_ATTACHMENTS = "KEY_MESSAGE_ATTACHMENTS"const val KEY_HEARTBEAT_ID = "KEY_HEARTBEAT_ID"diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.ktindex 4639b6c2..51fa21cd 100644--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt@@ -7,7 +7,6 @@ import okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientimport okhttp3.Requestimport okhttp3.RequestBody.Companion.toRequestBody-import org.apache.commons.text.StringEscapeUtilsimport timber.log.Timberimport java.io.Fileimport java.io.FileOutputStream@@ -75,17 +74,8 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {return sendEvent(messageId, "FAILED", timestamp, reason)}- fun receive(sim: String, from: String, to: String, content: String, encrypted: Boolean, timestamp: String): Boolean {- val body = """- {- "content": "${StringEscapeUtils.escapeJson(content)}",- "sim": "$sim",- "from": "$from",- "timestamp": "$timestamp",- "encrypted": $encrypted,- "to": "$to"- }- """.trimIndent()+ fun receive(requestPayload: ReceivedMessageRequest): Boolean {+ val body = com.beust.klaxon.Klaxon().toJsonString(requestPayload)val request: Request = Request.Builder().url(resolveURL("/v1/messages/receive"))@@ -94,16 +84,21 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {.header(clientVersionHeader, BuildConfig.VERSION_NAME).build()- val response = client.newCall(request).execute()+ val response = try {+ client.newCall(request).execute()+ } catch (e: Exception) {+ Timber.e(e, "Exception while sending received message request")+ return false+ }+if (!response.isSuccessful) {- Timber.e("error response [${response.body?.string()}] with code [${response.code}] while receiving message [${body}]")+ Timber.e("error response [${response.body?.string()}] with code [${response.code}] while receiving message")response.close()return response.code in 400..499}- val message = ResponseMessage.fromJson(response.body!!.string())response.close()- Timber.i("received message stored successfully for message with ID [${message?.data?.id}]" )+ Timber.i("received message stored successfully")return true}@@ -211,14 +206,14 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {val inputStream = body.byteStream()FileOutputStream(tempFile).use { outputStream ->inputStream.use { input ->- input.copyToWithLimit(outputStream, MAX_MMS_ATTACHMENT_SIZE.toLong())+ input.copyToWithLimit(outputStream, MAX_MMS_ATTACHMENT_SIZE)}}return Pair(tempFile, body.contentType())}} catch (e: Exception) {- Timber.e(e, "Exception while downloading attachment")+ Timber.e(e, "Exception while download attachment")return Pair(null, null)}}diff --git a/android/app/src/main/java/com/httpsms/Models.kt b/android/app/src/main/java/com/httpsms/Models.ktindex 84660ae5..b4bf5464 100644--- a/android/app/src/main/java/com/httpsms/Models.kt+++ b/android/app/src/main/java/com/httpsms/Models.kt@@ -72,3 +72,20 @@ data class Message (val attachments: List<String>? = null)++data class ReceivedAttachment(+ val name: String,+ @Json(name = "content_type")+ val contentType: String,+ val content: String+)++data class ReceivedMessageRequest(+ val sim: String,+ val from: String,+ val to: String,+ val content: String,+ val encrypted: Boolean,+ val timestamp: String,+ val attachments: List<ReceivedAttachment>? = null+)diff --git a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt b/android/app/src/main/java/com/httpsms/ReceivedReceiver.ktindex 9d0f3d83..3edc30e2 100644--- a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt+++ b/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt@@ -4,7 +4,7 @@ import android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.provider.Telephony-import androidx.work.BackoffPolicy+import android.util.Base64import androidx.work.Constraintsimport androidx.work.Dataimport androidx.work.NetworkType@@ -13,20 +13,30 @@ import androidx.work.WorkManagerimport androidx.work.Workerimport androidx.work.WorkerParametersimport androidx.work.workDataOf+import com.google.android.mms.pdu_alt.CharacterSets+import com.google.android.mms.pdu_alt.MultimediaMessagePdu+import com.google.android.mms.pdu_alt.PduParser+import com.google.android.mms.pdu_alt.RetrieveConfimport timber.log.Timber+import java.io.File+import java.io.FileOutputStreamimport java.time.ZoneOffsetimport java.time.ZonedDateTimeimport java.time.format.DateTimeFormatter-import java.util.concurrent.TimeUnitclass ReceivedReceiver: BroadcastReceiver(){- override fun onReceive(context: Context,intent: Intent) {- if (intent.action != Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {+ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {+ handleSmsReceived(context, intent)+ } else if (intent.action == Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION) {+ handleMmsReceived(context, intent)+ } else {Timber.e("received invalid intent with action [${intent.action}]")- return}+ }+ private fun handleSmsReceived(context: Context, intent: Intent) {var smsSender = ""var smsBody = ""@@ -35,12 +45,7 @@ class ReceivedReceiver: BroadcastReceiver()smsBody += smsMessage.messageBody}- var sim = Constants.SIM1- var owner = Settings.getSIM1PhoneNumber(context)- if (intent.getIntExtra("android.telephony.extra.SLOT_INDEX", 0) > 0 && Settings.isDualSIM(context)) {- owner = Settings.getSIM2PhoneNumber(context)- sim = Constants.SIM2- }+ val (sim, owner) = getSimAndOwner(context, intent)if (!Settings.isIncomingMessageEnabled(context, sim)) {Timber.w("[${sim}] is not active for incoming messages")@@ -56,7 +61,71 @@ class ReceivedReceiver: BroadcastReceiver())}- private fun handleMessageReceived(context: Context, sim: String, from: String, to : String, content: String) {+ private fun handleMmsReceived(context: Context, intent: Intent) {+ val pushData = intent.getByteArrayExtra("data") ?: return+ val pdu = PduParser(pushData, true).parse() ?: return++ if (pdu !is MultimediaMessagePdu) {+ Timber.d("Received PDU is not a MultimediaMessagePdu, ignoring.")+ return+ }++ val from = pdu.from?.string ?: ""+ var content = ""+ val attachmentFiles = mutableListOf<String>()++ // Check if it's a RetrieveConf (which contains the actual message body)+ if (pdu is RetrieveConf) {+ val body = pdu.body+ if (body != null) {+ for (i in 0 until body.partsNum) {+ val part = body.getPart(i)+ val partData = part.data ?: continue+ val contentType = String(part.contentType ?: "application/octet-stream".toByteArray())++ if (contentType.startsWith("text/plain")) {+ content += String(partData, charset(CharacterSets.getMimeName(part.charset)))+ } else {+ // Save attachment to a temporary file+ val fileName = String(part.name ?: part.contentLocation ?: part.contentId ?: "attachment_$i".toByteArray())+ val tempFile = File(context.cacheDir, "received_mms_${System.currentTimeMillis()}_$i")+ FileOutputStream(tempFile).use { it.write(partData) }+ attachmentFiles.add("${tempFile.absolutePath}|${contentType}|${fileName}")+ }+ }+ }+ } else {+ Timber.d("Received PDU is of type [${pdu.javaClass.simpleName}], body extraction not implemented.")+ }++ val (sim, owner) = getSimAndOwner(context, intent)++ if (!Settings.isIncomingMessageEnabled(context, sim)) {+ Timber.w("[${sim}] is not active for incoming messages")+ return+ }++ handleMessageReceived(+ context,+ sim,+ from,+ owner,+ content,+ attachmentFiles.toTypedArray()+ )+ }++ private fun getSimAndOwner(context: Context, intent: Intent): Pair<String, String> {+ var sim = Constants.SIM1+ var owner = Settings.getSIM1PhoneNumber(context)+ if (intent.getIntExtra("android.telephony.extra.SLOT_INDEX", 0) > 0 && Settings.isDualSIM(context)) {+ owner = Settings.getSIM2PhoneNumber(context)+ sim = Constants.SIM2+ }+ return Pair(sim, owner)+ }++ private fun handleMessageReceived(context: Context, sim: String, from: String, to : String, content: String, attachments: Array<String>? = null) {val timestamp = ZonedDateTime.now(ZoneOffset.UTC)if (!Settings.isLoggedIn(context)) {@@ -84,7 +153,8 @@ class ReceivedReceiver: BroadcastReceiver()Constants.KEY_MESSAGE_SIM to sim,Constants.KEY_MESSAGE_CONTENT to body,Constants.KEY_MESSAGE_ENCRYPTED to Settings.encryptReceivedMessages(context),- Constants.KEY_MESSAGE_TIMESTAMP to DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(timestamp).replace("+", "Z")+ Constants.KEY_MESSAGE_TIMESTAMP to DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(timestamp).replace("+", "Z"),+ Constants.KEY_MESSAGE_ATTACHMENTS to attachments)val work = OneTimeWorkRequest@@ -104,14 +174,52 @@ class ReceivedReceiver: BroadcastReceiver()override fun doWork(): Result {Timber.i("[${this.inputData.getString(Constants.KEY_MESSAGE_SIM)}] forwarding received message from [${this.inputData.getString(Constants.KEY_MESSAGE_FROM)}] to [${this.inputData.getString(Constants.KEY_MESSAGE_TO)}]")- if (HttpSmsApiService.create(applicationContext).receive(- this.inputData.getString(Constants.KEY_MESSAGE_SIM)!!,- this.inputData.getString(Constants.KEY_MESSAGE_FROM)!!,- this.inputData.getString(Constants.KEY_MESSAGE_TO)!!,- this.inputData.getString(Constants.KEY_MESSAGE_CONTENT)!!,- this.inputData.getBoolean(Constants.KEY_MESSAGE_ENCRYPTED, false),- this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)!!,- )) {+ val sim = this.inputData.getString(Constants.KEY_MESSAGE_SIM)!!+ val from = this.inputData.getString(Constants.KEY_MESSAGE_FROM)!!+ val to = this.inputData.getString(Constants.KEY_MESSAGE_TO)!!+ val content = this.inputData.getString(Constants.KEY_MESSAGE_CONTENT)!!+ val encrypted = this.inputData.getBoolean(Constants.KEY_MESSAGE_ENCRYPTED, false)+ val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)!!++ val attachmentsData = inputData.getStringArray(Constants.KEY_MESSAGE_ATTACHMENTS)+ val attachments = attachmentsData?.mapNotNull {+ val parts = it.split("|")+ val file = File(parts[0])+ if (file.exists()) {+ val bytes = file.readBytes()+ val base64Content = Base64.encodeToString(bytes, Base64.NO_WRAP)+ ReceivedAttachment(+ name = parts[2],+ contentType = parts[1],+ content = base64Content+ )+ } else {+ null+ }+ }++ val request = ReceivedMessageRequest(+ sim = sim,+ from = from,+ to = to,+ content = content,+ encrypted = encrypted,+ timestamp = timestamp,+ attachments = attachments+ )++ val success = HttpSmsApiService.create(applicationContext).receive(request)++ // Cleanup temp files+ attachmentsData?.forEach {+ val path = it.split("|")[0]+ val file = File(path)+ if (file.exists()) {+ file.delete()+ }+ }++ if (success) {return Result.success()}