Reorganize package structure to adhere to offical Kotlin style guide

This commit is contained in:
Moez Bhatti
2018-01-02 17:13:27 -05:00
parent 8cd5ec31c8
commit a5ce40a404
136 changed files with 429 additions and 431 deletions
@@ -0,0 +1,58 @@
/*
* 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 com.bugsnag.android.Bugsnag
import com.moez.QKSMS.BuildConfig
import common.di.AppComponentManager
import common.di.appComponent
import common.util.Analytics
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 analytics: Analytics
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())
Timber.plant(Timber.DebugTree())
}
}
@@ -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.di
import common.QKApplication
import common.util.ContactImageLoader
import presentation.common.widget.*
import presentation.compose.ComposeActivity
import presentation.compose.ComposeViewModel
import presentation.compose.DetailedChipView
import presentation.main.MainActivity
import presentation.main.MainViewModel
import presentation.settings.SettingsActivity
import presentation.settings.SettingsViewModel
import presentation.setup.SetupActivity
import presentation.setup.SetupViewModel
import receiver.*
import dagger.Component
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: ComposeActivity)
fun inject(activity: SettingsActivity)
fun inject(receiver: DefaultSmsChangedReceiver)
fun inject(receiver: SmsReceiver)
fun inject(receiver: MessageDeliveredReceiver)
fun inject(receiver: MessageSentReceiver)
fun inject(receiver: MarkSeenReceiver)
fun inject(receiver: MarkReadReceiver)
fun inject(receiver: RemoteMessagingReceiver)
fun inject(view: AvatarView)
fun inject(view: DetailedChipView)
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: ComposeViewModel)
fun inject(viewModel: SettingsViewModel)
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,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 common.di
import android.app.Application
import android.content.Context
import android.preference.PreferenceManager
import com.f2prateek.rx.preferences2.RxSharedPreferences
import dagger.Module
import dagger.Provides
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)
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package common.util
import android.content.Context
import com.amplitude.api.Amplitude
import com.amplitude.api.AmplitudeClient
import com.mixpanel.android.mpmetrics.MixpanelAPI
import com.moez.QKSMS.BuildConfig
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Analytics @Inject constructor(context: Context) {
private val amplitude: AmplitudeClient = Amplitude.getInstance().initialize(context, BuildConfig.AMPLITUDE_API_KEY)
private val mixpanel: MixpanelAPI = MixpanelAPI.getInstance(context, BuildConfig.MIXPANEL_API_KEY)
fun track(event: String) {
amplitude.logEvent(event)
synchronized(mixpanel, {
mixpanel.track(event)
})
}
}
@@ -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
}
}
+163
View File
@@ -0,0 +1,163 @@
/*
* 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.view.View
import com.moez.QKSMS.R
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Colors @Inject constructor(context: Context, prefs: Preferences) {
companion object {
private val MINIMUM_CONTRAST_RATIO = 2
}
// Cache these values so they don't need to be recalculated
private val primaryTextLuminance = measureLuminance(context.resources.getColor(R.color.textPrimaryDark))
private val secondaryTextLuminance = measureLuminance(context.resources.getColor(R.color.textSecondaryDark))
private val tertiaryTextLuminance = measureLuminance(context.resources.getColor(R.color.textTertiaryDark))
val theme: Observable<Int> = prefs.theme.asObservable()
.distinctUntilChanged()
val appThemeResources: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.style.AppThemeDark else R.style.AppThemeLight }
val popupThemeResource: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.style.PopupThemeDark else R.style.PopupThemeLight }
@SuppressLint("InlinedApi")
val statusBarIcons: Observable<Int> = prefs.dark.asObservable()
.map { dark -> dark || 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> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.statusBarDark else R.color.statusBarLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val toolbarColor: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.toolbarDark else R.color.toolbarLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val background: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.backgroundDark else R.color.white }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val field: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.fieldDark else R.color.fieldLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val composeBackground: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.backgroundDark else R.color.backgroundLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val separator: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.separatorDark else R.color.separatorLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val textPrimary: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.textPrimaryDark else R.color.textPrimary }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val textSecondary: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.textSecondaryDark else R.color.textSecondary }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val textTertiary: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.textTertiaryDark else R.color.textTertiary }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val textPrimaryOnTheme: Observable<Int> = prefs.theme.asObservable()
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> primaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < MINIMUM_CONTRAST_RATIO }
.map { contrastRatio -> if (contrastRatio) R.color.textPrimary else R.color.textPrimaryDark }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val textSecondaryOnTheme: Observable<Int> = prefs.theme.asObservable()
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> secondaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < MINIMUM_CONTRAST_RATIO }
.map { contrastRatio -> if (contrastRatio) R.color.textSecondary else R.color.textSecondaryDark }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val textTertiaryOnTheme: Observable<Int> = prefs.theme.asObservable()
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> tertiaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < MINIMUM_CONTRAST_RATIO }
.map { contrastRatio -> if (contrastRatio) R.color.textTertiary else R.color.textTertiaryDark }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val bubble: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.bubbleDark else R.color.bubbleLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val switchThumbEnabled: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.switchThumbEnabledDark else R.color.switchThumbEnabledLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val switchThumbDisabled: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.switchThumbDisabledDark else R.color.switchThumbDisabledLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val switchTrackEnabled: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.switchTrackEnabledDark else R.color.switchTrackEnabledLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
val switchTrackDisabled: Observable<Int> = prefs.dark.asObservable()
.map { dark -> if (dark) R.color.switchTrackDisabledDark else R.color.switchTrackDisabledLight }
.map { res -> context.resources.getColor(res) }
.distinctUntilChanged()
/**
* Measures the luminance value of a color to be able to measure the contrast ratio between two colors
* 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,87 @@
/*
* 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 data.repository.ContactRepository
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
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,72 @@
/*
* 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 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)
}
}
@@ -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))
}
}
+55
View File
@@ -0,0 +1,55 @@
/*
* 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 data.model.Message
import io.realm.Realm
import javax.inject.Inject
import javax.inject.Singleton
/**
* Helper class for generating incrementing ids for messages
*/
@Singleton
class Keys @Inject constructor() {
private var maxValue: Long = 0L
init {
refresh()
}
/**
* Should be called upon initialization, and after a sync
*/
fun refresh() {
val realm = Realm.getDefaultInstance()
maxValue = realm.where(Message::class.java).max("id")?.toLong() ?: 0L
realm.close()
}
/**
* Returns a valid ID that can be used to store a new message
*/
fun newId(): Long {
maxValue++
return maxValue
}
}
@@ -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,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 common.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()
}
}
@@ -0,0 +1,153 @@
/*
* 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.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 data.repository.MessageRepository
import interactor.MarkUnarchived
import presentation.compose.ComposeActivity
import receiver.MarkReadReceiver
import receiver.MarkSeenReceiver
import receiver.RemoteMessagingReceiver
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NotificationManager @Inject constructor(
private val context: Context,
private val prefs: Preferences,
private val colors: Colors,
private val messageRepo: MessageRepository,
private val markUnarchived: MarkUnarchived
) {
companion object {
val DEFAULT_CHANNEL_ID = "channel_1"
val VIBRATE_PATTERN = longArrayOf(0, 200, 0, 200)
}
private val notificationManager = NotificationManagerCompat.from(context)
init {
@SuppressLint("NewApi")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val name = "Message notifications"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(DEFAULT_CHANNEL_ID, name, importance).apply {
description = "Message notifications description"
enableLights(true)
lightColor = Color.WHITE
enableVibration(true)
vibrationPattern = VIBRATE_PATTERN
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Updates the notification for a particular conversation
*/
fun update(threadId: Long) {
// If notifications are disabled, don't do anything
if (!prefs.notifications.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.body, 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, DEFAULT_CHANNEL_ID)
.setColor(colors.theme.blockingFirst())
.setSmallIcon(R.mipmap.ic_launcher)
.setNumber(messages.size)
.setAutoCancel(true)
.setContentIntent(contentPI)
.setDeleteIntent(seenPI)
.addAction(readAction)
.setStyle(style)
.setVibrate(if (prefs.vibration.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())
}
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()
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package common.util
data class Optional<out T>(val value: T?) {
fun notNull() = value != null
}
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package common.util
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.content.ContextCompat
import javax.inject.Inject
class Permissions @Inject constructor(private val context: Context) {
fun hasSmsAndContacts() = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
}
@@ -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.provider.Settings
import com.f2prateek.rx.preferences2.RxSharedPreferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Preferences @Inject constructor(rxPrefs: RxSharedPreferences) {
val defaultSms = rxPrefs.getBoolean("defaultSms", false)
val theme = rxPrefs.getInteger("theme", 0xFF008389.toInt())
val dark = rxPrefs.getBoolean("dark", false)
val autoEmoji = rxPrefs.getBoolean("autoEmoji", true)
val notifications = rxPrefs.getBoolean("notifications", true)
val vibration = rxPrefs.getBoolean("vibration", true)
val ringtone = rxPrefs.getString("ringtone", Settings.System.DEFAULT_NOTIFICATION_URI.toString())
val delivery = rxPrefs.getBoolean("delivery", false)
val split = rxPrefs.getBoolean("split", false)
val unicode = rxPrefs.getBoolean("unicode", false)
val mms = rxPrefs.getBoolean("mms", true)
val mmsSize = rxPrefs.getLong("mmsSize", -1)
}
@@ -0,0 +1,104 @@
/*
* 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 common.util.extensions.map
import common.util.extensions.mapWhile
import data.mapper.CursorToConversation
import data.mapper.CursorToMessage
import data.mapper.CursorToRecipient
import data.model.Conversation
import data.model.Message
import data.model.Recipient
import data.model.SyncLog
import io.realm.Realm
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SyncManager @Inject constructor(
context: Context,
private val cursorToConversation: CursorToConversation,
private val cursorToMessage: CursorToMessage,
private val cursorToRecipient: CursorToRecipient) {
sealed class Status {
class Idle : Status()
class Running : Status()
}
private val contentResolver = context.contentResolver
private var status: Status = Status.Idle()
// TODO: This needs to be substantially faster
fun performSync(fullSync: Boolean = false) {
// 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(Recipient::class.java)
realm.delete(SyncLog::class.java)
}
val lastSync = realm.where(SyncLog::class.java)?.max("date")?.toLong() ?: 0
realm.insert(SyncLog())
// Sync conversations
val conversationCursor = contentResolver.query(
CursorToConversation.URI,
CursorToConversation.PROJECTION,
"date >= ?", arrayOf(lastSync.toString()),
"date desc")
val conversations = conversationCursor.map { cursor -> cursorToConversation.map(cursor) }
realm.insertOrUpdate(conversations)
conversationCursor.close()
// Sync messages
val messageCursor = contentResolver.query(CursorToMessage.URI, CursorToMessage.PROJECTION, null, null, "normalized_date desc")
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 = contentResolver.query(CursorToRecipient.URI, null, null, null, null)
val recipients = recipientCursor.map { cursor -> cursorToRecipient.map(cursor) }
realm.insertOrUpdate(recipients)
recipientCursor.close()
realm.commitTransaction()
realm.close()
status = Status.Idle()
}
}
@@ -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,32 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package 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()
}
@@ -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 common.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,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.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(0x4D, Color.red(this), Color.green(this), Color.blue(this))
}
@@ -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 common.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,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 common.util.extensions
import common.util.Optional
import io.reactivex.Flowable
fun <T, R> Flowable<T>.mapNotNull(mapper: (T) -> R?): Flowable<R>
= map { input -> Optional(mapper(input)) }
.filter { optional -> optional.notNull() }
.map { optional -> optional.value }
@@ -0,0 +1,61 @@
/*
* 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.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
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
}
@@ -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 data.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 data.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,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 android.telephony.PhoneNumberUtils
import javax.inject.Inject
class PhoneNumberFilter @Inject constructor() : Filter<String>() {
override fun filter(item: String, query: CharSequence): Boolean {
return query.all { PhoneNumberUtils.isReallyDialable(it) } &&
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 data.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
}
}