forked from upstream-mirrors/quik
Move packages to com.moez.QKSMS
This commit is contained in:
@@ -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 com.moez.QKSMS.repository
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.BaseColumns
|
||||
import android.provider.ContactsContract
|
||||
import com.moez.QKSMS.extensions.asFlowable
|
||||
import com.moez.QKSMS.extensions.mapNotNull
|
||||
import com.moez.QKSMS.model.Contact
|
||||
import io.reactivex.Flowable
|
||||
import io.reactivex.Single
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers
|
||||
import io.reactivex.schedulers.Schedulers
|
||||
import io.realm.Realm
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class ContactRepositoryImpl @Inject constructor(val context: Context) : ContactRepository {
|
||||
|
||||
override fun findContactUri(address: String): Single<Uri> {
|
||||
return Flowable.just(address)
|
||||
.map {
|
||||
when {
|
||||
address.contains('@') -> Uri.withAppendedPath(ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(address))
|
||||
else -> Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address))
|
||||
}
|
||||
}
|
||||
.mapNotNull { uri -> context.contentResolver.query(uri, arrayOf(BaseColumns._ID), null, null, null) }
|
||||
.flatMap { cursor -> cursor.asFlowable() }
|
||||
.firstOrError()
|
||||
.map { cursor -> cursor.getString(cursor.getColumnIndexOrThrow(BaseColumns._ID)) }
|
||||
.map { id -> Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, id) }
|
||||
}
|
||||
|
||||
override fun getUnmanagedContacts(): Flowable<List<Contact>> {
|
||||
val realm = Realm.getDefaultInstance()
|
||||
return realm.where(Contact::class.java)
|
||||
.sort("name")
|
||||
.findAllAsync()
|
||||
.asFlowable()
|
||||
.filter { it.isLoaded }
|
||||
.filter { it.isValid }
|
||||
.map { realm.copyFromRealm(it) }
|
||||
.subscribeOn(AndroidSchedulers.mainThread())
|
||||
.observeOn(Schedulers.io())
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package com.moez.QKSMS.repository
|
||||
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.provider.Telephony
|
||||
import android.telephony.PhoneNumberUtils
|
||||
import com.moez.QKSMS.compat.TelephonyCompat
|
||||
import com.moez.QKSMS.extensions.anyOf
|
||||
import com.moez.QKSMS.extensions.map
|
||||
import com.moez.QKSMS.filter.ConversationFilter
|
||||
import com.moez.QKSMS.mapper.CursorToConversation
|
||||
import com.moez.QKSMS.mapper.CursorToRecipient
|
||||
import com.moez.QKSMS.model.Contact
|
||||
import com.moez.QKSMS.model.Conversation
|
||||
import com.moez.QKSMS.model.Message
|
||||
import com.moez.QKSMS.model.SearchResult
|
||||
import com.moez.QKSMS.util.tryOrNull
|
||||
import io.realm.Case
|
||||
import io.realm.Realm
|
||||
import io.realm.RealmResults
|
||||
import io.realm.Sort
|
||||
import javax.inject.Inject
|
||||
|
||||
class ConversationRepositoryImpl @Inject constructor(
|
||||
private val context: Context,
|
||||
private val conversationFilter: ConversationFilter,
|
||||
private val cursorToConversation: CursorToConversation,
|
||||
private val cursorToRecipient: CursorToRecipient
|
||||
) : ConversationRepository {
|
||||
|
||||
override fun getConversations(archived: Boolean): RealmResults<Conversation> {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Conversation::class.java)
|
||||
.notEqualTo("id", 0L)
|
||||
.greaterThan("count", 0)
|
||||
.equalTo("archived", archived)
|
||||
.equalTo("blocked", false)
|
||||
.isNotEmpty("recipients")
|
||||
.sort("date", Sort.DESCENDING)
|
||||
.findAllAsync()
|
||||
}
|
||||
|
||||
override fun getConversationsSnapshot(): List<Conversation> {
|
||||
val realm = Realm.getDefaultInstance()
|
||||
return realm.copyFromRealm(realm.where(Conversation::class.java)
|
||||
.notEqualTo("id", 0L)
|
||||
.greaterThan("count", 0)
|
||||
.equalTo("archived", false)
|
||||
.equalTo("blocked", false)
|
||||
.isNotEmpty("recipients")
|
||||
.sort("date", Sort.DESCENDING)
|
||||
.findAll())
|
||||
}
|
||||
|
||||
override fun setConversationName(id: Long, name: String) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.executeTransaction {
|
||||
realm.where(Conversation::class.java)
|
||||
.equalTo("id", id)
|
||||
.findFirst()
|
||||
?.name = name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun searchConversations(query: String): List<SearchResult> {
|
||||
val conversations = getConversationsSnapshot()
|
||||
|
||||
val messagesByConversation = Realm.getDefaultInstance()
|
||||
.where(Message::class.java)
|
||||
.contains("body", query, Case.INSENSITIVE)
|
||||
.findAll()
|
||||
.groupBy { message -> message.threadId }
|
||||
.filter { (threadId, _) -> conversations.firstOrNull { it.id == threadId } != null }
|
||||
.map { (threadId, messages) -> Pair(conversations.first { it.id == threadId }, messages.size) }
|
||||
.map { (conversation, messages) -> SearchResult(query, conversation, messages) }
|
||||
.sortedByDescending { result -> result.messages }
|
||||
|
||||
return conversations
|
||||
.filter { conversation -> conversationFilter.filter(conversation, query) }
|
||||
.map { conversation -> SearchResult(query, conversation, 0) }
|
||||
.plus(messagesByConversation)
|
||||
}
|
||||
|
||||
override fun getBlockedConversations(): RealmResults<Conversation> {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Conversation::class.java)
|
||||
.equalTo("blocked", true)
|
||||
.findAllAsync()
|
||||
}
|
||||
|
||||
override fun getConversationAsync(threadId: Long): Conversation {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Conversation::class.java)
|
||||
.equalTo("id", threadId)
|
||||
.findFirstAsync()
|
||||
}
|
||||
|
||||
override fun getConversation(threadId: Long): Conversation? {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Conversation::class.java)
|
||||
.equalTo("id", threadId)
|
||||
.findFirst()
|
||||
}
|
||||
|
||||
override fun getThreadId(recipient: String): Long? {
|
||||
return getThreadId(listOf(recipient))
|
||||
}
|
||||
|
||||
override fun getThreadId(recipients: Collection<String>): Long? {
|
||||
return Realm.getDefaultInstance().use { realm ->
|
||||
realm.where(Conversation::class.java)
|
||||
.findAll()
|
||||
.firstOrNull { conversation ->
|
||||
conversation.recipients.size == recipients.size && conversation.recipients.map { it.address }.all { address ->
|
||||
recipients.any { recipient -> PhoneNumberUtils.compare(recipient, address) }
|
||||
}
|
||||
}
|
||||
?.id
|
||||
}
|
||||
}
|
||||
|
||||
override fun getOrCreateConversation(threadId: Long): Conversation? {
|
||||
return getConversation(threadId) ?: getConversationFromCp(threadId)
|
||||
}
|
||||
|
||||
override fun getOrCreateConversation(address: String): Conversation? {
|
||||
return getOrCreateConversation(listOf(address))
|
||||
}
|
||||
|
||||
override fun getOrCreateConversation(addresses: List<String>): Conversation? {
|
||||
return tryOrNull { TelephonyCompat.getOrCreateThreadId(context, addresses.toSet()) }
|
||||
?.takeIf { threadId -> threadId != 0L }
|
||||
?.let { threadId ->
|
||||
var conversation = getConversation(threadId)
|
||||
if (conversation != null) conversation = Realm.getDefaultInstance().copyFromRealm(conversation)
|
||||
|
||||
conversation ?: getConversationFromCp(threadId)
|
||||
}
|
||||
}
|
||||
|
||||
override fun saveDraft(threadId: Long, draft: String) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
val conversation = realm.where(Conversation::class.java)
|
||||
.equalTo("id", threadId)
|
||||
.findFirst()
|
||||
|
||||
conversation?.let {
|
||||
realm.executeTransaction {
|
||||
conversation.draft = draft
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun updateConversations(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
threadIds.forEach { threadId ->
|
||||
val conversation = realm
|
||||
.where(Conversation::class.java)
|
||||
.equalTo("id", threadId)
|
||||
.findFirst() ?: return
|
||||
|
||||
val messages = realm
|
||||
.where(Message::class.java)
|
||||
.equalTo("threadId", threadId)
|
||||
.sort("date", Sort.DESCENDING)
|
||||
.findAll()
|
||||
|
||||
val message = messages.firstOrNull()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversation.count = messages.size
|
||||
conversation.date = message?.date ?: 0
|
||||
conversation.snippet = message?.getSummary() ?: ""
|
||||
conversation.read = message?.read ?: true
|
||||
conversation.me = message?.isMe() ?: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markArchived(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
val conversations = realm.where(Conversation::class.java)
|
||||
.anyOf("id", threadIds)
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversations.forEach { it.archived = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markUnarchived(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
val conversations = realm.where(Conversation::class.java)
|
||||
.anyOf("id", threadIds)
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversations.forEach { it.archived = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markBlocked(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
val conversations = realm.where(Conversation::class.java)
|
||||
.anyOf("id", threadIds)
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversations.forEach { it.blocked = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markUnblocked(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
val conversations = realm.where(Conversation::class.java)
|
||||
.anyOf("id", threadIds)
|
||||
.equalTo("archived", false)
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversations.forEach { it.blocked = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun deleteConversations(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
val conversation = realm.where(Conversation::class.java).anyOf("id", threadIds).findAll()
|
||||
val messages = realm.where(Message::class.java).anyOf("threadId", threadIds).findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversation.deleteAllFromRealm()
|
||||
messages.deleteAllFromRealm()
|
||||
}
|
||||
}
|
||||
|
||||
threadIds.forEach { threadId ->
|
||||
val uri = ContentUris.withAppendedId(Telephony.Threads.CONTENT_URI, threadId)
|
||||
context.contentResolver.delete(uri, null, null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a [Conversation] from the system SMS ContentProvider, based on the [threadId]
|
||||
*
|
||||
* It should be noted that even if we have a valid [threadId], that does not guarantee that
|
||||
* we can return a [Conversation]. On some devices, the ContentProvider won't return the
|
||||
* conversation unless it contains at least 1 message
|
||||
*/
|
||||
private fun getConversationFromCp(threadId: Long): Conversation? {
|
||||
return cursorToConversation.getConversationCursor(threadId)
|
||||
?.takeIf { cursor -> cursor.moveToFirst() }
|
||||
?.use { cursor ->
|
||||
val conversation = cursorToConversation.map(cursor)
|
||||
|
||||
val realm = Realm.getDefaultInstance()
|
||||
val contacts = realm.copyFromRealm(realm.where(Contact::class.java).findAll())
|
||||
|
||||
val recipients = conversation.recipients
|
||||
.map { recipient -> recipient.id }
|
||||
.map { id -> cursorToRecipient.getRecipientCursor(id) }
|
||||
.mapNotNull { recipientCursor ->
|
||||
// Map the recipient cursor to a list of recipients
|
||||
recipientCursor?.use { recipientCursor.map { cursorToRecipient.map(recipientCursor) } }
|
||||
}
|
||||
.flatten()
|
||||
.map { recipient ->
|
||||
recipient.apply {
|
||||
contact = contacts.firstOrNull {
|
||||
it.numbers.any { PhoneNumberUtils.compare(recipient.address, it.address) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
conversation.recipients.clear()
|
||||
conversation.recipients.addAll(recipients)
|
||||
realm.executeTransaction { it.insertOrUpdate(conversation) }
|
||||
realm.close()
|
||||
|
||||
conversation
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.moez.QKSMS.repository
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.ContentUris
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import android.net.Uri
|
||||
import android.provider.MediaStore
|
||||
import android.provider.MediaStore.Images
|
||||
import android.support.media.ExifInterface
|
||||
import com.moez.QKSMS.util.tryOrNull
|
||||
import javax.inject.Inject
|
||||
|
||||
class ImageRepostoryImpl @Inject constructor(private val context: Context) : ImageRepository {
|
||||
|
||||
override fun loadImage(uri: Uri): Bitmap? {
|
||||
val exif = ExifInterface(context.contentResolver.openInputStream(uri))
|
||||
val bitmap = BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri))
|
||||
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
|
||||
|
||||
|
||||
return when (orientation) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90f)
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180f)
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270f)
|
||||
else -> bitmap
|
||||
}
|
||||
}
|
||||
|
||||
private fun rotateBitmap(bitmap: Bitmap, degree: Float): Bitmap {
|
||||
val w = bitmap.width
|
||||
val h = bitmap.height
|
||||
|
||||
val mtx = Matrix()
|
||||
mtx.postRotate(degree)
|
||||
|
||||
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true)
|
||||
}
|
||||
|
||||
override fun saveImage(uri: Uri) {
|
||||
val bitmap = tryOrNull { MediaStore.Images.Media.getBitmap(context.contentResolver, uri) }
|
||||
|
||||
var title = ""
|
||||
var description = ""
|
||||
|
||||
when (uri.scheme) {
|
||||
"file" -> title = uri.lastPathSegment
|
||||
|
||||
"content" -> {
|
||||
val projection = arrayOf(Images.Media.TITLE, Images.Media.DESCRIPTION)
|
||||
context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
|
||||
if (cursor.moveToFirst()) {
|
||||
title = cursor.getString(0)
|
||||
description = cursor.getString(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
insertImage(context.contentResolver, bitmap, title, description)
|
||||
}
|
||||
|
||||
/**
|
||||
* Modified from [android.provider.MediaStore.Images.Media.insertImage] to add date fields so
|
||||
* that the saved image is put at the start of the gallery
|
||||
*/
|
||||
private fun insertImage(cr: ContentResolver, source: Bitmap?, title: String, description: String): String? {
|
||||
|
||||
val values = ContentValues()
|
||||
values.put(Images.Media.TITLE, title)
|
||||
values.put(Images.Media.DISPLAY_NAME, title)
|
||||
values.put(Images.Media.DESCRIPTION, description)
|
||||
values.put(Images.Media.MIME_TYPE, "image/jpeg")
|
||||
|
||||
// Add the date meta data to ensure the image is added at the front of the gallery
|
||||
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
|
||||
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis())
|
||||
|
||||
var uri: Uri? = null
|
||||
|
||||
try {
|
||||
uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
|
||||
|
||||
if (source != null) {
|
||||
cr.openOutputStream(uri).use { imageOut ->
|
||||
source.compress(Bitmap.CompressFormat.JPEG, 100, imageOut)
|
||||
}
|
||||
|
||||
val id = ContentUris.parseId(uri)
|
||||
// Wait until MINI_KIND thumbnail is generated.
|
||||
val miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null)
|
||||
// This is for backward compatibility.
|
||||
storeThumbnail(cr, miniThumb, id, 50f, 50f, Images.Thumbnails.MICRO_KIND)
|
||||
} else {
|
||||
cr.delete(uri, null, null)
|
||||
uri = null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (uri != null) {
|
||||
cr.delete(uri, null, null)
|
||||
uri = null
|
||||
}
|
||||
}
|
||||
|
||||
return uri?.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Modified from [android.provider.MediaStore.Images.Media.insertImage] to add date fields so
|
||||
* that the saved image is put at the start of the gallery
|
||||
*/
|
||||
private fun storeThumbnail(cr: ContentResolver, source: Bitmap, id: Long, width: Float, height: Float, kind: Int): Bitmap? {
|
||||
val matrix = Matrix()
|
||||
|
||||
val scaleX = width / source.width
|
||||
val scaleY = height / source.height
|
||||
|
||||
matrix.setScale(scaleX, scaleY)
|
||||
|
||||
val thumb = Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
||||
|
||||
val values = ContentValues(4)
|
||||
values.put(Images.Thumbnails.KIND, kind)
|
||||
values.put(Images.Thumbnails.IMAGE_ID, id.toInt())
|
||||
values.put(Images.Thumbnails.HEIGHT, thumb.height)
|
||||
values.put(Images.Thumbnails.WIDTH, thumb.width)
|
||||
|
||||
val url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values)
|
||||
|
||||
return tryOrNull {
|
||||
val thumbOut = cr.openOutputStream(url)
|
||||
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut)
|
||||
thumbOut.close()
|
||||
thumb
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
/*
|
||||
* 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 com.moez.QKSMS.repository
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.ContentUris
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Build
|
||||
import android.provider.Telephony
|
||||
import android.telephony.SmsManager
|
||||
import com.google.android.mms.ContentType
|
||||
import com.klinker.android.send_message.BroadcastUtils
|
||||
import com.klinker.android.send_message.Settings
|
||||
import com.klinker.android.send_message.StripAccents
|
||||
import com.klinker.android.send_message.Transaction
|
||||
import com.moez.QKSMS.extensions.anyOf
|
||||
import com.moez.QKSMS.extensions.insertOrUpdate
|
||||
import com.moez.QKSMS.manager.KeyManager
|
||||
import com.moez.QKSMS.model.Attachment
|
||||
import com.moez.QKSMS.model.Conversation
|
||||
import com.moez.QKSMS.model.Message
|
||||
import com.moez.QKSMS.model.MmsPart
|
||||
import com.moez.QKSMS.util.Preferences
|
||||
import io.realm.Case
|
||||
import io.realm.Realm
|
||||
import io.realm.RealmResults
|
||||
import io.realm.Sort
|
||||
import timber.log.Timber
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class MessageRepositoryImpl @Inject constructor(
|
||||
private val context: Context,
|
||||
private val messageIds: KeyManager,
|
||||
private val conversationRepo: ConversationRepository,
|
||||
private val imageRepository: ImageRepository,
|
||||
private val prefs: Preferences) : MessageRepository {
|
||||
|
||||
override fun getMessages(threadId: Long, query: String): RealmResults<Message> {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Message::class.java)
|
||||
.equalTo("threadId", threadId)
|
||||
.let { if (query.isEmpty()) it else it.contains("body", query, Case.INSENSITIVE) }
|
||||
.sort("date")
|
||||
.findAllAsync()
|
||||
}
|
||||
|
||||
override fun getMessage(id: Long): Message? {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Message::class.java)
|
||||
.equalTo("id", id)
|
||||
.findFirst()
|
||||
}
|
||||
|
||||
override fun getMessageForPart(id: Long): Message? {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Message::class.java)
|
||||
.equalTo("parts.id", id)
|
||||
.findFirst()
|
||||
}
|
||||
|
||||
override fun getUnreadCount(): Long {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Conversation::class.java)
|
||||
.equalTo("archived", false)
|
||||
.equalTo("blocked", false)
|
||||
.equalTo("read", false)
|
||||
.count()
|
||||
}
|
||||
|
||||
override fun getPart(id: Long): MmsPart? {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(MmsPart::class.java)
|
||||
.equalTo("id", id)
|
||||
.findFirst()
|
||||
}
|
||||
|
||||
override fun getPartsForConversation(threadId: Long): RealmResults<MmsPart> {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(MmsPart::class.java)
|
||||
.equalTo("messages.threadId", threadId)
|
||||
.beginGroup()
|
||||
.contains("type", "image/")
|
||||
.or()
|
||||
.contains("type", "video/")
|
||||
.endGroup()
|
||||
.sort("id", Sort.DESCENDING)
|
||||
.findAllAsync()
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the list of messages which should be shown in the notification
|
||||
* for a given conversation
|
||||
*/
|
||||
override fun getUnreadUnseenMessages(threadId: Long): RealmResults<Message> {
|
||||
return Realm.getDefaultInstance()
|
||||
.also { it.refresh() }
|
||||
.where(Message::class.java)
|
||||
.equalTo("seen", false)
|
||||
.equalTo("read", false)
|
||||
.equalTo("threadId", threadId)
|
||||
.sort("date")
|
||||
.findAll()
|
||||
}
|
||||
|
||||
override fun getUnreadMessages(threadId: Long): RealmResults<Message> {
|
||||
return Realm.getDefaultInstance()
|
||||
.where(Message::class.java)
|
||||
.equalTo("read", false)
|
||||
.equalTo("threadId", threadId)
|
||||
.sort("date")
|
||||
.findAll()
|
||||
}
|
||||
|
||||
override fun markAllSeen() {
|
||||
val realm = Realm.getDefaultInstance()
|
||||
val messages = realm.where(Message::class.java).equalTo("seen", false).findAll()
|
||||
realm.executeTransaction { messages.forEach { message -> message.seen = true } }
|
||||
realm.close()
|
||||
}
|
||||
|
||||
override fun markSeen(threadId: Long) {
|
||||
val realm = Realm.getDefaultInstance()
|
||||
val messages = realm.where(Message::class.java)
|
||||
.equalTo("threadId", threadId)
|
||||
.equalTo("seen", false)
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
messages.forEach { message ->
|
||||
message.seen = true
|
||||
}
|
||||
}
|
||||
realm.close()
|
||||
}
|
||||
|
||||
override fun markRead(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance()?.use { realm ->
|
||||
val messages = realm.where(Message::class.java)
|
||||
.anyOf("threadId", threadIds)
|
||||
.beginGroup()
|
||||
.equalTo("read", false)
|
||||
.or()
|
||||
.equalTo("seen", false)
|
||||
.endGroup()
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
messages.forEach { message ->
|
||||
message.seen = true
|
||||
message.read = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val values = ContentValues()
|
||||
values.put(Telephony.Sms.SEEN, true)
|
||||
values.put(Telephony.Sms.READ, true)
|
||||
|
||||
threadIds.forEach { threadId ->
|
||||
try {
|
||||
val uri = ContentUris.withAppendedId(Telephony.MmsSms.CONTENT_CONVERSATIONS_URI, threadId)
|
||||
context.contentResolver.update(uri, values, "${Telephony.Sms.READ} = 0", null)
|
||||
} catch (exception: Exception) {
|
||||
Timber.w(exception)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markUnread(vararg threadIds: Long) {
|
||||
Realm.getDefaultInstance()?.use { realm ->
|
||||
val conversation = realm.where(Conversation::class.java)
|
||||
.anyOf("id", threadIds)
|
||||
.equalTo("read", true)
|
||||
.findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
conversation.forEach { it.read = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun sendSmsAndPersist(subId: Int, threadId: Long, address: String, body: String) {
|
||||
if (prefs.sendDelay.get() != Preferences.SEND_DELAY_NONE) {
|
||||
val delay = when (prefs.sendDelay.get()) {
|
||||
Preferences.SEND_DELAY_SHORT -> 3000
|
||||
Preferences.SEND_DELAY_MEDIUM -> 5000
|
||||
Preferences.SEND_DELAY_LONG -> 10000
|
||||
else -> 0
|
||||
}
|
||||
|
||||
val sendTime = System.currentTimeMillis() + delay
|
||||
val message = insertSentSms(subId, threadId, address, body, sendTime)
|
||||
|
||||
val intent = getIntentForDelayedSms(message.id)
|
||||
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, sendTime, intent)
|
||||
} else {
|
||||
alarmManager.setExact(AlarmManager.RTC_WAKEUP, sendTime, intent)
|
||||
}
|
||||
} else {
|
||||
val message = insertSentSms(subId, threadId, address, body, System.currentTimeMillis())
|
||||
sendSms(message)
|
||||
}
|
||||
}
|
||||
|
||||
override fun sendSms(message: Message) {
|
||||
val smsManager = message.subId.takeIf { it != -1 }
|
||||
?.let(SmsManager::getSmsManagerForSubscriptionId)
|
||||
?: SmsManager.getDefault()
|
||||
|
||||
val parts = smsManager.divideMessage(if (prefs.unicode.get()) StripAccents.stripAccents(message.body) else message.body)
|
||||
?: arrayListOf()
|
||||
|
||||
val sentIntents = parts.map {
|
||||
val action = "com.moez.QKSMS.SMS_SENT"
|
||||
val intent = Intent(action).putExtra("id", message.id)
|
||||
BroadcastUtils.addClassName(context, intent, action)
|
||||
PendingIntent.getBroadcast(context, message.id.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
}
|
||||
|
||||
val deliveredIntents = parts.map {
|
||||
val action = "com.moez.QKSMS.SMS_DELIVERED"
|
||||
val intent = Intent(action).putExtra("id", message.id)
|
||||
BroadcastUtils.addClassName(context, intent, action)
|
||||
val pendingIntent = PendingIntent.getBroadcast(context, message.id.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
if (prefs.delivery.get()) pendingIntent else null
|
||||
}
|
||||
|
||||
smsManager.sendMultipartTextMessage(message.address, null, parts, ArrayList(sentIntents), ArrayList(deliveredIntents))
|
||||
}
|
||||
|
||||
override fun sendMms(subId: Int, threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>) {
|
||||
val settings = Settings().apply { subscriptionId = subId }
|
||||
val message = com.klinker.android.send_message.Message(body, addresses.toTypedArray())
|
||||
|
||||
// Add the GIFs as attachments. The app currently can't compress them, which may result
|
||||
// in a lot of these messages failing to send
|
||||
// TODO Add support for GIF compression
|
||||
attachments
|
||||
.filter { attachment -> attachment.isGif(context) }
|
||||
.map { attachment -> attachment.getUri() }
|
||||
.map { uri -> context.contentResolver.openInputStream(uri) }
|
||||
.map { inputStream -> inputStream.readBytes() }
|
||||
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_GIF) }
|
||||
|
||||
// Compress the images and add them as attachments
|
||||
var totalImageBytes = 0
|
||||
attachments
|
||||
.filter { attachment -> !attachment.isGif(context) }
|
||||
.mapNotNull { attachment -> attachment.getUri() }
|
||||
.mapNotNull { uri -> imageRepository.loadImage(uri) }
|
||||
.also { totalImageBytes = it.sumBy { it.allocationByteCount } }
|
||||
.map { bitmap ->
|
||||
val byteRatio = bitmap.allocationByteCount / totalImageBytes.toFloat()
|
||||
shrink(bitmap, (prefs.mmsSize.get() * 1024 * byteRatio).toInt())
|
||||
}
|
||||
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_JPEG) }
|
||||
|
||||
val transaction = Transaction(context, settings)
|
||||
transaction.sendNewMessage(message, threadId)
|
||||
}
|
||||
|
||||
private fun shrink(src: Bitmap, maxBytes: Int): ByteArray {
|
||||
var step = 0.0
|
||||
val factor = 0.5
|
||||
val quality = 60
|
||||
|
||||
val height = src.height
|
||||
val width = src.width
|
||||
|
||||
val stream = ByteArrayOutputStream()
|
||||
src.compress(Bitmap.CompressFormat.JPEG, 100, stream)
|
||||
|
||||
while (maxBytes > 0 && stream.size() > maxBytes) {
|
||||
step++
|
||||
val scale = Math.pow(factor, step)
|
||||
|
||||
stream.reset()
|
||||
Bitmap.createScaledBitmap(src, (width * scale).toInt(), (height * scale).toInt(), false)
|
||||
.compress(Bitmap.CompressFormat.JPEG, quality, stream)
|
||||
}
|
||||
|
||||
return stream.toByteArray()
|
||||
}
|
||||
|
||||
override fun cancelDelayedSms(id: Long) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
alarmManager.cancel(getIntentForDelayedSms(id))
|
||||
}
|
||||
|
||||
private fun getIntentForDelayedSms(id: Long): PendingIntent {
|
||||
val action = "com.moez.QKSMS.SEND_SMS"
|
||||
val intent = Intent(action).putExtra("id", id)
|
||||
BroadcastUtils.addClassName(context, intent, action)
|
||||
return PendingIntent.getBroadcast(context, id.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
id = messageIds.newId()
|
||||
boxId = Telephony.Sms.MESSAGE_TYPE_OUTBOX
|
||||
type = "sms"
|
||||
read = true
|
||||
seen = true
|
||||
}
|
||||
val realm = Realm.getDefaultInstance()
|
||||
var managedMessage: Message? = null
|
||||
realm.executeTransaction { managedMessage = realm.copyToRealmOrUpdate(message) }
|
||||
|
||||
// Insert the message to the native content provider
|
||||
val values = ContentValues().apply {
|
||||
put(Telephony.Sms.ADDRESS, address)
|
||||
put(Telephony.Sms.BODY, body)
|
||||
put(Telephony.Sms.DATE, System.currentTimeMillis())
|
||||
put(Telephony.Sms.READ, true)
|
||||
put(Telephony.Sms.SEEN, true)
|
||||
put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_OUTBOX)
|
||||
put(Telephony.Sms.THREAD_ID, threadId)
|
||||
put(Telephony.Sms.SUBSCRIPTION_ID, subId)
|
||||
}
|
||||
val uri = context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values)
|
||||
|
||||
// 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
|
||||
//
|
||||
// We 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
|
||||
realm.executeTransaction { managedMessage?.takeIf { it.isValid }?.contentId = uri.lastPathSegment.toLong() }
|
||||
realm.close()
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
override fun insertReceivedSms(subId: Int, address: String, body: String, sentTime: Long): Message {
|
||||
|
||||
// Insert the message to the native content provider
|
||||
val values = ContentValues().apply {
|
||||
put(Telephony.Sms.ADDRESS, address)
|
||||
put(Telephony.Sms.BODY, body)
|
||||
put(Telephony.Sms.DATE_SENT, sentTime)
|
||||
put(Telephony.Sms.SUBSCRIPTION_ID, subId)
|
||||
}
|
||||
val uri = context.contentResolver.insert(Telephony.Sms.Inbox.CONTENT_URI, values)
|
||||
|
||||
// Insert the message to Realm
|
||||
return Message().apply {
|
||||
this.address = address
|
||||
this.body = body
|
||||
this.dateSent = sentTime
|
||||
this.date = System.currentTimeMillis()
|
||||
this.subId = subId
|
||||
|
||||
id = messageIds.newId()
|
||||
threadId = conversationRepo.getOrCreateConversation(address)?.id ?: 0L
|
||||
contentId = uri.lastPathSegment.toLong()
|
||||
boxId = Telephony.Sms.MESSAGE_TYPE_INBOX
|
||||
type = "sms"
|
||||
insertOrUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the message as sending, in case we need to retry sending it
|
||||
*/
|
||||
override fun markSending(id: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
val message = realm.where(Message::class.java).equalTo("id", id).findFirst()
|
||||
message?.let {
|
||||
// Update the message in realm
|
||||
realm.executeTransaction {
|
||||
message.boxId = Telephony.Sms.MESSAGE_TYPE_OUTBOX
|
||||
}
|
||||
|
||||
// Update the message in the native ContentProvider
|
||||
val values = ContentValues()
|
||||
values.put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_OUTBOX)
|
||||
context.contentResolver.update(message.getUri(), values, null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markSent(id: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
val message = realm.where(Message::class.java).equalTo("id", id).findFirst()
|
||||
message?.let {
|
||||
// Update the message in realm
|
||||
realm.executeTransaction {
|
||||
message.boxId = Telephony.Sms.MESSAGE_TYPE_SENT
|
||||
}
|
||||
|
||||
// Update the message in the native ContentProvider
|
||||
val values = ContentValues()
|
||||
values.put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_SENT)
|
||||
context.contentResolver.update(message.getUri(), values, null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markFailed(id: Long, resultCode: Int) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
val message = realm.where(Message::class.java).equalTo("id", id).findFirst()
|
||||
message?.let {
|
||||
// Update the message in realm
|
||||
realm.executeTransaction {
|
||||
message.boxId = Telephony.Sms.MESSAGE_TYPE_FAILED
|
||||
message.errorCode = resultCode
|
||||
}
|
||||
|
||||
// Update the message in the native ContentProvider
|
||||
val values = ContentValues()
|
||||
values.put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_FAILED)
|
||||
values.put(Telephony.Sms.ERROR_CODE, resultCode)
|
||||
context.contentResolver.update(message.getUri(), values, null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markDelivered(id: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
val message = realm.where(Message::class.java).equalTo("id", id).findFirst()
|
||||
message?.let {
|
||||
// Update the message in realm
|
||||
realm.executeTransaction {
|
||||
message.deliveryStatus = Telephony.Sms.STATUS_COMPLETE
|
||||
message.dateSent = System.currentTimeMillis()
|
||||
message.read = true
|
||||
}
|
||||
|
||||
// Update the message in the native ContentProvider
|
||||
val values = ContentValues()
|
||||
values.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_COMPLETE)
|
||||
values.put(Telephony.Sms.DATE_SENT, System.currentTimeMillis())
|
||||
values.put(Telephony.Sms.READ, true)
|
||||
context.contentResolver.update(message.getUri(), values, null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun markDeliveryFailed(id: Long, resultCode: Int) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
val message = realm.where(Message::class.java).equalTo("id", id).findFirst()
|
||||
message?.let {
|
||||
// Update the message in realm
|
||||
realm.executeTransaction {
|
||||
message.deliveryStatus = Telephony.Sms.STATUS_FAILED
|
||||
message.dateSent = System.currentTimeMillis()
|
||||
message.read = true
|
||||
message.errorCode = resultCode
|
||||
}
|
||||
|
||||
// Update the message in the native ContentProvider
|
||||
val values = ContentValues()
|
||||
values.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_FAILED)
|
||||
values.put(Telephony.Sms.DATE_SENT, System.currentTimeMillis())
|
||||
values.put(Telephony.Sms.READ, true)
|
||||
values.put(Telephony.Sms.ERROR_CODE, resultCode)
|
||||
context.contentResolver.update(message.getUri(), values, null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun deleteMessages(vararg messageIds: Long) {
|
||||
Realm.getDefaultInstance().use { realm ->
|
||||
realm.refresh()
|
||||
|
||||
val messages = realm.where(Message::class.java)
|
||||
.anyOf("id", messageIds)
|
||||
.findAll()
|
||||
|
||||
val uris = messages.map { it.getUri() }
|
||||
|
||||
realm.executeTransaction { messages.deleteAllFromRealm() }
|
||||
|
||||
uris.forEach { uri -> context.contentResolver.delete(uri, null, null) }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/*
|
||||
* 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 com.moez.QKSMS.repository
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.ContentUris
|
||||
import android.net.Uri
|
||||
import android.provider.Telephony
|
||||
import android.telephony.PhoneNumberUtils
|
||||
import com.f2prateek.rx.preferences2.RxSharedPreferences
|
||||
import com.moez.QKSMS.extensions.insertOrUpdate
|
||||
import com.moez.QKSMS.extensions.map
|
||||
import com.moez.QKSMS.manager.KeyManager
|
||||
import com.moez.QKSMS.mapper.CursorToContact
|
||||
import com.moez.QKSMS.mapper.CursorToConversation
|
||||
import com.moez.QKSMS.mapper.CursorToMessage
|
||||
import com.moez.QKSMS.mapper.CursorToRecipient
|
||||
import com.moez.QKSMS.model.Contact
|
||||
import com.moez.QKSMS.model.Conversation
|
||||
import com.moez.QKSMS.model.Message
|
||||
import com.moez.QKSMS.model.MmsPart
|
||||
import com.moez.QKSMS.model.Recipient
|
||||
import com.moez.QKSMS.model.SyncLog
|
||||
import com.moez.QKSMS.util.tryOrNull
|
||||
import io.reactivex.subjects.BehaviorSubject
|
||||
import io.reactivex.subjects.Subject
|
||||
import io.realm.Realm
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class SyncRepositoryImpl @Inject constructor(
|
||||
private val contentResolver: ContentResolver,
|
||||
private val conversationRepo: ConversationRepository,
|
||||
private val messageRepo: MessageRepository,
|
||||
private val cursorToConversation: CursorToConversation,
|
||||
private val cursorToMessage: CursorToMessage,
|
||||
private val cursorToRecipient: CursorToRecipient,
|
||||
private val cursorToContact: CursorToContact,
|
||||
private val keys: KeyManager,
|
||||
private val rxPrefs: RxSharedPreferences
|
||||
) : SyncRepository {
|
||||
|
||||
/**
|
||||
* Holds data that should be persisted across full syncs
|
||||
*/
|
||||
private data class PersistedData(
|
||||
val id: Long,
|
||||
val archived: Boolean,
|
||||
val blocked: Boolean,
|
||||
val name: String)
|
||||
|
||||
override val syncProgress: Subject<SyncRepository.SyncProgress> = BehaviorSubject.createDefault(SyncRepository.SyncProgress.Idle())
|
||||
|
||||
override fun syncMessages() {
|
||||
|
||||
// If the sync is already running, don't try to do another one
|
||||
if (syncProgress.blockingFirst() is SyncRepository.SyncProgress.Running) return
|
||||
syncProgress.onNext(SyncRepository.SyncProgress.Running(0f))
|
||||
|
||||
val realm = Realm.getDefaultInstance()
|
||||
realm.beginTransaction()
|
||||
|
||||
var persistedData = realm.where(Conversation::class.java)
|
||||
.beginGroup()
|
||||
.equalTo("archived", true)
|
||||
.or()
|
||||
.equalTo("blocked", true)
|
||||
.or()
|
||||
.isNotEmpty("name")
|
||||
.endGroup()
|
||||
.findAll()
|
||||
.map { PersistedData(it.id, it.archived, it.blocked, it.name) }
|
||||
|
||||
realm.delete(Contact::class.java)
|
||||
realm.delete(Conversation::class.java)
|
||||
realm.delete(Message::class.java)
|
||||
realm.delete(MmsPart::class.java)
|
||||
realm.delete(Recipient::class.java)
|
||||
|
||||
keys.reset()
|
||||
|
||||
|
||||
// Sync messages
|
||||
cursorToMessage.getMessagesCursor()?.use { messageCursor ->
|
||||
val messageColumns = CursorToMessage.MessageColumns(messageCursor)
|
||||
val messages = messageCursor.map { cursor -> cursorToMessage.map(Pair(cursor, messageColumns)) }
|
||||
realm.insertOrUpdate(messages)
|
||||
}
|
||||
|
||||
// Migrate blocked conversations from 2.7.3
|
||||
val oldBlockedSenders = rxPrefs.getStringSet("pref_key_blocked_senders")
|
||||
persistedData += oldBlockedSenders.get()
|
||||
.map { threadIdString -> threadIdString.toLong() }
|
||||
.filter { threadId -> persistedData.none { it.id == threadId } }
|
||||
.map { threadId -> PersistedData(threadId, false, true, "") }
|
||||
|
||||
// Sync conversations
|
||||
cursorToConversation.getConversationsCursor()?.use { conversationCursor ->
|
||||
val conversations = conversationCursor
|
||||
.map { cursor -> cursorToConversation.map(cursor) }
|
||||
|
||||
persistedData.forEach { data ->
|
||||
val conversation = conversations.firstOrNull { conversation -> conversation.id == data.id }
|
||||
conversation?.archived = data.archived
|
||||
conversation?.blocked = data.blocked
|
||||
conversation?.name = data.name
|
||||
}
|
||||
|
||||
realm.insertOrUpdate(conversations)
|
||||
}
|
||||
|
||||
|
||||
// Sync recipients
|
||||
cursorToRecipient.getRecipientCursor()?.use { recipientCursor ->
|
||||
val contacts = realm.copyToRealm(getContacts())
|
||||
val recipients = recipientCursor
|
||||
.map { cursor -> cursorToRecipient.map(cursor) }
|
||||
.map { recipient ->
|
||||
recipient.apply {
|
||||
contact = contacts.firstOrNull { contact ->
|
||||
contact.numbers.any { PhoneNumberUtils.compare(recipient.address, it.address) }
|
||||
}
|
||||
}
|
||||
}
|
||||
realm.insertOrUpdate(recipients)
|
||||
}
|
||||
|
||||
|
||||
realm.insert(SyncLog())
|
||||
realm.commitTransaction()
|
||||
realm.close()
|
||||
|
||||
// Only delete this after the sync has successfully completed
|
||||
oldBlockedSenders.delete()
|
||||
|
||||
syncProgress.onNext(SyncRepository.SyncProgress.Idle())
|
||||
}
|
||||
|
||||
override fun syncMessage(uri: Uri): Message? {
|
||||
|
||||
// If we don't have a valid type, return null
|
||||
val type = when {
|
||||
uri.toString().contains("mms") -> "mms"
|
||||
uri.toString().contains("sms") -> "sms"
|
||||
else -> return null
|
||||
}
|
||||
|
||||
// If we don't have a valid id, return null
|
||||
val id = tryOrNull { 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
return contentResolver.query(stableUri, null, null, null, null)?.use { cursor ->
|
||||
|
||||
// If there are no rows, return null. Otherwise, we've moved to the first row
|
||||
if (!cursor.moveToFirst()) return null
|
||||
|
||||
val columnsMap = CursorToMessage.MessageColumns(cursor)
|
||||
cursorToMessage.map(Pair(cursor, columnsMap)).apply {
|
||||
existingId?.let { this.id = it }
|
||||
|
||||
conversationRepo.getOrCreateConversation(threadId)
|
||||
insertOrUpdate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun syncContacts() {
|
||||
// Load all the contacts
|
||||
var contacts = getContacts()
|
||||
|
||||
Realm.getDefaultInstance()?.use { realm ->
|
||||
val recipients = realm.where(Recipient::class.java).findAll()
|
||||
|
||||
realm.executeTransaction {
|
||||
realm.delete(Contact::class.java)
|
||||
|
||||
contacts = realm.copyToRealm(contacts)
|
||||
|
||||
// Update all the recipients with the new contacts
|
||||
val updatedRecipients = recipients.map { recipient ->
|
||||
recipient.apply {
|
||||
contact = contacts.firstOrNull {
|
||||
it.numbers.any { PhoneNumberUtils.compare(recipient.address, it.address) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
realm.insertOrUpdate(updatedRecipients)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private fun getContacts(): List<Contact> {
|
||||
return cursorToContact.getContactsCursor()
|
||||
?.map { cursor -> cursorToContact.map(cursor) }
|
||||
?.groupBy { contact -> contact.lookupKey }
|
||||
?.map { contacts ->
|
||||
val allNumbers = contacts.value.map { it.numbers }.flatten()
|
||||
contacts.value.first().apply {
|
||||
numbers.clear()
|
||||
numbers.addAll(allNumbers)
|
||||
}
|
||||
} ?: listOf()
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user