Skip to content

Commit

Permalink
Fixed updating drafts on the thread details screen.| #74
Browse files Browse the repository at this point in the history
  • Loading branch information
DenBond7 committed Nov 21, 2024
1 parent 69eeae6 commit a4c588e
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class DraftViewModel(
if (isSavingDraftNeeded) {
if (showNotification) {
withContext(Dispatchers.Main) {
context.toast(context.getString(R.string.draft_saved))
context.toast(context.getString(R.string.saving_draft))
}
}
withContext(Dispatchers.IO) {
Expand All @@ -119,7 +119,7 @@ class DraftViewModel(
}
} else if (showNotification && timeToCompare < draftFingerprint.timeInMilliseconds) {
withContext(Dispatchers.Main) {
context.toast(context.getString(R.string.draft_saved))
context.toast(context.getString(R.string.saving_draft))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package com.flowcrypt.email.jetpack.workmanager.sync
import android.content.Context
import androidx.work.ExistingWorkPolicy
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.flowcrypt.email.BuildConfig
import com.flowcrypt.email.api.email.gmail.GmailApiHelper
import com.flowcrypt.email.database.MessageState
Expand Down Expand Up @@ -127,10 +128,25 @@ class UploadDraftsWorker(context: Context, params: WorkerParameters) :
}
val drafts = directory.listFiles(FileFilter { it.isFile }) ?: emptyArray()
try {
setProgress(
workDataOf(
EXTRA_KEY_MESSAGE_UID to existingDraftEntity.uid,
EXTRA_KEY_STATE to STATE_UPLOADING
)
)
val lastVersion = drafts.maxBy { it.lastModified() }
val inputStream = KeyStoreCryptoManager.getCipherInputStream(lastVersion.inputStream())
val mimeMessage = MimeMessage(Session.getInstance(Properties()), inputStream)
action.invoke(existingDraftEntity, mimeMessage)

if (existingDraftEntity.threadId != null) {
val threadEntity = roomDatabase.msgDao().getThreadMessageEntity(
existingDraftEntity.account,
existingDraftEntity.folder,
existingDraftEntity.threadId
)
setProgress(workDataOf("threadId" to (threadEntity?.id ?: 0L)))
}
drafts.forEach { FileAndDirectoryUtils.deleteFile(it) }
if ((directory.listFiles() ?: emptyArray<File>()).isEmpty()) {
FileAndDirectoryUtils.deleteDir(directory)
Expand Down Expand Up @@ -159,14 +175,32 @@ class UploadDraftsWorker(context: Context, params: WorkerParameters) :
}

continue
} finally {
setProgress(
workDataOf(
EXTRA_KEY_MESSAGE_UID to existingDraftEntity.uid,
EXTRA_KEY_STATE to STATE_UPLOAD_COMPLETED
)
)
}
}

attemptsCount++
}

setProgress(
workDataOf(EXTRA_KEY_STATE to STATE_COMMON_UPLOAD_COMPLETED)
)
}

companion object {
const val EXTRA_KEY_MESSAGE_UID = "MESSAGE_UID"
const val EXTRA_KEY_STATE = "STATE"

const val STATE_UPLOADING = 0
const val STATE_UPLOAD_COMPLETED = 1
const val STATE_COMMON_UPLOAD_COMPLETED = 2

const val GROUP_UNIQUE_TAG = BuildConfig.APPLICATION_ID + ".UPLOAD_DRAFTS"
const val MAX_ATTEMPTS_COUNT = 10

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import androidx.lifecycle.ViewModel
import androidx.navigation.NavDirections
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.work.WorkManager
import com.flowcrypt.email.Constants
import com.flowcrypt.email.R
import com.flowcrypt.email.api.email.FoldersManager
Expand Down Expand Up @@ -70,6 +71,7 @@ import com.flowcrypt.email.jetpack.workmanager.sync.MarkAsNotSpamWorker
import com.flowcrypt.email.jetpack.workmanager.sync.MovingToInboxWorker
import com.flowcrypt.email.jetpack.workmanager.sync.MovingToSpamWorker
import com.flowcrypt.email.jetpack.workmanager.sync.UpdateMsgsSeenStateWorker
import com.flowcrypt.email.jetpack.workmanager.sync.UploadDraftsWorker
import com.flowcrypt.email.model.MessageAction
import com.flowcrypt.email.model.MessageEncryptionType
import com.flowcrypt.email.model.MessageType
Expand Down Expand Up @@ -287,6 +289,7 @@ class ThreadDetailsFragment : BaseFragment<FragmentThreadDetailsBinding>(), Prog
subscribeToImportingAdditionalPrivateKeys()
subscribeToChoosePublicKeyDialogFragment()
subscribeToDecryptAttachmentViaDialog()
subscribeToDraftsUpdates()
}

override fun onSetupActionBarMenu(menuHost: MenuHost) {
Expand Down Expand Up @@ -833,6 +836,42 @@ class ThreadDetailsFragment : BaseFragment<FragmentThreadDetailsBinding>(), Prog
}
}

