Allow selecting schedule time for message

This commit is contained in:
Moez Bhatti
2018-06-26 17:00:42 -04:00
parent 431edfe2ee
commit 75b728c301
11 changed files with 189 additions and 32 deletions
@@ -57,6 +57,7 @@ class QkRealmMigration : RealmMigration {
realm.schema.create("ScheduledMessage")
.addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED)
.addField("date", Long::class.java, FieldAttribute.REQUIRED)
.addField("subId", Long::class.java, FieldAttribute.REQUIRED)
.addRealmListField("recipients", String::class.java)
.addField("sendAsGroup", Boolean::class.java, FieldAttribute.REQUIRED)
.addField("body", String::class.java, FieldAttribute.REQUIRED)
@@ -4,15 +4,19 @@ import com.moez.QKSMS.model.ScheduledMessage
import io.realm.Realm
import io.realm.RealmList
import io.realm.RealmResults
import javax.inject.Inject
class ScheduledMessageRepositoryImpl : ScheduledMessageRepository {
class ScheduledMessageRepositoryImpl @Inject constructor() : ScheduledMessageRepository {
override fun saveScheduledMessage(date: Long, recipients: RealmList<String>, sendAsGroup: Boolean, body: String,
attachments: RealmList<String>): Long {
override fun saveScheduledMessage(date: Long, subId: Int, recipients: List<String>, sendAsGroup: Boolean,
body: String, attachments: List<String>): Long {
return Realm.getDefaultInstance().use { realm ->
val id = (realm.where(ScheduledMessage::class.java).max("id")?.toLong() ?: -1) + 1
val message = ScheduledMessage(id, date, recipients, sendAsGroup, body, attachments)
val recipientsRealmList = RealmList(*recipients.toTypedArray())
val attachmentsRealmList = RealmList(*attachments.toTypedArray())
val message = ScheduledMessage(id, date, subId, recipientsRealmList, sendAsGroup, body, attachmentsRealmList)
realm.executeTransaction { realm.insertOrUpdate(message) }
@@ -24,7 +28,7 @@ class ScheduledMessageRepositoryImpl : ScheduledMessageRepository {
return Realm.getDefaultInstance()
.where(ScheduledMessage::class.java)
.sort("date")
.findAll()
.findAllAsync()
}
override fun getScheduledMessage(id: Long): ScheduledMessage? {
@@ -7,6 +7,7 @@ import io.realm.annotations.PrimaryKey
open class ScheduledMessage(
@PrimaryKey var id: Long = 0,
var date: Long = 0,
var subId: Int = -1,
var recipients: RealmList<String> = RealmList(),
var sendAsGroup: Boolean = true,
var body: String = "",
@@ -1,7 +1,6 @@
package com.moez.QKSMS.repository
import com.moez.QKSMS.model.ScheduledMessage
import io.realm.RealmList
import io.realm.RealmResults
interface ScheduledMessageRepository {
@@ -9,8 +8,8 @@ interface ScheduledMessageRepository {
/**
* Saves a scheduled message and returns the id if successful
*/
fun saveScheduledMessage(date: Long, recipients: RealmList<String>, sendAsGroup: Boolean, body: String,
attachments: RealmList<String>): Long
fun saveScheduledMessage(date: Long, subId: Int, recipients: List<String>, sendAsGroup: Boolean, body: String,
attachments: List<String>): Long
/**
* Returns all of the scheduled messages, sorted chronologically
@@ -75,4 +75,16 @@ class DateFormatter @Inject constructor(val context: Context) {
}.format(date)
}
fun getScheduledTimestamp(date: Long): String {
val now = Calendar.getInstance()
val then = Calendar.getInstance()
then.timeInMillis = date
return when {
now.isSameDay(then) -> getFormatter("h:mm a")
now.isSameYear(then) -> getFormatter("MMM d h:mm a")
else -> getFormatter("MMM d yyyy h:mm a")
}.format(date)
}
}
@@ -20,6 +20,8 @@ package com.moez.QKSMS.feature.compose
import android.Manifest
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import android.content.ContentValues
@@ -29,17 +31,20 @@ import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.text.format.DateFormat
import androidx.core.app.ActivityCompat
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import androidx.core.view.isVisible
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import com.moez.QKSMS.common.androidxcompat.scope
import com.moez.QKSMS.common.base.QkThemedActivity
import com.moez.QKSMS.common.util.DateFormatter
import com.moez.QKSMS.common.util.extensions.autoScrollToStart
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.common.util.extensions.scrapViews
@@ -59,6 +64,7 @@ import kotlinx.android.synthetic.main.compose_activity.*
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import kotlin.math.min
class ComposeActivity : QkThemedActivity(), ComposeView {
@@ -71,6 +77,7 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
@Inject lateinit var attachmentAdapter: AttachmentAdapter
@Inject lateinit var chipsAdapter: ChipsAdapter
@Inject lateinit var contactsAdapter: ContactAdapter
@Inject lateinit var dateFormatter: DateFormatter
@Inject lateinit var messageAdapter: MessagesAdapter
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
@@ -91,9 +98,12 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
override val attachIntent by lazy { attach.clicks() }
override val cameraIntent by lazy { camera.clicks() }
override val galleryIntent by lazy { gallery.clicks() }
override val scheduleIntent by lazy { schedule.clicks() }
override val attachmentSelectedIntent: Subject<Uri> = PublishSubject.create()
override val inputContentIntent by lazy { message.inputContentSelected }
override val scheduleSelectedIntent: Subject<Long> = PublishSubject.create()
override val changeSimIntent by lazy { sim.clicks() }
override val scheduleCancelIntent by lazy { scheduledCancel.clicks() }
override val sendIntent by lazy { send.clicks() }
override val backPressedIntent: Subject<Unit> = PublishSubject.create()
@@ -206,12 +216,16 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
messageAdapter.data = state.messages
messageAdapter.highlight = state.searchSelectionId
scheduledGroup.isVisible = state.scheduled != 0L
scheduledTime.text = dateFormatter.getScheduledTimestamp(state.scheduled)
attachments.setVisible(state.attachments.isNotEmpty())
attachmentAdapter.data = state.attachments
attach.animate().rotation(if (state.attaching) 45f else 0f).start()
attach.animate().rotation(if (state.attaching) 135f else 0f).start()
camera.setVisible(state.attaching)
gallery.setVisible(state.attaching)
schedule.setVisible(state.attaching)
counter.text = state.remaining
counter.setVisible(counter.text.isNotBlank())
@@ -240,6 +254,20 @@ class ComposeActivity : QkThemedActivity(), ComposeView {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
}
override fun requestDatePicker() {
val calendar = Calendar.getInstance()
DatePickerDialog(this, DatePickerDialog.OnDateSetListener { _, year, month, day ->
TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { _, hour, minute ->
calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, month)
calendar.set(Calendar.DAY_OF_MONTH, day)
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, minute)
scheduleSelectedIntent.onNext(calendar.timeInMillis)
}, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), DateFormat.is24HourFormat(this)).show()
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show()
}
override fun requestCamera() {
cameraDestination = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
.let { timestamp -> ContentValues().apply { put(MediaStore.Images.Media.TITLE, timestamp) } }
@@ -41,6 +41,7 @@ data class ComposeState(
val searchResults: Int = 0,
val messages: Pair<Conversation, RealmResults<Message>>? = null,
val selectedMessages: Int = 0,
val scheduled: Long = 0,
val attachments: List<Attachment> = ArrayList(),
val attaching: Boolean = false,
val remaining: String = "",
@@ -46,8 +46,11 @@ interface ComposeView : QkView<ComposeState> {
val attachIntent: Observable<Unit>
val cameraIntent: Observable<*>
val galleryIntent: Observable<*>
val scheduleIntent: Observable<*>
val attachmentSelectedIntent: Observable<Uri>
val inputContentIntent: Observable<InputContentInfoCompat>
val scheduleSelectedIntent: Observable<Long>
val scheduleCancelIntent: Observable<*>
val changeSimIntent: Observable<*>
val sendIntent: Observable<Unit>
@@ -56,6 +59,7 @@ interface ComposeView : QkView<ComposeState> {
fun requestStoragePermission()
fun requestCamera()
fun requestGallery()
fun requestDatePicker()
fun setDraft(draft: String)
fun scrollToMessage(id: Long)
val backPressedIntent: Observable<Unit>
@@ -22,6 +22,7 @@ import android.content.Context
import android.telephony.PhoneNumberUtils
import android.telephony.SmsMessage
import android.view.inputmethod.EditorInfo
import androidx.core.widget.toast
import com.moez.QKSMS.R
import com.moez.QKSMS.common.Navigator
import com.moez.QKSMS.common.androidxcompat.scope
@@ -51,6 +52,7 @@ import com.moez.QKSMS.model.PhoneNumber
import com.moez.QKSMS.repository.ContactRepository
import com.moez.QKSMS.repository.ConversationRepository
import com.moez.QKSMS.repository.MessageRepository
import com.moez.QKSMS.repository.ScheduledMessageRepository
import com.moez.QKSMS.util.ActiveSubscriptionObservable
import com.moez.QKSMS.util.tryOrNull
import com.uber.autodispose.kotlin.autoDisposable
@@ -87,6 +89,7 @@ class ComposeViewModel @Inject constructor(
private val navigator: Navigator,
private val permissionManager: PermissionManager,
private val retrySending: RetrySending,
private val scheduledMessageRepo: ScheduledMessageRepository,
private val sendMessage: SendMessage,
private val subscriptionManager: SubscriptionManagerCompat,
private val syncContacts: ContactSync
@@ -442,17 +445,26 @@ class ComposeViewModel @Inject constructor(
view.cameraIntent
.autoDisposable(view.scope())
.subscribe {
when (permissionManager.hasStorage()) {
true -> view.requestCamera()
false -> view.requestStoragePermission()
if (permissionManager.hasStorage()) {
newState { copy(attaching = false) }
view.requestCamera()
} else {
view.requestStoragePermission()
}
}
// Attach a photo from gallery
view.galleryIntent
.doOnNext { newState { copy(attaching = false) } }
.autoDisposable(view.scope())
.subscribe { view.requestGallery() }
// Choose a time to schedule the message
view.scheduleIntent
.doOnNext { newState { copy(attaching = false) } }
.autoDisposable(view.scope())
.subscribe { view.requestDatePicker() }
// A photo was selected
Observable.merge(
view.attachmentSelectedIntent.map { uri -> Attachment(uri) },
@@ -462,6 +474,11 @@ class ComposeViewModel @Inject constructor(
.autoDisposable(view.scope())
.subscribe { newState { copy(attaching = false) } }
// Set the scheduled time
view.scheduleSelectedIntent
.autoDisposable(view.scope())
.subscribe { scheduled -> newState { copy(scheduled = scheduled) } }
// Detach a photo
view.attachmentDeletedIntent
.withLatestFrom(attachments) { bitmap, attachments -> attachments.filter { it !== bitmap } }
@@ -512,6 +529,11 @@ class ComposeViewModel @Inject constructor(
.autoDisposable(view.scope())
.subscribe { remaining -> newState { copy(remaining = remaining) } }
// Cancel the scheduled time
view.scheduleCancelIntent
.autoDisposable(view.scope())
.subscribe { newState { copy(scheduled = 0) } }
// Toggle to the next sim slot
view.changeSimIntent
.withLatestFrom(state) { _, state ->
@@ -533,26 +555,33 @@ class ComposeViewModel @Inject constructor(
.map { body -> body.toString() }
.withLatestFrom(state, attachments, conversation, selectedContacts) { body, state, attachments, conversation, contacts ->
val subId = state.subscription?.subscriptionId ?: -1
val addresses = when (conversation.recipients.isNotEmpty()) {
true -> conversation.recipients.map { it.address }
false -> contacts.mapNotNull { it.numbers.firstOrNull()?.address }
}
if (state.sendAsGroup) {
val addresses = when (conversation.recipients.isNotEmpty()) {
true -> conversation.recipients.map { it.address }
false -> contacts.mapNotNull { it.numbers.firstOrNull()?.address }
when {
state.scheduled != 0L -> {
newState { copy(scheduled = 0) }
val uris = attachments.map { it.getUri() }.map { it.toString() }
scheduledMessageRepo.saveScheduledMessage(state.scheduled, subId, addresses, state.sendAsGroup, body, uris)
context.toast(R.string.compose_scheduled_toast)
}
state.sendAsGroup -> {
val threadId = conversation.id.takeIf { it > 0 }
?: TelephonyCompat.getOrCreateThreadId(context, addresses).also(threadIdSubject::onNext)
sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body, attachments))
}
else -> {
addresses.forEach { addr ->
val threadId = TelephonyCompat.getOrCreateThreadId(context, addr)
val address = listOf(conversationRepo.getConversation(threadId)?.recipients?.firstOrNull()?.address
?: addr)
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, attachments))
}
}
val threadId = conversation.id.takeIf { it > 0 }
?: TelephonyCompat.getOrCreateThreadId(context, addresses).also(threadIdSubject::onNext)
sendMessage.execute(SendMessage.Params(subId, threadId, addresses, body, attachments))
} else {
contacts
.map { contact -> contact.numbers }
.mapNotNull { numbers -> numbers.firstOrNull() }
.map { number -> number.address }
.forEach { addr ->
val threadId = TelephonyCompat.getOrCreateThreadId(context, addr)
val address = listOf(conversationRepo.getConversation(threadId)?.recipients?.firstOrNull()?.address
?: addr)
sendMessage.execute(SendMessage.Params(subId, threadId, address, body, attachments))
}
}
view.setDraft("")
@@ -163,6 +163,22 @@
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/messageBackground" />
<ImageView
android:id="@+id/schedule"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginBottom="12dp"
android:background="@drawable/circle"
android:contentDescription="@string/compose_schedule_cd"
android:elevation="4dp"
android:padding="10dp"
android:src="@drawable/ic_event_black_24dp"
android:tint="?android:attr/textColorSecondary"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="@id/gallery"
app:layout_constraintEnd_toEndOf="@id/attach"
app:layout_constraintStart_toStartOf="@id/attach" />
<ImageView
android:id="@+id/gallery"
android:layout_width="40dp"
@@ -224,7 +240,67 @@
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/attach"
app:layout_constraintTop_toTopOf="@id/attachments" />
app:layout_constraintTop_toTopOf="@id/scheduledCancel" />
<androidx.constraintlayout.widget.Group
android:id="@+id/scheduledGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
app:constraint_referenced_ids="scheduledTitle, scheduledTime, scheduledCancel, scheduledSeparator" />
<com.moez.QKSMS.common.widget.QkTextView
android:id="@+id/scheduledTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:elevation="4dp"
android:paddingEnd="16dp"
android:paddingStart="16dp"
android:text="@string/compose_scheduled_for"
android:textColor="?android:attr/textColorPrimary"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@id/scheduledTime"
app:layout_constraintEnd_toStartOf="@id/scheduledCancel"
app:layout_constraintStart_toStartOf="@id/messageBackground"
app:layout_constraintTop_toTopOf="@id/scheduledCancel"
app:layout_constraintVertical_chainStyle="packed"
app:textSize="secondary" />
<com.moez.QKSMS.common.widget.QkTextView
android:id="@+id/scheduledTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:elevation="4dp"
android:paddingEnd="16dp"
android:paddingStart="16dp"
android:textColor="?android:attr/textColorTertiary"
app:layout_constraintBottom_toBottomOf="@id/scheduledCancel"
app:layout_constraintEnd_toStartOf="@id/scheduledCancel"
app:layout_constraintStart_toStartOf="@id/messageBackground"
app:layout_constraintTop_toBottomOf="@id/scheduledTitle"
app:textSize="secondary"
tools:text="Decemeber 23rd at 12:00AM" />
<ImageView
android:id="@+id/scheduledCancel"
android:layout_width="44dp"
android:layout_height="56dp"
android:elevation="4dp"
android:padding="10dp"
android:src="@drawable/ic_cancel_black_24dp"
android:tint="?android:attr/textColorSecondary"
app:layout_constraintBottom_toTopOf="@id/scheduledSeparator"
app:layout_constraintEnd_toEndOf="@id/messageBackground" />
<View
android:id="@+id/scheduledSeparator"
android:layout_width="0dp"
android:layout_height="1dp"
android:background="?android:attr/divider"
android:elevation="4dp"
app:layout_constraintBottom_toTopOf="@id/attachments"
app:layout_constraintEnd_toEndOf="@id/messageBackground"
app:layout_constraintStart_toStartOf="@id/messageBackground" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/attachments"
@@ -240,7 +316,6 @@
app:layout_constraintBottom_toTopOf="@id/message"
app:layout_constraintEnd_toEndOf="@id/messageBackground"
app:layout_constraintStart_toStartOf="@id/messageBackground"
app:layout_constraintTop_toTopOf="@id/messageBackground"
tools:listitem="@layout/attachment_list_item" />
<com.moez.QKSMS.common.widget.QkEditText
@@ -90,6 +90,8 @@
<string name="compose_send_group_summary">Recipients and replies will be visible to everyone</string>
<string name="compose_messages_empty">This is the start of your conversation. Say something nice!</string>
<string name="compose_vcard_label">Contact card</string>
<string name="compose_scheduled_for">Scheduled for</string>
<string name="compose_scheduled_toast">Added to scheduled messages</string>
<string name="compose_hint">Write a message…</string>
<string name="compose_menu_copy">Copy text</string>
<string name="compose_menu_forward">Forward</string>
@@ -111,6 +113,7 @@
<string name="compose_attach_cd">Add an attachment</string>
<string name="compose_gallery_cd">Attach a photo</string>
<string name="compose_camera_cd">Take a photo</string>
<string name="compose_schedule_cd">Send later</string>
<string name="compose_sim_cd">%s selected, change SIM card</string>
<string name="compose_send_cd">Send message</string>