Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Add fix for MMS attachments

Acho Arnold75459a110963
diff --git a/android/app/src/main/java/com/httpsms/Constants.kt b/android/app/src/main/java/com/httpsms/Constants.kt
index fd8a0b90..7734055b 100644
--- a/android/app/src/main/java/com/httpsms/Constants.kt
+++ b/android/app/src/main/java/com/httpsms/Constants.kt
@@ -18,5 +18,7 @@ class Constants {
const val SIM2 = "SIM2"
const val TIMESTAMP_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'000000'ZZZZZ"
+
+ const val MAX_MMS_ATTACHMENT_SIZE = 1.5 * 1024 * 1024;
}
}
diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
index 294eb18e..41530f53 100644
--- a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
+++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
@@ -15,6 +15,8 @@ import com.google.android.mms.pdu_alt.PduBody
import com.google.android.mms.pdu_alt.PduComposer
import com.google.android.mms.pdu_alt.PduPart
import com.google.android.mms.pdu_alt.SendReq
+import okhttp3.MediaType
+import java.io.File
class MyFirebaseMessagingService : FirebaseMessagingService() {
// [START receive_message]
@@ -177,20 +179,35 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
return handleMultipartMessage(message, parts)
}
+ fun extractFileName(url: String, prefix: String, mimeType: String? = null): String {
+ val fileName = url.substringAfterLast("/")
+ .substringBefore("?")
+ .takeIf { it.isNotBlank() && it.contains(".") }
+ ?: run {
+ val extension = mimeType?.let { mime ->
+ val ext = mime.substringAfterLast("/")
+ if (ext.isNotBlank()) ".$ext" else ""
+ } ?: ""
+ "attachment$extension"
+ }
+
+ return "${prefix}_$fileName"
+ }
+
private fun handleMmsMessage(message: Message): Result {
Timber.d("Processing MMS for message ID [${message.id}]")
val apiService = HttpSmsApiService.create(applicationContext)
- val downloadedFiles = mutableListOf<java.io.File>()
+ val downloadedFiles = mutableListOf<Pair<File, MediaType>>()
try {
for ((index, attachment) in message.attachments!!.withIndex()) {
- val file = apiService.downloadAttachment(applicationContext, attachment.url, message.id, index)
- if (file == null) {
+ val file = apiService.downloadAttachment(applicationContext, attachment, message.id, index)
+ if (file.first == null || file.second == null) {
handleFailed(applicationContext, message.id, "Failed to download attachment or file size exceeded 1.5MB.")
return Result.failure()
}
- downloadedFiles.add(file)
+ downloadedFiles.add(Pair(file.first!!, file.second!!))
}
val sendReq = SendReq()
@@ -207,30 +224,32 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
textPart.name = "text".toByteArray()
textPart.contentId = "text".toByteArray()
textPart.contentLocation = "text".toByteArray()
-
+
var messageBody = message.content
val encryptionKey = Settings.getEncryptionKey(applicationContext)
if (message.encrypted && !encryptionKey.isNullOrEmpty()) {
messageBody = Encrypter.decrypt(encryptionKey, messageBody)
}
textPart.data = messageBody.toByteArray(Charsets.UTF_8)
-
+
pduBody.addPart(textPart)
}
for ((index, file) in downloadedFiles.withIndex()) {
- val attachment = message.attachments[index]
- val fileBytes = file.readBytes()
+ val fileBytes = file.first.readBytes()
val mediaPart = PduPart()
- mediaPart.contentType = attachment.contentType.toByteArray()
-
- val fileName = "attachment_$index".toByteArray()
- mediaPart.name = fileName
- mediaPart.contentId = fileName
- mediaPart.contentLocation = fileName
+ mediaPart.contentType = file.second.toString().toByteArray()
+
+
+ val fileName = extractFileName(message.attachments[index], index.toString(), file.second.toString())
+ mediaPart.name = fileName.toByteArray()
+ mediaPart.contentId = fileName.toByteArray()
+ mediaPart.contentLocation = fileName.toByteArray()
mediaPart.data = fileBytes
-
+
+ Timber.d("Adding MMS attachment with name [$fileName] and size [${fileBytes.size}] and type [${file.second}]")
+
pduBody.addPart(mediaPart)
}
@@ -249,7 +268,7 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
if (!mmsDir.exists()) {
mmsDir.mkdirs()
}
-
+
val pduFile = java.io.File(mmsDir, "pdu_${message.id}.dat")
java.io.FileOutputStream(pduFile).use { it.write(pduBytes) }
@@ -272,15 +291,15 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
} finally {
// Clean up any downloaded temporary files
downloadedFiles.forEach { file ->
- if (file.exists()) {
- file.delete()
+ if (file.first.exists()) {
+ file.first.delete()
}
}
// Also clean up the MMS PDU file to avoid cache buildup in cases where
// sendMultimediaMessage fails before the sent broadcast is delivered.
try {
- val pduFile = java.io.File(applicationContext.cacheDir, "pdu_${message.id}.dat")
+ val pduFile = File(applicationContext.cacheDir, "pdu_${message.id}.dat")
if (pduFile.exists()) {
val deleted = pduFile.delete()
if (!deleted) {
diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
index b252d1fd..d501f7f6 100644
--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
@@ -1,21 +1,23 @@
package com.httpsms
import android.content.Context
+import com.httpsms.Constants.Companion.MAX_MMS_ATTACHMENT_SIZE
+import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.apache.commons.text.StringEscapeUtils
import timber.log.Timber
-import java.net.URI
-import java.net.URL
-import java.util.logging.Level
-import java.util.logging.Logger.getLogger
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
+import java.net.URI
+import java.net.URL
+import java.util.logging.Level
+import java.util.logging.Logger.getLogger
class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
@@ -162,21 +164,21 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
}
fun InputStream.copyToWithLimit(
- out: OutputStream,
- limit: Long,
+ out: OutputStream,
+ limit: Long,
bufferSize: Int = DEFAULT_BUFFER_SIZE
): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(bufferSize)
var bytes = read(buffer)
-
+
while (bytes >= 0) {
bytesCopied += bytes
-
+
if (bytesCopied > limit) {
throw IOException("Download aborted: File exceeded maximum allowed size of $limit bytes.")
}
-
+
out.write(buffer, 0, bytes)
bytes = read(buffer)
}
@@ -184,27 +186,21 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
}
// Downloads the attachment URL content locally
- fun downloadAttachment(context: Context, urlString: String, messageId: String, attachmentIndex: Int): File? {
+ fun downloadAttachment(context: Context, urlString: String, messageId: String, attachmentIndex: Int): Pair<File?, MediaType?> {
val request = Request.Builder().url(urlString).build()
try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
Timber.e("Failed to download attachment: ${response.code}")
- return null
+ return Pair(null, null)
}
val body = response.body
- if (body == null) {
- Timber.e("Failed to download attachment: response body is null")
- return null
- }
-
- val maxSizeBytes = 1.5 * 1024 * 1024 // most (modern?) carriers have a 2MB limit, so targetting 1.5MB should be safe
val contentLength = body.contentLength()
- if (contentLength > maxSizeBytes) {
+ if (contentLength > MAX_MMS_ATTACHMENT_SIZE) {
Timber.e("Attachment is too large ($contentLength bytes).")
- return null
+ return Pair(null, null)
}
val mmsDir = File(context.cacheDir, "mms_attachments")
@@ -216,15 +212,15 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
val inputStream = body.byteStream()
FileOutputStream(tempFile).use { outputStream ->
inputStream.use { input ->
- input.copyToWithLimit(outputStream, maxSizeBytes.toLong())
+ input.copyToWithLimit(outputStream, MAX_MMS_ATTACHMENT_SIZE.toLong())
}
}
- return tempFile
+ return Pair(tempFile, response.body.contentType())
}
} catch (e: Exception) {
Timber.e(e, "Exception while downloading attachment")
- return null
+ 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.kt
index 1ee2dbc8..84660ae5 100644
--- a/android/app/src/main/java/com/httpsms/Models.kt
+++ b/android/app/src/main/java/com/httpsms/Models.kt
@@ -29,14 +29,6 @@ data class Phone (
val userID: String,
)
-// mms attachment
-data class Attachment (
- @Json(name = "content_type")
- val contentType: String,
-
- val url: String
-)
-
data class Message (
val contact: String,
val content: String,
@@ -78,5 +70,5 @@ data class Message (
@Json(name = "updated_at")
val updatedAt: String,
- val attachments: List<Attachment>? = null
+ val attachments: List<String>? = null
)
diff --git a/api/pkg/entities/message.go b/api/pkg/entities/message.go
index 6f0f75e6..b7d423fb 100644
--- a/api/pkg/entities/message.go
+++ b/api/pkg/entities/message.go
@@ -1,10 +1,10 @@
package entities
import (
- "strings"
"time"
"github.com/google/uuid"
+ "github.com/lib/pq"
)
// MessageType is the type of message if it is incoming or outgoing
@@ -82,23 +82,18 @@ func (s SIM) String() string {
return string(s)
}
-type MessageAttachment struct {
- ContentType string `json:"content_type" example:"image/jpeg"`
- URL string `json:"url" example:"https://example.com/image.jpg"`
-}
-
// Message represents a message sent between 2 phone numbers
type Message struct {
- ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`
- RequestID *string `json:"request_id" example:"153554b5-ae44-44a0-8f4f-7bbac5657ad4" validate:"optional"`
- Owner string `json:"owner" example:"+18005550199"`
- UserID UserID `json:"user_id" gorm:"index:idx_messages__user_id" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`
- Contact string `json:"contact" example:"+18005550100"`
- Content string `json:"content" example:"This is a sample text message"`
- Attachments []MessageAttachment `json:"attachments,omitempty" gorm:"type:json;serializer:json"`
- Encrypted bool `json:"encrypted" example:"false" gorm:"default:false"`
- Type MessageType `json:"type" example:"mobile-terminated"`
- Status MessageStatus `json:"status" example:"pending"`
+ ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`
+ RequestID *string `json:"request_id" example:"153554b5-ae44-44a0-8f4f-7bbac5657ad4" validate:"optional"`
+ Owner string `json:"owner" example:"+18005550199"`
+ UserID UserID `json:"user_id" gorm:"index:idx_messages__user_id" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`
+ Contact string `json:"contact" example:"+18005550100"`
+ Content string `json:"content" example:"This is a sample text message"`
+ Attachments pq.StringArray `json:"attachments" gorm:"type:text[]" swaggertype:"array,string"`
+ Encrypted bool `json:"encrypted" example:"false" gorm:"default:false"`
+ Type MessageType `json:"type" example:"mobile-terminated"`
+ Status MessageStatus `json:"status" example:"pending"`
// SIM is the SIM card to use to send the message
// * SMS1: use the SIM card in slot 1
// * SMS2: use the SIM card in slot 2
@@ -234,19 +229,3 @@ func (message *Message) updateOrderTimestamp(timestamp time.Time) {
message.OrderTimestamp = timestamp
}
}
-
-func GetAttachmentContentType(url string) string {
- // Since there's no easy way to set a type in the CSV, defaulting to octet-stream and then just checking the file extension in the URL
- contentType := "application/octet-stream"
- lowerURL := strings.ToLower(url)
- if strings.HasSuffix(lowerURL, ".jpg") || strings.HasSuffix(lowerURL, ".jpeg") {
- contentType = "image/jpeg"
- } else if strings.HasSuffix(lowerURL, ".png") {
- contentType = "image/png"
- } else if strings.HasSuffix(lowerURL, ".gif") {
- contentType = "image/gif"
- } else if strings.HasSuffix(lowerURL, ".mp4") {
- contentType = "video/mp4"
- }
- return contentType
-}
diff --git a/api/pkg/events/message_api_sent_event.go b/api/pkg/events/message_api_sent_event.go
index 9aeabd90..60a418b2 100644
--- a/api/pkg/events/message_api_sent_event.go
+++ b/api/pkg/events/message_api_sent_event.go
@@ -13,16 +13,16 @@ const EventTypeMessageAPISent = "message.api.sent"
// MessageAPISentPayload is the payload of the EventTypeMessageSent event
type MessageAPISentPayload struct {
- MessageID uuid.UUID `json:"message_id"`
- UserID entities.UserID `json:"user_id"`
- Owner string `json:"owner"`
- RequestID *string `json:"request_id"`
- MaxSendAttempts uint `json:"max_send_attempts"`
- Contact string `json:"contact"`
- ScheduledSendTime *time.Time `json:"scheduled_send_time"`
- RequestReceivedAt time.Time `json:"request_received_at"`
- Content string `json:"content"`
- Attachments []entities.MessageAttachment `json:"attachments"`
- Encrypted bool `json:"encrypted"`
- SIM entities.SIM `json:"sim"`
+ MessageID uuid.UUID `json:"message_id"`
+ UserID entities.UserID `json:"user_id"`
+ Owner string `json:"owner"`
+ RequestID *string `json:"request_id"`
+ MaxSendAttempts uint `json:"max_send_attempts"`
+ Contact string `json:"contact"`
+ ScheduledSendTime *time.Time `json:"scheduled_send_time"`
+ RequestReceivedAt time.Time `json:"request_received_at"`
+ Content string `json:"content"`
+ Attachments []string `json:"attachments"`
+ Encrypted bool `json:"encrypted"`
+ SIM entities.SIM `json:"sim"`
}
diff --git a/api/pkg/handlers/discord_handler.go b/api/pkg/handlers/discord_handler.go
index 729c6ce6..95591c2b 100644
--- a/api/pkg/handlers/discord_handler.go
+++ b/api/pkg/handlers/discord_handler.go
@@ -8,11 +8,9 @@ import (
"encoding/json"
"fmt"
"os"
- "strings"
"github.com/google/uuid"
- "github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/httpsms/pkg/requests"
"github.com/NdoleStudio/httpsms/pkg/services"
@@ -292,30 +290,10 @@ func (h *DiscordHandler) createRequest(payload map[string]any) requests.MessageS
}
return ""
}
- var attachments []entities.MessageAttachment
- attachmentURLsStr := getOption("attachment_urls")
-
- if attachmentURLsStr != "" {
- urls := strings.Split(attachmentURLsStr, ",")
- for _, u := range urls {
- cleanURL := strings.TrimSpace(u)
- if cleanURL == "" {
- continue
- }
-
- contentType := entities.GetAttachmentContentType(cleanURL)
-
- attachments = append(attachments, entities.MessageAttachment{
- ContentType: contentType,
- URL: cleanURL,
- })
- }
- }
return requests.MessageSend{
- From: getOption("from"),
- To: getOption("to"),
- Content: getOption("message"),
- Attachments: attachments,
+ From: getOption("from"),
+ To: getOption("to"),
+ Content: getOption("message"),
}
}
@@ -363,19 +341,6 @@ func (h *DiscordHandler) sendSMS(ctx context.Context, c *fiber.Ctx, payload map[
},
}
- if len(request.Attachments) > 0 {
- var urls []string
- for _, att := range request.Attachments {
- urls = append(urls, att.URL)
- }
-
- fields := messageEmbed["fields"].([]fiber.Map)
- messageEmbed["fields"] = append(fields, fiber.Map{
- "name": "Attachments:",
- "value": strings.Join(urls, "\n"),
- })
- }
-
if errors := h.messageValidator.ValidateMessageSend(ctx, discord.UserID, request.Sanitize()); len(errors) != 0 {
msg := fmt.Sprintf("validation errors [%s], while sending payload [%s]", spew.Sdump(errors), c.Body())
ctxLogger.Warn(stacktrace.NewError(msg))
diff --git a/api/pkg/requests/bulk_message_request.go b/api/pkg/requests/bulk_message_request.go
index a5aca7ce..84007176 100644
--- a/api/pkg/requests/bulk_message_request.go
+++ b/api/pkg/requests/bulk_message_request.go
@@ -26,7 +26,14 @@ func (input *BulkMessage) Sanitize() *BulkMessage {
input.ToPhoneNumber = input.sanitizeAddress(input.ToPhoneNumber)
input.Content = strings.TrimSpace(input.Content)
input.FromPhoneNumber = input.sanitizeAddress(input.FromPhoneNumber)
- input.AttachmentURLs = strings.TrimSpace(input.AttachmentURLs)
+
+ var attachments []string
+ for _, attachment := range strings.Split(input.AttachmentURLs, ",") {
+ if strings.TrimSpace(attachment) != "" {
+ attachments = append(attachments, strings.TrimSpace(attachment))
+ }
+ }
+ input.AttachmentURLs = strings.Join(attachments, ",")
return input
}
@@ -34,24 +41,6 @@ func (input *BulkMessage) Sanitize() *BulkMessage {
func (input *BulkMessage) ToMessageSendParams(userID entities.UserID, requestID uuid.UUID, source string) services.MessageSendParams {
from, _ := phonenumbers.Parse(input.FromPhoneNumber, phonenumbers.UNKNOWN_REGION)
- var attachments []entities.MessageAttachment
- if input.AttachmentURLs != "" {
- urls := strings.Split(input.AttachmentURLs, ",")
- for _, u := range urls {
- cleanURL := strings.TrimSpace(u)
- if cleanURL == "" {
- continue
- }
-
- contentType := entities.GetAttachmentContentType(cleanURL)
-
- attachments = append(attachments, entities.MessageAttachment{
- ContentType: contentType,
- URL: cleanURL,
- })
- }
- }
-
return services.MessageSendParams{
Source: source,
Owner: from,
@@ -61,6 +50,6 @@ func (input *BulkMessage) ToMessageSendParams(userID entities.UserID, requestID
RequestReceivedAt: time.Now().UTC(),
Contact: input.sanitizeAddress(input.ToPhoneNumber),
Content: input.Content,
- Attachments: attachments,
+ Attachments: strings.Split(input.AttachmentURLs, ","),
}
}
diff --git a/api/pkg/requests/message_bulk_send_request.go b/api/pkg/requests/message_bulk_send_request.go
index 47c2af7d..461ac2ed 100644
--- a/api/pkg/requests/message_bulk_send_request.go
+++ b/api/pkg/requests/message_bulk_send_request.go
@@ -1,6 +1,7 @@
package requests
import (
+ "strings"
"time"
"github.com/NdoleStudio/httpsms/pkg/entities"
@@ -16,10 +17,12 @@ type MessageBulkSend struct {
From string `json:"from" example:"+18005550199"`
To []string `json:"to" example:"+18005550100,+18005550100"`
Content string `json:"content" example:"This is a sample text message"`
- Attachments []entities.MessageAttachment `json:"attachments" validate:"optional"`
+
+ // Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS
+ Attachments []string `json:"attachments" validate:"optional"`
// Encrypted is used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app
- Encrypted bool `json:"encrypted" example:"false"`
+ Encrypted bool `json:"encrypted" example:"false" validate:"optional"`
// RequestID is an optional parameter used to track a request from the client's perspective
RequestID string `json:"request_id" example:"153554b5-ae44-44a0-8f4f-7bbac5657ad4" validate:"optional"`
@@ -31,6 +34,15 @@ func (input *MessageBulkSend) Sanitize() MessageBulkSend {
for _, address := range input.To {
to = append(to, input.sanitizeAddress(address))
}
+
+ var attachments []string
+ for _, attachment := range input.Attachments {
+ if strings.TrimSpace(attachment) != "" {
+ attachments = append(attachments, strings.TrimSpace(attachment))
+ }
+ }
+
+ input.Attachments = attachments
input.To = to
input.From = input.sanitizeAddress(input.From)
return *input
diff --git a/api/pkg/requests/message_send_request.go b/api/pkg/requests/message_send_request.go
index d40f0f88..bebf6f48 100644
--- a/api/pkg/requests/message_send_request.go
+++ b/api/pkg/requests/message_send_request.go
@@ -19,7 +19,7 @@ type MessageSend struct {
Content string `json:"content" example:"This is a sample text message"`
// Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS
- Attachments []entities.MessageAttachment `json:"attachments" validate:"optional"`
+ Attachments []string `json:"attachments" validate:"optional"`
// Encrypted is an optional parameter used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app
Encrypted bool `json:"encrypted" example:"false" validate:"optional"`
@@ -34,6 +34,13 @@ func (input *MessageSend) Sanitize() MessageSend {
input.To = input.sanitizeAddress(input.To)
input.RequestID = strings.TrimSpace(input.RequestID)
input.From = input.sanitizeAddress(input.From)
+ var attachments []string
+ for _, attachment := range input.Attachments {
+ if strings.TrimSpace(attachment) != "" {
+ attachments = append(attachments, strings.TrimSpace(attachment))
+ }
+ }
+ input.Attachments = attachments
return *input
}
diff --git a/api/pkg/services/message_service.go b/api/pkg/services/message_service.go
index eca2334c..c7dca231 100644
--- a/api/pkg/services/message_service.go
+++ b/api/pkg/services/message_service.go
@@ -7,7 +7,6 @@ import (
"time"
"github.com/davecgh/go-spew/spew"
-
"github.com/nyaruka/phonenumbers"
"github.com/NdoleStudio/httpsms/pkg/events"
@@ -430,7 +429,7 @@ type MessageSendParams struct {
Contact string
Encrypted bool
Content string
- Attachments []entities.MessageAttachment
+ Attachments []string
Source string
SendAt *time.Time
RequestID *string
diff --git a/api/pkg/validators/message_handler_validator.go b/api/pkg/validators/message_handler_validator.go
index 52741891..9a63886b 100644
--- a/api/pkg/validators/message_handler_validator.go
+++ b/api/pkg/validators/message_handler_validator.go
@@ -97,6 +97,10 @@ func (validator MessageHandlerValidator) ValidateMessageSend(ctx context.Context
"required",
phoneNumberRule,
},
+ "attachments": []string{
+ "max:10",
+ multipleAttachmentURLRule,
+ },
"content": []string{
"required",
"min:1",
@@ -110,31 +114,6 @@ func (validator MessageHandlerValidator) ValidateMessageSend(ctx context.Context
return result
}
- if len(request.Attachments) > 10 {
- result.Add("attachments", "you cannot attach more than 10 files to a single message")
- }
-
- for i, attachment := range request.Attachments {
- if strings.TrimSpace(attachment.ContentType) == "" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d is missing content_type", i))
- }
-
- if strings.TrimSpace(attachment.URL) == "" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d is missing url", i))
- } else {
- parsedURL, err := url.ParseRequestURI(attachment.URL)
- if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d has an invalid url format", i))
- } else if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d must use http or https scheme", i))
- } else {
- if err := validateAttachmentURL(ctx, validator.cache, attachment.URL); err != nil {
- result.Add("attachments", fmt.Sprintf("attachment at index %d failed validation: %s", i, err.Error()))
- }
- }
- }
- }
-
if request.SendAt != nil && request.SendAt.After(time.Now().Add(480*time.Hour)) {
result.Add("send_at", "the scheduled time cannot be more than 20 days (480 hours) in the future")
}
@@ -172,6 +151,10 @@ func (validator MessageHandlerValidator) ValidateMessageBulkSend(ctx context.Con
"required",
phoneNumberRule,
},
+ "attachments": []string{
+ "max:10",
+ multipleAttachmentURLRule,
+ },
"content": []string{
"required",
"min:1",
@@ -185,31 +168,6 @@ func (validator MessageHandlerValidator) ValidateMessageBulkSend(ctx context.Con
return result
}
- if len(request.Attachments) > 10 {
- result.Add("attachments", "you cannot attach more than 10 files to a single message")
- }
-
- for i, attachment := range request.Attachments {
- if strings.TrimSpace(attachment.ContentType) == "" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d is missing content_type", i))
- }
-
- if strings.TrimSpace(attachment.URL) == "" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d is missing url", i))
- } else {
- parsedURL, err := url.ParseRequestURI(attachment.URL)
- if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d has an invalid url format", i))
- } else if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
- result.Add("attachments", fmt.Sprintf("attachment at index %d must use http or https scheme", i))
- } else {
- if err := validateAttachmentURL(ctx, validator.cache, attachment.URL); err != nil {
- result.Add("attachments", fmt.Sprintf("attachment at index %d failed validation: %s", i, err.Error()))
- }
- }
- }
- }
-
_, err := validator.phoneService.Load(ctx, userID, request.From)
if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {
result.Add("from", fmt.Sprintf("no phone found with with 'from' number [%s]. Install the android app on your phone to start sending messages", request.From))
diff --git a/api/pkg/validators/validator.go b/api/pkg/validators/validator.go
index 3cd85de2..2645c450 100644
--- a/api/pkg/validators/validator.go
+++ b/api/pkg/validators/validator.go
@@ -23,6 +23,7 @@ const (
multiplePhoneNumberRule = "multiplePhoneNumber"
contactPhoneNumberRule = "contactPhoneNumber"
multipleContactPhoneNumberRule = "multipleContactPhoneNumber"
+ multipleAttachmentURLRule = "multipleAttachmentURL"
multipleInRule = "multipleIn"
webhookEventsRule = "webhookEvents"
)
@@ -90,6 +91,21 @@ func init() {
return nil
})
+ govalidator.AddCustomRule(multipleAttachmentURLRule, func(field string, rule string, message string, value interface{}) error {
+ attachments, ok := value.([]string)
+ if !ok {
+ return fmt.Errorf("The %s field must be an array of valid attachment URL's", field)
+ }
+
+ for index, attachment := range attachments {
+ u, err := url.ParseRequestURI(attachment)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return fmt.Errorf("The attachment %d with URL [%s] must be a valid URL e.g https://placehold.co/600x400", index, attachment)
+ }
+ }
+ return nil
+ })
+
govalidator.AddCustomRule(multipleInRule, func(field string, rule string, message string, value interface{}) error {
values, ok := value.([]string)
if !ok {
@@ -108,7 +124,7 @@ func init() {
for index, item := range values {
if !contains(item) {
- return fmt.Errorf("the %s field in contains an invalid value [%s] at index [%d] ", field, item, index)
+ return fmt.Errorf("the %s field in contains an invalid value [%s] at index [%d]", field, item, index)
}
}
diff --git a/web/models/message.ts b/web/models/message.ts
index c0d09f12..b17b53ec 100644
--- a/web/models/message.ts
+++ b/web/models/message.ts
@@ -1,12 +1,7 @@
-export interface MessageAttachment {
- content_type: string
- url: string
-}
-
export interface Message {
contact: string
content: string
- attachments?: MessageAttachment[]
+ attachments: Array<string> | null
created_at: string
failure_reason: string
id: string
diff --git a/web/pages/messages/index.vue b/web/pages/messages/index.vue
index c4dc2734..bdc21e37 100644
--- a/web/pages/messages/index.vue
+++ b/web/pages/messages/index.vue
@@ -94,7 +94,7 @@ export default {
},
head() {
return {
- title: 'New Message - Http SMS',
+ title: 'New Message - httpSMS',
}
},
@@ -103,31 +103,16 @@ export default {
this.errors = new Map()
this.sending = true
- const attachments = []
- if (this.formAttachments.trim() !== '') {
- const urls = this.formAttachments.split(',')
- for (const u of urls) {
- const cleanUrl = u.trim()
- if (!cleanUrl) continue
-
- let contentType = 'application/octet-stream'
- const lowerUrl = cleanUrl.toLowerCase()
- if (lowerUrl.endsWith('.jpg') || lowerUrl.endsWith('.jpeg'))
- contentType = 'image/jpeg'
- else if (lowerUrl.endsWith('.png')) contentType = 'image/png'
- else if (lowerUrl.endsWith('.gif')) contentType = 'image/gif'
- else if (lowerUrl.endsWith('.mp4')) contentType = 'video/mp4'
-
- attachments.push({ content_type: contentType, url: cleanUrl })
- }
- }
-
axios
.post('/v1/messages/send', {
to: this.formPhoneNumber,
from: this.$store.getters.getOwner,
content: this.formContent,
- attachments,
+ attachments: this.formAttachments
+ .trim()
+ .split(',')
+ .filter((x) => x.trim() !== '')
+ .map((x) => x.trim()),
sim: this.simSelected.code,
})
.then(() => {
diff --git a/web/pages/threads/_id/index.vue b/web/pages/threads/_id/index.vue
index 4ea6504d..09b6dfc2 100644
--- a/web/pages/threads/_id/index.vue
+++ b/web/pages/threads/_id/index.vue
@@ -173,53 +173,20 @@
>
</v-card-text>
</v-card>
- <v-card v-if="message.attachments?.length" shaped>
- <v-card-title>Message Attachments</v-card-title>
- <v-card-text>
- <v-row>
- <v-col
- v-for="(attachment, index) in message.attachments"
- :key="index"
- cols="12"
- sm="6"
- md="4"
- >
- <v-img
- v-if="attachment.content_type?.startsWith('image/')"
- :src="attachment.url"
- :alt="`Attachment ${index + 1}`"
- aspect-ratio="1"
- class="bg-grey-lighten-2 rounded"
- cover
- >
- <template #placeholder>
- <v-row
- class="fill-height ma-0"
- align="center"
- justify="center"
- >
- <v-progress-circular
- indeterminate
- color="grey-lighten-1"
- ></v-progress-circular>
- </v-row>
- </template>
- </v-img>
-
- <div
- v-else
- class="text-center pa-4 bg-grey-lighten-4 rounded"
- >
- <v-icon
- icon="mdi-file-document-outline"
- size="large"
- ></v-icon>
- <div class="text-caption mt-2">
- Unsupported file type
- </div>
- </div>
- </v-col>
- </v-row>
+ <v-card rounded v-if="message.attachments?.length">
+ <v-card-text class="pb-2">
+ <a
+ v-for="(attachment, index) in message.attachments"
+ target="_blank"
+ :href="attachment"
+ class="text-decoration-none hover:text-decoration-underline body-2 mb-2 d-flex w-full"
+ :key="index"
+ >
+ <v-icon x-small class="text--secondary mt-1">{{
+ mdiPaperclip
+ }}</v-icon>
+ {{ attachment }}
+ </a>
</v-card-text>
</v-card>
<div class="d-flex">
@@ -383,6 +350,7 @@ import {
mdiCheckAll,
mdiDelete,
mdiCallMissed,
+ mdiPaperclip,
mdiCheck,
mdiAlert,
mdiPackageUp,
@@ -411,6 +379,7 @@ export default Vue.extend({
mdiArrowLeft,
mdiCheckAll,
mdiCallMissed,
+ mdiPaperclip,
mdiCheck,
mdiAlert,
mdiDelete,
@@ -677,6 +646,10 @@ export default Vue.extend({
}
}
+.hover\:text-decoration-underline:hover {
+ text-decoration: underline !important;
+}
+
.no-scrollbar,
.no-scrollbar textarea {
overflow-x: hidden;