private fun subscribeToDraftsUpdates() {
launchAndRepeatWithViewLifecycle(Lifecycle.State.CREATED) {
WorkManager.getInstance(requireContext())
.getWorkInfosForUniqueWorkFlow(UploadDraftsWorker.GROUP_UNIQUE_TAG)
.collect { workInfoList ->
val workInfo = workInfoList.firstOrNull() ?: return@collect
val messageUID = workInfo.progress.getLong(UploadDraftsWorker.EXTRA_KEY_MESSAGE_UID, -1)
val state = workInfo.progress.getInt(UploadDraftsWorker.EXTRA_KEY_STATE, -1)

val message = messagesInThreadListAdapter.currentList.firstOrNull {
it is MessagesInThreadListAdapter.Message && it.messageEntity.uid == messageUID
} as? MessagesInThreadListAdapter.Message

if (message != null) {
when (state) {
UploadDraftsWorker.STATE_UPLOADING -> {
threadDetailsViewModel.onMessageChanged(
message.copy(hasActiveDraftUploadingProcess = true)
)
}

UploadDraftsWorker.STATE_UPLOAD_COMPLETED -> {
threadDetailsViewModel.loadMessages(silentUpdate = true)
}
}
} else if (state == UploadDraftsWorker.STATE_COMMON_UPLOAD_COMPLETED) {
if (messagesInThreadListAdapter.currentList.any {
it is MessagesInThreadListAdapter.Message && it.hasActiveDraftUploadingProcess
}) {
threadDetailsViewModel.loadMessages(silentUpdate = true)
}
}
}
}
}

private fun replyTo(message: MessagesInThreadListAdapter.Message) {
if (message.incomingMessageInfo != null) {
startActivity(prepareReply(message, MessageType.REPLY))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,19 +322,23 @@ class MessagesInThreadListAdapter(
}

binding.imageButtonEditDraft.apply {
visibleOrGone(message.messageEntity.isDraft)
visibleOrGone(message.messageEntity.isDraft && !message.hasActiveDraftUploadingProcess)
setOnClickListener {
onMessageActionsListener.onEditDraft(message)
}
}

binding.imageButtonDeleteDraft.apply {
visibleOrGone(message.messageEntity.isDraft)
visibleOrGone(message.messageEntity.isDraft && !message.hasActiveDraftUploadingProcess)
setOnClickListener {
onMessageActionsListener.onDeleteDraft(message)
}
}

binding.progressBarSavingDraft.apply {
visibleOrGone(message.messageEntity.isDraft && message.hasActiveDraftUploadingProcess)
}

binding.imageButtonReplyAll.apply {
visibleOrInvisible(!message.messageEntity.isDraft)
setOnClickListener {
Expand Down Expand Up @@ -991,7 +995,8 @@ class MessagesInThreadListAdapter(
val isHeadersDetailsExpanded: Boolean,
val attachments: List<AttachmentInfo>,
val incomingMessageInfo: IncomingMessageInfo? = null,
val hasActiveSignatureVerification: Boolean = false
val hasActiveSignatureVerification: Boolean = false,
val hasActiveDraftUploadingProcess: Boolean = false
) : Item(), Parcelable {
override val id: Long
get() = messageEntity.uid
Expand Down
11 changes: 11 additions & 0 deletions FlowCrypt/src/main/res/layout/item_message_in_thread_expanded.xml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@
app:layout_goneMarginRight="@dimen/default_margin_medium"
app:srcCompat="@drawable/ic_baseline_edit_draft_24" />

<ProgressBar
android:id="@+id/progressBarSavingDraft"
style="?android:attr/progressBarStyleSmall"
android:layout_width="24dp"
android:layout_height="24dp"
android:indeterminate="true"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_goneMarginRight="@dimen/default_margin_medium" />

<TextView
android:id="@+id/textViewDate"
android:layout_width="0dp"
Expand Down
2 changes: 1 addition & 1 deletion FlowCrypt/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@
<string name="add_recipient_to_send_message">Пожалуйста, добавьте хотя бы одного получателя в поле \"Кому\" для отправки этого сообщения</string>
<string name="send_feedback_failed_hint">При отправке сообщения произошла ошибка. Пожалуйста, напишите нам напрямую на %1$s.\n\nДетали ошибки:\n%2$s</string>
<string name="edit_draft">Редактировать черновик</string>
<string name="draft_saved">Черновик сохранен</string>
<string name="saving_draft">Сохранение черновика</string>
<string name="fetching_drafts_info_failed">Не удалось загрузить информацию о черновиках. Пожалуйста, попробуйте еще раз.</string>
<string name="no_recipients">(без получателей)</string>
<string name="could_not_save_draft">Не удалось сохранить черновик\n\nДетали ошибки:\n%1$s</string>
Expand Down
2 changes: 1 addition & 1 deletion FlowCrypt/src/main/res/values-uk/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@
<string name="add_recipient_to_send_message">Щоб надіслати це повідомлення, додайте принаймні одного одержувача в поле \"Кому\"</string>
<string name="send_feedback_failed_hint">Під час відправки повідомлення виникла помилка. Будь ласка, напишіть нам безпосередньо на %1$s.\n\nДеталі помилки:\n%2$s</string>
<string name="edit_draft">Редагувати чорновик</string>
<string name="draft_saved">Чорновик збережено</string>
<string name="saving_draft">Збереження чорновика</string>
<string name="fetching_drafts_info_failed">Не вдалося отримати інформацію про чорновики. Будь ласка, спробуйте ще раз.</string>
<string name="no_recipients">(без отримувачів)</string>
<string name="could_not_save_draft">Не вдалося зберегти чорновик\n\nДеталі помилки:\n%1$s</string>
Expand Down
2 changes: 1 addition & 1 deletion FlowCrypt/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@
<string name="add_recipient_to_send_message">Please add at least one recipient in \"To\" to send this message</string>
<string name="send_feedback_failed_hint">There was an error sending message. Our direct email is %1$s.\n\nError details:\n%2$s</string>
<string name="edit_draft">Edit draft</string>
<string name="draft_saved">Draft saved</string>
<string name="saving_draft">Saving draft</string>
<string name="fetching_drafts_info_failed">Fetching drafts info failed. Please try again.</string>
<string name="no_recipients">(no recipients)</string>
<string name="could_not_save_draft">Could not save a draft\n\nError details:\n%1$s</string>
Expand Down

0 comments on commit a4c588e

Please sign in to comment.