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,70 @@
/*
* 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 common
import android.app.Application
import android.support.text.emoji.EmojiCompat
import android.support.text.emoji.FontRequestEmojiCompatConfig
import android.support.v4.provider.FontRequest
import com.bugsnag.android.Bugsnag
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.R
import common.di.AppComponentManager
import common.di.appComponent
import manager.AnalyticsManager
import io.realm.Realm
import io.realm.RealmConfiguration
import timber.log.Timber
import javax.inject.Inject
class QKApplication : Application() {
/**
* Inject this so that it is forced to initialize
*/
@Suppress("unused")
@Inject lateinit var analyticsManager: AnalyticsManager
override fun onCreate() {
super.onCreate()
Bugsnag.init(this, BuildConfig.BUGSNAG_API_KEY)
AppComponentManager.init(this)
appComponent.inject(this)
Realm.init(this)
Realm.setDefaultConfiguration(RealmConfiguration.Builder()
.compactOnLaunch()
.deleteRealmIfMigrationNeeded()
.build())
val fontRequest = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Noto Color Emoji Compat",
R.array.com_google_android_gms_fonts_certs)
EmojiCompat.init(FontRequestEmojiCompatConfig(this, fontRequest))
Timber.plant(Timber.DebugTree())
}
}
@@ -0,0 +1,120 @@
/*
* 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 common.di
import common.QKApplication
import common.util.ContactImageLoader
import dagger.Component
import presentation.common.widget.AvatarView
import presentation.common.widget.MmsPreviewView
import presentation.common.widget.PagerTitleView
import presentation.common.widget.PreferenceView
import presentation.common.widget.QkEditText
import presentation.common.widget.QkSwitch
import presentation.common.widget.QkTextView
import presentation.common.widget.Separator
import presentation.feature.blocked.BlockedActivity
import presentation.feature.blocked.BlockedViewModel
import presentation.feature.compose.ComposeActivity
import presentation.feature.compose.ComposeViewModel
import presentation.feature.compose.DetailedChipView
import presentation.feature.conversationinfo.ConversationInfoActivity
import presentation.feature.conversationinfo.ConversationInfoViewModel
import presentation.feature.gallery.GalleryActivity
import presentation.feature.gallery.GalleryViewModel
import presentation.feature.main.MainActivity
import presentation.feature.main.MainViewModel
import presentation.feature.notificationprefs.NotificationPrefsActivity
import presentation.feature.notificationprefs.NotificationPrefsViewModel
import presentation.feature.plus.PlusActivity
import presentation.feature.plus.PlusViewModel
import presentation.feature.settings.SettingsActivity
import presentation.feature.settings.SettingsViewModel
import presentation.feature.setup.SetupActivity
import presentation.feature.setup.SetupViewModel
import presentation.feature.themepicker.ThemePickerActivity
import presentation.feature.themepicker.ThemePickerViewModel
import presentation.receiver.DefaultSmsChangedReceiver
import presentation.receiver.MarkReadReceiver
import presentation.receiver.MarkSeenReceiver
import presentation.receiver.MmsReceivedReceiver
import presentation.receiver.MmsSentReceiver
import presentation.receiver.MmsUpdatedReceiver
import presentation.receiver.NightModeReceiver
import presentation.receiver.RemoteMessagingReceiver
import presentation.receiver.SmsDeliveredReceiver
import presentation.receiver.SmsProviderChangedReceiver
import presentation.receiver.SmsReceiver
import presentation.receiver.SmsSentReceiver
import javax.inject.Singleton
@Singleton
@Component(modules = [(AppModule::class)])
interface AppComponent {
fun inject(application: QKApplication)
fun inject(activity: MainActivity)
fun inject(activity: SetupActivity)
fun inject(activity: BlockedActivity)
fun inject(activity: ComposeActivity)
fun inject(activity: ConversationInfoActivity)
fun inject(activity: GalleryActivity)
fun inject(activity: NotificationPrefsActivity)
fun inject(activity: PlusActivity)
fun inject(activity: SettingsActivity)
fun inject(activity: ThemePickerActivity)
fun inject(receiver: DefaultSmsChangedReceiver)
fun inject(receiver: SmsDeliveredReceiver)
fun inject(receiver: SmsSentReceiver)
fun inject(receiver: MarkSeenReceiver)
fun inject(receiver: MarkReadReceiver)
fun inject(receiver: MmsReceivedReceiver)
fun inject(receiver: MmsSentReceiver)
fun inject(receiver: MmsUpdatedReceiver)
fun inject(receiver: NightModeReceiver)
fun inject(receiver: RemoteMessagingReceiver)
fun inject(receiver: SmsProviderChangedReceiver)
fun inject(receiver: SmsReceiver)
fun inject(view: AvatarView)
fun inject(view: DetailedChipView)
fun inject(view: MmsPreviewView)
fun inject(view: PagerTitleView)
fun inject(view: PreferenceView)
fun inject(view: QkEditText)
fun inject(view: QkSwitch)
fun inject(view: QkTextView)
fun inject(view: Separator)
fun inject(viewModel: MainViewModel)
fun inject(viewModel: SetupViewModel)
fun inject(viewModel: BlockedViewModel)
fun inject(viewModel: ComposeViewModel)
fun inject(viewModel: ConversationInfoViewModel)
fun inject(viewModel: GalleryViewModel)
fun inject(viewModel: NotificationPrefsViewModel)
fun inject(viewModel: PlusViewModel)
fun inject(viewModel: SettingsViewModel)
fun inject(viewModel: ThemePickerViewModel)
fun inject(fetcher: ContactImageLoader.ContactImageFetcher)
}
@@ -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 common.di
import common.QKApplication
internal lateinit var appComponent: AppComponent
private set
internal object AppComponentManager {
fun init(application: QKApplication) {
appComponent = DaggerAppComponent.builder()
.appModule(AppModule(application))
.build()
}
}
@@ -0,0 +1,118 @@
/*
* 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 common.di
import android.app.Application
import android.content.Context
import android.preference.PreferenceManager
import com.f2prateek.rx.preferences2.RxSharedPreferences
import common.util.AnalyticsManagerImpl
import common.util.NotificationManagerImpl
import dagger.Module
import dagger.Provides
import manager.AnalyticsManager
import manager.KeyManager
import manager.KeyManagerImpl
import manager.NotificationManager
import manager.PermissionManager
import manager.PermissionManagerImpl
import manager.WidgetManager
import manager.WidgetManagerImpl
import mapper.CursorToContact
import mapper.CursorToContactImpl
import mapper.CursorToConversation
import mapper.CursorToConversationImpl
import mapper.CursorToMessage
import mapper.CursorToMessageImpl
import mapper.CursorToPart
import mapper.CursorToPartImpl
import mapper.CursorToRecipienImpl
import mapper.CursorToRecipient
import repository.ContactRepository
import repository.ContactRepositoryImpl
import repository.MessageRepository
import repository.MessageRepositoryImpl
import repository.SyncRepository
import repository.SyncRepositoryImpl
import javax.inject.Singleton
@Module
class AppModule(private var application: Application) {
@Provides
@Singleton
fun provideContext(): Context {
return application
}
@Provides
@Singleton
fun provideRxPreferences(context: Context): RxSharedPreferences {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
return RxSharedPreferences.create(preferences)
}
// Manager
@Provides
fun provideAnalyticsManager(manager: AnalyticsManagerImpl): AnalyticsManager = manager
@Provides
fun provideKeyManager(manager: KeyManagerImpl): KeyManager = manager
@Provides
fun provideNotificationsManager(manager: NotificationManagerImpl): NotificationManager = manager
@Provides
fun providePermissionsManager(manager: PermissionManagerImpl): PermissionManager = manager
@Provides
fun provideWidgetManager(manager: WidgetManagerImpl): WidgetManager = manager
// Mapper
@Provides
fun provideCursorToContact(mapper: CursorToContactImpl): CursorToContact = mapper
@Provides
fun provideCursorToConversation(mapper: CursorToConversationImpl): CursorToConversation = mapper
@Provides
fun provideCursorToMessage(mapper: CursorToMessageImpl): CursorToMessage = mapper
@Provides
fun provideCursorToPart(mapper: CursorToPartImpl): CursorToPart = mapper
@Provides
fun provideCursorToRecipient(mapper: CursorToRecipienImpl): CursorToRecipient = mapper
// Repository
@Provides
fun provideContactRepository(repository: ContactRepositoryImpl): ContactRepository = repository
@Provides
fun provideMessageRepository(repository: MessageRepositoryImpl): MessageRepository = repository
@Provides
fun provideSyncRepository(repository: SyncRepositoryImpl): SyncRepository = repository
}
@@ -0,0 +1,138 @@
/*
* 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 common.util
import android.app.Activity
import android.content.Context
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.BillingResponse
import com.android.billingclient.api.BillingClient.SkuType
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class BillingManager @Inject constructor(context: Context) : PurchasesUpdatedListener {
enum class UpgradeStatus { REGULAR, UPGRADED }
companion object {
const val SKU_PLUS = "remove_ads"
const val SKU_PLUS_DONATE = "qksms_plus_donate"
}
val products: Observable<List<SkuDetails>> = BehaviorSubject.create()
val plusStatus: Observable<UpgradeStatus>
private val skus = listOf(SKU_PLUS, SKU_PLUS_DONATE)
private val purchaseList = mutableListOf<Purchase>()
private val purchaseListObservable: Observable<List<Purchase>> = BehaviorSubject.create()
private val billingClient: BillingClient = BillingClient.newBuilder(context).setListener(this).build()
private var isServiceConnected = false
init {
startServiceConnection {
queryPurchases()
querySkuDetailsAsync()
}
plusStatus = purchaseListObservable
.map { purchases ->
when {
purchases.any { it.sku == SKU_PLUS } -> UpgradeStatus.UPGRADED
purchases.any { it.sku == SKU_PLUS_DONATE } -> UpgradeStatus.UPGRADED
else -> UpgradeStatus.REGULAR
}
}
}
private fun queryPurchases() {
executeServiceRequest {
val purchasesResult = billingClient.queryPurchases(SkuType.INAPP)
// Handle purchase result
purchaseList.clear()
purchaseList.addAll(purchasesResult.purchasesList)
(this.purchaseListObservable as Subject).onNext(purchaseList)
}
}
private fun startServiceConnection(onSuccess: () -> Unit) {
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(@BillingResponse billingResponseCode: Int) {
if (billingResponseCode == BillingResponse.OK) {
isServiceConnected = true
onSuccess()
}
}
override fun onBillingServiceDisconnected() {
isServiceConnected = false
}
})
}
private fun querySkuDetailsAsync() {
executeServiceRequest {
val subParams = SkuDetailsParams.newBuilder().setSkusList(skus).setType(BillingClient.SkuType.INAPP)
billingClient.querySkuDetailsAsync(subParams.build()) { responseCode, skuDetailsList ->
if (responseCode == BillingResponse.OK) {
(products as Subject).onNext(skuDetailsList)
}
}
}
}
fun initiatePurchaseFlow(activity: Activity, sku: String) {
executeServiceRequest {
val params = BillingFlowParams.newBuilder().setSku(sku).setType(SkuType.INAPP)
billingClient.launchBillingFlow(activity, params.build())
}
}
private fun executeServiceRequest(runnable: () -> Unit) {
when (isServiceConnected) {
true -> runnable()
false -> startServiceConnection(runnable)
}
}
override fun onPurchasesUpdated(resultCode: Int, purchases: List<Purchase>?) {
when (resultCode) {
BillingResponse.OK -> {
purchaseList.clear()
purchases?.let { purchaseList.addAll(it) }
(this.purchaseListObservable as Subject).onNext(purchaseList)
}
else -> {
// Ignored
}
}
}
}
@@ -0,0 +1,33 @@
/*
* 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 common.util
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
object ClipboardUtils {
fun copy(context: Context, string: String) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("SMS", string)
clipboard.primaryClip = clip
}
}
@@ -0,0 +1,235 @@
/*
* 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 common.util
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.support.annotation.ColorRes
import android.view.View
import com.moez.QKSMS.R
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import util.Preferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Colors @Inject constructor(private val context: Context, private val prefs: Preferences) {
val materialColors = listOf(
listOf(0xffffebee, 0xffffcdd2, 0xffef9a9a, 0xffe57373, 0xffef5350, 0xfff44336, 0xffe53935, 0xffd32f2f, 0xffc62828, 0xffb71c1c),
listOf(0xffFCE4EC, 0xffF8BBD0, 0xffF48FB1, 0xffF06292, 0xffEC407A, 0xffE91E63, 0xffD81B60, 0xffC2185B, 0xffAD1457, 0xff880E4F),
listOf(0xffF3E5F5, 0xffE1BEE7, 0xffCE93D8, 0xffBA68C8, 0xffAB47BC, 0xff9C27B0, 0xff8E24AA, 0xff7B1FA2, 0xff6A1B9A, 0xff4A148C),
listOf(0xffEDE7F6, 0xffD1C4E9, 0xffB39DDB, 0xff9575CD, 0xff7E57C2, 0xff673AB7, 0xff5E35B1, 0xff512DA8, 0xff4527A0, 0xff311B92),
listOf(0xffE8EAF6, 0xffC5CAE9, 0xff9FA8DA, 0xff7986CB, 0xff5C6BC0, 0xff3F51B5, 0xff3949AB, 0xff303F9F, 0xff283593, 0xff1A237E),
listOf(0xffE3F2FD, 0xffBBDEFB, 0xff90CAF9, 0xff64B5F6, 0xff42A5F5, 0xff2196F3, 0xff1E88E5, 0xff1976D2, 0xff1565C0, 0xff0D47A1),
listOf(0xffE1F5FE, 0xffB3E5FC, 0xff81D4FA, 0xff4FC3F7, 0xff29B6F6, 0xff03A9F4, 0xff039BE5, 0xff0288D1, 0xff0277BD, 0xff01579B),
listOf(0xffE0F7FA, 0xffB2EBF2, 0xff80DEEA, 0xff4DD0E1, 0xff26C6DA, 0xff00BCD4, 0xff00ACC1, 0xff0097A7, 0xff00838F, 0xff006064),
listOf(0xffE0F2F1, 0xffB2DFDB, 0xff80CBC4, 0xff4DB6AC, 0xff26A69A, 0xff009688, 0xff00897B, 0xff00796B, 0xff00695C, 0xff004D40),
listOf(0xffE8F5E9, 0xffC8E6C9, 0xffA5D6A7, 0xff81C784, 0xff66BB6A, 0xff4CAF50, 0xff43A047, 0xff388E3C, 0xff2E7D32, 0xff1B5E20),
listOf(0xffF1F8E9, 0xffDCEDC8, 0xffC5E1A5, 0xffAED581, 0xff9CCC65, 0xff8BC34A, 0xff7CB342, 0xff689F38, 0xff558B2F, 0xff33691E),
listOf(0xffF9FBE7, 0xffF0F4C3, 0xffE6EE9C, 0xffDCE775, 0xffD4E157, 0xffCDDC39, 0xffC0CA33, 0xffAFB42B, 0xff9E9D24, 0xff827717),
listOf(0xffFFFDE7, 0xffFFF9C4, 0xffFFF59D, 0xffFFF176, 0xffFFEE58, 0xffFFEB3B, 0xffFDD835, 0xffFBC02D, 0xffF9A825, 0xffF57F17),
listOf(0xffFFF8E1, 0xffFFECB3, 0xffFFE082, 0xffFFD54F, 0xffFFCA28, 0xffFFC107, 0xffFFB300, 0xffFFA000, 0xffFF8F00, 0xffFF6F00),
listOf(0xffFFF3E0, 0xffFFE0B2, 0xffFFCC80, 0xffFFB74D, 0xffFFA726, 0xffFF9800, 0xffFB8C00, 0xffF57C00, 0xffEF6C00, 0xffE65100),
listOf(0xffFBE9E7, 0xffFFCCBC, 0xffFFAB91, 0xffFF8A65, 0xffFF7043, 0xffFF5722, 0xffF4511E, 0xffE64A19, 0xffD84315, 0xffBF360C),
listOf(0xffEFEBE9, 0xffD7CCC8, 0xffBCAAA4, 0xffA1887F, 0xff8D6E63, 0xff795548, 0xff6D4C41, 0xff5D4037, 0xff4E342E, 0xff3E2723),
listOf(0xffFAFAFA, 0xffF5F5F5, 0xffEEEEEE, 0xffE0E0E0, 0xffBDBDBD, 0xff9E9E9E, 0xff757575, 0xff616161, 0xff424242, 0xff212121),
listOf(0xffECEFF1, 0xffCFD8DC, 0xffB0BEC5, 0xff90A4AE, 0xff78909C, 0xff607D8B, 0xff546E7A, 0xff455A64, 0xff37474F, 0xff263238))
.map { it.map { it.toInt() } }
private val minimumContrastRatio = 2
// Cache these values so they don't need to be recalculated
private val primaryTextLuminance = measureLuminance(getColor(R.color.textPrimaryDark))
private val secondaryTextLuminance = measureLuminance(getColor(R.color.textSecondaryDark))
private val tertiaryTextLuminance = measureLuminance(getColor(R.color.textTertiaryDark))
val theme = themeForConversation()
val appThemeResources = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.style.AppThemeBlack
night && !black -> R.style.AppThemeDark
else -> R.style.AppThemeLight
}
})
val popupThemeResource = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.style.PopupThemeBlack
night && !black -> R.style.PopupThemeDark
else -> R.style.PopupThemeLight
}
})
@SuppressLint("InlinedApi")
val statusBarIcons: Observable<Int> = prefs.night.asObservable()
.map { night -> night || Build.VERSION.SDK_INT < Build.VERSION_CODES.M }
.map { lightIcons -> if (lightIcons) 0 else View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR }
.distinctUntilChanged()
val statusBar: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.statusBarDark
else -> R.color.statusBarLight
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val toolbarColor: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.toolbarDark
else -> R.color.toolbarLight
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val background: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.backgroundDark
else -> R.color.white
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val field: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.fieldDark else R.color.fieldLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val composeBackground: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.backgroundDark
else -> R.color.backgroundLight
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val separator: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.separatorDark else R.color.separatorLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textPrimary: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.textPrimaryDark else R.color.textPrimary }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textSecondary: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.textSecondaryDark else R.color.textSecondary }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textTertiary: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.textTertiaryDark else R.color.textTertiary }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textPrimaryOnTheme = textPrimaryOnThemeForConversation()
val textSecondaryOnTheme = textSecondaryOnThemeForConversation()
val textTertiaryOnTheme = textTertiaryOnThemeForConversation()
val bubble: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.bubbleDark else R.color.bubbleLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchThumbEnabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchThumbEnabledDark else R.color.switchThumbEnabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchThumbDisabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchThumbDisabledDark else R.color.switchThumbDisabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchTrackEnabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchTrackEnabledDark else R.color.switchTrackEnabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchTrackDisabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchTrackDisabledDark else R.color.switchTrackDisabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
fun themeForConversation(threadId: Long = 0): Observable<Int> = prefs.theme(threadId)
.asObservable()
.distinctUntilChanged()
fun textPrimaryOnThemeForConversation(threadId: Long = 0): Observable<Int> = themeForConversation(threadId)
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> primaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < minimumContrastRatio }
.map { contrastRatio -> if (contrastRatio) R.color.textPrimary else R.color.textPrimaryDark }
.map { res -> getColor(res) }
.distinctUntilChanged()
fun textSecondaryOnThemeForConversation(threadId: Long = 0): Observable<Int> = themeForConversation(threadId)
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> secondaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < minimumContrastRatio }
.map { contrastRatio -> if (contrastRatio) R.color.textSecondary else R.color.textSecondaryDark }
.map { res -> getColor(res) }
.distinctUntilChanged()
fun textTertiaryOnThemeForConversation(threadId: Long = 0): Observable<Int> = themeForConversation(threadId)
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> tertiaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < minimumContrastRatio }
.map { contrastRatio -> if (contrastRatio) R.color.textTertiary else R.color.textTertiaryDark }
.map { res -> getColor(res) }
.distinctUntilChanged()
private fun getColor(@ColorRes res: Int): Int {
return context.resources.getColor(res)
}
/**
* Measures the luminance value of a color to be able to measure the contrast ratio between two materialColors
* Based on https://stackoverflow.com/a/9733420
*/
private fun measureLuminance(color: Int): Double {
val array = intArrayOf(Color.red(color), Color.green(color), Color.blue(color))
.map { if (it < 0.03928) it / 12.92 else Math.pow((it + 0.055) / 1.055, 2.4) }
return 0.2126 * array[0] + 0.7152 * array[1] + 0.0722 * array[2] + 0.05
}
}
@@ -0,0 +1,88 @@
/*
* 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 common.util
import android.content.Context
import android.provider.ContactsContract
import android.telephony.PhoneNumberUtils
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import common.di.appComponent
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import repository.ContactRepository
import java.io.InputStream
import java.security.MessageDigest
import javax.inject.Inject
class ContactImageLoader(val context: Context) : ModelLoader<String, InputStream> {
override fun handles(model: String?): Boolean {
return PhoneNumberUtils.isGlobalPhoneNumber(model)
}
override fun buildLoadData(model: String, width: Int, height: Int, options: Options?): ModelLoader.LoadData<InputStream> {
return ModelLoader.LoadData(ContactImageKey(model), ContactImageFetcher(context, model))
}
class Factory(val context: Context) : ModelLoaderFactory<String, InputStream> {
override fun build(multiFactory: MultiModelLoaderFactory) = ContactImageLoader(context)
override fun teardown() {} // nothing to do here
}
class ContactImageKey(private val address: String) : Key {
override fun updateDiskCacheKey(digest: MessageDigest) = digest.update(address.toByteArray())
}
class ContactImageFetcher(private val context: Context, private val address: String) : DataFetcher<InputStream> {
@Inject lateinit var contactRepo: ContactRepository
private var loadPhotoDisposable: Disposable? = null
init {
appComponent.inject(this)
}
override fun cleanup() {}
override fun getDataClass() = InputStream::class.java
override fun getDataSource() = DataSource.LOCAL
override fun loadData(priority: Priority?, callback: DataFetcher.DataCallback<in InputStream>) {
loadPhotoDisposable = contactRepo.findContactUri(address)
.map { uri -> ContactsContract.Contacts.openContactPhotoInputStream(context.contentResolver, uri) }
.subscribeOn(Schedulers.io())
.subscribe(
{ inputStream -> callback.onDataReady(inputStream) },
{ error -> callback.onLoadFailed(Exception(error)) })
}
override fun cancel() {
loadPhotoDisposable?.dispose()
}
}
}
@@ -0,0 +1,88 @@
/*
* 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 common.util
import android.content.Context
import android.text.format.DateFormat
import common.util.extensions.isSameDay
import common.util.extensions.isSameWeek
import common.util.extensions.isSameYear
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DateFormatter @Inject constructor(val context: Context) {
/**
* Replace 12 hour format with 24 hour format if necessary
*/
private fun getFormatter(pattern: String): SimpleDateFormat {
val isUsing24HourTime = DateFormat.is24HourFormat(context)
return if (isUsing24HourTime) SimpleDateFormat(pattern.replace('h', 'H').replace(" a".toRegex(), ""), Locale.US)
else SimpleDateFormat(pattern, Locale.US)
}
fun getTimestamp(date: Long): String {
return getFormatter("h:mm a").format(date)
}
fun getMessageTimestamp(date: Long): String {
val now = Calendar.getInstance()
val then = Calendar.getInstance()
then.timeInMillis = date
return when {
now.isSameDay(then) -> getFormatter("h:mm a")
now.isSameWeek(then) -> getFormatter("E h:mm a")
now.isSameYear(then) -> getFormatter("MMM d, h:mm a")
else -> getFormatter("MMM d yyyy, h:mm a")
}.format(date)
}
fun getConversationTimestamp(date: Long): String {
val now = Calendar.getInstance()
val then = Calendar.getInstance()
then.timeInMillis = date
return when {
now.isSameDay(then) -> getFormatter("h:mm a")
now.isSameWeek(then) -> getFormatter("E")
now.isSameYear(then) -> getFormatter("MMM d")
else -> getFormatter("d/MM/yy")
}.format(date)
}
fun formatTime(hour: Int, minute: Int): String {
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, minute)
val simpleDateFormat = getFormatter("h:mm a")
return simpleDateFormat.format(calendar.time)
}
fun parseTime(time: String): Calendar {
val simpleDateFormat = if (time.contains(" ")) getFormatter("h:mm a") else SimpleDateFormat("H:mm", Locale.US)
return Calendar.getInstance().apply { this.time = simpleDateFormat.parse(time) }
}
}
@@ -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 common.util
import android.content.Context
import android.graphics.Typeface
import android.support.v4.content.res.ResourcesCompat
import com.moez.QKSMS.R
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class FontProvider @Inject constructor(context: Context) {
private var lato: Typeface? = null
private val pendingCallbacks = ArrayList<(Typeface) -> Unit>()
init {
ResourcesCompat.getFont(context, R.font.lato, object : ResourcesCompat.FontCallback() {
override fun onFontRetrievalFailed(reason: Int) {
Timber.w("Font retrieval failed: $reason")
}
override fun onFontRetrieved(typeface: Typeface) {
lato = typeface
pendingCallbacks.forEach { lato?.run(it) }
pendingCallbacks.clear()
}
}, null)
}
fun getLato(callback: (Typeface) -> Unit) {
lato?.run(callback)
if (lato == null) {
pendingCallbacks += callback
}
}
}
@@ -0,0 +1,41 @@
/*
* 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 common.util
import android.content.Context
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
import java.io.InputStream
@GlideModule
class GlideAppModule : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
builder.setLogLevel(Log.ERROR)
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.append(String::class.java, InputStream::class.java, ContactImageLoader.Factory(context))
}
}
@@ -0,0 +1,42 @@
/*
* 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 common.util
import android.arch.lifecycle.LiveData
import io.realm.RealmChangeListener
import io.realm.RealmModel
import io.realm.RealmResults
class LiveRealmData<T : RealmModel>(private val results: RealmResults<T>) : LiveData<RealmResults<T>>() {
private val listener: RealmChangeListener<RealmResults<T>> = RealmChangeListener { results ->
value = results
}
override fun onActive() {
super.onActive()
results.addChangeListener(listener)
}
override fun onInactive() {
super.onInactive()
results.removeChangeListener(listener)
}
}
@@ -0,0 +1,107 @@
/*
* 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 common.util
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import presentation.receiver.NightModeReceiver
import util.Preferences
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NightModeManager @Inject constructor(
private val context: Context,
private val dateFormatter: DateFormatter,
private val prefs: Preferences) {
fun updateCurrentTheme() {
// If night mode is not on auto, then there's nothing to do here
if (prefs.nightMode.get() != Preferences.NIGHT_MODE_AUTO) {
return
}
val nightStartTime = getPreviousInstanceOfTime(prefs.nightStart.get())
val nightEndTime = getPreviousInstanceOfTime(prefs.nightEnd.get())
// If the last nightStart was more recent than the last nightEnd, then it's night time
prefs.night.set(nightStartTime > nightEndTime)
}
fun updateNightMode(mode: Int) {
prefs.nightMode.set(mode)
// If it's not on auto mode, set the appropriate night mode
if (mode != Preferences.NIGHT_MODE_AUTO) {
prefs.night.set(mode == Preferences.NIGHT_MODE_ON)
}
updateAlarms()
}
fun updateAlarms() {
val dayCalendar = createCalendar(prefs.nightEnd.get())
val day = Intent(context, NightModeReceiver::class.java)
val dayIntent = PendingIntent.getBroadcast(context, 0, day, 0)
val nightCalendar = createCalendar(prefs.nightStart.get())
val night = Intent(context, NightModeReceiver::class.java)
val nightIntent = PendingIntent.getBroadcast(context, 1, night, 0)
context.sendBroadcast(day)
context.sendBroadcast(night)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (prefs.nightMode.get() == Preferences.NIGHT_MODE_AUTO) {
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, dayCalendar.timeInMillis, AlarmManager.INTERVAL_DAY, dayIntent)
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nightCalendar.timeInMillis, AlarmManager.INTERVAL_DAY, nightIntent)
} else {
alarmManager.cancel(dayIntent)
alarmManager.cancel(nightIntent)
}
}
private fun createCalendar(time: String): Calendar {
val calendar = dateFormatter.parseTime(time)
return Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY))
set(Calendar.MINUTE, calendar.get(Calendar.MINUTE))
}
}
/**
* Returns a Calendar set to the most recent occurrence of this time
*/
private fun getPreviousInstanceOfTime(time: String): Calendar {
val currentTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10)
val calendar = createCalendar(time)
while (calendar.timeInMillis > currentTime) {
calendar.add(Calendar.DAY_OF_YEAR, -1)
}
return calendar
}
}
@@ -0,0 +1,252 @@
/*
* 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 common.util
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.app.RemoteInput
import android.support.v4.app.TaskStackBuilder
import com.moez.QKSMS.R
import presentation.feature.compose.ComposeActivity
import presentation.receiver.MarkReadReceiver
import presentation.receiver.MarkSeenReceiver
import presentation.receiver.RemoteMessagingReceiver
import repository.MessageRepository
import util.Preferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NotificationManagerImpl @Inject constructor(
private val context: Context,
private val prefs: Preferences,
private val colors: Colors,
private val messageRepo: MessageRepository
): manager.NotificationManager {
companion object {
const val DEFAULT_CHANNEL_ID = "notifications_default"
val VIBRATE_PATTERN = longArrayOf(0, 200, 0, 200)
}
private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
init {
@SuppressLint("NewApi")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Default"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(DEFAULT_CHANNEL_ID, name, importance).apply {
enableLights(true)
lightColor = Color.WHITE
enableVibration(true)
vibrationPattern = VIBRATE_PATTERN
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Updates the notification for a particular conversation
*/
override fun update(threadId: Long) {
// If notifications are disabled, don't do anything
if (!prefs.notifications(threadId).get()) {
return
}
val messages = messageRepo.getUnreadUnseenMessages(threadId)
// If there are no messages to be displayed, make sure that the notification is dismissed
if (messages.isEmpty()) {
notificationManager.cancel(threadId.toInt())
return
}
val conversation = messageRepo.getConversation(threadId) ?: return
val style = NotificationCompat.MessagingStyle("Me")
messages.forEach { message ->
val name = if (message.isMe()) null else conversation.getTitle()
style.addMessage(message.getSummary(), message.date, name)
}
val contentIntent = Intent(context, ComposeActivity::class.java).putExtra("threadId", threadId)
val taskStackBuilder = TaskStackBuilder.create(context)
taskStackBuilder.addParentStack(ComposeActivity::class.java)
taskStackBuilder.addNextIntent(contentIntent)
val contentPI = taskStackBuilder.getPendingIntent(threadId.toInt() + 10000, PendingIntent.FLAG_UPDATE_CURRENT)
val seenIntent = Intent(context, MarkSeenReceiver::class.java).putExtra("threadId", threadId)
val seenPI = PendingIntent.getBroadcast(context, threadId.toInt() + 20000, seenIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val readIntent = Intent(context, MarkReadReceiver::class.java).putExtra("threadId", threadId)
val readPI = PendingIntent.getBroadcast(context, threadId.toInt() + 30000, readIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val readAction = NotificationCompat.Action(R.drawable.ic_done_black_24dp, context.getString(R.string.notification_read), readPI)
val notification = NotificationCompat.Builder(context, getChannelIdForNotification(threadId))
.setColor(colors.themeForConversation(threadId).blockingFirst())
.setPriority(NotificationManagerCompat.IMPORTANCE_MAX)
.setSmallIcon(R.drawable.ic_notification)
.setNumber(messages.size)
.setAutoCancel(true)
.setContentIntent(contentPI)
.setDeleteIntent(seenPI)
.addAction(readAction)
.setStyle(style)
.setSound(Uri.parse(prefs.ringtone(threadId).get()))
.setLights(Color.WHITE, 500, 2000)
.setVibrate(if (prefs.vibration(threadId).get()) VIBRATE_PATTERN else longArrayOf(0))
if (Build.VERSION.SDK_INT >= 24) {
notification.addAction(getReplyAction(conversation.recipients[0]?.address.orEmpty(), threadId))
}
notificationManager.notify(threadId.toInt(), notification.build())
}
override fun notifyFailed(msgId: Long) {
val message = messageRepo.getMessage(msgId)
if (message == null || !message.isFailedMessage()) {
return
}
val threadId = message.threadId
val conversation = messageRepo.getConversation(threadId) ?: return
val contentIntent = Intent(context, ComposeActivity::class.java).putExtra("threadId", threadId)
val taskStackBuilder = TaskStackBuilder.create(context)
taskStackBuilder.addParentStack(ComposeActivity::class.java)
taskStackBuilder.addNextIntent(contentIntent)
val contentPI = taskStackBuilder.getPendingIntent(threadId.toInt() + 40000, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, getChannelIdForNotification(threadId))
.setContentTitle(context.getString(R.string.notification_message_failed_title))
.setContentText(context.getString(R.string.notification_message_failed_text, conversation.getTitle()))
.setColor(colors.themeForConversation(threadId).blockingFirst())
.setPriority(NotificationManagerCompat.IMPORTANCE_MAX)
.setSmallIcon(R.drawable.ic_notification_failed)
.setAutoCancel(true)
.setContentIntent(contentPI)
.setSound(Uri.parse(prefs.ringtone(threadId).get()))
.setLights(Color.WHITE, 500, 2000)
.setVibrate(if (prefs.vibration(threadId).get()) VIBRATE_PATTERN else longArrayOf(0))
notificationManager.notify(threadId.toInt() + 50000, notification.build())
}
private fun getReplyAction(address: String, threadId: Long): NotificationCompat.Action {
val replyIntent = Intent(context, RemoteMessagingReceiver::class.java)
.putExtra("address", address)
.putExtra("threadId", threadId)
val replyPI = PendingIntent.getBroadcast(context, threadId.toInt() + 40000, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val responseSet = arrayListOf("Hello", "Hey").toTypedArray().sortedArray()
val remoteInput = RemoteInput.Builder("body")
.setLabel(context.getString(R.string.notification_reply))
.setChoices(responseSet)
.build()
return NotificationCompat.Action.Builder(
R.drawable.ic_reply_black_24dp,
context.getString(R.string.notification_reply), replyPI)
.addRemoteInput(remoteInput)
.build()
}
/**
* Creates a notification channel for the given conversation
*/
override fun createNotificationChannel(threadId: Long) {
// Only proceed if the android version supports notification channels
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
messageRepo.getConversation(threadId)?.let { conversation ->
val channelId = buildNotificationChannelId(threadId)
val name = conversation.getTitle()
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(channelId, name, importance).apply {
enableLights(true)
lightColor = Color.WHITE
enableVibration(true)
vibrationPattern = VIBRATE_PATTERN
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Returns the notification channel for the given conversation, or null if it doesn't exist
*/
private fun getNotificationChannel(threadId: Long): NotificationChannel? {
val channelId = buildNotificationChannelId(threadId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return notificationManager
.notificationChannels
.firstOrNull { channel -> channel.id == channelId }
}
return null
}
/**
* Returns the channel id that should be used for a notification based on the threadId
*
* If a notification channel for the conversation exists, use the id for that. Otherwise return
* the default channel id
*/
private fun getChannelIdForNotification(threadId: Long): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = buildNotificationChannelId(threadId)
return notificationManager
.notificationChannels
.map { channel -> channel.id }
.firstOrNull { id -> id == channelId }
?: DEFAULT_CHANNEL_ID
}
return DEFAULT_CHANNEL_ID
}
/**
* Formats a notification channel id for a given thread id, whether the channel exists or not
*/
override fun buildNotificationChannelId(threadId: Long): String {
return when (threadId) {
0L -> DEFAULT_CHANNEL_ID
else -> "notifications_$threadId"
}
}
}
@@ -0,0 +1,33 @@
/*
* 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 common.util.extensions
import java.util.*
fun Calendar.isSameDay(other: Calendar): Boolean {
return get(Calendar.YEAR) == other.get(Calendar.YEAR) && get(Calendar.DAY_OF_YEAR) == other.get(Calendar.DAY_OF_YEAR)
}
fun Calendar.isSameWeek(other: Calendar): Boolean {
return get(Calendar.YEAR) == other.get(Calendar.YEAR) && get(Calendar.WEEK_OF_YEAR) == other.get(Calendar.WEEK_OF_YEAR)
}
fun Calendar.isSameYear(other: Calendar): Boolean {
return get(Calendar.YEAR) == other.get(Calendar.YEAR)
}
@@ -0,0 +1,36 @@
/*
* 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 common.util.extensions
import android.content.Context
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.widget.Toast
fun Context.getColorCompat(colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}
fun Context.makeToast(@StringRes res: Int, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, res, duration).show()
}
fun Context.makeToast(text: String, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).show()
}
@@ -0,0 +1,37 @@
/*
* 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 common.util.extensions
import android.content.Context
import android.graphics.Color
import android.util.TypedValue
fun Int.dpToPx(context: Context): Int {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics).toInt()
}
fun Int.withAlpha(alpha: Int): Int {
return Color.argb(alpha, Color.red(this), Color.green(this), Color.blue(this))
}
fun Int.forEach(action: (Int) -> Unit) {
for (index in 0 until this) {
action(index)
}
}
@@ -0,0 +1,76 @@
/*
* 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 common.util.extensions
import android.content.Context
import android.content.res.ColorStateList
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import io.reactivex.Observable
fun EditText.showKeyboard() {
requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, 0)
}
fun ImageView.setTint(color: Int) {
imageTintList = ColorStateList.valueOf(color)
}
fun View.setBackgroundTint(color: Int) {
backgroundTintList = ColorStateList.valueOf(color)
}
fun View.setMargins(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
val lp = layoutParams as? ViewGroup.MarginLayoutParams ?: return
lp.setMargins(
left ?: lp.leftMargin,
top ?: lp.topMargin,
right ?: lp.rightMargin,
bottom ?: lp.rightMargin)
layoutParams = lp
}
fun View.setPadding(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
setPadding(left ?: paddingLeft, top ?: paddingTop, right ?: paddingRight, bottom ?: paddingBottom)
}
fun View.setVisible(visible: Boolean, invisible: Int = View.GONE) {
visibility = if (visible) View.VISIBLE else invisible
}
data class PageScroll(val position: Int, val offset: Float)
fun ViewPager.pageScrolled(): Observable<PageScroll> {
return Observable.create<PageScroll> { emitter ->
addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
emitter.onNext(PageScroll(position, positionOffset))
}
})
}
}
@@ -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 common.util.filter
import model.Contact
import javax.inject.Inject
class ContactFilter @Inject constructor(private val phoneNumberFilter: PhoneNumberFilter) : Filter<Contact>() {
override fun filter(item: Contact, query: CharSequence): Boolean {
return item.name.contains(query, true) || // Name
item.numbers.map { it.address }.any { address -> phoneNumberFilter.filter(address, query) } // Number
}
}
@@ -0,0 +1,30 @@
/*
* 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 common.util.filter
import model.Conversation
import javax.inject.Inject
class ConversationFilter @Inject constructor(private val recipientFilter: RecipientFilter) : Filter<Conversation>() {
override fun filter(item: Conversation, query: CharSequence): Boolean {
return item.recipients.any { recipient -> recipientFilter.filter(recipient, query) }
}
}
@@ -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 common.util.filter
abstract class Filter<in T> {
abstract fun filter(item: T, query: CharSequence): Boolean
}
@@ -0,0 +1,33 @@
/*
* 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 common.util.filter
import android.telephony.PhoneNumberUtils
import javax.inject.Inject
class PhoneNumberFilter @Inject constructor() : Filter<String>() {
override fun filter(item: String, query: CharSequence): Boolean {
val allCharactersDialable = query.all { PhoneNumberUtils.isReallyDialable(it) }
return allCharactersDialable && (PhoneNumberUtils.compare(item, query.toString()) ||
PhoneNumberUtils.stripSeparators(item).contains(PhoneNumberUtils.stripSeparators(query.toString())))
}
}
@@ -0,0 +1,35 @@
/*
* 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 common.util.filter
import model.Recipient
import javax.inject.Inject
class RecipientFilter @Inject constructor(
private val contactFilter: ContactFilter,
private val phoneNumberFilter: PhoneNumberFilter)
: Filter<Recipient>() {
override fun filter(item: Recipient, query: CharSequence) = when {
item.contact?.let { contactFilter.filter(it, query) } == true -> true
phoneNumberFilter.filter(item.address, query) -> true
else -> false
}
}