Split up app module into domain/data/presentation

This commit is contained in:
Moez Bhatti
2018-03-22 00:32:07 -04:00
parent 4ef97ab854
commit d7d202392c
282 changed files with 1153 additions and 482 deletions
@@ -0,0 +1,52 @@
/*
* 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 manager
import io.realm.Realm
import model.Message
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class KeyManagerImpl @Inject constructor() : KeyManager {
private var maxValue: Long = 0L
init {
val realm = Realm.getDefaultInstance()
maxValue = realm.where(Message::class.java).max("id")?.toLong() ?: 0L
realm.close()
}
/**
* Should be called when a new sync is being started
*/
override fun reset() {
maxValue = 0L
}
/**
* Returns a valid ID that can be used to store a new message
*/
override fun newId(): Long {
maxValue++
return maxValue
}
}
@@ -0,0 +1,34 @@
/*
* 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 manager
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.content.ContextCompat
import javax.inject.Inject
class PermissionManagerImpl @Inject constructor(private val context: Context) : PermissionManager {
override fun hasSmsAndContacts(): Boolean {
return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
}
}
@@ -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 manager
import android.content.Context
import me.leolin.shortcutbadger.ShortcutBadger
import javax.inject.Inject
class WidgetManagerImpl @Inject constructor(private val context: Context) : WidgetManager {
override fun updateUnreadCount(count: Int) {
ShortcutBadger.applyCount(context, count)
}
}
@@ -0,0 +1,54 @@
/*
* 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 mapper
import android.content.Context
import android.database.Cursor
import android.provider.ContactsContract.CommonDataKinds.Phone.*
import model.Contact
import model.PhoneNumber
import javax.inject.Inject
class CursorToContactImpl @Inject constructor(private val context: Context) : CursorToContact {
companion object {
val URI = CONTENT_URI
val PROJECTION = arrayOf(LOOKUP_KEY, NUMBER, TYPE, DISPLAY_NAME)
const val COLUMN_LOOKUP_KEY = 0
const val COLUMN_NUMBER = 1
const val COLUMN_TYPE = 2
const val COLUMN_DISPLAY_NAME = 3
}
override fun map(from: Cursor) = Contact().apply {
lookupKey = from.getString(COLUMN_LOOKUP_KEY)
name = from.getString(COLUMN_DISPLAY_NAME)
numbers.add(PhoneNumber().apply {
address = from.getString(COLUMN_NUMBER)
type = context.getString(getTypeLabelResource(from.getInt(COLUMN_TYPE)))
})
lastUpdate = System.currentTimeMillis()
}
override fun getContactsCursor(): Cursor {
return context.contentResolver.query(URI, PROJECTION, null, null, null)
}
}
@@ -0,0 +1,64 @@
/*
* 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 mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony
import android.provider.Telephony.Threads
import model.Conversation
import model.Recipient
import javax.inject.Inject
class CursorToConversationImpl @Inject constructor(private val context: Context) : CursorToConversation {
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 } })
}
}
override fun getConversationsCursor(lastSync: Long): Cursor {
return context.contentResolver.query(URI, PROJECTION,
"date > $lastSync AND ${Telephony.Threads.MESSAGE_COUNT} > 0", null,
"date desc")
}
override fun getConversationCursor(threadId: Long): Cursor {
return context.contentResolver.query(URI, PROJECTION,
"_id = ?", arrayOf(threadId.toString()), null)
}
}
@@ -0,0 +1,145 @@
/*
* 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 mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony.*
import com.google.android.mms.pdu_alt.PduHeaders
import manager.KeyManager
import model.Message
import util.extensions.map
import javax.inject.Inject
class CursorToMessageImpl @Inject constructor(
private val context: Context,
private val keys: KeyManager,
private val cursorToPart: CursorToPart
) : CursorToMessage {
companion object {
val URI = Uri.parse("content://mms-sms/complete-conversations")
val PROJECTION = arrayOf(
MmsSms.TYPE_DISCRIMINATOR_COLUMN,
MmsSms._ID,
Mms.DATE,
Mms.DATE_SENT,
Mms.READ,
Mms.THREAD_ID,
Mms.LOCKED,
Sms.ADDRESS,
Sms.BODY,
Sms.SEEN,
Sms.TYPE,
Sms.STATUS,
Sms.ERROR_CODE,
Mms.SUBJECT,
Mms.SUBJECT_CHARSET,
Mms.SEEN,
Mms.MESSAGE_TYPE,
Mms.MESSAGE_BOX,
Mms.DELIVERY_REPORT,
Mms.READ_REPORT,
MmsSms.PendingMessages.ERROR_TYPE,
Mms.STATUS)
}
override fun map(from: Pair<Cursor, CursorToMessage.MessageColumns>): Message {
val cursor = from.first
val columnsMap = from.second
return Message().apply {
type = when {
cursor.getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN) != -1 -> cursor.getString(columnsMap.msgType)
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> "mms"
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> "sms"
else -> "unknown"
}
id = keys.newId()
contentId = cursor.getLong(columnsMap.msgId)
threadId = cursor.getLong(columnsMap.threadId)
date = cursor.getLong(columnsMap.date)
dateSent = cursor.getLong(columnsMap.dateSent)
read = cursor.getInt(columnsMap.read) != 0
locked = cursor.getInt(columnsMap.locked) != 0
when (type) {
"sms" -> {
address = cursor.getString(columnsMap.smsAddress) ?: ""
boxId = cursor.getInt(columnsMap.smsType)
seen = cursor.getInt(columnsMap.smsSeen) != 0
body = if (columnsMap.smsBody != -1) cursor.getString(columnsMap.smsBody) else null ?: ""
errorCode = cursor.getInt(columnsMap.smsErrorCode)
deliveryStatus = cursor.getInt(columnsMap.smsStatus)
}
"mms" -> {
address = getMmsAddress(contentId)
boxId = cursor.getInt(columnsMap.mmsMessageBox)
date *= 1000L
dateSent *= 1000L
seen = cursor.getInt(columnsMap.mmsSeen) != 0
mmsDeliveryStatusString = cursor.getString(columnsMap.mmsDeliveryReport) ?: ""
errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
messageSize = 0
readReportString = cursor.getString(columnsMap.mmsReadReport) ?: ""
messageType = cursor.getInt(columnsMap.mmsMessageType)
mmsStatus = cursor.getInt(columnsMap.mmsStatus)
subject = cursor.getString(columnsMap.mmsSubject) ?: ""
textContentType = ""
attachmentType = Message.AttachmentType.NOT_LOADED
parts.addAll(cursorToPart.getPartsCursor(contentId)?.map { cursorToPart.map(it) } ?: listOf())
}
}
}
}
override fun getMessagesCursor(): Cursor {
return context.contentResolver.query(URI, PROJECTION, null, null, "normalized_date desc")
}
override fun getMessageCursor(id: Long): Cursor {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
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} = ${PduHeaders.FROM}"
val cursor = context.contentResolver.query(uri, projection, selection, null, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getString(0)
}
}
return ""
}
}
@@ -0,0 +1,85 @@
/*
* 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 mapper
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony
import model.MmsPart
import timber.log.Timber
import util.extensions.isImage
import util.extensions.isSmil
import util.extensions.isText
import java.io.BufferedReader
import java.io.InputStreamReader
import javax.inject.Inject
class CursorToPartImpl @Inject constructor(private val context: Context) : CursorToPart {
companion object {
val CONTENT_URI: Uri = Uri.parse("content://mms/part")
}
override fun map(from: Cursor) = MmsPart().apply {
id = from.getLong(from.getColumnIndexOrThrow(Telephony.Mms.Part._ID))
messageId = from.getLong(from.getColumnIndexOrThrow(Telephony.Mms.Part.MSG_ID))
// Type will sometimes return null, resulting in a crash if we don't default to an empty string
type = from.getString(from.getColumnIndexOrThrow(Telephony.Mms.Part.CONTENT_TYPE)) ?: ""
val data = from.getString(from.getColumnIndexOrThrow(Telephony.Mms.Part._DATA))
when {
isSmil() -> {
// Do nothing
}
isImage() -> image = ContentUris.withAppendedId(CONTENT_URI, id).toString()
isText() -> {
text = if (data == null) {
from.getString(from.getColumnIndexOrThrow("text"))
} else {
val uri = ContentUris.withAppendedId(CONTENT_URI, id)
val sb = StringBuilder()
context.contentResolver.openInputStream(uri)?.use { inputStream ->
val isr = InputStreamReader(inputStream, "UTF-8")
val reader = BufferedReader(isr)
var temp = reader.readLine()
while (temp != null) {
sb.append(temp)
temp = reader.readLine()
}
}
sb.toString()
}
}
else -> Timber.v("Unhandled type: $type")
}
}
override fun getPartsCursor(messageId: Long): Cursor? {
return context.contentResolver.query(CONTENT_URI, null,
"${Telephony.Mms.Part.MSG_ID} = ?", arrayOf(messageId.toString()), null)
}
}
@@ -0,0 +1,50 @@
/*
* 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 mapper
import android.content.Context
import android.database.Cursor
import android.net.Uri
import model.Recipient
import javax.inject.Inject
class CursorToRecipienImpl @Inject constructor(private val context: Context) : CursorToRecipient {
companion object {
val URI = Uri.parse("content://mms-sms/canonical-addresses")
const val COLUMN_ID = 0
const val COLUMN_ADDRESS = 1
}
override fun map(from: Cursor) = Recipient().apply {
id = from.getLong(COLUMN_ID)
address = from.getString(COLUMN_ADDRESS)
lastUpdate = System.currentTimeMillis()
}
override fun getRecipientCursor(): Cursor {
return context.contentResolver.query(URI, null, null, null, null)
}
override fun getRecipientCursor(id: Long): Cursor {
return context.contentResolver.query(URI, null, "_id = ?", arrayOf(id.toString()), null)
}
}
@@ -0,0 +1,59 @@
/*
* 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 repository
import android.content.Context
import android.net.Uri
import android.provider.ContactsContract
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import model.Contact
import util.extensions.asFlowable
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 { 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) }
}
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,603 @@
/*
* 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 repository
import android.app.PendingIntent
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.BaseColumns
import android.provider.Telephony
import android.telephony.PhoneNumberUtils
import android.telephony.SmsManager
import com.klinker.android.send_message.BroadcastUtils
import com.klinker.android.send_message.StripAccents
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Flowables
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import io.realm.RealmResults
import io.realm.Sort
import manager.KeyManager
import mapper.CursorToConversation
import mapper.CursorToRecipient
import model.Contact
import model.Conversation
import model.Message
import model.MmsPart
import util.MessageUtils
import util.Preferences
import util.extensions.asFlowable
import util.extensions.asMaybe
import util.extensions.asObservable
import util.extensions.insertOrUpdate
import util.extensions.map
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MessageRepositoryImpl @Inject constructor(
private val context: Context,
private val messageIds: KeyManager,
private val cursorToConversation: CursorToConversation,
private val cursorToRecipient: CursorToRecipient,
private val prefs: Preferences) : MessageRepository {
override fun getConversations(archived: Boolean): Flowable<List<Pair<Conversation, Message>>> {
val realm = Realm.getDefaultInstance()
val conversationFlowable = realm.where(Conversation::class.java)
.equalTo("archived", archived)
.equalTo("blocked", false)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.map { realm.copyFromRealm(it) }
val messageFlowable = realm.where(Message::class.java)
.sort("date", Sort.DESCENDING)
.distinctValues("threadId")
.findAllAsync()
.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 Pair(conversation, message)
}
})
}
override fun getBlockedConversations(): Flowable<List<Conversation>> {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("blocked", true)
.findAllAsync()
.asFlowable()
.filter { it.isLoaded }
.map { it.toList() }
}
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 getOrCreateConversation(threadId: Long): Conversation? {
return getConversation(threadId) ?: getConversationFromCp(threadId)
}
override fun getOrCreateConversation(address: String): Maybe<Conversation> {
return getOrCreateConversation(listOf(address))
}
override 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())
}
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 getMessages(threadId: Long): RealmResults<Message> {
return Realm.getDefaultInstance()
.where(Message::class.java)
.equalTo("threadId", threadId)
.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 getUnreadMessageCount(): Long {
return Realm.getDefaultInstance()
.where(Message::class.java)
.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): Observable<List<MmsPart>> {
return Realm.getDefaultInstance()
.where(Message::class.java)
.equalTo("threadId", threadId)
.isNotEmpty("parts")
.sort("date")
.findAll()
.asObservable()
.map { messages -> messages.flatMap { it.parts } }
}
/**
* 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()
.where(Message::class.java)
.equalTo("seen", false)
.equalTo("read", false)
.equalTo("threadId", threadId)
.sort("date")
.findAll()
}
override fun markArchived(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
realm.executeTransaction { conversation?.archived = true }
realm.close()
}
override fun markUnarchived(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
realm.executeTransaction { conversation?.archived = false }
realm.close()
}
override fun markBlocked(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
realm.executeTransaction { conversation?.blocked = true }
realm.close()
}
override fun markUnblocked(threadId: Long) {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
realm.executeTransaction { conversation?.blocked = false }
realm.close()
}
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(threadId: Long) {
// TODO also need to mark MMS in ContentProvider as Read
val projection = arrayOf(BaseColumns._ID)
val selection = "${Telephony.Sms.THREAD_ID} = $threadId AND (${Telephony.Sms.SEEN} = 0 OR ${Telephony.Sms.READ} = 0)"
val contentResolver = context.contentResolver
contentResolver.query(Telephony.Sms.Inbox.CONTENT_URI, projection, selection, null, null)
.asFlowable()
.subscribeOn(Schedulers.io())
.map { cursor -> cursor.getLong(0) }
.map { id -> Uri.withAppendedPath(Telephony.Sms.CONTENT_URI, id.toString()) }
.subscribe { uri ->
val values = ContentValues()
values.put(Telephony.Sms.SEEN, true)
values.put(Telephony.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()
}
override fun sendSmsAndPersist(threadId: Long, address: String, body: String) {
val message = insertSentSms(threadId, address, body)
sendSms(message)
}
override fun sendSms(message: Message) {
val smsManager = SmsManager.getDefault()
val parts = smsManager.divideMessage(if (prefs.unicode.get()) StripAccents.stripAccents(message.body) else message.body)
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 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 = Telephony.Sms.MESSAGE_TYPE_OUTBOX
type = "sms"
read = true
seen = true
}
val realm = Realm.getDefaultInstance()
var managedMessage: Message? = null
realm.executeTransaction { managedMessage = realm.copyToRealm(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)
}
val uri = context.contentResolver.insert(Telephony.Sms.CONTENT_URI, values)
// Update the contentId after the message has been inserted to the content provider
realm.executeTransaction { managedMessage?.contentId = uri.lastPathSegment.toLong() }
realm.close()
return message
}
override fun insertReceivedSms(address: String, body: String, sentTime: Long): Message {
// Insert the message to Realm
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 = Telephony.Sms.MESSAGE_TYPE_INBOX
type = "sms"
}
val realm = Realm.getDefaultInstance()
var managedMessage: Message? = null
realm.executeTransaction { managedMessage = realm.copyToRealm(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)
}
val uri = context.contentResolver.insert(Telephony.Sms.Inbox.CONTENT_URI, values)
// Update the contentId after the message has been inserted to the content provider
realm.executeTransaction { managedMessage?.contentId = uri.lastPathSegment.toLong() }
realm.close()
return message
}
/**
* 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 deleteMessage(messageId: Long) {
val realm = Realm.getDefaultInstance()
realm.where(Message::class.java).equalTo("id", messageId).findFirst()?.let { message ->
val uri = message.getUri()
realm.executeTransaction { message.deleteFromRealm() }
context.contentResolver.delete(uri, null, null)
}
realm.close()
}
override fun deleteConversation(threadId: Long) {
Realm.getDefaultInstance().use { realm ->
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()
}
}
val uri = ContentUris.withAppendedId(Telephony.Threads.CONTENT_URI, threadId)
context.contentResolver.delete(uri, null, null)
}
private fun getConversationFromCp(threadId: Long): Conversation? {
var conversation: Conversation? = null
val cursor = cursorToConversation.getConversationCursor(threadId)
if (cursor.moveToFirst()) {
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) }
.map { recipientCursor -> 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)
conversation.insertOrUpdate()
realm.close()
}
cursor.close()
return conversation
}
}
@@ -0,0 +1,188 @@
/*
* 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 repository
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.Telephony
import android.telephony.PhoneNumberUtils
import io.reactivex.Flowable
import io.realm.Realm
import mapper.CursorToContact
import mapper.CursorToConversation
import mapper.CursorToMessage
import mapper.CursorToRecipient
import model.Contact
import model.Conversation
import model.Message
import model.MmsPart
import model.Recipient
import model.SyncLog
import util.extensions.asFlowable
import util.extensions.insertOrUpdate
import util.extensions.map
import util.extensions.mapWhile
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SyncRepositoryImpl @Inject constructor(
private val context: Context,
private val messageRepo: MessageRepository,
private val cursorToConversation: CursorToConversation,
private val cursorToMessage: CursorToMessage,
private val cursorToRecipient: CursorToRecipient,
private val cursorToContact: CursorToContact
) : SyncRepository {
sealed class Status {
class Idle : Status()
class Running : Status()
}
private val contentResolver = context.contentResolver
private var status: Status = Status.Idle()
override fun syncMessages(fullSync: Boolean) {
// If the sync is already running, don't try to do another one
if (status is Status.Running) return
status = Status.Running()
val realm = Realm.getDefaultInstance()
realm.beginTransaction()
if (fullSync) {
realm.delete(Conversation::class.java)
realm.delete(Message::class.java)
realm.delete(MmsPart::class.java)
realm.delete(Recipient::class.java)
realm.delete(SyncLog::class.java)
}
val lastSync = realm.where(Message::class.java)?.max("date")?.toLong() ?: 0
realm.insert(SyncLog())
// Sync conversations
val conversationCursor = cursorToConversation.getConversationsCursor()
val conversations = conversationCursor.map { cursor -> cursorToConversation.map(cursor) }
realm.insertOrUpdate(conversations)
conversationCursor.close()
// Sync messages
val messageCursor = cursorToMessage.getMessagesCursor()
val messageColumns = CursorToMessage.MessageColumns(messageCursor)
val messages = messageCursor.mapWhile(
{ cursor -> cursorToMessage.map(Pair(cursor, messageColumns)) },
{ message -> message.date > lastSync })
realm.insertOrUpdate(messages)
messageCursor.close()
// Sync recipients
val recipientCursor = cursorToRecipient.getRecipientCursor()
val recipients = recipientCursor.map { cursor -> cursorToRecipient.map(cursor) }
realm.insertOrUpdate(recipients)
recipientCursor.close()
realm.commitTransaction()
realm.close()
syncContacts()
status = Status.Idle()
}
override fun syncMessage(uri: Uri): Flowable<Message> {
val id = ContentUris.parseId(uri)
val type = when {
uri.toString().contains("mms") -> "mms"
uri.toString().contains("sms") -> "sms"
else -> return Flowable.empty()
}
// 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)
}
val cursor = context.contentResolver.query(stableUri, null, null, null, null)
val columnsMap = CursorToMessage.MessageColumns(cursor)
// Map the cursor to a message
return cursor.asFlowable()
.map { cursorToMessage.map(Pair(it, columnsMap)) }
.map { message ->
existingId?.let { message.id = it }
message
}
.doOnNext { message -> messageRepo.getOrCreateConversation(message.threadId) }
.doOnNext { message -> message.insertOrUpdate() }
}
override fun syncContacts() {
// Load all the contacts
var contacts = 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)
}
}
val realm = Realm.getDefaultInstance()
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)
}
realm.close()
}
}
+50
View File
@@ -0,0 +1,50 @@
/*
* 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 util
import android.text.TextUtils
import android.util.Patterns
import java.util.regex.Pattern
/**
* Utils for using Telephony functions on lower API levels
*
* Adapted from https://android.googlesource.com/platform/packages/apps/Messaging/+/master/src/com/android/messaging/sms/MmsSmsUtils.java
*/
object MessageUtils {
val NAME_ADDR_EMAIL_PATTERN = Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*")
fun extractAddrSpec(address: String): String {
val match = NAME_ADDR_EMAIL_PATTERN.matcher(address)
return if (match.matches()) {
match.group(2)
} else address
}
fun isEmailAddress(address: String): Boolean {
if (TextUtils.isEmpty(address)) {
return false
}
val s = extractAddrSpec(address)
val match = Patterns.EMAIL_ADDRESS.matcher(s)
return match.matches()
}
}
+83
View File
@@ -0,0 +1,83 @@
/*
* 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 util
import android.provider.Settings
import com.f2prateek.rx.preferences2.Preference
import com.f2prateek.rx.preferences2.RxSharedPreferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Preferences @Inject constructor(private val rxPrefs: RxSharedPreferences) {
companion object {
const val NIGHT_MODE_OFF = 0
const val NIGHT_MODE_ON = 1
const val NIGHT_MODE_AUTO = 2
}
val defaultSms = rxPrefs.getBoolean("defaultSms", false)
val night = rxPrefs.getBoolean("night", false)
val nightMode = rxPrefs.getInteger("nightModeSummary", NIGHT_MODE_OFF)
val nightStart = rxPrefs.getString("nightStart", "6:00 PM")
val nightEnd = rxPrefs.getString("nightEnd", "6:00 AM")
val black = rxPrefs.getBoolean("black", false)
val autoEmoji = rxPrefs.getBoolean("autoEmoji", true)
val delivery = rxPrefs.getBoolean("delivery", false)
val unicode = rxPrefs.getBoolean("unicode", false)
val mms = rxPrefs.getBoolean("mms", true)
val mmsSize = rxPrefs.getInteger("mmsSize", 100)
fun theme(threadId: Long = 0): Preference<Int> {
val default = rxPrefs.getInteger("theme", 0xFF0097A7.toInt())
return when (threadId) {
0L -> default
else -> rxPrefs.getInteger("theme_$threadId", default.get())
}
}
fun notifications(threadId: Long = 0): Preference<Boolean> {
val default = rxPrefs.getBoolean("notifications", true)
return when (threadId) {
0L -> default
else -> rxPrefs.getBoolean("notifications_$threadId", default.get())
}
}
fun vibration(threadId: Long = 0): Preference<Boolean> {
val default = rxPrefs.getBoolean("vibration", true)
return when (threadId) {
0L -> default
else -> rxPrefs.getBoolean("vibration$threadId", default.get())
}
}
fun ringtone(threadId: Long = 0): Preference<String> {
val default = rxPrefs.getString("ringtone", Settings.System.DEFAULT_NOTIFICATION_URI.toString())
return when (threadId) {
0L -> default
else -> rxPrefs.getString("ringtone_$threadId", default.get())
}
}
}
@@ -0,0 +1,89 @@
/*
* 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 util.extensions
import android.database.Cursor
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.subjects.MaybeSubject
fun Cursor.forEach(closeOnComplete: Boolean = true, method: (Cursor) -> Unit = {}) {
moveToPosition(-1)
while (moveToNext()) {
method.invoke(this)
}
if (closeOnComplete) {
close()
}
}
fun <T> Cursor.map(map: (Cursor) -> T): List<T> {
return List(count, { position ->
moveToPosition(position)
map(this)
})
}
fun <T> Cursor.mapWhile(map: (Cursor) -> T, predicate: (T) -> Boolean): ArrayList<T> {
val result = ArrayList<T>()
moveToPosition(-1)
while (moveToNext()) {
val item = map(this)
if (!predicate(item)) break
result.add(item)
}
return result
}
/**
* We're using this simple implementation with .range() because of the
* complexities of dealing with Backpressure with a Cursor. We can't simply
* use a loop and call onNext() from a generator because we'll need to close
* the cursor at the end, and if any items are still in the buffer, then
* they will be made invalid
*/
fun Cursor.asFlowable(): Flowable<Cursor> {
return Flowable.range(0, count)
.map {
moveToPosition(it)
this
}
.doOnComplete { close() }
}
fun Cursor.asMaybe(): Maybe<Cursor> {
val subject = MaybeSubject.create<Cursor>()
if (moveToFirst()) {
subject.onSuccess(this)
} else {
subject.onError(IndexOutOfBoundsException("The cursor has no items"))
}
subject.doOnComplete { close() }
return subject
}
@@ -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 util.extensions
import com.google.android.mms.ContentType
import model.MmsPart
fun MmsPart.isSmil() = ContentType.APP_SMIL == type
fun MmsPart.isImage() = ContentType.isImageType(type)
fun MmsPart.isText() = ContentType.isTextType(type)
@@ -0,0 +1,45 @@
/*
* 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 util.extensions
import io.reactivex.Observable
import io.realm.Realm
import io.realm.RealmModel
import io.realm.RealmObject
import io.realm.RealmResults
fun RealmModel.insertOrUpdate() {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.insertOrUpdate(this) }
realm.close()
}
fun <T : RealmModel> Collection<T>.insertOrUpdate() {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.insertOrUpdate(this) }
realm.close()
}
fun <T : RealmObject> RealmObject.asObservable(): Observable<T> {
return asFlowable<T>().toObservable()
}
fun <T : RealmObject> RealmResults<T>.asObservable(): Observable<RealmResults<T>> {
return asFlowable().toObservable()
}
@@ -0,0 +1,39 @@
/*
* 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 util.extensions
import io.reactivex.Flowable
import io.reactivex.Observable
data class Optional<out T>(val value: T?) {
fun notNull() = value != null
}
fun <T, R> Flowable<T>.mapNotNull(mapper: (T) -> R?): Flowable<R>
= map { input -> Optional(mapper(input)) }
.filter { optional -> optional.notNull() }
.map { optional -> optional.value }
fun <T, R> Observable<T>.mapNotNull(mapper: (T) -> R?): Observable<R>
= map { input -> Optional(mapper(input)) }
.filter { optional -> optional.notNull() }
.map { optional -> optional.value }
fun <T> Observable<T>.toFlowable(): Flowable<T> = this.toFlowable(io.reactivex.BackpressureStrategy.BUFFER)