Reorganize package structure to adhere to offical Kotlin style guide

This commit is contained in:
Moez Bhatti
2018-01-02 17:13:27 -05:00
parent 8cd5ec31c8
commit a5ce40a404
136 changed files with 429 additions and 431 deletions
@@ -0,0 +1,48 @@
/*
* 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 data.mapper
import android.database.Cursor
import android.provider.ContactsContract
import data.model.Contact
import data.model.PhoneNumber
import javax.inject.Inject
class CursorToContact @Inject constructor() : Mapper<Cursor, Contact> {
companion object {
val URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
val PROJECTION = arrayOf(
ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
val LOOKUP_KEY = 0
val NUMBER = 1
val DISPLAY_NAME = 2
}
override fun map(from: Cursor) = Contact().apply {
lookupKey = from.getString(LOOKUP_KEY)
name = from.getString(DISPLAY_NAME)
numbers.add(PhoneNumber().apply { address = from.getString(NUMBER) })
lastUpdate = System.currentTimeMillis()
}
}
@@ -0,0 +1,51 @@
/*
* 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 data.mapper
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony.Threads
import data.model.Conversation
import data.model.Recipient
import javax.inject.Inject
class CursorToConversation @Inject constructor() : Mapper<Cursor, Conversation> {
companion object {
val URI: Uri = Uri.parse("content://mms-sms/conversations?simple=true")
val PROJECTION = arrayOf(
Threads._ID,
Threads.RECIPIENT_IDS)
val ID = 0
val RECIPIENT_IDS = 1
}
override fun map(from: Cursor): Conversation {
return Conversation().apply {
id = from.getLong(ID)
recipients.addAll(from.getString(RECIPIENT_IDS)
.split(" ")
.filter { it.isNotBlank() }
.map { recipientId -> recipientId.toLong() }
.map { recipientId -> Recipient().apply { id = recipientId } })
}
}
}
@@ -0,0 +1,193 @@
/*
* 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 data.mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony.*
import data.model.Message
import data.model.Message.DeliveryStatus
import timber.log.Timber
import javax.inject.Inject
class CursorToMessage @Inject constructor(val context: Context) : Mapper<Pair<Cursor, CursorToMessage.MessageColumns>, Message> {
override fun map(from: Pair<Cursor, MessageColumns>): Message {
val cursor = from.first
val columnsMap = from.second
return Message().apply {
type = when (cursor.getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN)) {
-1 -> "sms"
else -> cursor.getString(columnsMap.msgType)
}
id = cursor.getLong(columnsMap.msgId)
when (type) {
"sms" -> {
threadId = cursor.getLong(columnsMap.smsThreadId)
address = cursor.getString(columnsMap.smsAddress) ?: ""
boxId = cursor.getInt(columnsMap.smsType)
date = cursor.getLong(columnsMap.smsDate)
dateSent = cursor.getLong(columnsMap.smsDateSent)
read = cursor.getInt(columnsMap.smsRead) != 0
seen = cursor.getInt(columnsMap.smsSeen) != 0
locked = cursor.getInt(columnsMap.smsLocked) != 0
val status = cursor.getLong(columnsMap.smsStatus)
deliveryStatus = when {
status == Sms.STATUS_NONE.toLong() -> DeliveryStatus.NONE
status >= Sms.STATUS_FAILED -> DeliveryStatus.FAILED
status >= Sms.STATUS_PENDING -> DeliveryStatus.PENDING
else -> DeliveryStatus.RECEIVED
}
// SMS Specific
body = cursor.getString(columnsMap.smsBody) ?: ""
errorCode = cursor.getInt(columnsMap.smsErrorCode)
}
"mms" -> {
threadId = cursor.getLong(columnsMap.mmsThreadId)
address = getMmsAddress(id)
boxId = cursor.getInt(columnsMap.mmsMessageBox)
date = cursor.getLong(columnsMap.mmsDate) * 1000L
dateSent = cursor.getLong(columnsMap.mmsDateSent)
read = cursor.getInt(columnsMap.mmsRead) != 0
seen = cursor.getInt(columnsMap.mmsSeen) != 0
locked = cursor.getInt(columnsMap.mmsLocked) != 0
// MMS Specific
attachmentType = when (cursor.getInt(columnsMap.mmsTextOnly)) {
0 -> Message.AttachmentType.NOT_LOADED
else -> Message.AttachmentType.TEXT
}
mmsDeliveryStatusString = cursor.getString(columnsMap.mmsDeliveryReport) ?: ""
errorType = cursor.getInt(columnsMap.mmsErrorType)
messageSize = 0
readReportString = cursor.getString(columnsMap.mmsReadReport) ?: ""
messageType = cursor.getInt(columnsMap.mmsMessageType)
mmsStatus = cursor.getInt(columnsMap.mmsStatus)
subject = cursor.getString(columnsMap.mmsSubject) ?: ""
textContentType = ""
}
}
}
}
private fun getMmsAddress(messageId: Long): String {
val uri = Mms.CONTENT_URI.buildUpon()
.appendPath(messageId.toString())
.appendPath("addr").build()
//TODO: Use Charset to ensure address is decoded correctly
val projection = arrayOf(Mms.Addr.ADDRESS, Mms.Addr.CHARSET)
val selection = "${Mms.Addr.TYPE} = 137"
val cursor = context.contentResolver.query(uri, projection, selection, null, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getString(0)
}
}
return ""
}
companion object {
val URI = Uri.parse("content://mms-sms/complete-conversations")
val PROJECTION = arrayOf(
MmsSms.TYPE_DISCRIMINATOR_COLUMN,
MmsSms._ID,
Sms.THREAD_ID,
Sms.ADDRESS,
Sms.BODY,
Sms.DATE,
Sms.DATE_SENT,
Sms.SEEN,
Sms.READ,
Sms.TYPE,
Sms.STATUS,
Sms.LOCKED,
Sms.ERROR_CODE,
Mms.THREAD_ID,
Mms.Addr.ADDRESS,
Mms.SUBJECT,
Mms.SUBJECT_CHARSET,
Mms.DATE,
Mms.DATE_SENT,
Mms.SEEN,
Mms.READ,
Mms.MESSAGE_TYPE,
Mms.MESSAGE_BOX,
Mms.DELIVERY_REPORT,
Mms.READ_REPORT,
MmsSms.PendingMessages.ERROR_TYPE,
Mms.LOCKED,
Mms.STATUS,
Mms.TEXT_ONLY)
}
class MessageColumns(private val cursor: Cursor) {
val msgType by lazy { getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN) }
val msgId by lazy { getColumnIndex(MmsSms._ID) }
val smsThreadId by lazy { getColumnIndex(Sms.THREAD_ID) }
val smsAddress by lazy { getColumnIndex(Sms.ADDRESS) }
val smsBody by lazy { getColumnIndex(Sms.BODY) }
val smsDate by lazy { getColumnIndex(Sms.DATE) }
val smsDateSent by lazy { getColumnIndex(Sms.DATE_SENT) }
val smsSeen by lazy { getColumnIndex(Sms.SEEN) }
val smsRead by lazy { getColumnIndex(Sms.READ) }
val smsType by lazy { getColumnIndex(Sms.TYPE) }
val smsStatus by lazy { getColumnIndex(Sms.STATUS) }
val smsLocked by lazy { getColumnIndex(Sms.LOCKED) }
val smsErrorCode by lazy { getColumnIndex(Sms.ERROR_CODE) }
val mmsThreadId by lazy { getColumnIndex(Mms.THREAD_ID) }
val mmsAddress by lazy { getColumnIndex(Mms.Addr.ADDRESS) }
val mmsSubject by lazy { getColumnIndex(Mms.SUBJECT) }
val mmsSubjectCharset by lazy { getColumnIndex(Mms.SUBJECT_CHARSET) }
val mmsDate by lazy { getColumnIndex(Mms.DATE) }
val mmsDateSent by lazy { getColumnIndex(Mms.DATE_SENT) }
val mmsSeen by lazy { getColumnIndex(Mms.SEEN) }
val mmsRead by lazy { getColumnIndex(Mms.READ) }
val mmsMessageType by lazy { getColumnIndex(Mms.MESSAGE_TYPE) }
val mmsMessageBox by lazy { getColumnIndex(Mms.MESSAGE_BOX) }
val mmsDeliveryReport by lazy { getColumnIndex(Mms.DELIVERY_REPORT) }
val mmsReadReport by lazy { getColumnIndex(Mms.READ_REPORT) }
val mmsErrorType by lazy { getColumnIndex(MmsSms.PendingMessages.ERROR_TYPE) }
val mmsLocked by lazy { getColumnIndex(Mms.LOCKED) }
val mmsStatus by lazy { getColumnIndex(Mms.STATUS) }
val mmsTextOnly by lazy { getColumnIndex(Mms.TEXT_ONLY) }
private fun getColumnIndex(columnsName: String) = try {
cursor.getColumnIndexOrThrow(columnsName)
} catch (e: Exception) {
Timber.w(e)
-1
}
}
}
@@ -0,0 +1,43 @@
/*
* 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 data.mapper
import android.database.Cursor
import android.net.Uri
import data.model.Recipient
import data.repository.ContactRepository
import javax.inject.Inject
class CursorToRecipient @Inject constructor(private val contactRepository: ContactRepository) : Mapper<Cursor, Recipient> {
companion object {
val URI = Uri.parse("content://mms-sms/canonical-addresses")
val COLUMN_ID = 0
val COLUMN_ADDRESS = 1
}
override fun map(from: Cursor) = Recipient().apply {
id = from.getLong(COLUMN_ID)
address = from.getString(COLUMN_ADDRESS)
contact = contactRepository.getContactBlocking(address) // TODO do this lazily for faster syncs
lastUpdate = System.currentTimeMillis()
}
}
+25
View File
@@ -0,0 +1,25 @@
/*
* 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 data.mapper
interface Mapper<in From, out To> {
fun map(from: From): To
}
+32
View File
@@ -0,0 +1,32 @@
/*
* 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 data.model
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Contact : RealmObject() {
@PrimaryKey var lookupKey: String = ""
var numbers: RealmList<PhoneNumber> = RealmList()
var name: String = ""
var lastUpdate: Long = 0
}
@@ -0,0 +1,43 @@
/*
* 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 data.model
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Conversation : RealmObject() {
@PrimaryKey var id: Long = 0
var recipients: RealmList<Recipient> = RealmList()
var archived: Boolean = false
fun getTitle(): String {
var title = ""
recipients.forEachIndexed { index, recipient ->
val name = recipient.contact?.name
title += if (name.isNullOrBlank()) recipient.address else name
if (index < recipients.size - 1) {
title += ", "
}
}
return title
}
}
@@ -0,0 +1,24 @@
/*
* 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 data.model
/**
* Groups a conversation with its latest message into a single model
*/
data class InboxItem(val conversation: Conversation, val message: Message)
@@ -0,0 +1,23 @@
/*
* 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 data.model
import android.support.annotation.StringRes
data class MenuItem(@StringRes val title: Int, val actionId: Int)
+111
View File
@@ -0,0 +1,111 @@
/*
* 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 data.model
import android.content.ContentUris
import android.net.Uri
import android.provider.Telephony.*
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Message : RealmObject() {
enum class DeliveryStatus { NONE, INFO, FAILED, PENDING, RECEIVED }
enum class AttachmentType { TEXT, IMAGE, VIDEO, AUDIO, SLIDESHOW, NOT_LOADED }
@PrimaryKey var id: Long = 0
var threadId: Long = 0
var address: String = ""
var boxId: Int = 0
var type: String = ""
var body: String = ""
var date: Long = 0
var dateSent: Long = 0
var seen: Boolean = false
var read: Boolean = false
var locked: Boolean = false
var deliveryStatusString: String = DeliveryStatus.NONE.toString()
var deliveryStatus: DeliveryStatus
get() = DeliveryStatus.valueOf(deliveryStatusString)
set(value) {
deliveryStatusString = value.toString()
}
// SMS only
var errorCode: Int = 0
// MMS only
var attachmentTypeString: String = AttachmentType.NOT_LOADED.toString()
var attachmentType: AttachmentType
get() = AttachmentType.valueOf(attachmentTypeString)
set(value) {
attachmentTypeString = value.toString()
}
var mmsDeliveryStatusString: String = ""
var readReportString: String = ""
var errorType: Int = 0
var messageSize: Int = 0
var messageType: Int = 0
var mmsStatus: Int = 0
var subject: String = ""
var textContentType: String = ""
fun getUri(): Uri {
val baseUri = if (isMms()) Mms.CONTENT_URI else Sms.CONTENT_URI
return ContentUris.withAppendedId(baseUri, id)
}
fun isMms(): Boolean = type == "mms"
fun isSms(): Boolean = type == "sms"
fun isMe(): Boolean {
val isIncomingMms = isMms() && (boxId == Mms.MESSAGE_BOX_INBOX || boxId == Mms.MESSAGE_BOX_ALL)
val isIncomingSms = isSms() && (boxId == Sms.MESSAGE_TYPE_INBOX || boxId == Sms.MESSAGE_TYPE_ALL)
return !(isIncomingMms || isIncomingSms)
}
fun isOutgoingMessage(): Boolean {
val isOutgoingMms = isMms() && boxId == Mms.MESSAGE_BOX_OUTBOX
val isOutgoingSms = isSms() && (boxId == Sms.MESSAGE_TYPE_FAILED
|| boxId == Sms.MESSAGE_TYPE_OUTBOX
|| boxId == Sms.MESSAGE_TYPE_QUEUED)
return isOutgoingMms || isOutgoingSms
}
fun isSending(): Boolean {
return !isFailedMessage() && isOutgoingMessage()
}
fun isDelivered(): Boolean {
val isDeliveredMms = false // TODO
val isDeliveredSms = deliveryStatus == DeliveryStatus.RECEIVED
return isDeliveredMms || isDeliveredSms
}
fun isFailedMessage(): Boolean {
val isFailedMms = isMms() && errorType >= MmsSms.ERR_TYPE_GENERIC_PERMANENT
val isFailedSms = isSms() && boxId == Sms.MESSAGE_TYPE_FAILED
return isFailedMms || isFailedSms
}
}
+28
View File
@@ -0,0 +1,28 @@
/*
* 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 data.model
import android.net.Uri
class MmsPart {
var name = ""
var mimeType = ""
var data: ByteArray? = null
var path: Uri? = null
}
@@ -0,0 +1,28 @@
/*
* 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 data.model
import io.realm.RealmObject
open class PhoneNumber : RealmObject() {
var address: String = ""
var label: String = ""
}
@@ -0,0 +1,31 @@
/*
* 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 data.model
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Recipient : RealmObject() {
@PrimaryKey var id: Long = 0
var address: String = ""
var contact: Contact? = null
var lastUpdate: Long = 0
}
+27
View File
@@ -0,0 +1,27 @@
/*
* 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 data.model
import io.realm.RealmObject
open class SyncLog : RealmObject() {
var date: Long = System.currentTimeMillis()
}
@@ -0,0 +1,96 @@
/*
* 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 data.repository
import android.content.Context
import android.net.Uri
import android.provider.BaseColumns
import android.provider.ContactsContract
import common.util.extensions.asFlowable
import data.model.Contact
import data.model.PhoneNumber
import io.reactivex.Flowable
import io.reactivex.Single
import io.realm.Realm
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ContactRepository @Inject constructor(val context: Context) {
fun findContactUri(address: String): Single<Uri> {
return Flowable.just(address)
.map { address -> Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address)) }
.flatMap { uri -> context.contentResolver.query(uri, arrayOf(ContactsContract.PhoneLookup._ID), null, null, null).asFlowable() }
.firstOrError()
.map { cursor -> cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID)) }
.map { id -> Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, id) }
}
fun getContacts(): List<Contact> {
val realm = Realm.getDefaultInstance()
val results = realm.copyFromRealm(realm
.where(Contact::class.java)
.findAllSorted("name"))
realm.close()
return results
}
fun getContact(address: String): Flowable<Contact> {
return Flowable.fromPublisher<Contact> { emitter ->
getContactBlocking(address)?.let { emitter.onNext(it) }
emitter.onComplete()
}
}
fun getContactBlocking(address: String): Contact? {
if (address.isEmpty()) return null
val realm = Realm.getDefaultInstance()
var contact = realm.where(Contact::class.java)
.equalTo("numbers.address", address)
.findFirst()
realm.close()
if (contact == null) {
val contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address))
val projection = arrayOf(BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.LOOKUP_KEY)
try {
context.contentResolver.query(contactUri, projection, null, null, null).use { contactCursor ->
if (contactCursor.moveToFirst()) {
contact = Contact().apply {
numbers.add(PhoneNumber().apply { this.address = address })
name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).orEmpty()
lookupKey = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.LOOKUP_KEY)).orEmpty()
lastUpdate = System.currentTimeMillis()
}
}
}
} catch (e: Exception) {
Timber.w(e)
}
}
return contact
}
}
@@ -0,0 +1,472 @@
/*
* 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 data.repository
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.provider.BaseColumns
import android.provider.Telephony
import android.provider.Telephony.Sms
import android.provider.Telephony.TextBasedSmsColumns
import common.util.Keys
import common.util.MessageUtils
import common.util.extensions.asFlowable
import common.util.extensions.asMaybe
import common.util.extensions.insertOrUpdate
import common.util.extensions.mapNotNull
import data.mapper.CursorToConversation
import data.mapper.CursorToRecipient
import data.model.Conversation
import data.model.InboxItem
import data.model.Message
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Flowables
import io.reactivex.rxkotlin.toFlowable
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import io.realm.RealmResults
import io.realm.Sort
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MessageRepository @Inject constructor(
private val context: Context,
private val messageIds: Keys,
private val cursorToConversation: CursorToConversation,
private val cursorToRecipient: CursorToRecipient) {
fun getConversations(archived: Boolean = false): Flowable<List<InboxItem>> {
val realm = Realm.getDefaultInstance()
val conversationFlowable = realm.where(Conversation::class.java)
.equalTo("archived", archived)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.map { realm.copyFromRealm(it) }
// Adding the #distinct() call makes this call approx 20x slower
// With ~70,000 messages on a Google Pixel, it goes from 15ms -> 300ms
// This should be fixed by using Realm 4.3, but that breaks the build
// Will fix
val messageFlowable = realm.where(Message::class.java)
.findAllSortedAsync("date", Sort.DESCENDING)
.where()
.distinctAsync("threadId")
.asFlowable()
.filter { it.isLoaded }
.map { realm.copyFromRealm(it) }
return Flowables.combineLatest(conversationFlowable, messageFlowable, { conversations, messages ->
val conversationMap = conversations.associateBy { conversation -> conversation.id }
messages.mapNotNull { message ->
val conversation = conversationMap[message.threadId]
if (conversation == null) null else InboxItem(conversation, message)
}
})
}
fun getConversationAsync(threadId: Long): Conversation {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirstAsync()
}
fun getConversation(threadId: Long): Conversation? {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
}
fun getOrCreateConversation(address: String): Maybe<Conversation> {
return getOrCreateConversation(listOf(address))
}
fun getOrCreateConversation(addresses: List<String>): Maybe<Conversation> {
return Maybe.just(addresses)
.map { recipients ->
recipients.map { address ->
when (MessageUtils.isEmailAddress(address)) {
true -> MessageUtils.extractAddrSpec(address)
false -> address
}
}
}
.map { recipients ->
Uri.parse("content://mms-sms/threadID").buildUpon().apply {
recipients.forEach { recipient -> appendQueryParameter("recipient", recipient) }
}
}
.flatMap { uriBuilder ->
context.contentResolver.query(uriBuilder.build(), arrayOf(BaseColumns._ID), null, null, null).asMaybe()
}
.map { cursor -> cursor.getLong(0) }
.filter { threadId -> threadId != 0L }
.map { threadId ->
var conversation = getConversation(threadId)
if (conversation != null) conversation = Realm.getDefaultInstance().copyFromRealm(conversation)
conversation ?: getConversationFromCp(threadId)?.apply { insertOrUpdate() } ?: Conversation()
}
.onErrorReturn { Conversation() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
fun getMessages(threadId: Long): RealmResults<Message> {
return Realm.getDefaultInstance()
.where(Message::class.java)
.equalTo("threadId", threadId)
.findAllSorted("date")
}
/**
* Retrieves the list of messages which should be shown in the notification
* for a given conversation
*/
fun getUnreadUnseenMessages(threadId: Long): RealmResults<Message> {
return Realm.getDefaultInstance()
.where(Message::class.java)
.equalTo("seen", false)
.equalTo("read", false)
.equalTo("threadId", threadId)
.findAllSorted("date")
}
fun markArchived(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.equalTo("archived", false)
.findFirst()
realm.executeTransaction { conversation?.archived = true }
realm.close()
}
fun markUnarchived(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.equalTo("archived", true)
.findFirst()
realm.executeTransaction { conversation?.archived = false }
realm.close()
}
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()
}
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()
}
fun markRead(threadId: Long) {
// TODO also need to mark MMS in ContentProvider as Read
val projection = arrayOf(BaseColumns._ID)
val selection = "${Sms.THREAD_ID} = $threadId AND (${Sms.SEEN} = 0 OR ${Sms.READ} = 0)"
val contentResolver = context.contentResolver
contentResolver.query(Sms.Inbox.CONTENT_URI, projection, selection, null, null)
.asFlowable()
.subscribeOn(Schedulers.io())
.map { cursor -> cursor.getLong(0) }
.map { id -> Uri.withAppendedPath(Sms.CONTENT_URI, id.toString()) }
.subscribe { uri ->
val values = ContentValues()
values.put(Sms.SEEN, true)
values.put(Sms.READ, true)
contentResolver.update(uri, values, null, null)
}
val realm = Realm.getDefaultInstance()
val messages = realm.where(Message::class.java)
.equalTo("threadId", threadId)
.beginGroup()
.equalTo("read", false)
.or()
.equalTo("seen", false)
.endGroup()
.findAll()
realm.executeTransaction {
messages.forEach { message ->
message.seen = true
message.read = true
}
}
realm.close()
}
fun insertSentSms(threadId: Long, address: String, body: String): Message {
// Insert the message to Realm
val message = Message().apply {
this.threadId = threadId
this.address = address
this.body = body
this.date = System.currentTimeMillis()
id = messageIds.newId()
boxId = Sms.MESSAGE_TYPE_OUTBOX
type = "sms"
read = true
seen = true
}
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.insert(message) }
realm.close()
// 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)
}
context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values)
return message
}
fun insertReceivedSms(address: String, body: String, sentTime: Long): Message {
// Insert the message to Realm
val realm = Realm.getDefaultInstance()
val message = Message().apply {
this.address = address
this.body = body
this.dateSent = sentTime
this.date = System.currentTimeMillis()
id = messageIds.newId()
threadId = getOrCreateConversation(address).blockingGet().id
boxId = Sms.MESSAGE_TYPE_INBOX
type = "sms"
realm.executeTransaction { realm.insert(this) }
}
realm.close()
// Insert the message to the native content provider
ContentValues().apply {
put(Telephony.Sms.ADDRESS, address)
put(Telephony.Sms.BODY, body)
put(Telephony.Sms.DATE_SENT, sentTime)
put(Telephony.Sms.READ, false)
put(Telephony.Sms.SEEN, false)
context.contentResolver.insert(Telephony.Sms.Inbox.CONTENT_URI, this)
}
return message
}
fun markSent(id: Long): Flowable<*> {
val realm = Realm.getDefaultInstance()
return realm.where(Message::class.java).equalTo("id", id)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.filter { it.isValid }
.mapNotNull { it[0] }
.take(1)
.doOnNext { message ->
// Update the message in realm
realm.executeTransaction {
message.boxId = Sms.MESSAGE_TYPE_SENT
}
}
.map { message -> message.getUri() }
.observeOn(Schedulers.computation())
.doOnNext { uri ->
// Update the message in the native ContentProvider
val values = ContentValues()
values.put(Sms.TYPE, Sms.MESSAGE_TYPE_SENT)
context.contentResolver.update(uri, values, null, null)
}
}
fun markFailed(id: Long, resultCode: Int): Flowable<*> {
val realm = Realm.getDefaultInstance()
return realm.where(Message::class.java).equalTo("id", id)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.filter { it.isValid }
.mapNotNull { it[0] }
.take(1)
.doOnNext { message ->
// Update the message in realm
realm.executeTransaction {
message.boxId = Sms.MESSAGE_TYPE_FAILED
message.errorCode = resultCode
}
}
.map { message -> message.getUri() }
.observeOn(Schedulers.computation())
.doOnNext { uri ->
// Update the message in the native ContentProvider
val values = ContentValues()
values.put(Sms.TYPE, Sms.MESSAGE_TYPE_FAILED)
values.put(Sms.ERROR_CODE, resultCode)
context.contentResolver.update(uri, values, null, null)
}
}
fun markDelivered(id: Long): Flowable<*> {
val realm = Realm.getDefaultInstance()
return realm.where(Message::class.java).equalTo("id", id)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.filter { it.isValid }
.mapNotNull { it[0] }
.take(1)
.doOnNext { message ->
// Update the message in realm
realm.executeTransaction {
message.deliveryStatus = Message.DeliveryStatus.RECEIVED
message.dateSent = System.currentTimeMillis()
message.read = true
}
}
.map { message -> message.getUri() }
.observeOn(Schedulers.computation())
.doOnNext { uri ->
// Update the message in the native ContentProvider
val values = ContentValues()
values.put(Sms.STATUS, TextBasedSmsColumns.STATUS_COMPLETE)
values.put(Sms.DATE_SENT, System.currentTimeMillis())
values.put(Sms.READ, true)
context.contentResolver.update(uri, values, null, null)
}
}
fun markDeliveryFailed(id: Long, resultCode: Int): Flowable<*> {
val realm = Realm.getDefaultInstance()
return realm.where(Message::class.java).equalTo("id", id)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.filter { it.isValid }
.mapNotNull { it[0] }
.take(1)
.doOnNext { message ->
// Update the message in realm
realm.executeTransaction {
message.deliveryStatus = Message.DeliveryStatus.FAILED
message.dateSent = System.currentTimeMillis()
message.read = true
message.errorCode = resultCode
}
}
.map { message -> message.getUri() }
.observeOn(Schedulers.computation())
.doOnNext { uri ->
// Update the message in the native ContentProvider
val values = ContentValues()
values.put(Sms.STATUS, TextBasedSmsColumns.STATUS_FAILED)
values.put(Sms.DATE_SENT, System.currentTimeMillis())
values.put(Sms.READ, true)
values.put(Sms.ERROR_CODE, resultCode)
context.contentResolver.update(uri, values, null, null)
}
}
fun deleteMessage(messageId: Long) {
val realm = Realm.getDefaultInstance()
realm.where(Message::class.java).equalTo("id", messageId).findFirst()?.let { message ->
realm.executeTransaction { message.deleteFromRealm() }
context.contentResolver.delete(message.getUri(), null, null)
}
realm.close()
}
fun deleteConversation(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java).equalTo("id", threadId).findAll()
val messages = realm.where(Message::class.java).equalTo("threadId", threadId).findAll()
realm.executeTransaction {
conversation.deleteAllFromRealm()
messages.deleteAllFromRealm()
}
realm.close()
val uri = Uri.withAppendedPath(Telephony.Threads.CONTENT_URI, threadId.toString())
context.contentResolver.delete(uri, null, null)
}
private fun getConversationFromCp(threadId: Long): Conversation? {
var conversation: Conversation? = null
val cursor = context.contentResolver.query(
CursorToConversation.URI,
CursorToConversation.PROJECTION,
"_id = ?",
arrayOf(threadId.toString()),
null)
if (cursor.moveToFirst()) {
conversation = cursorToConversation.map(cursor)
conversation.insertOrUpdate()
conversation.recipients.toFlowable()
.map { recipient -> recipient.id.toString() }
.map { id -> context.contentResolver.query(CursorToRecipient.URI, null, "_id = ?", arrayOf(id), null) }
.flatMap { recipientCursor -> recipientCursor.asFlowable().map { cursor -> cursorToRecipient.map(cursor) } }
.doOnNext { recipient -> recipient.insertOrUpdate() }
.blockingSubscribe()
}
cursor.close()
return conversation
}
}