work with threadIds as Longs, not Ints

This commit is contained in:
tibbi 2020-12-21 20:01:57 +01:00
parent e357b4a659
commit 6405b7431f
12 changed files with 56 additions and 59 deletions

View File

@ -193,20 +193,20 @@ class MainActivity : SimpleActivity() {
}
conversations.forEach { clonedConversation ->
if (!cachedConversations.map { it.thread_id }.contains(clonedConversation.thread_id)) {
if (!cachedConversations.map { it.threadId }.contains(clonedConversation.threadId)) {
conversationsDB.insertOrUpdate(clonedConversation)
cachedConversations.add(clonedConversation)
}
}
cachedConversations.forEach { cachedConversation ->
if (!conversations.map { it.thread_id }.contains(cachedConversation.thread_id)) {
if (!conversations.map { it.threadId }.contains(cachedConversation.threadId)) {
conversationsDB.delete(cachedConversation.id!!)
}
}
cachedConversations.forEach { cachedConversation ->
val conv = conversations.firstOrNull { it.thread_id == cachedConversation.thread_id && it.getStringToCompare() != cachedConversation.getStringToCompare() }
val conv = conversations.firstOrNull { it.threadId == cachedConversation.threadId && it.getStringToCompare() != cachedConversation.getStringToCompare() }
if (conv != null) {
conversationsDB.insertOrUpdate(conv)
}
@ -224,7 +224,7 @@ class MainActivity : SimpleActivity() {
if (currAdapter == null) {
ConversationsAdapter(this, conversations, conversations_list, conversations_fastscroller) {
Intent(this, ThreadActivity::class.java).apply {
putExtra(THREAD_ID, (it as Conversation).thread_id)
putExtra(THREAD_ID, (it as Conversation).threadId)
putExtra(THREAD_TITLE, it.title)
startActivity(this)
}

View File

@ -50,7 +50,7 @@ class ThreadActivity : SimpleActivity() {
private val MIN_DATE_TIME_DIFF_SECS = 300
private val PICK_ATTACHMENT_INTENT = 1
private var threadId = 0
private var threadId = 0L
private var currentSIMCardIndex = 0
private var isActivityVisible = false
private var threadItems = ArrayList<ThreadItem>()
@ -72,7 +72,7 @@ class ThreadActivity : SimpleActivity() {
return
}
threadId = intent.getIntExtra(THREAD_ID, 0)
threadId = intent.getLongExtra(THREAD_ID, 0L)
intent.getStringExtra(THREAD_TITLE)?.let {
supportActionBar?.title = it
}
@ -290,7 +290,7 @@ class ThreadActivity : SimpleActivity() {
}
}
val newThreadId = getThreadId(numbers).toInt()
val newThreadId = getThreadId(numbers)
if (threadId != newThreadId) {
Intent(this, ThreadActivity::class.java).apply {
putExtra(THREAD_ID, newThreadId)
@ -430,7 +430,7 @@ class ThreadActivity : SimpleActivity() {
private fun markAsUnread() {
ensureBackgroundThread {
conversationsDB.markUnread(threadId.toLong())
conversationsDB.markUnread(threadId)
markThreadMessagesUnread(threadId)
runOnUiThread {
finish()
@ -474,7 +474,7 @@ class ThreadActivity : SimpleActivity() {
if (!message.read) {
hadUnreadItems = true
markMessageRead(message.id, message.isMMS)
conversationsDB.markRead(threadId.toLong())
conversationsDB.markRead(threadId)
}
if (i == cnt - 1 && message.type == Telephony.Sms.MESSAGE_TYPE_SENT) {
@ -595,7 +595,7 @@ class ThreadActivity : SimpleActivity() {
}
try {
transaction.sendNewMessage(message, threadId.toLong())
transaction.sendNewMessage(message, threadId)
thread_type_message.setText("")
attachmentUris.clear()
@ -665,7 +665,7 @@ class ThreadActivity : SimpleActivity() {
@Subscribe(threadMode = ThreadMode.ASYNC)
fun refreshMessages(event: Events.RefreshMessages) {
if (isActivityVisible) {
notificationManager.cancel(threadId)
notificationManager.cancel(threadId.hashCode())
}
messages = getMessages(threadId)

View File

@ -63,9 +63,9 @@ class ConversationsAdapter(activity: SimpleActivity, var conversations: ArrayLis
override fun getIsItemSelectable(position: Int) = true
override fun getItemSelectionKey(position: Int) = conversations.getOrNull(position)?.thread_id
override fun getItemSelectionKey(position: Int) = conversations.getOrNull(position)?.hashCode()
override fun getItemKeyPosition(key: Int) = conversations.indexOfFirst { it.thread_id == key }
override fun getItemKeyPosition(key: Int) = conversations.indexOfFirst { it.hashCode() == key }
override fun onActionModeCreated() {}
@ -153,11 +153,11 @@ class ConversationsAdapter(activity: SimpleActivity, var conversations: ArrayLis
return
}
val conversationsToRemove = conversations.filter { selectedKeys.contains(it.thread_id) } as ArrayList<Conversation>
val conversationsToRemove = conversations.filter { selectedKeys.contains(it.hashCode()) } as ArrayList<Conversation>
val positions = getSelectedItemPositions()
conversationsToRemove.forEach {
activity.deleteConversation(it.thread_id)
activity.notificationManager.cancel(it.thread_id)
activity.deleteConversation(it.threadId)
activity.notificationManager.cancel(it.hashCode())
}
try {
@ -193,7 +193,7 @@ class ConversationsAdapter(activity: SimpleActivity, var conversations: ArrayLis
}
}
private fun getSelectedItems() = conversations.filter { selectedKeys.contains(it.thread_id) } as ArrayList<Conversation>
private fun getSelectedItems() = conversations.filter { selectedKeys.contains(it.hashCode()) } as ArrayList<Conversation>
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
@ -218,7 +218,7 @@ class ConversationsAdapter(activity: SimpleActivity, var conversations: ArrayLis
private fun setupView(view: View, conversation: Conversation) {
view.apply {
conversation_frame.isSelected = selectedKeys.contains(conversation.thread_id)
conversation_frame.isSelected = selectedKeys.contains(conversation.hashCode())
conversation_address.apply {
text = conversation.title

View File

@ -48,7 +48,7 @@ abstract class MessagesDatabase : RoomDatabase() {
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER PRIMARY KEY NOT NULL, `body` TEXT NOT NULL, `type` INTEGER NOT NULL, `participants` TEXT NOT NULL, `date` INTEGER NOT NULL, `read` INTEGER NOT NULL, `thread` INTEGER NOT NULL, `is_mms` INTEGER NOT NULL, `attachment` TEXT, `sender_name` TEXT NOT NULL, `sender_photo_uri` TEXT NOT NULL, `subscription_id` INTEGER NOT NULL)")
database.execSQL("CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER PRIMARY KEY NOT NULL, `body` TEXT NOT NULL, `type` INTEGER NOT NULL, `participants` TEXT NOT NULL, `date` INTEGER NOT NULL, `read` INTEGER NOT NULL, `thread_id` INTEGER NOT NULL, `is_mms` INTEGER NOT NULL, `attachment` TEXT, `sender_name` TEXT NOT NULL, `sender_photo_uri` TEXT NOT NULL, `subscription_id` INTEGER NOT NULL)")
database.execSQL("CREATE TABLE IF NOT EXISTS `message_attachments` (`id` INTEGER PRIMARY KEY NOT NULL, `text` TEXT NOT NULL, `attachments` TEXT NOT NULL)")

View File

@ -50,7 +50,7 @@ val Context.messageAttachmentsDB: MessageAttachmentsDao get() = getMessagessDB()
val Context.messagesDB: MessagesDao get() = getMessagessDB().MessagesDao()
fun Context.getMessages(threadId: Int): ArrayList<Message> {
fun Context.getMessages(threadId: Long): ArrayList<Message> {
val uri = Sms.CONTENT_URI
val projection = arrayOf(
Sms._ID,
@ -93,7 +93,7 @@ fun Context.getMessages(threadId: Int): ArrayList<Message> {
val photoUri = namePhoto.photoUri ?: ""
val date = (cursor.getLongValue(Sms.DATE) / 1000).toInt()
val read = cursor.getIntValue(Sms.READ) == 1
val thread = cursor.getIntValue(Sms.THREAD_ID)
val thread = cursor.getLongValue(Sms.THREAD_ID)
val subscriptionId = cursor.getIntValue(Sms.SUBSCRIPTION_ID)
val participant = SimpleContact(0, 0, senderName, photoUri, arrayListOf(senderNumber), ArrayList(), ArrayList())
val isMMS = false
@ -105,18 +105,15 @@ fun Context.getMessages(threadId: Int): ArrayList<Message> {
messages = messages.filter { it.participants.isNotEmpty() }
.sortedWith(compareBy<Message> { it.date }.thenBy { it.id }).toMutableList() as ArrayList<Message>
// use a separate thread for saving messages in a db
Thread {
messages.chunked(30).forEach { currentMessages ->
messagesDB.insertMessages(*currentMessages.toTypedArray())
}
}.start()
return messages
}
// as soon as a message contains multiple recipients it counts as an MMS instead of SMS
fun Context.getMMS(threadId: Int? = null, sortOrder: String? = null): ArrayList<Message> {
fun Context.getMMS(threadId: Long? = null, sortOrder: String? = null): ArrayList<Message> {
val uri = Mms.CONTENT_URI
val projection = arrayOf(
Mms._ID,
@ -141,13 +138,13 @@ fun Context.getMMS(threadId: Int? = null, sortOrder: String? = null): ArrayList<
val messages = ArrayList<Message>()
val contactsMap = HashMap<Int, SimpleContact>()
val threadParticipants = HashMap<Int, ArrayList<SimpleContact>>()
val threadParticipants = HashMap<Long, ArrayList<SimpleContact>>()
queryCursor(uri, projection, selection, selectionArgs, sortOrder, showErrors = true) { cursor ->
val mmsId = cursor.getLongValue(Mms._ID)
val type = cursor.getIntValue(Mms.MESSAGE_BOX)
val date = cursor.getLongValue(Mms.DATE).toInt()
val read = cursor.getIntValue(Mms.READ) == 1
val threadId = cursor.getIntValue(Mms.THREAD_ID)
val threadId = cursor.getLongValue(Mms.THREAD_ID)
val subscriptionId = cursor.getIntValue(Mms.SUBSCRIPTION_ID)
val participants = if (threadParticipants.containsKey(threadId)) {
threadParticipants[threadId]!!
@ -222,7 +219,7 @@ fun Context.getConversations(threadId: Long? = null, privateContacts: ArrayList<
val simpleContactHelper = SimpleContactsHelper(this)
val blockedNumbers = getBlockedNumbers()
queryCursor(uri, projection, selection, selectionArgs, sortOrder, true) { cursor ->
val id = cursor.getIntValue(Threads._ID)
val id = cursor.getLongValue(Threads._ID)
var snippet = cursor.getStringValue(Threads.SNIPPET) ?: ""
if (snippet.isEmpty()) {
snippet = getThreadSnippet(id)
@ -300,7 +297,7 @@ fun Context.getLatestMMS(): Message? {
return getMMS(sortOrder = sortOrder).firstOrNull()
}
fun Context.getThreadSnippet(threadId: Int): String {
fun Context.getThreadSnippet(threadId: Long): String {
val sortOrder = "${Mms.DATE} DESC LIMIT 1"
val latestMms = getMMS(threadId, sortOrder).firstOrNull()
var snippet = latestMms?.body ?: ""
@ -327,7 +324,7 @@ fun Context.getThreadSnippet(threadId: Int): String {
return snippet
}
fun Context.getThreadParticipants(threadId: Int, contactsMap: HashMap<Int, SimpleContact>?): ArrayList<SimpleContact> {
fun Context.getThreadParticipants(threadId: Long, contactsMap: HashMap<Int, SimpleContact>?): ArrayList<SimpleContact> {
val uri = Uri.parse("${MmsSms.CONTENT_CONVERSATIONS_URI}?simple=true")
val projection = arrayOf(
ThreadsColumns.RECIPIENT_IDS
@ -495,7 +492,7 @@ fun Context.insertNewSMS(address: String, subject: String, body: String, date: L
return newUri?.lastPathSegment?.toInt() ?: 0
}
fun Context.deleteConversation(threadId: Int) {
fun Context.deleteConversation(threadId: Long) {
var uri = Sms.CONTENT_URI
val selection = "${Sms.THREAD_ID} = ?"
val selectionArgs = arrayOf(threadId.toString())
@ -508,7 +505,7 @@ fun Context.deleteConversation(threadId: Int) {
uri = Mms.CONTENT_URI
contentResolver.delete(uri, selection, selectionArgs)
conversationsDB.deleteThreadId(threadId.toLong())
conversationsDB.deleteThreadId(threadId)
}
fun Context.deleteMessage(id: Long, isMMS: Boolean) {
@ -533,7 +530,7 @@ fun Context.markMessageRead(id: Long, isMMS: Boolean) {
contentResolver.update(uri, contentValues, selection, selectionArgs)
}
fun Context.markThreadMessagesRead(threadId: Int) {
fun Context.markThreadMessagesRead(threadId: Long) {
arrayOf(Sms.CONTENT_URI, Mms.CONTENT_URI).forEach { uri ->
val contentValues = ContentValues().apply {
put(Sms.READ, 1)
@ -545,7 +542,7 @@ fun Context.markThreadMessagesRead(threadId: Int) {
}
}
fun Context.markThreadMessagesUnread(threadId: Int) {
fun Context.markThreadMessagesUnread(threadId: Long) {
arrayOf(Sms.CONTENT_URI, Mms.CONTENT_URI).forEach { uri ->
val contentValues = ContentValues().apply {
put(Sms.READ, 0)
@ -592,7 +589,7 @@ fun Context.getThreadId(addresses: Set<String>): Long {
}
}
fun Context.showReceivedMessageNotification(address: String, body: String, threadID: Int, bitmap: Bitmap?) {
fun Context.showReceivedMessageNotification(address: String, body: String, threadId: Long, bitmap: Bitmap?) {
val privateCursor = getMyContactsCursor()?.loadInBackground()
ensureBackgroundThread {
var sender = getNameAndPhotoFromPhoneNumber(address).name
@ -602,13 +599,13 @@ fun Context.showReceivedMessageNotification(address: String, body: String, threa
}
Handler(Looper.getMainLooper()).post {
showMessageNotification(address, body, threadID, bitmap, sender)
showMessageNotification(address, body, threadId, bitmap, sender)
}
}
}
@SuppressLint("NewApi")
fun Context.showMessageNotification(address: String, body: String, threadID: Int, bitmap: Bitmap?, sender: String) {
fun Context.showMessageNotification(address: String, body: String, threadId: Long, bitmap: Bitmap?, sender: String) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
if (isOreoPlus()) {
@ -630,14 +627,14 @@ fun Context.showMessageNotification(address: String, body: String, threadID: Int
}
val intent = Intent(this, ThreadActivity::class.java).apply {
putExtra(THREAD_ID, threadID)
putExtra(THREAD_ID, threadId)
}
val pendingIntent = PendingIntent.getActivity(this, threadID, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val pendingIntent = PendingIntent.getActivity(this, threadId.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
val summaryText = getString(R.string.new_message)
val markAsReadIntent = Intent(this, MarkAsReadReceiver::class.java).apply {
action = MARK_AS_READ
putExtra(THREAD_ID, threadID)
putExtra(THREAD_ID, threadId)
}
val markAsReadPendingIntent = PendingIntent.getBroadcast(this, 0, markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT)
@ -650,11 +647,11 @@ fun Context.showMessageNotification(address: String, body: String, threadID: Int
.build()
val replyIntent = Intent(this, DirectReplyReceiver::class.java).apply {
putExtra(THREAD_ID, threadID)
putExtra(THREAD_ID, threadId)
putExtra(THREAD_NUMBER, address)
}
val replyPendingIntent = PendingIntent.getBroadcast(applicationContext, threadID, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val replyPendingIntent = PendingIntent.getBroadcast(applicationContext, threadId.hashCode(), replyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
replyAction = NotificationCompat.Action.Builder(R.drawable.ic_send_vector, replyLabel, replyPendingIntent)
.addRemoteInput(remoteInput)
.build()
@ -680,5 +677,5 @@ fun Context.showMessageNotification(address: String, body: String, threadID: Int
builder.addAction(R.drawable.ic_check_vector, getString(R.string.mark_as_read), markAsReadPendingIntent)
.setChannelId(NOTIFICATION_CHANNEL)
notificationManager.notify(threadID, builder.build())
notificationManager.notify(threadId.hashCode(), builder.build())
}

View File

@ -17,6 +17,6 @@ interface MessagesDao {
@Query("SELECT * FROM messages")
fun getAll(): List<Message>
@Query("SELECT * FROM messages WHERE thread = :threadId")
@Query("SELECT * FROM messages WHERE thread_id = :threadId")
fun getThreadMessages(threadId: Long): List<Message>
}

View File

@ -8,7 +8,7 @@ import androidx.room.PrimaryKey
@Entity(tableName = "conversations", indices = [(Index(value = ["thread_id"], unique = true))])
data class Conversation(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "thread_id") var thread_id: Int,
@ColumnInfo(name = "thread_id") var threadId: Long,
@ColumnInfo(name = "snippet") var snippet: String,
@ColumnInfo(name = "date") var date: Int,
@ColumnInfo(name = "read") var read: Boolean,

View File

@ -14,7 +14,7 @@ data class Message(
@ColumnInfo(name = "participants") val participants: ArrayList<SimpleContact>,
@ColumnInfo(name = "date") val date: Int,
@ColumnInfo(name = "read") val read: Boolean,
@ColumnInfo(name = "thread") val thread: Int,
@ColumnInfo(name = "thread_id") val threadId: Long,
@ColumnInfo(name = "is_mms") val isMMS: Boolean,
@ColumnInfo(name = "attachment") val attachment: MessageAttachment?,
@ColumnInfo(name = "sender_name") var senderName: String,

View File

@ -21,7 +21,7 @@ import com.simplemobiletools.smsmessenger.helpers.THREAD_NUMBER
class DirectReplyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val address = intent.getStringExtra(THREAD_NUMBER)
val threadId = intent.getIntExtra(THREAD_ID, 0)
val threadId = intent.getLongExtra(THREAD_ID, 0L)
val msg = RemoteInput.getResultsFromIntent(intent).getCharSequence(REPLY).toString()
val settings = Settings()
@ -31,7 +31,7 @@ class DirectReplyReceiver : BroadcastReceiver() {
val message = com.klinker.android.send_message.Message(msg, address)
try {
transaction.sendNewMessage(message, threadId.toLong())
transaction.sendNewMessage(message, threadId)
} catch (e: Exception) {
context.showErrorToast(e)
}
@ -41,11 +41,11 @@ class DirectReplyReceiver : BroadcastReceiver() {
.setContentText(msg)
.build()
context.notificationManager.notify(threadId, repliedNotification)
context.notificationManager.notify(threadId.hashCode(), repliedNotification)
ensureBackgroundThread {
context.markThreadMessagesRead(threadId)
context.conversationsDB.markRead(threadId.toLong())
context.conversationsDB.markRead(threadId)
}
}
}

View File

@ -15,11 +15,11 @@ class MarkAsReadReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
MARK_AS_READ -> {
val threadId = intent.getIntExtra(THREAD_ID, 0)
context.notificationManager.cancel(threadId)
val threadId = intent.getLongExtra(THREAD_ID, 0L)
context.notificationManager.cancel(threadId.hashCode())
ensureBackgroundThread {
context.markThreadMessagesRead(threadId)
context.conversationsDB.markRead(threadId.toLong())
context.conversationsDB.markRead(threadId)
context.updateUnreadCountBadge(context.conversationsDB.getUnreadConversations())
}
}

View File

@ -33,8 +33,8 @@ class MmsReceiver : com.klinker.android.send_message.MmsReceivedReceiver() {
}
Handler(Looper.getMainLooper()).post {
context.showReceivedMessageNotification(address, mms.body, mms.thread, glideBitmap)
val conversation = context.getConversations(mms.thread.toLong()).firstOrNull() ?: return@post
context.showReceivedMessageNotification(address, mms.body, mms.threadId, glideBitmap)
val conversation = context.getConversations(mms.threadId).firstOrNull() ?: return@post
ensureBackgroundThread {
context.conversationsDB.insertOrUpdate(conversation)
context.updateUnreadCountBadge(context.conversationsDB.getUnreadConversations())

View File

@ -42,7 +42,7 @@ class SmsReceiver : BroadcastReceiver() {
context.updateUnreadCountBadge(context.conversationsDB.getUnreadConversations())
}
context.showReceivedMessageNotification(address, body, threadId.toInt(), null)
context.showReceivedMessageNotification(address, body, threadId, null)
refreshMessages()
}
}