add delay send mms. add group send to individual recipients - sms and mms. add immediate show messages in convo, not wait for sent. new qktransaction that replaces android/smsmms transaction with mods for quik. lots of code cleanups and removing superfluous code. some bug fixes.

This commit is contained in:
gavine99
2025-04-10 16:59:35 +10:00
parent 6f70c8e932
commit 2810b56cd0
375 changed files with 20297 additions and 3161 deletions
@@ -18,8 +18,6 @@
*/
package dev.octoshrimpy.quik.compat
import android.annotation.TargetApi
import android.os.Build
import android.telephony.SubscriptionInfo
data class SubscriptionInfoCompat(private val subscriptionInfo: SubscriptionInfo) {
@@ -28,6 +26,6 @@ data class SubscriptionInfoCompat(private val subscriptionInfo: SubscriptionInfo
val simSlotIndex get() = subscriptionInfo.simSlotIndex
val displayName get() = subscriptionInfo.displayName
val displayName: CharSequence get() = subscriptionInfo.displayName
}
@@ -19,7 +19,6 @@
package dev.octoshrimpy.quik.compat
import android.content.Context
import android.os.Build
import android.telephony.SubscriptionManager
import dev.octoshrimpy.quik.manager.PermissionManager
import javax.inject.Inject
@@ -59,7 +58,7 @@ class SubscriptionManagerCompat @Inject constructor(context: Context, private va
abstract class OnSubscriptionsChangedListener {
val listener: SubscriptionManager.OnSubscriptionsChangedListener? =
val listener: SubscriptionManager.OnSubscriptionsChangedListener =
object : SubscriptionManager.OnSubscriptionsChangedListener() {
override fun onSubscriptionsChanged() {
this@OnSubscriptionsChangedListener.onSubscriptionsChanged()
@@ -44,7 +44,7 @@ class ContactAddedListenerImpl @Inject constructor(
private class ContactContentObserver(context: Context) : ContentObserver(Handler()) {
private val subject = BehaviorSubject.createDefault<Unit>(Unit)
private val subject = BehaviorSubject.createDefault(Unit)
val observable: Observable<Unit> = subject
.doOnSubscribe { context.contentResolver.registerContentObserver(URI, true, this) }
@@ -21,7 +21,6 @@ package dev.octoshrimpy.quik.manager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import dev.octoshrimpy.quik.receiver.SendScheduledMessageReceiver
import javax.inject.Inject
@@ -50,12 +50,6 @@ class BluetoothMicManager(
})
}
enum class StartBluetoothDevice {
NoDevice,
Connecting,
Connected
}
var device: AudioDeviceInfo? = null
private set
@@ -26,15 +26,8 @@ import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import javax.inject.Inject
class ChangelogManagerImpl @Inject constructor(
@@ -43,7 +36,7 @@ class ChangelogManagerImpl @Inject constructor(
private val prefs: Preferences
) : ChangelogManager {
override fun didUpdate(): Boolean = (prefs.changelogVersion.get() ?: 0) != context.versionCode
override fun didUpdate(): Boolean = prefs.changelogVersion.get() != context.versionCode
override suspend fun getChangelog(): ChangelogManager.CumulativeChangelog {
val listType = Types.newParameterizedType(List::class.java, Changeset::class.java)
@@ -56,7 +49,7 @@ class ChangelogManagerImpl @Inject constructor(
.orEmpty()
.sortedBy { changelog -> changelog.versionCode }
.filter { changelog ->
changelog.versionCode in (prefs.changelogVersion.get() ?: 0).inc()..context.versionCode
changelog.versionCode in prefs.changelogVersion.get().inc()..context.versionCode
}
ChangelogManager.CumulativeChangelog(
@@ -40,8 +40,7 @@ object MediaRecorderManager : MediaRecorder() {
const val AUDIO_FILE_PREFIX = "recorded-"
const val AUDIO_FILE_SUFFIX = ".3ga"
var recordingState: RecordingState = RecordingState.Initial
private set
private var recordingState: RecordingState = RecordingState.Initial
var uri: Uri = Uri.EMPTY
private set
@@ -64,7 +63,7 @@ object MediaRecorderManager : MediaRecorder() {
fun startRecording(context: Context, preferredAudioDevice: AudioDeviceInfo? = null): Uri {
return try {
val (newUri, e) = FileUtils.create(
FileUtils.Companion.Location.Cache,
FileUtils.Location.Cache,
context,
"$AUDIO_FILE_PREFIX${UUID.randomUUID()}$AUDIO_FILE_SUFFIX",
""
@@ -0,0 +1,636 @@
/*
* Copyright 2013 Jacob Klinker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2025
*
* modified from original for QUIK
*
* This file is part of QUIK.
*
* QUIK is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QUIK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QUIK. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.manager
import android.app.PendingIntent
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Telephony
import android.telephony.SmsManager
import android.telephony.SmsMessage
import androidx.core.content.contentValuesOf
import com.android.mms.MmsConfig
import com.android.mms.dom.smil.parser.SmilXmlSerializer
import com.android.mms.util.DownloadManager
import com.android.mms.util.RateController
import com.google.android.mms.ContentType
import com.google.android.mms.InvalidHeaderValueException
import com.google.android.mms.MMSPart
import com.google.android.mms.MmsException
import com.google.android.mms.pdu_alt.CharacterSets
import com.google.android.mms.pdu_alt.EncodedStringValue
import com.google.android.mms.pdu_alt.GenericPdu
import com.google.android.mms.pdu_alt.PduBody
import com.google.android.mms.pdu_alt.PduComposer
import com.google.android.mms.pdu_alt.PduHeaders
import com.google.android.mms.pdu_alt.PduPart
import com.google.android.mms.pdu_alt.PduPersister
import com.google.android.mms.pdu_alt.SendReq
import com.google.android.mms.smil.SmilHelper
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.MmsSentReceiver
import com.klinker.android.send_message.SmsManagerFactory
import com.klinker.android.send_message.StripAccents
import com.klinker.android.send_message.Utils
import timber.log.Timber
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Calendar
import java.util.UUID
import androidx.core.net.toUri
object QkTransaction {
private const val DEFAULT_EXPIRY_TIME: Long = (7 * 24 * 60 * 60).toLong()
private const val DEFAULT_PRIORITY: Int = PduHeaders.PRIORITY_NORMAL
private fun getNumSmsPages(stripUnicode: Boolean, body: String?): Int {
var text = body
if (stripUnicode) {
text = StripAccents.stripAccents(text)
}
val data = SmsMessage.calculateLength(text, false)
return data[0]
}
private fun checkMMS(
body: String?, numToAddresses: Int, numParts: Int, asGroup: Boolean, longAsMms: Boolean,
stripUnicode: Boolean
): Boolean {
return (numParts > 0) ||
((numToAddresses > 1) && asGroup) ||
(longAsMms && getNumSmsPages(stripUnicode, body) > 3)
}
fun createMessage(
context: Context,
subscriptionId: Int,
body: String?,
signature: String,
toAddresses: Array<String>,
parts: MutableCollection<MMSPart>,
asGroup: Boolean,
longAsMms: Boolean,
stripUnicode: Boolean
): Uri {
Timber.v("creating message")
// add signature to original text to be saved in db
var text = body
if (signature.isNotEmpty())
text += "\n$signature"
// strip unicode if flagged to do so
if (stripUnicode)
text = StripAccents.stripAccents(text)
if (checkMMS(text, toAddresses.size, parts.size, asGroup, longAsMms, stripUnicode)) {
RateController.init(context)
DownloadManager.init(context)
return createMmsMessage(context, subscriptionId, text, toAddresses, parts)
}
return createSmsMessage(context, subscriptionId, text, toAddresses)
}
fun explodeMessage(context: Context, messageUri: Uri, asGroup: Boolean): Collection<Uri> {
Timber.v("exploding message uri $messageUri")
if (asGroup)
return listOf(messageUri)
return if (messageUri.toString().startsWith(Telephony.Mms.CONTENT_URI.toString()))
explodeMmsMessage(context, messageUri)
else explodeSmsMessage(context, messageUri)
}
fun sendMessage(context: Context, messageUri: Uri, sentIntent: Intent, deliveryIntent: Intent?
): Boolean {
Timber.v("sending message uri $messageUri")
return if (messageUri.toString().startsWith(Telephony.Mms.CONTENT_URI.toString()))
sendMmsMessage(context, messageUri, sentIntent)
else sendSmsMessage(context, messageUri, sentIntent, deliveryIntent)
}
private fun getProviderRecipients(context: Context, threadId: Long): Collection<String> {
// get recipient ids
val spaceSeparatedRecipients = context.contentResolver.query(
(Telephony.MmsSms.CONTENT_CONVERSATIONS_URI.toString() + "?simple=true").toUri(),
arrayOf(Telephony.Threads._ID, Telephony.Threads.RECIPIENT_IDS),
Telephony.Threads._ID + " = ?", arrayOf(threadId.toString()),
null
)
?.use { cursor ->
if (cursor.moveToFirst())
cursor.getString(1)
else {
Timber.e("recipient id provider db query returned no rows")
""
}
}
?: let {
Timber.e("recipient id provider db query failed")
""
}
if (spaceSeparatedRecipients.isEmpty()) {
Timber.e("failed to get provider recipient ids for thread $threadId")
return listOf()
}
// get addresses from recipient ids
val addresses = ArrayList<String>()
context.contentResolver.query(
"content://mms-sms/canonical-addresses".toUri(),
arrayOf(
Telephony.CanonicalAddressesColumns._ID,
Telephony.CanonicalAddressesColumns.ADDRESS
),
Telephony.CanonicalAddressesColumns._ID + " in (" +
spaceSeparatedRecipients.replace(' ', ',') + ")",
null,
null
)
?.use { cursor ->
if (cursor.moveToFirst())
do {
addresses.add(cursor.getString(1))
} while (cursor.moveToNext())
else
Timber.e("address provider db query returned no rows")
}
?: let { Timber.e("address provider db query failed") }
if (addresses.isEmpty())
Timber.e("no addresses from recipient ids for thread $threadId")
return addresses
}
private fun createSmsMessage(
context: Context, subscriptionId: Int, body: String?, addresses: Array<String>
): Uri {
val threadId = Utils.getOrCreateThreadId(context, addresses.toSet())
val cal = Calendar.getInstance()
val values = ContentValues()
values.put(Telephony.Sms.ADDRESS, if (addresses.size > 1) "" else addresses[0])
values.put(Telephony.Sms.BODY, body)
values.put(Telephony.Sms.DATE, cal.timeInMillis.toString() + "")
values.put(Telephony.Sms.READ, 1)
values.put(Telephony.Sms.TYPE, 4)
values.put(Telephony.Sms.THREAD_ID, threadId)
values.put(Telephony.Sms.SUBSCRIPTION_ID, subscriptionId)
val messageUri = context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values)
if (messageUri == null) {
Timber.e("unable to create sms provider record")
return Uri.EMPTY
}
return messageUri
}
private fun explodeSmsMessage(context: Context, messageUri: Uri): Collection<Uri> {
val retVal: MutableCollection<Uri> = ArrayList()
var threadId: Long = -1
var subscriptionId = -1
var body = ""
// get pertinent message values of source message
context.contentResolver.query(
messageUri,
arrayOf(Telephony.Sms.THREAD_ID, Telephony.Sms.SUBSCRIPTION_ID, Telephony.Sms.BODY),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
threadId = cursor.getInt(0).toLong()
subscriptionId = cursor.getInt(1)
body = cursor.getString(2)
} else {
Timber.e("provider db query returned no rows")
return retVal
}
}
?: let {
Timber.e("provider db query failed")
return retVal
}
// get thread recipients
val addresses = getProviderRecipients(context, threadId)
// if zero (!) or one recipient in thread, return original message only
if (addresses.size <= 1) {
retVal.add(messageUri)
return retVal
}
// create individual messages
for (address in addresses)
retVal.add(createSmsMessage(context, subscriptionId, body, arrayOf(address)))
return retVal
}
private fun sendSmsMessage(
context: Context, messageUri: Uri, sentIntent: Intent, deliveryIntent: Intent?
): Boolean {
if (messageUri === Uri.EMPTY) {
Timber.e("can't send sms. message uri is empty")
return false
}
var id = -1
var subscriptionId = -1
var body = ""
var address = ""
// get message values from provider db
context.contentResolver.query(
messageUri,
arrayOf(
Telephony.Sms._ID,
Telephony.Sms.SUBSCRIPTION_ID,
Telephony.Sms.ADDRESS,
Telephony.Sms.BODY
),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
id = cursor.getInt(0)
subscriptionId = cursor.getInt(1)
address = cursor.getString(2)
body = cursor.getString(3)
} else {
Timber.e("sms provider db query returned no rows")
return false
}
}
?: let {
Timber.e("sms provider db query failed")
return false
}
val sPI = ArrayList<PendingIntent>()
val dPI = ArrayList<PendingIntent>()
// set up sent and delivered pending intents to be used with message request
val sentPI = PendingIntent.getBroadcast(
context, id, sentIntent.setData(messageUri),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val deliveredPI =
if (deliveryIntent != null) PendingIntent.getBroadcast(
context, -id, deliveryIntent.setData(messageUri),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
else null
val smsManager = SmsManagerFactory.createSmsManager(subscriptionId)
val parts = smsManager.divideMessage(body)
// add pending intent for each part
for (i in parts.indices) {
sPI.add(sentPI)
if (deliveredPI != null) dPI.add(deliveredPI)
}
Timber.v("send sms message uri $messageUri")
try {
smsManager.sendMultipartTextMessage(
address, null, parts, sPI, dPI.ifEmpty { null }
)
} catch (e: Exception) {
Timber.e("send sms exception", e)
}
return true
}
private fun createMmsMessage(
context: Context, subscriptionId: Int, text: String?, addresses: Array<String>,
parts: MutableCollection<MMSPart>
): Uri {
// add text to the end of the part and send
if (!text.isNullOrEmpty())
parts.add(MMSPart().apply {
Name = "text"
MimeType = "text/plain"
Data = text.toByteArray()
})
try {
return PduPersister.getPduPersister(context).persist(
buildPdu(context, subscriptionId, addresses, ArrayList(parts)),
Telephony.Mms.Outbox.CONTENT_URI, true, true,
null, subscriptionId
)
} catch (e: Exception) {
Timber.e("failed to create mms message", e)
}
return Uri.EMPTY
}
private fun explodeMmsMessage(context: Context, messageUri: Uri): Collection<Uri> {
val retVal: MutableCollection<Uri> = ArrayList()
Timber.v("explode mms message $messageUri")
// load message from provider db as a generic pdu
val pdu: GenericPdu
try {
pdu = PduPersister.getPduPersister(context).load(messageUri)
} catch (e: MmsException) {
Timber.e("load pdu from provider failed", e)
return retVal
}
// get recipient addresses from pdu
val sendReq = pdu as SendReq
val encodedTos = sendReq.to
// if one recipient in thread, return original message only
if (encodedTos.size == 1) {
Timber.v("single recipient thread")
retVal.add(messageUri)
return retVal
}
// get subscription id from provider
val subscriptionId = context.contentResolver.query(
messageUri,
arrayOf(Telephony.Mms.SUBSCRIPTION_ID),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
cursor.getInt(0)
} else {
Timber.e("sub id provider db query returned no rows")
return retVal
}
}
?: let {
Timber.e("sub id provider db query failed")
return retVal
}
// create individual messages
for (encodedTo in encodedTos) {
try {
sendReq.to = arrayOf(encodedTo)
retVal.add(
PduPersister.getPduPersister(context).persist(
sendReq,
Telephony.Mms.Outbox.CONTENT_URI,
true,
true,
null,
subscriptionId
)
)
} catch (e: Exception) {
Timber.e("failed creating provider mms message", e)
}
}
return retVal
}
private fun sendMmsMessage(context: Context, messageUri: Uri, sentIntent: Intent): Boolean {
try {
Timber.v("send mms message uri $messageUri")
// update message status to outbox in provider
if (SqliteWrapper.update(
context, context.contentResolver,
messageUri,
contentValuesOf(
Telephony.Mms.MESSAGE_BOX to Telephony.Mms.MESSAGE_BOX_OUTBOX
),
null, null
) <= 0)
Timber.v("failed to update $messageUri to mms outbox")
// get mms id and subscription id from provider
var id = -1
var subscriptionId = -1
context.contentResolver.query(
messageUri,
arrayOf(Telephony.Mms._ID, Telephony.Mms.SUBSCRIPTION_ID),
null, null, null
)
?.use { cursor ->
if (cursor.moveToFirst()) {
id = cursor.getInt(0)
subscriptionId = cursor.getInt(1)
} else {
Timber.e("sub id provider db query returned no rows")
Utils.getDefaultSubscriptionId()
}
}
?: let {
Timber.e("sub id provider db query failed")
Utils.getDefaultSubscriptionId()
}
// load message from provider db as a generic pdu
val sendPdu = try {
PduPersister.getPduPersister(context).load(messageUri)
} catch (e: MmsException) {
Timber.e("pdu from provider db failed", e)
return false
}
val fileName = "send." + UUID.randomUUID() + ".dat"
val mSendFile = File(context.cacheDir, fileName)
Timber.v("using file name $fileName")
val contentUri = try {
FileOutputStream(mSendFile).use {
it.write(PduComposer(context, sendPdu).make())
}
(Uri.Builder())
.authority(context.packageName + ".MmsFileProvider")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build()
} catch (e: IOException) {
Timber.e("error writing send file", e)
return false
}
// overrides of default mmsc config values
val configOverrides = Bundle()
configOverrides.putBoolean(SmsManager.MMS_CONFIG_GROUP_MMS_ENABLED, true)
val httpParams = MmsConfig.getHttpParams()
if (!httpParams.isNullOrEmpty())
configOverrides.putString(SmsManager.MMS_CONFIG_HTTP_PARAMS, httpParams)
configOverrides.putInt(
SmsManager.MMS_CONFIG_MAX_MESSAGE_SIZE, MmsConfig.getMaxMessageSize()
)
// build intent to send when message sent
val pendingIntent = PendingIntent.getBroadcast(
context, id,
sentIntent
.setData(messageUri)
.putExtra(MmsSentReceiver.EXTRA_FILE_PATH, mSendFile.path),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
SmsManagerFactory.createSmsManager(subscriptionId).sendMultimediaMessage(
context, contentUri, null, configOverrides, pendingIntent
)
} catch (e: Exception) {
Timber.e("failed sending mms", e)
return false
}
return true
}
private fun buildPdu(
context: Context, subscriptionId: Int, recipients: Array<String>, parts: List<MMSPart>
): SendReq {
val req = SendReq()
// From, per spec
req.prepareFromAddress(context, "", subscriptionId)
// To
for (recipient in recipients)
req.addTo(EncodedStringValue(recipient))
// Subject { commented but left for future use }
// if (subject.isNotEmpty())
// req.subject = EncodedStringValue(subject)
// Date
req.date = System.currentTimeMillis() / 1000
// Body
val body = PduBody()
var size = 0
// Add text part. Always add a smil part for compatibility, without it there
// may be issues on some carriers/client apps
parts.forEach { size += addTextPart(body, it) }
// add a SMIL document for compatibility
val out = ByteArrayOutputStream()
SmilXmlSerializer.serialize(SmilHelper.createSmilDocument(body), out)
body.addPart(0, PduPart().apply {
contentId = "smil".toByteArray()
contentLocation = "smil.xml".toByteArray()
contentType = ContentType.APP_SMIL.toByteArray()
data = out.toByteArray()
})
req.body = body
// Message size
req.messageSize = size.toLong()
// Message class
req.messageClass = PduHeaders.MESSAGE_CLASS_PERSONAL_STR.toByteArray()
// Expiry
req.expiry = DEFAULT_EXPIRY_TIME
try {
// Priority
req.priority = DEFAULT_PRIORITY
// Delivery report
req.deliveryReport = PduHeaders.VALUE_NO
// Read report
req.readReport = PduHeaders.VALUE_NO
} catch (e: InvalidHeaderValueException) {
Timber.e("invalid header value when building pdu")
}
return req
}
private fun addTextPart(pb: PduBody, p: MMSPart): Int {
val filename = p.Name
val part = PduPart().apply {
// Set Charset if it's a text media.
if (p.MimeType.startsWith("text"))
charset = CharacterSets.UTF_8
// Set Content-Type.
contentType = p.MimeType.toByteArray()
// Set Content-Location.
contentLocation = filename.toByteArray()
val index = filename.lastIndexOf(".")
contentId =
(
if (index == -1) filename
else filename.substring(0, index)
).toByteArray()
data = p.Data
}
pb.addPart(part)
return part.data.size
}
}
@@ -24,22 +24,20 @@ import android.content.Context
import android.content.Intent
import com.klinker.android.send_message.BroadcastUtils
import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.nonDebugPackageName
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
class WidgetManagerImpl @Inject constructor(
private val context: Context,
private val prefs: Preferences
) : WidgetManager {
class WidgetManagerImpl @Inject constructor(private val context: Context, prefs: Preferences)
: WidgetManager {
companion object {
private var staticUnreadAtTopPrefsDisposable = AtomicReference<Disposable>(null)
fun sendDatasetChanged(context: Context) {
BroadcastUtils.sendExplicitBroadcast(context, Intent(), WidgetManager.ACTION_NOTIFY_DATASET_CHANGED)
BroadcastUtils.sendExplicitBroadcast(context, Intent(), "${context.packageName}.${WidgetManager.ACTION_NOTIFY_DATASET_CHANGED}")
}
}
@@ -61,7 +59,12 @@ class WidgetManagerImpl @Inject constructor(
override fun updateTheme() {
val ids = AppWidgetManager.getInstance(context)
.getAppWidgetIds(ComponentName(context.packageName, "dev.octoshrimpy.quik.feature.widget.WidgetProvider"))
.getAppWidgetIds(
ComponentName(
context.packageName,
"${nonDebugPackageName(context.packageName)}.feature.widget.WidgetProvider"
)
)
val intent = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
@@ -32,7 +32,7 @@ class CursorToContactImpl @Inject constructor(
) : CursorToContact {
companion object {
val URI = Phone.CONTENT_URI
val URI = Phone.CONTENT_URI!!
val PROJECTION = arrayOf(
Phone._ID,
Phone.LOOKUP_KEY,
@@ -20,12 +20,10 @@ package dev.octoshrimpy.quik.mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony.*
import com.google.android.mms.pdu_alt.EncodedStringValue
import com.google.android.mms.pdu_alt.PduHeaders
import com.google.android.mms.pdu_alt.PduPersister
import dev.octoshrimpy.quik.extensions.map
import dev.octoshrimpy.quik.manager.KeyManager
import dev.octoshrimpy.quik.manager.PermissionManager
import dev.octoshrimpy.quik.model.Message
@@ -33,16 +31,16 @@ import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.SqliteWrapper
import dev.octoshrimpy.quik.util.tryOrNull
import javax.inject.Inject
import androidx.core.net.toUri
class CursorToMessageImpl @Inject constructor(
private val context: Context,
private val cursorToPart: CursorToPart,
private val keys: KeyManager,
private val permissionManager: PermissionManager,
private val preferences: Preferences
) : CursorToMessage {
private val uri = Uri.parse("content://mms-sms/complete-conversations")
private val uri = "content://mms-sms/complete-conversations".toUri()
private val projection = arrayOf(
MmsSms.TYPE_DISCRIMINATOR_COLUMN,
MmsSms._ID,
@@ -66,7 +64,7 @@ class CursorToMessageImpl @Inject constructor(
Mms.MESSAGE_BOX,
Mms.DELIVERY_REPORT,
Mms.READ_REPORT,
MmsSms.PendingMessages.ERROR_TYPE,
// MmsSms.PendingMessages.ERROR_TYPE,
Mms.STATUS
)
@@ -77,8 +75,8 @@ class CursorToMessageImpl @Inject constructor(
return Message().apply {
type = when {
cursor.getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN) != -1 -> cursor.getString(columnsMap.msgType)
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> "mms"
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> "sms"
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> Message.TYPE_MMS
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> Message.TYPE_SMS
else -> "unknown"
}
@@ -92,7 +90,8 @@ class CursorToMessageImpl @Inject constructor(
subId = if (columnsMap.subId != -1) cursor.getInt(columnsMap.subId) else -1
when (type) {
"sms" -> {
Message.TYPE_SMS -> {
type = Message.TYPE_SMS
address = cursor.getString(columnsMap.smsAddress) ?: ""
boxId = cursor.getInt(columnsMap.smsType)
seen = cursor.getInt(columnsMap.smsSeen) != 0
@@ -105,14 +104,15 @@ class CursorToMessageImpl @Inject constructor(
deliveryStatus = cursor.getInt(columnsMap.smsStatus)
}
"mms" -> {
Message.TYPE_MMS -> {
type = Message.TYPE_MMS
address = getMmsAddress(contentId)
boxId = cursor.getInt(columnsMap.mmsMessageBox)
date *= 1000L
dateSent *= 1000L
seen = cursor.getInt(columnsMap.mmsSeen) != 0
mmsDeliveryStatusString = cursor.getString(columnsMap.mmsDeliveryReport) ?: ""
errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
// errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
messageSize = 0
readReportString = cursor.getString(columnsMap.mmsReadReport) ?: ""
messageType = cursor.getInt(columnsMap.mmsMessageType)
@@ -20,10 +20,10 @@ package dev.octoshrimpy.quik.mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import dev.octoshrimpy.quik.manager.PermissionManager
import dev.octoshrimpy.quik.model.Recipient
import javax.inject.Inject
import androidx.core.net.toUri
class CursorToRecipientImpl @Inject constructor(
private val context: Context,
@@ -31,7 +31,7 @@ class CursorToRecipientImpl @Inject constructor(
) : CursorToRecipient {
companion object {
val URI = Uri.parse("content://mms-sms/canonical-addresses")
val URI = "content://mms-sms/canonical-addresses".toUri()
const val COLUMN_ID = 0
const val COLUMN_ADDRESS = 1
@@ -28,6 +28,7 @@ import io.realm.FieldAttribute
import io.realm.RealmList
import io.realm.RealmMigration
import io.realm.Sort
import timber.log.Timber
import javax.inject.Inject
class QkRealmMigration @Inject constructor(
@@ -36,7 +37,7 @@ class QkRealmMigration @Inject constructor(
) : RealmMigration {
companion object {
const val SchemaVersion: Long = 11
const val SCHEMA_VERSION: Long = 12
}
@SuppressLint("ApplySharedPref")
@@ -45,82 +46,82 @@ class QkRealmMigration @Inject constructor(
if (version == 0L) {
realm.schema.get("MmsPart")
?.removeField("image")
?.removeField("image")
version++
}
if (version == 1L) {
realm.schema.get("Message")
?.addField("subId", Int::class.java)
?.addField("subId", Int::class.java)
version++
}
if (version == 2L) {
realm.schema.get("Conversation")
?.addField("name", String::class.java, FieldAttribute.REQUIRED)
?.addField("name", String::class.java, FieldAttribute.REQUIRED)
version++
}
if (version == 3L) {
realm.schema.create("ScheduledMessage")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("date", Long::class.java, FieldAttribute.REQUIRED)
.addField("subId", Long::class.java, FieldAttribute.REQUIRED)
.addRealmListField("recipients", String::class.java)
.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
.addField("body", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("attachments", String::class.java)
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("date", Long::class.java, FieldAttribute.REQUIRED)
.addField("subId", Long::class.java, FieldAttribute.REQUIRED)
.addRealmListField("recipients", String::class.java)
.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
.addField("body", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("attachments", String::class.java)
version++
}
if (version == 4L) {
realm.schema.get("Conversation")
?.addField("pinned", Boolean::class.java, FieldAttribute.REQUIRED, FieldAttribute.INDEXED)
?.addField("pinned", Boolean::class.java, FieldAttribute.REQUIRED, FieldAttribute.INDEXED)
version++
}
if (version == 5L) {
realm.schema.create("BlockedNumber")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("address", String::class.java, FieldAttribute.REQUIRED)
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("address", String::class.java, FieldAttribute.REQUIRED)
version++
}
if (version == 6L) {
realm.schema.get("Conversation")
?.addField("blockingClient", Integer::class.java)
?.addField("blockReason", String::class.java)
?.addField("blockingClient", Integer::class.java)
?.addField("blockReason", String::class.java)
realm.schema.get("MmsPart")
?.addField("seq", Integer::class.java, FieldAttribute.REQUIRED)
?.addField("name", String::class.java)
?.addField("seq", Integer::class.java, FieldAttribute.REQUIRED)
?.addField("name", String::class.java)
version++
}
if (version == 7L) {
realm.schema.get("Conversation")
?.addRealmObjectField("lastMessage", realm.schema.get("Message"))
?.removeField("count")
?.removeField("date")
?.removeField("snippet")
?.removeField("read")
?.removeField("me")
?.addRealmObjectField("lastMessage", realm.schema.get("Message"))
?.removeField("count")
?.removeField("date")
?.removeField("snippet")
?.removeField("read")
?.removeField("me")
val conversations = realm.where("Conversation")
.findAll()
.findAll()
val messages = realm.where("Message")
.sort("date", Sort.DESCENDING)
.distinct("threadId")
.findAll()
.associateBy { message -> message.getLong("threadId") }
.sort("date", Sort.DESCENDING)
.distinct("threadId")
.findAll()
.associateBy { message -> message.getLong("threadId") }
conversations.forEach { conversation ->
conversation.setObject("lastMessage", messages[conversation.getLong("id")])
@@ -134,44 +135,44 @@ class QkRealmMigration @Inject constructor(
realm.delete("PhoneNumber")
realm.schema.create("ContactGroup")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("title", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("contacts", realm.schema.get("Contact"))
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("title", String::class.java, FieldAttribute.REQUIRED)
.addRealmListField("contacts", realm.schema.get("Contact"))
realm.schema.get("PhoneNumber")
?.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
?.addField("accountType", String::class.java)
?.addField("isDefault", Boolean::class.java, FieldAttribute.REQUIRED)
?.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
?.addField("accountType", String::class.java)
?.addField("isDefault", Boolean::class.java, FieldAttribute.REQUIRED)
val phoneNumbers = cursorToContact.getContactsCursor()
?.map(cursorToContact::map)
?.distinctBy { contact -> contact.numbers.firstOrNull()?.id } // Each row has only one number
?.groupBy { contact -> contact.lookupKey }
?: mapOf()
?.map(cursorToContact::map)
?.distinctBy { contact -> contact.numbers.firstOrNull()?.id } // Each row has only one number
?.groupBy { contact -> contact.lookupKey }
?: mapOf()
realm.schema.get("Contact")
?.addField("starred", Boolean::class.java, FieldAttribute.REQUIRED)
?.addField("photoUri", String::class.java)
?.transform { realmContact ->
val numbers = RealmList<DynamicRealmObject>()
phoneNumbers[realmContact.get("lookupKey")]
?.flatMap { contact -> contact.numbers }
?.map { number ->
realm.createObject("PhoneNumber", number.id).apply {
setString("accountType", number.accountType)
setString("address", number.address)
setString("type", number.type)
}
}
?.let(numbers::addAll)
?.addField("starred", Boolean::class.java, FieldAttribute.REQUIRED)
?.addField("photoUri", String::class.java)
?.transform { realmContact ->
val numbers = RealmList<DynamicRealmObject>()
phoneNumbers[realmContact.get("lookupKey")]
?.flatMap { contact -> contact.numbers }
?.map { number ->
realm.createObject("PhoneNumber", number.id).apply {
setString("accountType", number.accountType)
setString("address", number.address)
setString("type", number.type)
}
}
?.let(numbers::addAll)
val photoUri = phoneNumbers[realmContact.get("lookupKey")]
?.firstOrNull { number -> number.photoUri != null }
?.photoUri
val photoUri = phoneNumbers[realmContact.get("lookupKey")]
?.firstOrNull { number -> number.photoUri != null }
?.photoUri
realmContact.setList("numbers", numbers)
realmContact.setString("photoUri", photoUri)
}
realmContact.setList("numbers", numbers)
realmContact.setString("photoUri", photoUri)
}
// Migrate conversation themes
val recipients = mutableMapOf<Long, Int>() // Map of recipientId:theme
@@ -225,16 +226,42 @@ class QkRealmMigration @Inject constructor(
if (version == 10L) {
realm.schema.get("MmsPart")
?.addField("messageId", Long::class.java, FieldAttribute.INDEXED, FieldAttribute.REQUIRED)
?.transform { part ->
val messageId = part.linkingObjects("Message", "parts").firstOrNull()?.getLong("contentId") ?: 0
part.setLong("messageId", messageId)
}
?.addField("messageId", Long::class.java, FieldAttribute.INDEXED, FieldAttribute.REQUIRED)
?.transform { part ->
val messageId = part.linkingObjects("Message", "parts").firstOrNull()?.getLong("contentId") ?: 0
part.setLong("messageId", messageId)
}
version++
}
check(version >= newVersion) { "Migration missing from v$oldVersion to v$newVersion" }
if (version == 11L) {
realm.schema.get("Conversation")
?.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
?.transform { conversation ->
conversation.setBoolean(
"sendAsGroup",
(conversation.getList("recipients").size > 1)
)
}
realm.schema.get("Message")
?.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
version++
}
check(version >= SCHEMA_VERSION) {
"Migration from v$oldVersion to v$newVersion failed at v$version"
}
// throw an exception if migration failed
check(version >= newVersion) {
"Realm migration from v$oldVersion to v$newVersion after v$version"
}
// else
Timber.d("Realm migration from v$oldVersion to v$newVersion succeeded")
}
}
@@ -27,6 +27,7 @@ import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.util.Preferences
import dagger.android.AndroidInjection
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import javax.inject.Inject
class BlockThreadReceiver : BroadcastReceiver() {
@@ -39,6 +40,8 @@ class BlockThreadReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
val threadId = intent.getLongExtra("threadId", 0)
blockingClient
@@ -23,19 +23,25 @@ import android.content.Context
import android.content.Intent
import dev.octoshrimpy.quik.interactor.DeleteMessages
import dagger.android.AndroidInjection
import timber.log.Timber
import javax.inject.Inject
class DeleteMessagesReceiver : BroadcastReceiver() {
@Inject lateinit var deleteMessages: DeleteMessages
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
val messageIds = intent.getLongArrayExtra("messageIds") ?: longArrayOf()
deleteMessages.execute(DeleteMessages.Params(messageIds.toList(), threadId)) { pendingResult.finish() }
Timber.v("received")
intent.getLongExtra("threadId", 0).takeIf { it > 0 }?.let { threadId ->
intent.getLongArrayExtra("messageIds")?.let { messageIds ->
val pendingResult = goAsync()
deleteMessages.execute(DeleteMessages.Params(messageIds.toList(), threadId)) {
pendingResult.finish()
}
}
}
}
}
@@ -1,40 +0,0 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dev.octoshrimpy.quik.interactor.MarkArchived
import dagger.android.AndroidInjection
import javax.inject.Inject
class MarkArchivedReceiver : BroadcastReceiver() {
@Inject lateinit var markArchived: MarkArchived
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
markArchived.execute(listOf(threadId)) { pendingResult.finish() }
}
}
@@ -1,40 +0,0 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dev.octoshrimpy.quik.interactor.MarkRead
import dagger.android.AndroidInjection
import javax.inject.Inject
class MarkReadReceiver : BroadcastReceiver() {
@Inject lateinit var markRead: MarkRead
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
markRead.execute(listOf(threadId)) { pendingResult.finish() }
}
}
@@ -1,40 +0,0 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dev.octoshrimpy.quik.interactor.MarkSeen
import dagger.android.AndroidInjection
import javax.inject.Inject
class MarkSeenReceiver : BroadcastReceiver() {
@Inject lateinit var markSeen: MarkSeen
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val pendingResult = goAsync()
val threadId = intent.getLongExtra("threadId", 0)
markSeen.execute(threadId) { pendingResult.finish() }
}
}
@@ -25,9 +25,13 @@ import android.content.Intent
import dev.octoshrimpy.quik.interactor.MarkDelivered
import dev.octoshrimpy.quik.interactor.MarkDeliveryFailed
import dagger.android.AndroidInjection
import timber.log.Timber
import javax.inject.Inject
class SmsDeliveredReceiver : BroadcastReceiver() {
class MessageDeliveredReceiver : BroadcastReceiver() {
companion object {
const val EXTRA_QUIK_MESSAGE_ID = "messageId"
}
@Inject lateinit var markDelivered: MarkDelivered
@Inject lateinit var markDeliveryFailed: MarkDeliveryFailed
@@ -35,21 +39,25 @@ class SmsDeliveredReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val id = intent.getLongExtra("id", 0L)
Timber.v("received")
when (resultCode) {
// TODO notify about delivery
Activity.RESULT_OK -> {
intent.extras?.getLong(EXTRA_QUIK_MESSAGE_ID)?.takeIf { it > 0 }
?.let { messageId ->
val pendingResult = goAsync()
markDelivered.execute(id) { pendingResult.finish() }
}
// TODO notify about delivery failure
Activity.RESULT_CANCELED -> {
val pendingResult = goAsync()
markDeliveryFailed.execute(MarkDeliveryFailed.Params(id, resultCode)) { pendingResult.finish() }
}
}
Timber.v("resultcode: ${pendingResult.resultCode}")
when (pendingResult.resultCode) {
// TODO notify about delivery
Activity.RESULT_OK -> markDelivered.execute(messageId) { pendingResult.finish() }
// TODO notify about delivery failure
else ->
markDeliveryFailed.execute(MarkDeliveryFailed.Params(messageId, resultCode)) {
pendingResult.finish()
}
}
} ?: let { Timber.e("couldn't get message id") }
}
}
@@ -0,0 +1,67 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkArchived
import dev.octoshrimpy.quik.interactor.MarkSeen
import dev.octoshrimpy.quik.interactor.MarkRead
import timber.log.Timber
import javax.inject.Inject
class MessageMarkReceiver : BroadcastReceiver() {
enum class MarkType {
Seen,
Read,
Archived
}
@Inject lateinit var markSeen: MarkSeen
@Inject lateinit var markRead: MarkRead
@Inject lateinit var markArchived: MarkArchived
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
intent.getLongExtra("threadId", 0).takeIf { it > 0 }?.let { threadId ->
intent.getIntExtra("type", -1).takeIf { it >= 0 }?.let { type ->
val pendingResult = goAsync()
when (type) {
MarkType.Seen.ordinal -> markSeen.execute(threadId) {
pendingResult.finish()
}
MarkType.Read.ordinal -> markRead.execute(listOf(threadId)) {
pendingResult.finish()
}
MarkType.Archived.ordinal -> markArchived.execute(listOf(threadId)) {
pendingResult.finish()
}
}
} ?:let { Timber.e("didn't get a valid type") }
} ?:let { Timber.e("didn't get a valid thread id") }
}
}
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.klinker.android.send_message.MmsSentReceiver.EXTRA_FILE_PATH
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.MarkFailed
import dev.octoshrimpy.quik.interactor.MarkSent
import dev.octoshrimpy.quik.repository.MessageRepository
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class MessageSentReceiver : BroadcastReceiver() {
companion object {
const val EXTRA_QUIK_MESSAGE_ID = "messageId"
const val EXTRA_IS_NOTIFY = "isNotify"
}
@Inject lateinit var markSent: MarkSent
@Inject lateinit var markFailed: MarkFailed
@Inject lateinit var messageRepo: MessageRepository
override fun onReceive(context: Context?, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
// if have EXTRA_FILE_PATH then need to delete mms cache file
intent.extras?.getString(EXTRA_FILE_PATH)?.let { filePath ->
Timber.v("delete mms temp file $filePath")
File(filePath).delete()
}
if (intent.extras?.getInt(EXTRA_IS_NOTIFY, -1) != -1) {
Timber.v("notify message sent resultcode $resultCode")
return
}
intent.extras?.getLong(EXTRA_QUIK_MESSAGE_ID)?.takeIf { it > 0 }
?.let { messageId ->
Timber.v("resultcode: $resultCode")
val pendingResult = goAsync()
when (pendingResult.resultCode) {
Activity.RESULT_OK ->
markSent.execute(messageId) { pendingResult.finish() }
else -> markFailed.execute(
MarkFailed.Params(messageId, pendingResult.resultCode)
) {
pendingResult.finish()
}
}
} ?: let { Timber.e("couldn't get message id") }
}
}
@@ -1,45 +1,333 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
* Copyright (C) 2015 Jacob Klinker
*
* This file is part of QKSMS.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* QKSMS is free software: you can redistribute it and/or modify
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* modifications from original:
* Copyright (C) 2025
*
* This file is part of QUIK.
*
* QUIK is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* QUIK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
* along with QUIK. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.klinker.android.send_message.MmsReceivedReceiver
import android.os.AsyncTask
import android.os.Parcelable
import android.provider.Telephony
import android.telephony.SmsManager
import androidx.core.net.toUri
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.android.mms.service_alt.DownloadRequest
import com.android.mms.service_alt.MmsConfig
import com.android.mms.service_alt.MmsConfig.Overridden
import com.android.mms.transaction.DownloadManager
import com.google.android.mms.pdu_alt.AcknowledgeInd
import com.google.android.mms.pdu_alt.EncodedStringValue
import com.google.android.mms.pdu_alt.NotificationInd
import com.google.android.mms.pdu_alt.NotifyRespInd
import com.google.android.mms.pdu_alt.PduComposer
import com.google.android.mms.pdu_alt.PduHeaders
import com.google.android.mms.pdu_alt.PduParser
import com.google.android.mms.pdu_alt.PduPersister
import com.google.android.mms.pdu_alt.RetrieveConf
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.MmsSentReceiver
import com.klinker.android.send_message.SmsManagerFactory
import com.klinker.android.send_message.Utils
import dev.octoshrimpy.quik.interactor.ReceiveMms
import dagger.android.AndroidInjection
import javax.inject.Inject
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_FILE_PATH
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_LOCATION_URL
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_MMS_HTTP_STATUS
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_URI
import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_SUBSCRIPTION_ID
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.UUID
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class MmsReceivedReceiver : MmsReceivedReceiver() {
class MmsReceivedReceiver : BroadcastReceiver() {
companion object {
const val EXTRA_FILE_PATH: String = "file_path"
const val EXTRA_LOCATION_URL: String = "location_url"
const val EXTRA_URI: String = "notification_ind_uri"
const val SUBSCRIPTION_ID: String = "subscription_id"
@Inject lateinit var receiveMms: ReceiveMms
private const val LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?"
override fun onReceive(context: Context?, intent: Intent?) {
AndroidInjection.inject(this, context)
super.onReceive(context, intent)
}
private val RECEIVE_NOTIFICATION_EXECUTOR: ExecutorService =
Executors.newSingleThreadExecutor()
override fun onMessageReceived(messageUri: Uri?) {
messageUri?.let { uri ->
val pendingResult = goAsync()
receiveMms.execute(uri) { pendingResult.finish() }
private fun getNotificationInd(context: Context, extraUri: String) =
PduPersister.getPduPersister(context).load(extraUri.toUri()) as NotificationInd
fun onReceiveWorker(
context: Context, subscriptionId: Int, filePath: String, locationUrl: String,
mmsHttpStatus: Int, extraUri: String, receiveMms: ReceiveMms
) {
if (filePath.isEmpty()) {
Timber.e("empty file path")
return
}
if (locationUrl.isEmpty()) {
Timber.e("empty location url")
return
}
if (extraUri.isEmpty()) {
Timber.e("empty extra uri")
return
}
Timber.v(filePath)
val downloadFile = File(filePath)
try {
// read file into a bytearray
val mmsData = FileInputStream(downloadFile).use { inputStream ->
val fileLength = downloadFile.length().toInt()
ByteArray(fileLength).let { bytes ->
inputStream.read(bytes, 0, fileLength)
bytes
}
}
Timber.v("response buffered length: ${mmsData.size}")
if (mmsData.isNotEmpty()) {
val notificationTasks =
getNotificationTasks(context, subscriptionId, extraUri, mmsData)
// persist message
val messageUri = DownloadRequest.persist(
context, mmsData, Overridden(MmsConfig(context), null),
locationUrl, subscriptionId, null
)
// run notifiers to notify back to mmsc
Timber.v("running the common async notifier for download")
for (task in notificationTasks)
task.executeOnExecutor(RECEIVE_NOTIFICATION_EXECUTOR)
handleHttpError(context, mmsHttpStatus, locationUrl)
DownloadManager.finishDownload(locationUrl)
// message is 'raw' received, so do quik app processing
if (messageUri != null)
receiveMms.execute(messageUri)
}
else Timber.e("empty mms data")
} catch (e: FileNotFoundException) {
Timber.e("file not found", e)
} catch (e: IOException) {
Timber.e("io exception", e)
} finally {
downloadFile.delete()
}
}
private fun handleHttpError(context: Context, mmsHttpStatus: Int, locationUrl: String) {
if ((mmsHttpStatus == 404) || (mmsHttpStatus == 400)) {
// Delete the corresponding NotificationInd
SqliteWrapper.delete(
context, context.contentResolver, Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
arrayOf(
PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND.toString(),
locationUrl
)
)
}
}
private abstract class CommonAsyncTask(
protected val mContext: Context, private val subscriptionId: Int,
protected val mNotificationInd: NotificationInd
) : AsyncTask<Void?, Void?, Void?>() {
fun sendPdu(pduBytes: ByteArray) {
// write pdu bytes to temporary file
val fileName = "send.notify.${UUID.randomUUID()}.dat"
val contentUri = Uri.Builder()
.authority("${mContext.packageName}.MmsFileProvider")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build()
try {
FileOutputStream(File(mContext.cacheDir, fileName)).use { outputStream ->
outputStream.write(pduBytes)
}
Timber.v("notify send file $fileName")
} catch (e: Exception) {
Timber.e("error writing notify send file", e)
}
val useWapMmsc = com.android.mms.MmsConfig.getNotifyWapMMSC()
if (useWapMmsc)
Timber.v("using content location for wap mmsc")
SmsManagerFactory.createSmsManager(subscriptionId).sendMultimediaMessage(
mContext, contentUri,
if (useWapMmsc) String(mNotificationInd.contentLocation)
else null,
null,
PendingIntent.getBroadcast(
mContext, 0,
Intent(mContext, MessageSentReceiver::class.java)
.putExtra(MmsSentReceiver.EXTRA_FILE_PATH, fileName)
.putExtra(MessageSentReceiver.EXTRA_IS_NOTIFY, 1),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
}
private class NotifyRespTask(context: Context, subscriptionId: Int, ind: NotificationInd) :
CommonAsyncTask(context, subscriptionId, ind) {
override fun doInBackground(vararg params: Void?): Void? {
// Create the M-NotifyResp.ind
Timber.v("create m-notifyresp.ind")
try {
val notifyRespInd = NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.transactionId,
PduHeaders.STATUS_RETRIEVED
)
// Pack M-NotifyResp.ind and send it
sendPdu(PduComposer(mContext, notifyRespInd).make())
} catch (e: Exception) {
Timber.e("error creating m-notifyresp.ind", e)
}
return null
}
}
private class AcknowledgeIndTask(
context: Context, subscriptionId: Int, ind: NotificationInd,
private val mRetrieveConf: RetrieveConf
) : CommonAsyncTask(context, subscriptionId, ind) {
override fun doInBackground(vararg params: Void?): Void? {
// Send M-Acknowledge.ind to MMSC if required.
// If the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK.
Timber.v("create m-acknowledge.ind")
mRetrieveConf.transactionId?.let { tranId ->
// Create M-Acknowledge.ind
try {
val acknowledgeInd = AcknowledgeInd(PduHeaders.CURRENT_MMS_VERSION, tranId)
// insert the 'from' address per spec
acknowledgeInd.from = EncodedStringValue(
Utils.getMyPhoneNumber(mContext).orEmpty()
)
// Pack M-Acknowledge.ind and send it
sendPdu(PduComposer(mContext, acknowledgeInd).make())
} catch (e: Exception) {
Timber.e("error creating m-acknowledge.ind", e)
}
} ?: let { Timber.e("no transaction id for creating m-acknowledge.ind") }
return null
}
}
private fun getNotificationTasks(
context: Context, subscriptionId: Int, extraUri: String, mmsData: ByteArray
): List<CommonAsyncTask> {
val pdu = PduParser(
mmsData,
Overridden(MmsConfig(context), null).supportMmsContentDisposition
).parse()
if (pdu is RetrieveConf) {
try {
Timber.v("create notification tasks")
return getNotificationInd(context, extraUri).let { notificationInd ->
listOf(
AcknowledgeIndTask(context, subscriptionId, notificationInd, pdu),
NotifyRespTask(context, subscriptionId, notificationInd)
)
}
} catch (e: Exception) {
Timber.e("error get notification tasks", e)
}
} else
Timber.e("MmsReceivedReceiver.sendNotification failed to parse pdu")
return listOf()
}
}
override fun onReceive(context: Context, intent: Intent) {
Timber.v("mms downloaded, persisting it to the database with worker")
// start worker with message id as param
WorkManager.getInstance(context).enqueue(
OneTimeWorkRequestBuilder<ReceiveMmsWorker>()
.setInputData(
workDataOf(
INPUT_DATA_SUBSCRIPTION_ID to intent.getIntExtra(
SUBSCRIPTION_ID,
Utils.getDefaultSubscriptionId()
),
INPUT_DATA_EXTRA_FILE_PATH to intent.getStringExtra(EXTRA_FILE_PATH),
INPUT_DATA_EXTRA_LOCATION_URL to intent.getStringExtra(EXTRA_LOCATION_URL),
INPUT_DATA_EXTRA_MMS_HTTP_STATUS to intent.getIntExtra(
SmsManager.EXTRA_MMS_HTTP_STATUS,
0
),
INPUT_DATA_EXTRA_URI to
(intent.getParcelableExtra<Parcelable>(EXTRA_URI) as Uri?)?.toString()
)
)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
)
}
}
@@ -1,93 +0,0 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Telephony
import com.google.android.mms.MmsException
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.Transaction
import dev.octoshrimpy.quik.interactor.SyncMessage
import dagger.android.AndroidInjection
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class MmsSentReceiver : BroadcastReceiver() {
@Inject lateinit var syncMessage: SyncMessage
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("MMS sending result: $resultCode")
val uri = Uri.parse(intent.getStringExtra(Transaction.EXTRA_CONTENT_URI))
Timber.v(uri.toString())
when (resultCode) {
Activity.RESULT_OK -> {
Timber.v("MMS has finished sending, marking it as so in the database")
val values = ContentValues(1)
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT)
SqliteWrapper.update(context, context.contentResolver, uri, values, null, null)
}
else -> {
Timber.v("MMS has failed to send, marking it as so in the database")
try {
val messageId = ContentUris.parseId(uri)
val values = ContentValues(1)
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_FAILED)
SqliteWrapper.update(context, context.contentResolver, Telephony.Mms.CONTENT_URI, values,
"${Telephony.Mms._ID} = ?", arrayOf(messageId.toString()))
// TODO this query isn't able to find any results
// Need to figure out why the message isn't appearing in the PendingMessages Uri,
// so that we can properly assign the error type
val errorTypeValues = ContentValues(1)
errorTypeValues.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE,
Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT)
SqliteWrapper.update(context, context.contentResolver, Telephony.MmsSms.PendingMessages.CONTENT_URI,
errorTypeValues, "${Telephony.MmsSms.PendingMessages.MSG_ID} = ?",
arrayOf(messageId.toString()))
} catch (e: MmsException) {
e.printStackTrace()
}
}
}
val filePath = intent.getStringExtra(Transaction.EXTRA_FILE_PATH)
Timber.v(filePath)
File(filePath).delete()
Uri.parse(intent.getStringExtra("content_uri"))?.let { uri ->
val pendingResult = goAsync()
syncMessage.execute(uri) { pendingResult.finish() }
}
}
}
@@ -20,4 +20,4 @@ package dev.octoshrimpy.quik.receiver
import com.android.mms.transaction.PushReceiver
class MmsReceiver : PushReceiver()
class MmsWapPushReceiver : PushReceiver()
@@ -24,18 +24,17 @@ import android.content.Intent
import androidx.core.app.RemoteInput
import dev.octoshrimpy.quik.compat.SubscriptionManagerCompat
import dev.octoshrimpy.quik.interactor.MarkRead
import dev.octoshrimpy.quik.interactor.SendMessage
import dev.octoshrimpy.quik.interactor.SendNewMessage
import dev.octoshrimpy.quik.repository.ConversationRepository
import dev.octoshrimpy.quik.repository.MessageRepository
import dagger.android.AndroidInjection
import javax.inject.Inject
class RemoteMessagingReceiver : BroadcastReceiver() {
@Inject lateinit var conversationRepo: ConversationRepository
@Inject lateinit var markRead: MarkRead
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var sendNewMessage: SendNewMessage
@Inject lateinit var subscriptionManager: SubscriptionManagerCompat
override fun onReceive(context: Context, intent: Intent) {
@@ -45,16 +44,23 @@ class RemoteMessagingReceiver : BroadcastReceiver() {
val bundle = intent.extras ?: return
val threadId = bundle.getLong("threadId")
val body = remoteInput.getCharSequence("body").toString()
markRead.execute(listOf(threadId))
val lastMessage = messageRepo.getMessages(threadId).lastOrNull()
val subId = subscriptionManager.activeSubscriptionInfoList
.firstOrNull { it.subscriptionId == lastMessage?.subId }
?.subscriptionId ?: -1
val addresses = conversationRepo.getConversation(threadId)?.recipients?.map { it.address } ?: return
val conversation = conversationRepo.getConversation(threadId)
val pendingRepository = goAsync()
sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body)) { pendingRepository.finish() }
sendNewMessage.execute(
SendNewMessage.Params(
subscriptionManager.activeSubscriptionInfoList
.firstOrNull { it.subscriptionId == lastMessage?.subId }
?.subscriptionId ?: -1,
0,
conversation?.recipients?.map { it.address } ?: return,
remoteInput.getCharSequence("body").toString(),
conversation.sendAsGroup
)
) { pendingRepository.finish() }
}
}
@@ -21,26 +21,31 @@ package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import dev.octoshrimpy.quik.interactor.SyncMessage
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.interactor.ActionDelayedMessage
import timber.log.Timber
import javax.inject.Inject
class MmsUpdatedReceiver : BroadcastReceiver() {
class SendDelayedMessageReceiver : BroadcastReceiver() {
companion object {
const val URI = "uri"
const val MESSAGE_ID_EXTRA = "messageId"
}
@Inject lateinit var syncMessage: SyncMessage
@Inject lateinit var actionDelayedMessage: ActionDelayedMessage
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
intent.getStringExtra(URI)?.let { uriString ->
val pendingResult = goAsync()
syncMessage.execute(Uri.parse(uriString)) { pendingResult.finish() }
}
Timber.v("received")
intent.extras?.getLong(MESSAGE_ID_EXTRA)?.takeIf { it > 0 }
?.let { messageId ->
val result = goAsync()
actionDelayedMessage.execute(
ActionDelayedMessage.Params(messageId, ActionDelayedMessage.Action.Send)
) { result.finish() }
}
}
}
}
@@ -24,6 +24,7 @@ import android.content.Intent
import dev.octoshrimpy.quik.interactor.SendScheduledMessage
import dev.octoshrimpy.quik.repository.MessageRepository
import dagger.android.AndroidInjection
import timber.log.Timber
import javax.inject.Inject
class SendScheduledMessageReceiver : BroadcastReceiver() {
@@ -34,6 +35,8 @@ class SendScheduledMessageReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("received")
intent.getLongExtra("id", -1L).takeIf { it >= 0 }?.let { id ->
val result = goAsync()
sendScheduledMessage.execute(id) { result.finish() }
@@ -1,43 +0,0 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dev.octoshrimpy.quik.interactor.RetrySending
import dev.octoshrimpy.quik.repository.MessageRepository
import dagger.android.AndroidInjection
import javax.inject.Inject
class SendSmsReceiver : BroadcastReceiver() {
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var retrySending: RetrySending
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val messageId = intent.getLongExtra("id", -1L).takeIf { it >= 0 } ?: return
val result = goAsync()
retrySending.execute(messageId) { result.finish() }
}
}
@@ -43,13 +43,11 @@ class SmsProviderChangedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
// Obtain the uri for the changed data
// If the value is null, don't continue
val uri = intent.data ?: return
// Sync the message to our realm
val pendingResult = goAsync()
syncMessage.execute(uri) { pendingResult.finish() }
syncMessage.execute(SyncMessage.Params(intent.data ?: return)) {
pendingResult.finish()
}
}
}
@@ -35,7 +35,7 @@ import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import javax.inject.Inject
class SmsReceiver : BroadcastReceiver() {
class SmsReceivedReceiver : BroadcastReceiver() {
@Inject lateinit var messageRepo: MessageRepository
override fun onReceive(context: Context, intent: Intent) {
@@ -1,53 +0,0 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dev.octoshrimpy.quik.interactor.MarkFailed
import dev.octoshrimpy.quik.interactor.MarkSent
import dagger.android.AndroidInjection
import javax.inject.Inject
class SmsSentReceiver : BroadcastReceiver() {
@Inject lateinit var markSent: MarkSent
@Inject lateinit var markFailed: MarkFailed
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val id = intent.getLongExtra("id", 0L)
when (resultCode) {
Activity.RESULT_OK -> {
val pendingResult = goAsync()
markSent.execute(id) { pendingResult.finish() }
}
else -> {
val pendingResult = goAsync()
markFailed.execute(MarkFailed.Params(id, resultCode)) { pendingResult.finish() }
}
}
}
}
@@ -23,6 +23,7 @@ import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import dagger.android.AndroidInjection
import dev.octoshrimpy.quik.util.nonDebugPackageName
class StartActivityFromWidgetReceiver : BroadcastReceiver() {
// why does this shim class exist rather than the widget launching activities more directly?
@@ -51,7 +52,7 @@ class StartActivityFromWidgetReceiver : BroadcastReceiver() {
}
context.startActivity(
Intent(context, Class.forName(context.packageName + activityToStartName))
Intent(context, Class.forName(nonDebugPackageName(context.packageName) + activityToStartName))
.setFlags(FLAG_ACTIVITY_NEW_TASK)
.putExtra("threadId", intent.getLongExtra("threadId", 0L))
)
@@ -128,7 +128,7 @@ class ContactRepositoryImpl @Inject constructor(
}
}
.map { contacts ->
contacts.sortedWith(Comparator { c1, c2 ->
contacts.sortedWith { c1, c2 ->
val initial = c1.name.firstOrNull()
val other = c2.name.firstOrNull()
if (initial?.isLetter() == true && other?.isLetter() != true) {
@@ -138,7 +138,7 @@ class ContactRepositoryImpl @Inject constructor(
} else {
c1.name.compareTo(c2.name, ignoreCase = true)
}
})
}
}
}
@@ -41,6 +41,7 @@ import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Case
import io.realm.Realm
import io.realm.RealmQuery
import io.realm.RealmResults
import io.realm.Sort
import java.util.concurrent.TimeUnit
@@ -53,17 +54,20 @@ class ConversationRepositoryImpl @Inject constructor(
private val cursorToRecipient: CursorToRecipient,
private val phoneNumberUtils: PhoneNumberUtils
) : ConversationRepository {
override fun getConversations(unreadAtTop: Boolean, archived: Boolean): RealmResults<Conversation> {
val sortOrder: MutableList<String> = arrayListOf("pinned", "draft", "lastMessage.date")
val sortDirections: MutableList<Sort> = arrayListOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
private fun getConversationsBase(
realm: Realm,
unreadAtTop: Boolean,
archived: Boolean
): RealmQuery<Conversation> {
val sortOrder = mutableListOf("pinned", "draft", "lastMessage.date")
val sortDirections = mutableListOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
if (unreadAtTop) {
sortOrder.add(0, "lastMessage.read")
sortDirections.add(0, Sort.ASCENDING)
}
return Realm.getDefaultInstance()
return realm
.where(Conversation::class.java)
.notEqualTo("id", 0L)
.equalTo("archived", archived)
@@ -74,39 +78,22 @@ class ConversationRepositoryImpl @Inject constructor(
.or()
.isNotEmpty("draft")
.endGroup()
.sort(
sortOrder.toTypedArray(),
sortDirections.toTypedArray()
)
.findAllAsync()
.sort(sortOrder.toTypedArray(), sortDirections.toTypedArray())
}
override fun getConversationsSnapshot(unreadAtTop: Boolean): List<Conversation> {
val sortOrder: MutableList<String> = arrayListOf("pinned", "draft", "lastMessage.date")
val sortDirections: MutableList<Sort> = arrayListOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
override fun getConversations(
unreadAtTop: Boolean,
archived: Boolean
): RealmResults<Conversation> =
getConversationsBase(Realm.getDefaultInstance(), unreadAtTop, archived)
.findAllAsync()
if (unreadAtTop) {
sortOrder.add(0, "lastMessage.read")
sortDirections.add(0, Sort.ASCENDING)
}
return Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.notEqualTo("id", 0L)
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.beginGroup()
.isNotNull("lastMessage")
.or()
.isNotEmpty("draft")
.endGroup()
.sort(sortOrder.toTypedArray(), sortDirections.toTypedArray())
override fun getConversationsSnapshot(unreadAtTop: Boolean): List<Conversation> =
Realm.getDefaultInstance().use { realm ->
getConversationsBase(realm, unreadAtTop, false)
.findAll()
.let(realm::copyFromRealm)
}
}
override fun getTopConversations() =
Realm.getDefaultInstance().use { realm ->
@@ -116,34 +103,42 @@ class ConversationRepositoryImpl @Inject constructor(
.beginGroup()
.equalTo("pinned", true)
.or()
.greaterThan("lastMessage.date", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
.greaterThan(
"lastMessage.date",
System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7)
)
.endGroup()
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.findAll()
.let(realm::copyFromRealm)
.sortedWith(compareByDescending<Conversation> { conversation -> conversation.pinned }
.sortedWith(compareByDescending<Conversation> {
conversation -> conversation.pinned
}
.thenByDescending { conversation ->
realm.where(Message::class.java)
.equalTo("threadId", conversation.id)
.greaterThan("date", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
.greaterThan(
"date",
System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7)
)
.count()
}
}
)
}
override fun setConversationName(id: Long, name: String) =
Completable.fromAction {
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.where(Conversation::class.java)
.equalTo("id", id)
.findFirst()
?.name = name
}
override fun setConversationName(id: Long, name: String) =
Completable.fromAction {
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.where(Conversation::class.java)
.equalTo("id", id)
.findFirst()
?.name = name
}
}.subscribeOn(Schedulers.io()) // Ensure the operation is performed on a background thread
}
}.subscribeOn(Schedulers.io()) // Ensure the operation is performed on a background thread
override fun searchConversations(query: CharSequence): List<SearchResult> {
val realm = Realm.getDefaultInstance()
@@ -166,7 +161,6 @@ class ConversationRepositoryImpl @Inject constructor(
.contains("parts.text", normalizedQuery, Case.INSENSITIVE)
.endGroup()
.findAll())
.asSequence()
.groupBy { message -> message.threadId }
.filter { (threadId, _) -> conversations.firstOrNull { it.id == threadId } != null }
.map { (threadId, messages) -> Pair(conversations.first { it.id == threadId }, messages.size) }
@@ -179,7 +173,7 @@ class ConversationRepositoryImpl @Inject constructor(
return conversations
.filter { conversation -> conversationFilter.filter(conversation, normalizedQuery) }
.map {
conversation -> SearchResult(normalizedQuery, conversation, 0)
conversation -> SearchResult(normalizedQuery, conversation, 0)
} + messagesByConversation
}
@@ -210,11 +204,25 @@ class ConversationRepositoryImpl @Inject constructor(
.findFirstAsync()
override fun getConversation(threadId: Long) =
Realm.getDefaultInstance()
.apply { refresh() }
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
tryOrNull(true) {
Realm.getDefaultInstance()
.apply { refresh() }
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
}
override fun updateSendAsGroup(threadId: Long, sendAsGroup: Boolean) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
?.let { conversation ->
realm.executeTransaction { conversation.sendAsGroup = sendAsGroup }
}
}
override fun getUnseenIds(archived: Boolean) =
ArrayList<Long>().apply {
@@ -291,7 +299,7 @@ class ConversationRepositoryImpl @Inject constructor(
override fun getRecipients(): RealmResults<Recipient> =
Realm.getDefaultInstance()
.where(Recipient::class.java)
.findAll()
.findAll()
override fun getUnmanagedRecipients(): Observable<List<Recipient>> =
Realm.getDefaultInstance().let { realm ->
@@ -310,38 +318,32 @@ class ConversationRepositoryImpl @Inject constructor(
.equalTo("id", recipientId)
.findFirst()
override fun getConversation(recipient: String) =
getConversation(listOf(recipient))
override fun getOrCreateConversation(threadId: Long, sendAsGroup: Boolean) =
getConversation(threadId) ?: createConversation(threadId, sendAsGroup)
override fun getConversation(recipients: Collection<String>) =
Realm.getDefaultInstance().use { realm ->
override fun createConversation(threadId: Long, sendAsGroup: Boolean) =
createConversationFromCp(threadId, sendAsGroup)
override fun getConversation(addresses: Collection<String>) =
Realm.getDefaultInstance().let { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.findAll()
.asSequence()
.filter { conversation -> conversation.recipients.size == recipients.size }
.filter { conversation -> conversation.recipients.size == addresses.size }
.find { conversation ->
conversation.recipients.map { it.address }.all { address ->
recipients.any { recipient -> phoneNumberUtils.compare(recipient, address) }
conversation.recipients.map { it.address }.all { recipientAddress ->
addresses.any { phoneNumberUtils.compare(it, recipientAddress) }
}
}
}
override fun getOrCreateConversation(threadId: Long) =
tryOrNull(true) {
getConversation(threadId) ?: createConversationFromCp(threadId)
}
override fun createConversation(addresses: Collection<String>, sendAsGroup: Boolean) =
TelephonyCompat.getOrCreateThreadId(context, addresses.toSet())
.takeIf { it != 0L }
?.let { providerThreadId -> createConversationFromCp(providerThreadId, sendAsGroup) }
override fun getOrCreateConversation(address: String) =
getOrCreateConversation(listOf(address))
override fun getOrCreateConversation(addresses: Collection<String>) =
tryOrNull(true) {
getConversation(addresses)
?: tryOrNull { TelephonyCompat.getOrCreateThreadId(context, addresses.toSet()) }
?.takeIf { it != 0L }
?.let { threadId -> getOrCreateConversation(threadId) }
}
override fun getOrCreateConversation(addresses: Collection<String>, sendAsGroup: Boolean) =
getConversation(addresses) ?: createConversation(addresses, sendAsGroup)
override fun saveDraft(threadId: Long, draft: String) =
Realm.getDefaultInstance().use { realm ->
@@ -356,24 +358,31 @@ class ConversationRepositoryImpl @Inject constructor(
}
}
override fun updateConversations(vararg threadIds: Long) =
override fun updateConversations(threadIds: Collection<Long>) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
threadIds.forEach { threadId ->
val conversation = realm
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst() ?: return@forEach
realm.where(Conversation::class.java)
.anyOf("id", threadIds.toLongArray())
.findAll()
?.map { conversation ->
Pair(
conversation,
realm.where(Message::class.java)
.equalTo("threadId", conversation.id)
.sort("date", Sort.DESCENDING)
.findFirst()
)
}
?.let { conversationAndMessages ->
realm.executeTransaction {
conversationAndMessages.forEach { (conversation, message) ->
conversation.lastMessage = message
}
}
}
val message = realm
.where(Message::class.java)
.equalTo("threadId", threadId)
.sort("date", Sort.DESCENDING)
.findFirst()
realm.executeTransaction { conversation.lastMessage = message }
}
Unit
}
override fun markArchived(vararg threadIds: Long) =
@@ -385,10 +394,10 @@ class ConversationRepositoryImpl @Inject constructor(
realm.executeTransaction { conversations.forEach { it.archived = true } }
}
override fun markUnarchived(vararg threadIds: Long) =
override fun markUnarchived(threadIds: Collection<Long>) =
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.anyOf("id", threadIds.toLongArray())
.findAll()
realm.executeTransaction { conversations.forEach { it.archived = false } }
@@ -474,7 +483,7 @@ class ConversationRepositoryImpl @Inject constructor(
* we can return a [Conversation]. On some devices, the ContentProvider won't return the
* conversation unless it contains at least 1 message
*/
private fun createConversationFromCp(threadId: Long) =
private fun createConversationFromCp(threadId: Long, sendAsGroup: Boolean) =
tryOrNull(true) {
cursorToConversation.getConversationsCursor()
?.map(cursorToConversation::map)
@@ -505,6 +514,11 @@ class ConversationRepositoryImpl @Inject constructor(
conversation.apply {
recipients.clear()
recipients.addAll(matchedRecipients)
this.sendAsGroup =
if (recipients.size <= 1) false
else sendAsGroup
lastMessage = realm.where(Message::class.java)
.equalTo("threadId", threadId)
.sort("date", Sort.DESCENDING)
@@ -515,4 +529,5 @@ class ConversationRepositoryImpl @Inject constructor(
}
}
}
}
}
@@ -18,6 +18,7 @@
*/
package dev.octoshrimpy.quik.repository
import com.moez.QKSMS.manager.QkTransaction
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.ContentUris
@@ -35,40 +36,42 @@ import android.telephony.SmsManager
import android.webkit.MimeTypeMap
import androidx.core.content.contentValuesOf
import com.google.android.mms.ContentType
import com.google.android.mms.MMSPart
import com.google.android.mms.pdu_alt.MultimediaMessagePdu
import com.google.android.mms.pdu_alt.PduPersister
import com.klinker.android.send_message.SmsManagerFactory
import com.klinker.android.send_message.StripAccents
import com.klinker.android.send_message.Transaction
import dev.octoshrimpy.quik.common.util.extensions.now
import dev.octoshrimpy.quik.compat.TelephonyCompat
import dev.octoshrimpy.quik.extensions.anyOf
import dev.octoshrimpy.quik.extensions.insertOrUpdate
import dev.octoshrimpy.quik.extensions.isImage
import dev.octoshrimpy.quik.extensions.isVideo
import dev.octoshrimpy.quik.extensions.map
import dev.octoshrimpy.quik.extensions.resourceExists
import dev.octoshrimpy.quik.manager.ActiveConversationManager
import dev.octoshrimpy.quik.manager.KeyManager
import dev.octoshrimpy.quik.mapper.CursorToMessage
import dev.octoshrimpy.quik.mapper.CursorToPart
import dev.octoshrimpy.quik.model.Attachment
import dev.octoshrimpy.quik.model.Conversation
import dev.octoshrimpy.quik.model.Message
import dev.octoshrimpy.quik.model.Message.Companion.TYPE_MMS
import dev.octoshrimpy.quik.model.Message.Companion.TYPE_SMS
import dev.octoshrimpy.quik.model.MmsPart
import dev.octoshrimpy.quik.receiver.SendSmsReceiver
import dev.octoshrimpy.quik.receiver.SmsDeliveredReceiver
import dev.octoshrimpy.quik.receiver.SmsSentReceiver
import dev.octoshrimpy.quik.receiver.MessageDeliveredReceiver
import dev.octoshrimpy.quik.receiver.MessageSentReceiver
import dev.octoshrimpy.quik.receiver.SendDelayedMessageReceiver
import dev.octoshrimpy.quik.receiver.SendDelayedMessageReceiver.Companion.MESSAGE_ID_EXTRA
import dev.octoshrimpy.quik.util.ImageUtils
import dev.octoshrimpy.quik.util.PhoneNumberUtils
import dev.octoshrimpy.quik.util.Preferences
import dev.octoshrimpy.quik.util.tryOrNull
import io.realm.Case
import io.realm.Realm
import io.realm.RealmList
import io.realm.RealmResults
import io.realm.Sort
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.collections.ArrayList
import kotlin.math.sqrt
@Singleton
@@ -78,7 +81,8 @@ open class MessageRepositoryImpl @Inject constructor(
private val messageIds: KeyManager,
private val phoneNumberUtils: PhoneNumberUtils,
private val prefs: Preferences,
private val syncRepository: SyncRepository,
private val cursorToMessage: CursorToMessage,
private val cursorToPart: CursorToPart,
) : MessageRepository {
companion object {
@@ -108,13 +112,25 @@ open class MessageRepositoryImpl @Inject constructor(
override fun getMessagesSync(threadId: Long, query: String): RealmResults<Message> =
getMessagesBase(threadId, query).findAll()
override fun getMessage(id: Long) =
override fun getMessage(messageId: Long) =
Realm.getDefaultInstance()
.also { it.refresh() }
.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
override fun getUnmanagedMessage(messageId: Long) =
Realm.getDefaultInstance().use { realm ->
getMessage(messageId)?.let(realm::copyFromRealm)
}
override fun getMessages(messageIds: Collection<Long>): RealmResults<Message> =
Realm.getDefaultInstance()
.also { it.refresh() }
.where(Message::class.java)
.anyOf("id", messageIds.toLongArray())
.findAll()
override fun getMessageForPart(id: Long) =
Realm.getDefaultInstance()
.where(Message::class.java)
@@ -127,12 +143,12 @@ open class MessageRepositoryImpl @Inject constructor(
.equalTo("threadId", threadId)
.beginGroup()
.beginGroup()
.equalTo("type", "sms")
.equalTo("type", TYPE_SMS)
.`in`("boxId", arrayOf(Sms.MESSAGE_TYPE_INBOX, Sms.MESSAGE_TYPE_ALL))
.endGroup()
.or()
.beginGroup()
.equalTo("type", "mms")
.equalTo("type", TYPE_MMS)
.`in`("boxId", arrayOf(Mms.MESSAGE_BOX_INBOX, Mms.MESSAGE_BOX_ALL))
.endGroup()
.endGroup()
@@ -197,6 +213,7 @@ open class MessageRepositoryImpl @Inject constructor(
part.isVideo() -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ->
MediaStore.Downloads.EXTERNAL_CONTENT_URI
else -> MediaStore.Files.getContentUri("external")
}
@@ -277,26 +294,20 @@ open class MessageRepositoryImpl @Inject constructor(
threadIds.chunked(TELEPHONY_UPDATE_CHUNK_SIZE).forEach {
// chunked for smaller where clause size
val values = contentValuesOf(Sms.SEEN to seen)
val whereClause ="${Sms.SEEN} = ${if (seen) 0 else 1} " +
val whereClause = "${Sms.SEEN} = ${if (seen) 0 else 1} " +
"and ${Sms.THREAD_ID} in (${it.joinToString(",")})"
// sms messages
tryOrNull(true) {
countUpdated += context.contentResolver.update(
Sms.CONTENT_URI,
values,
whereClause,
null
Sms.CONTENT_URI, values, whereClause, null
)
}
// mms messages
tryOrNull(true) {
countUpdated += context.contentResolver.update(
Mms.CONTENT_URI,
values,
whereClause,
null
Mms.CONTENT_URI, values, whereClause, null
)
}
}
@@ -325,10 +336,10 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
override fun markSeen(threadId: Long) =
override fun markSeen(threadIds: Collection<Long>) =
Realm.getDefaultInstance().use { realm ->
realm.where(Message::class.java)
.equalTo("threadId", threadId)
.anyOf("threadId", threadIds.toLongArray())
.equalTo("seen", false)
.findAll()
.let { messages ->
@@ -337,7 +348,7 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
}.run {
telephonyMarkSeenRead(true, null, listOf(threadId))
telephonyMarkSeenRead(true, null, threadIds)
}
override fun markRead(threadIds: Collection<Long>) =
@@ -358,7 +369,7 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
}.run {
telephonyMarkSeenRead(true, true, threadIds)
telephonyMarkSeenRead(seen = true, read = true, threadIds = threadIds)
}
}
?: 0
@@ -381,67 +392,70 @@ open class MessageRepositoryImpl @Inject constructor(
}
?: 0
override fun sendMessage(
subId: Int,
threadId: Long,
addresses: Collection<String>,
body: String,
attachments: Collection<Attachment>,
delay: Int
) {
val signedBody = when {
prefs.signature.get().isEmpty() -> body
body.isNotEmpty() -> body + '\n' + prefs.signature.get()
else -> prefs.signature.get()
private fun syncProviderMessage(uri: Uri, sendAsGroup: Boolean): Message? {
// if uri doesn't have valid type
val type = when {
uri.toString().contains(TYPE_MMS) -> TYPE_MMS
uri.toString().contains(TYPE_SMS) -> TYPE_SMS
else -> return null
}
val smsManager = subId.takeIf { it != -1 }
?.let(SmsManagerFactory::createSmsManager)
?: SmsManager.getDefault()
// if uri doesn't have a valid id, fail
val contentId = tryOrNull(false) { ContentUris.parseId(uri) } ?: return null
// We only care about stripping SMS
val strippedBody = when (prefs.unicode.get()) {
true -> StripAccents.stripAccents(signedBody)
false -> signedBody
val stableUri = when (type) {
TYPE_MMS -> ContentUris.withAppendedId(Mms.CONTENT_URI, contentId)
else -> ContentUris.withAppendedId(Sms.CONTENT_URI, contentId)
}
val parts = smsManager.divideMessage(strippedBody).orEmpty()
val forceMms = prefs.longAsMms.get() && parts.size > 1
return context.contentResolver.query(
stableUri, null, null, null, null
)?.use { cursor ->
// if there are no rows, return null. else, move to the first row
if (!cursor.moveToFirst())
return null
if (addresses.size == 1 && attachments.isEmpty() && !forceMms) { // SMS
if (delay > 0) { // With delay
val sendTime = System.currentTimeMillis() + delay
val message = insertSentSms(
subId,
threadId,
addresses.first(),
strippedBody,
sendTime
)
cursorToMessage.map(Pair(cursor, CursorToMessage.MessageColumns(cursor))).apply {
this.sendAsGroup = sendAsGroup
val intent = getIntentForDelayedSms(message.id)
if (isMms()) {
parts = RealmList<MmsPart>().apply {
addAll(
cursorToPart.getPartsCursor(contentId)
?.map { cursorToPart.map(it) }
.orEmpty()
)
}
}
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, sendTime, intent)
} else { // No delay
val message = insertSentSms(
subId,
threadId,
addresses.first(),
strippedBody, now()
)
sendSms(message)
insertOrUpdate()
}
} else { // MMS
val parts = arrayListOf<MMSPart>()
}
}
override fun sendNewMessages(
subId: Int, toAddresses: Collection<String>, body: String,
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int
): Collection<Message> {
Timber.v("sending message(s)")
val parts = mutableListOf<com.google.android.mms.MMSPart>()
if (attachments.isNotEmpty()) {
Timber.v("has attachments")
val smsManager = subId.takeIf { it != -1 }
?.let(SmsManagerFactory::createSmsManager)
?: SmsManager.getDefault()
val maxWidth = smsManager.carrierConfigValues
.getInt(SmsManager.MMS_CONFIG_MAX_IMAGE_WIDTH)
.takeIf { prefs.mmsSize.get() == -1 } ?: Int.MAX_VALUE
.takeIf { prefs.mmsSize.get() == -1 }
?: Int.MAX_VALUE
val maxHeight = smsManager.carrierConfigValues
.getInt(SmsManager.MMS_CONFIG_MAX_IMAGE_HEIGHT)
.takeIf { prefs.mmsSize.get() == -1 } ?: Int.MAX_VALUE
.takeIf { prefs.mmsSize.get() == -1 }
?: Int.MAX_VALUE
var remainingBytes = when (prefs.mmsSize.get()) {
-1 -> smsManager.carrierConfigValues.getInt(SmsManager.MMS_CONFIG_MAX_MESSAGE_SIZE)
@@ -449,10 +463,7 @@ open class MessageRepositoryImpl @Inject constructor(
else -> prefs.mmsSize.get() * 1024
} * 0.9 // Ugly, but buys us a bit of wiggle room
signedBody.takeIf { it.isNotEmpty() }?.toByteArray()?.let { bytes ->
remainingBytes -= bytes.size
parts += MMSPart("text", ContentType.TEXT_PLAIN, bytes)
}
remainingBytes -= body.takeIf { it.isNotEmpty() }?.toByteArray()?.size ?: 0
// Attach those that can't be compressed (ie. everything but images)
parts += attachments
@@ -462,16 +473,16 @@ open class MessageRepositoryImpl @Inject constructor(
.filter { it.uri.resourceExists(context) }
.map {
remainingBytes -= it.getResourceBytes(context).size
val mmsPart = MMSPart(
it.getName(context),
it.getType(context),
it.getResourceBytes(context)
)
val part = com.google.android.mms.MMSPart().apply {
MimeType = it.getType(context)
Name = it.getName(context)
Data = it.getResourceBytes(context)
}
// release the attachment hold on the image bytes so the GC can reclaim
it.releaseResourceBytes()
mmsPart
part
}
val imageBytesByAttachment = attachments
@@ -512,8 +523,11 @@ open class MessageRepositoryImpl @Inject constructor(
// too big, we'll need to try smaller and smaller values
val scale = maxBytes / originalBytes.size * (0.9 - attempts * 0.2)
if (scale <= 0) {
Timber.w("Failed to compress ${originalBytes.size / 1024
}Kb to ${maxBytes.toInt() / 1024}Kb")
Timber.w(
"Failed to compress ${
originalBytes.size / 1024
}Kb to ${maxBytes.toInt() / 1024}Kb"
)
return@forEach
}
@@ -524,243 +538,200 @@ open class MessageRepositoryImpl @Inject constructor(
attempts++
scaledBytes = when (attachment.getType(context) == "image/gif") {
true -> ImageUtils.getScaledGif(
context,
attachment.uri,
newWidth,
newHeight
context, attachment.uri, newWidth, newHeight
)
false -> ImageUtils.getScaledImage(
context,
attachment.uri,
newWidth,
newHeight
context, attachment.uri, newWidth, newHeight
)
}
Timber.d("Compression attempt $attempts: ${scaledBytes.size / 1024
}/${maxBytes.toInt() / 1024}Kb ($width*$height -> $newWidth*${
newHeight})")
Timber.d(
"Compression attempt $attempts: ${
scaledBytes.size / 1024
}/${maxBytes.toInt() / 1024}Kb ($width*$height -> $newWidth*${
newHeight
})"
)
// release the attachment hold on the image bytes so the GC can reclaim
attachment.releaseResourceBytes()
}
Timber.v("Compressed ${originalBytes.size / 1024}Kb to ${
scaledBytes.size / 1024}Kb with a target size of ${
maxBytes.toInt() / 1024}Kb in $attempts attempts")
Timber.v(
"Compressed ${originalBytes.size / 1024}Kb to ${
scaledBytes.size / 1024
}Kb with a target size of ${
maxBytes.toInt() / 1024
}Kb in $attempts attempts"
)
imageBytesByAttachment[attachment] = scaledBytes
}
}
imageBytesByAttachment.forEach { (attachment, bytes) ->
parts += when (attachment.getType(context) == "image/gif") {
true -> MMSPart(attachment.getName(context), ContentType.IMAGE_GIF, bytes)
false -> MMSPart(attachment.getName(context), ContentType.IMAGE_JPEG, bytes)
parts += com.google.android.mms.MMSPart().apply {
MimeType =
if (attachment.getType(context) == "image/gif") ContentType.IMAGE_GIF
else ContentType.IMAGE_JPEG
Name = attachment.getName(context)
Data = bytes
}
}
}
Timber.v("create os provider message")
// 3 stage sending process - stage 1, create records in os provider
val group = (sendAsGroup && (toAddresses.size > 1))
val messageUri = QkTransaction.createMessage(
context, subId, body, prefs.signature.get(),
toAddresses.map(phoneNumberUtils::normalizeNumber).toTypedArray(),
parts, group, prefs.longAsMms.get(), prefs.unicode.get()
)
if (messageUri == Uri.EMPTY) {
Timber.v("create os provider message failed")
return listOf()
}
val message = syncProviderMessage(messageUri, group)
if (message == null) {
Timber.v("sync message failed for uri $messageUri")
return listOf()
}
Timber.v("created message id ${message.id} from uri $messageUri")
if (delayMs > 0) { // if delaying
val sendTime = (now() + delayMs)
// set delay time on the db message
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.copyToRealmOrUpdate(message.apply { date = sendTime })
}
}
// We need to strip the separators from outgoing MMS, or else they'll appear to have
// sent and not go through
val transaction = Transaction(context)
val recipients = addresses.map(phoneNumberUtils::normalizeNumber)
transaction.sendNewMessage(
subId,
threadId,
recipients,
parts,
null,
null
)
// create alarm that will trigger sending the message
(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager)
.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, sendTime, getIntentForDelayedSms(message.id)
)
Timber.v("set ${delayMs}ms delay for message id ${message.id}")
return listOf(message)
}
// send now (message will be exploded, as required, and all sent)
return sendMessage(message)
}
override fun sendSms(message: Message) {
val smsManager = message.subId.takeIf { it != -1 }
?.let(SmsManagerFactory::createSmsManager)
?: SmsManager.getDefault()
override fun sendMessage(message: Message): Collection<Message> {
val retVal = mutableListOf<Message>()
val parts = smsManager.divideMessage(
if (prefs.unicode.get()) StripAccents.stripAccents(message.body)
else message.body
)
?: arrayListOf()
tryOrNull(true) {
// explode message if needed
val explodedMessages = QkTransaction.explodeMessage(
context, message.getUri(), message.sendAsGroup
).filter { explodedMessageUri -> (explodedMessageUri != Uri.EMPTY) }
try {
smsManager.sendMultipartTextMessage(
message.address,
null,
parts,
ArrayList(
parts.map {
PendingIntent.getBroadcast(
context,
message.id.toInt(),
Intent(context, SmsSentReceiver::class.java)
.putExtra("id", message.id),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
// if multiple messages to send, create each and recurse to send
if (explodedMessages.size > 1) {
explodedMessages.forEach { explodedMessageUri ->
val childMessage = syncProviderMessage(explodedMessageUri, message.sendAsGroup)
if (childMessage != null) {
Timber.v("created message id ${childMessage.id} from uri $explodedMessageUri")
retVal.addAll(sendMessage(childMessage))
}
),
ArrayList(
parts.map {
val pendingIntent = PendingIntent.getBroadcast(
context,
message.id.toInt(),
Intent(context, SmsDeliveredReceiver::class.java)
.putExtra("id", message.id),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
if (prefs.delivery.get()) pendingIntent else null
}
)
)
} catch (e: IllegalArgumentException) {
Timber.w(e, "Message body lengths: ${parts.map { it?.length }}")
markFailed(message.id, Telephony.MmsSms.ERR_TYPE_GENERIC)
}
}
else
Timber.e("sync failed for uri $explodedMessageUri")
}
override fun resendMms(message: Message) =
tryOrNull {
PduPersister.getPduPersister(context).load(message.getUri()) as MultimediaMessagePdu
}
?.let { pdu ->
Transaction(context).sendNewMessage(
message.subId,
message.threadId,
pdu.to.map { it.string }.filter { it.isNotBlank() },
message.parts.mapNotNull { part ->
val bytes = tryOrNull(false) {
context.contentResolver.openInputStream(part.getUri())?.use {
inputStream -> inputStream.readBytes()
}
} ?: return@mapNotNull null
// mark original message as sent
markSent(message.id)
} else {
markSending(message.id)
MMSPart(part.name.orEmpty(), part.type, bytes)
},
message.subject,
message.getUri()
)
// individual message to send, send it
val sentIntent = Intent(context, MessageSentReceiver::class.java)
.putExtra(MessageSentReceiver.EXTRA_QUIK_MESSAGE_ID, message.id)
val deliveryIntent =
if (prefs.delivery.get())
Intent(context, MessageDeliveredReceiver::class.java)
.putExtra(MessageDeliveredReceiver.EXTRA_QUIK_MESSAGE_ID, message.id)
else null
// use values from os provider to resend the message, except subId
if (!QkTransaction.sendMessage(context, message.getUri(), sentIntent, deliveryIntent))
Timber.e("message id ${message.id} not sent by smsmms")
}
?: Unit
override fun cancelDelayedSms(id: Long) =
retVal.add(message)
}
return retVal
}
override fun sendMessage(messageId: Long) =
getMessage(messageId)
?.let { message -> sendMessage(message) }
?: listOf()
override fun cancelDelayedSmsAlarm(messageId: Long) =
(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager)
.cancel(getIntentForDelayedSms(id))
.cancel(getIntentForDelayedSms(messageId))
private fun getIntentForDelayedSms(id: Long) =
private fun getIntentForDelayedSms(messageId: Long) =
PendingIntent.getBroadcast(
context,
id.toInt(),
Intent(context, SendSmsReceiver::class.java).putExtra("id", id),
messageId.toInt(),
Intent(context, SendDelayedMessageReceiver::class.java)
.putExtra(MESSAGE_ID_EXTRA, messageId),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
override fun insertSentSms(
subId: Int,
threadId: Long,
address: String,
body: String,
date: Long
): Message {
// Insert the message to Realm
val message = Message().apply {
this.threadId = threadId
this.address = address
this.body = body
this.date = date
this.subId = subId
override fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long)
: Message {
val threadId = TelephonyCompat.getOrCreateThreadId(context, address)
id = messageIds.newId()
boxId = Sms.MESSAGE_TYPE_OUTBOX
type = "sms"
read = true
seen = true
}
// Insert the message to the native content provider
// insert the message to the native content provider
val values = contentValuesOf(
Sms.ADDRESS to address,
Sms.BODY to body,
Sms.DATE to System.currentTimeMillis(),
Sms.READ to true,
Sms.SEEN to true,
Sms.TYPE to Sms.MESSAGE_TYPE_OUTBOX,
Sms.DATE_SENT to sentTime,
Sms.THREAD_ID to threadId
)
if (prefs.canUseSubId.get())
values.put(Sms.SUBSCRIPTION_ID, message.subId)
values.put(Sms.SUBSCRIPTION_ID, subId)
var uri: Uri?
var managedMessage: Message? = null
val providerContentId = context.contentResolver.insert(Sms.Inbox.CONTENT_URI, values)
?.let { insertedUri -> ContentUris.parseId(insertedUri) }
?: 0
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction { managedMessage = realm.copyToRealmOrUpdate(message) }
// Update the contentId after the message has been inserted to the content provider
// The message might have been deleted by now, so only proceed if it's valid
//
// do this after inserting the message because it might be slow, and we want the message
// to be inserted into Realm immediately. We don't need to do this after receiving one
uri = context.contentResolver.insert(Sms.CONTENT_URI, values)?.apply {
lastPathSegment?.toLong()?.let { id ->
realm.executeTransaction {
managedMessage?.takeIf { it.isValid }?.contentId = id
}
}
}
}
// On some devices, we can't obtain a threadId until after the first message is sent in a
// conversation. In this case, update the message's threadId after it gets added
// to the native ContentProvider
if (threadId == 0L)
uri?.let(syncRepository::syncMessage)
return message
}
override fun insertReceivedSms(
subId: Int,
address: String,
body: String,
sentTime: Long
): Message {
// Insert the message to Realm
// insert the message to Realm
val message = Message().apply {
id = messageIds.newId()
this.address = address
this.body = body
this.dateSent = sentTime
this.date = System.currentTimeMillis()
this.threadId = threadId
this.subId = subId
id = messageIds.newId()
threadId = TelephonyCompat.getOrCreateThreadId(context, address)
date = System.currentTimeMillis()
contentId = providerContentId
boxId = Sms.MESSAGE_TYPE_INBOX
type = "sms"
read = activeConversationManager.getActiveConversation() == threadId
type = TYPE_SMS
read = (activeConversationManager.getActiveConversation() == threadId)
}
// Insert the message to the native content provider
val values = contentValuesOf(
Sms.ADDRESS to address,
Sms.BODY to body,
Sms.DATE_SENT to sentTime
)
if (prefs.canUseSubId.get())
values.put(Sms.SUBSCRIPTION_ID, message.subId)
Realm.getDefaultInstance().use { realm ->
var managedMessage: Message? = null
realm.executeTransaction { managedMessage = realm.copyToRealmOrUpdate(message) }
context.contentResolver.insert(Sms.Inbox.CONTENT_URI, values)
?.lastPathSegment?.toLong()?.let { id ->
// Update contentId after the message has been inserted to the content provider
realm.executeTransaction { managedMessage?.contentId = id }
}
realm.executeTransaction { realm.copyToRealmOrUpdate(message) }
}
return message
@@ -769,12 +740,12 @@ open class MessageRepositoryImpl @Inject constructor(
/**
* Marks the message as sending, in case we need to retry sending it
*/
override fun markSending(id: Long) =
override fun markSending(messageId: Long) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
?.let { message ->
// Update the message in realm
@@ -799,62 +770,112 @@ open class MessageRepositoryImpl @Inject constructor(
Unit
}
override fun markSent(id: Long) =
override fun markSent(messageId: Long) {
Timber.v("mark message id $messageId as sent")
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.findFirst()
realm.where(Message::class.java).equalTo("id", messageId).findFirst()
?.let { message ->
// Update the message in realm
realm.executeTransaction { message.boxId = Sms.MESSAGE_TYPE_SENT }
if (message.isSms()) {
// update the message in realm
realm.executeTransaction { message.boxId = Sms.MESSAGE_TYPE_SENT }
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(Sms.TYPE to Sms.MESSAGE_TYPE_SENT),
null,
null
)
}
Unit
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(Sms.TYPE to Sms.MESSAGE_TYPE_SENT),
null,
null
)
} else {
// update the message in realm
realm.executeTransaction { message.boxId = Mms.MESSAGE_BOX_SENT }
override fun markFailed(id: Long, resultCode: Int) =
Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.findFirst()
?.let { message ->
// Update the message in realm
realm.executeTransaction {
message.boxId = Sms.MESSAGE_TYPE_FAILED
message.errorCode = resultCode
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(Mms.MESSAGE_BOX to Mms.MESSAGE_BOX_SENT),
null,
null
)
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(
Sms.TYPE to Sms.MESSAGE_TYPE_FAILED,
Sms.ERROR_CODE to resultCode,
),
null,
null
)
}
Unit
}
}
override fun markFailed(messageId: Long, resultCode: Int) =
Realm.getDefaultInstance().use { realm ->
Timber.v("mark message id $messageId as failed. code $resultCode")
realm.refresh()
realm.where(Message::class.java).equalTo("id", messageId).findFirst()
?.let { message ->
if (message.isSms()) {
if (message.boxId != Sms.MESSAGE_TYPE_FAILED) {
// Update the message in realm
realm.executeTransaction {
message.boxId = Sms.MESSAGE_TYPE_FAILED
message.errorCode = resultCode
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(
Sms.TYPE to Sms.MESSAGE_TYPE_FAILED,
Sms.ERROR_CODE to resultCode,
),
null,
null
)
true
} else false
} else { // mms
if (message.boxId != Mms.MESSAGE_BOX_FAILED) {
// Update the message in realm
realm.executeTransaction {
message.boxId = Mms.MESSAGE_BOX_FAILED
message.errorCode = resultCode
}
// Update the message in the native ContentProvider
context.contentResolver.update(
message.getUri(),
contentValuesOf(
Mms.MESSAGE_BOX to Mms.MESSAGE_BOX_FAILED
),
null,
null
)
// TODO this query isn't able to find any results
// Need to figure out why the message isn't appearing in the PendingMessages Uri,
// so that we can properly assign the error type
context.contentResolver.update(
Telephony.MmsSms.PendingMessages.CONTENT_URI,
contentValuesOf(
Telephony.MmsSms.PendingMessages.ERROR_TYPE to Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT
),
"${Telephony.MmsSms.PendingMessages.MSG_ID} = ?",
arrayOf(message.id.toString())
)
true
} else false
}
} ?: false
}
override fun markDelivered(id: Long) =
override fun markDelivered(messageId: Long) =
Realm.getDefaultInstance().use { realm ->
Timber.v("mark message id $messageId as delivered")
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
?.let { message ->
// Update the message in realm
@@ -879,12 +900,14 @@ open class MessageRepositoryImpl @Inject constructor(
Unit
}
override fun markDeliveryFailed(id: Long, resultCode: Int) =
override fun markDeliveryFailed(messageId: Long, resultCode: Int) =
Realm.getDefaultInstance().use { realm ->
Timber.v("mark message id $messageId as delivery failed result code $resultCode")
realm.refresh()
realm.where(Message::class.java)
.equalTo("id", id)
.equalTo("id", messageId)
.findFirst()
?.let { message ->
// Update the message in realm
@@ -915,17 +938,18 @@ open class MessageRepositoryImpl @Inject constructor(
Realm.getDefaultInstance().use { realm ->
realm.refresh()
val messages = realm.where(Message::class.java)
realm.where(Message::class.java)
.anyOf("id", messageIds.toLongArray())
.findAll()
?.let { messages ->
messages.mapNotNull { message ->
val uri = message.getUri()
if (uri != Uri.EMPTY)
context.contentResolver.delete(uri, null, null)
}
val uris = messages.map { it.getUri() }
realm.executeTransaction { messages.deleteAllFromRealm() }
uris.forEach {
uri -> context.contentResolver.delete(uri, null, null)
}
realm.executeTransaction { messages.deleteAllFromRealm() }
} ?: Unit
}
override fun getOldMessageCounts(maxAgeDays: Int) =
@@ -958,3 +982,4 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
}
@@ -97,8 +97,4 @@ class ScheduledMessageRepositoryImpl @Inject constructor() : ScheduledMessageRep
}
}
// Ensure to clear disposables when the repository is no longer needed
fun clearDisposables() {
disposables.clear()
}
}
@@ -213,33 +213,39 @@ class SyncRepositoryImpl @Inject constructor(
syncProgress.onNext(SyncRepository.SyncProgress.Idle)
}
override fun syncMessage(uri: Uri): Message? {
override fun syncMessage(uri: Uri, messageId: Long): Message? {
// If we don't have a valid type, return null
val type = when {
uri.toString().contains("mms") -> "mms"
uri.toString().contains("sms") -> "sms"
uri.toString().contains(Message.TYPE_MMS) -> Message.TYPE_MMS
uri.toString().contains(Message.TYPE_SMS) -> Message.TYPE_SMS
else -> return null
}
// If we don't have a valid id, return null
val id = tryOrNull(false) { ContentUris.parseId(uri) } ?: return null
val contentId = tryOrNull(false) { ContentUris.parseId(uri) } ?: return null
// Check if the message already exists, so we can reuse the id
val existingId = Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Message::class.java)
.equalTo("type", type)
.equalTo("contentId", id)
.findFirst()
?.id
.equalTo("type", type)
.equalTo("contentId", contentId)
.or()
.beginGroup()
.equalTo("id", messageId)
.and()
.equalTo("contentId", 0L)
.endGroup()
.findFirst()
?.id
}
// The uri might be something like content://mms/inbox/id
// The box might change though, so we should just use the mms/id uri
val stableUri = when (type) {
"mms" -> ContentUris.withAppendedId(Telephony.Mms.CONTENT_URI, id)
else -> ContentUris.withAppendedId(Telephony.Sms.CONTENT_URI, id)
Message.TYPE_MMS -> ContentUris.withAppendedId(Telephony.Mms.CONTENT_URI, contentId)
else -> ContentUris.withAppendedId(Telephony.Sms.CONTENT_URI, contentId)
}
return contentResolver.query(stableUri, null, null, null, null)?.use { cursor ->
@@ -6,13 +6,11 @@ import android.app.job.JobParameters
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import androidx.core.content.getSystemService
import dev.octoshrimpy.quik.common.util.extensions.jobScheduler
import dev.octoshrimpy.quik.interactor.DeleteOldMessages
import dagger.android.AndroidInjection
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import kotlinx.coroutines.Job
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@@ -20,13 +18,13 @@ import javax.inject.Inject
class AutoDeleteService : JobService() {
companion object {
private const val JobId = 8120235
private const val JOB_ID = 8120235
@SuppressLint("MissingPermission") // Added in [presentation]'s AndroidManifest.xml
fun scheduleJob(context: Context) {
Timber.i("Scheduling job")
val serviceComponent = ComponentName(context, AutoDeleteService::class.java)
val periodicJob = JobInfo.Builder(JobId, serviceComponent)
val periodicJob = JobInfo.Builder(JOB_ID, serviceComponent)
.setPeriodic(TimeUnit.DAYS.toMillis(1))
.setPersisted(true)
.build()
@@ -36,7 +34,7 @@ class AutoDeleteService : JobService() {
fun cancelJob(context: Context) {
Timber.i("Canceling job")
context.jobScheduler.cancel(JobId)
context.jobScheduler.cancel(JOB_ID)
}
}
@@ -22,25 +22,27 @@ import android.app.IntentService
import android.content.Intent
import android.net.Uri
import android.telephony.TelephonyManager
import dev.octoshrimpy.quik.interactor.SendMessage
import dev.octoshrimpy.quik.interactor.SendNewMessage
import dev.octoshrimpy.quik.repository.ConversationRepository
import dagger.android.AndroidInjection
import javax.inject.Inject
class HeadlessSmsSendService : IntentService("HeadlessSmsSendService") {
@Inject lateinit var conversationRepo: ConversationRepository
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var sendNewMessage: SendNewMessage
override fun onHandleIntent(intent: Intent?) {
if (intent?.action != TelephonyManager.ACTION_RESPOND_VIA_MESSAGE) return
AndroidInjection.inject(this)
intent.extras?.getString(Intent.EXTRA_TEXT)?.takeIf { it.isNotBlank() }?.let { body ->
val intentUri = intent.data
val recipients = intentUri?.let(::getRecipients)?.split(";") ?: return@let
val threadId = conversationRepo.getOrCreateConversation(recipients)?.id ?: 0L
sendMessage.execute(SendMessage.Params(-1, threadId, recipients, body))
val recipients = intent.data?.let(::getRecipients)?.split(";") ?: return@let
val conversation = conversationRepo.getOrCreateConversation(recipients)
sendNewMessage.execute(SendNewMessage.Params(
-1, 0, recipients, body, conversation?.sendAsGroup ?: false
))
}
}
@@ -1,7 +0,0 @@
package com.moez.QKSMS.util
class Constants {
companion object {
const val SAVED_MESSAGE_TEXT_FILE_PREFIX = "QuikSmsText-"
}
}
@@ -1,149 +0,0 @@
package dev.octoshrimpy.quik.util
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.contentValuesOf
import androidx.core.net.toFile
import dev.octoshrimpy.quik.extensions.isEmpty
import java.io.File
class FileUtils {
companion object {
enum class Location {
Downloads,
ExternalCache,
Cache,
Files,
Obb,
CodeCache,
NoBackup,
}
fun create(
location: Location,
context: Context,
filename: String,
mimeType: String
) =
if (location == Location.Downloads) createDownloadsFile(context, filename, mimeType)
else createLocation(location, context, filename)
private fun createDownloadsFile(
context: Context,
filename: String,
mimeType: String
): Pair<Uri, Exception?> =
try {
val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // use media store
context.contentResolver.insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
contentValuesOf(
MediaStore.MediaColumns.MIME_TYPE to mimeType,
MediaStore.MediaColumns.RELATIVE_PATH to
Environment.DIRECTORY_DOWNLOADS,
MediaStore.MediaColumns.DISPLAY_NAME to filename,
)
) ?: Uri.EMPTY
} else { // use direct access to 'external' dir
File(Environment.getExternalStorageDirectory(), filename).let {
if (tryOrNull { it.createNewFile() } == true) Uri.fromFile(it)
else Uri.EMPTY
}
}
if (uri.isEmpty())
throw Exception("Opening file returned an empty uri")
Pair(uri, null)
} catch (e: Exception) {
Pair(Uri.EMPTY, e)
}
private fun createLocation(
location: Location,
context: Context,
filename: String
): Pair<Uri, Exception?> =
try {
val uri = File(
when (location) {
Location.ExternalCache -> context.externalCacheDir
Location.Files -> context.filesDir
Location.Obb -> context.obbDir
Location.CodeCache -> context.codeCacheDir
Location.NoBackup -> context.noBackupFilesDir
else -> context.cacheDir
},
filename
).let {
if (tryOrNull { it.createNewFile() } == true) Uri.fromFile(it)
else Uri.EMPTY
}
if (uri.isEmpty())
throw Exception("Opening file returned an empty uri")
Pair(uri, null)
} catch (e: Exception) {
Pair(Uri.EMPTY, e)
}
private fun writeBytes(
context: Context,
uri: Uri,
bytes: ByteArray,
mode: String
): Exception? =
try {
context.contentResolver.openOutputStream(uri, mode)?.use { it.write(bytes) }
null
} catch (e: Exception) {
e
}
fun append(context: Context, uri: Uri, bytes: ByteArray): Exception? =
writeBytes(context, uri, bytes, "wa")
fun write(context: Context, uri: Uri, bytes: ByteArray): Exception? =
writeBytes(context, uri, bytes, "w")
fun truncateAndWrite(context: Context, uri: Uri, bytes: ByteArray): Exception? =
writeBytes(context, uri, bytes, "wt")
fun createAndWrite(
context: Context,
location: Location,
filename: String,
mimeType: String,
bytes: ByteArray
): Pair<Uri, Exception?> =
create(location, context, filename, mimeType).let { (uri, e) ->
if (e is Exception) Pair(Uri.EMPTY, e)
else {
val we = writeBytes(context, uri, bytes, "w")
if (we is Exception) {
deleteFile(uri)
Pair(Uri.EMPTY, we)
}
else
Pair(uri, null)
}
}
fun deleteFile(uri: Uri): Boolean {
return try {
if (uri == Uri.EMPTY) false
else uri.toFile().delete()
}
catch (e: Exception) { false }
}
fun renameTo(fromUri: Uri, toUri: Uri) {
fromUri.toFile().renameTo(toUri.toFile())
}
}
}
@@ -25,7 +25,7 @@ import java.io.File
class QkFileObserver(path: String) : FileObserver(path, CREATE or DELETE or MODIFY) {
private val subject = BehaviorSubject.createDefault<String>(path).toSerialized()
private val subject = BehaviorSubject.createDefault(path).toSerialized()
val observable: Observable<String> = subject
.doOnSubscribe { startWatching() }
@@ -25,9 +25,9 @@ import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.moez.QKSMS.util.Constants
import com.moez.QKSMS.manager.MediaRecorderManager
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import dev.octoshrimpy.quik.util.Constants
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@@ -77,6 +77,8 @@ class HousekeepingWorker(appContext: Context, workerParams: WorkerParameters)
removeSavedMessagesTexts(twoHoursAgo)
removeOrphanedComposeDelayCancelledAttachments(twoHoursAgo)
return Result.success()
}
@@ -87,7 +89,7 @@ class HousekeepingWorker(appContext: Context, workerParams: WorkerParameters)
// remove orphaned scheduled message dirs in files dir
File(applicationContext.filesDir,"")
// get dirs that match prefix 'scheduled-'
.listFiles { entry -> entry.isDirectory && entry.name.startsWith("scheduled-") }
.listFiles { entry -> entry.isDirectory && entry.name.startsWith(Constants.SCHEDULED_MESSAGE_FILE_PREFIX) }
// filter out any dirs that have an associated scheduled message in db
?.filterNot {
scheduledMessageIds.contains(it.name.substringAfter('-').toLong())
@@ -113,4 +115,12 @@ class HousekeepingWorker(appContext: Context, workerParams: WorkerParameters)
(entry.lastModified() < removeOlderThan)
}?.forEach { it.delete() } // delete message text file
private fun removeOrphanedComposeDelayCancelledAttachments(removeOlderThan: Long) =
// find dirs in cache dir
applicationContext.cacheDir.listFiles { entry ->
entry.isDirectory &&
entry.name.startsWith(Constants.DELAY_CANCELLED_CACHED_ATTACHMENTS_FILE_PREFIX)
(entry.lastModified() < removeOlderThan)
}?.forEach { it.deleteRecursively() } // recursively delete dir
}
@@ -23,15 +23,16 @@ import androidx.work.ListenableWorker
import androidx.work.Worker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import dev.octoshrimpy.quik.interactor.ReceiveMms
import dev.octoshrimpy.quik.interactor.ReceiveSms
import dev.octoshrimpy.quik.repository.ScheduledMessageRepository
import javax.inject.Inject
class InjectionWorkerFactory @Inject constructor(
private val receiveSms: ReceiveSms,
private val scheduledMessageRepository: ScheduledMessageRepository
)
: WorkerFactory() {
private val receiveMms: ReceiveMms,
private val scheduledMessageRepository: ScheduledMessageRepository,
) : WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
@@ -44,12 +45,12 @@ class InjectionWorkerFactory @Inject constructor(
.newInstance(appContext, workerParameters)
when (instance) {
is HousekeepingWorker -> {
is HousekeepingWorker ->
instance.scheduledMessageRepository = scheduledMessageRepository
}
is ReceiveSmsWorker -> {
is ReceiveSmsWorker ->
instance.receiveSms = receiveSms
}
is ReceiveMmsWorker ->
instance.receiveMms = receiveMms
}
return instance
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2025
*
* This file is part of QUIK.
*
* QUIK is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QUIK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QUIK. If not, see <http://www.gnu.org/licenses/>.
*/
package dev.octoshrimpy.quik.worker
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import dev.octoshrimpy.quik.interactor.ReceiveMms
import dev.octoshrimpy.quik.receiver.MmsReceivedReceiver
import timber.log.Timber
import javax.inject.Inject
class ReceiveMmsWorker(appContext: Context, workerParams: WorkerParameters)
: Worker(appContext, workerParams) {
companion object {
const val INPUT_DATA_SUBSCRIPTION_ID = "subscriptionId"
const val INPUT_DATA_EXTRA_FILE_PATH = "filePath"
const val INPUT_DATA_EXTRA_LOCATION_URL = "locationUrl"
const val INPUT_DATA_EXTRA_MMS_HTTP_STATUS = "mmsHttpStatus"
const val INPUT_DATA_EXTRA_URI = "extraUri"
}
@Inject lateinit var receiveMms: ReceiveMms
override fun doWork(): Result {
Timber.v("started")
MmsReceivedReceiver.onReceiveWorker(
applicationContext,
inputData.getInt(INPUT_DATA_SUBSCRIPTION_ID, -1),
inputData.getString(INPUT_DATA_EXTRA_FILE_PATH) ?: "",
inputData.getString(INPUT_DATA_EXTRA_LOCATION_URL) ?: "",
inputData.getInt(INPUT_DATA_EXTRA_MMS_HTTP_STATUS, 0),
inputData.getString(INPUT_DATA_EXTRA_URI) ?: "",
receiveMms
)
Timber.v("finished")
return Result.success()
}
}