Added flag to stop listening to new emails

This commit is contained in:
dankito 2024-11-26 03:24:46 +01:00
parent dcc4e233aa
commit 199310de86
2 changed files with 9 additions and 7 deletions

View File

@ -54,22 +54,20 @@ open class EmailsFetcher(
}) })
launch(coroutineDispatcher) { launch(coroutineDispatcher) {
keepConnectionOpen(account, folder) keepConnectionOpen(account, folder, options)
} }
} }
} catch (e: Throwable) { } catch (e: Throwable) {
log.error(e) { "Listening to new emails of '${account.username}' failed" } log.error(e) { "Listening to new emails of '${account.username}' failed" }
options.onError?.invoke(FetchEmailsError(FetchEmailsErrorType.ListenForNewEmails, null, e)) options.onError?.invoke(FetchEmailsError(FetchEmailsErrorType.ListenForNewEmails, null, e))
} }
log.info { "Stopped listening to new emails of '${account.username}'" }
} }
protected open suspend fun keepConnectionOpen(account: EmailAccount, folder: Folder) { protected open suspend fun keepConnectionOpen(account: EmailAccount, folder: Folder, options: ListenForNewMailsOptions) {
log.info { "Listening to new emails of ${account.username}" } log.info { "Listening to new emails of ${account.username}" }
// Use IMAP IDLE to keep the connection alive // Use IMAP IDLE to keep the connection alive
while (true) { while (options.stopListening.get() == false) {
if (!folder.isOpen) { if (!folder.isOpen) {
log.info { "Reopening inbox of ${account.username} ..." } log.info { "Reopening inbox of ${account.username} ..." }
folder.open(Folder.READ_ONLY) folder.open(Folder.READ_ONLY)
@ -79,6 +77,8 @@ open class EmailsFetcher(
delay(250) delay(250)
} }
log.info { "Stopped listening to new emails of '${account.username}'" }
} }

View File

@ -1,12 +1,14 @@
package net.codinux.invoicing.email package net.codinux.invoicing.email
import net.codinux.invoicing.email.model.EmailWithInvoice import net.codinux.invoicing.email.model.EmailWithInvoice
import java.util.concurrent.atomic.AtomicBoolean
open class ListenForNewMailsOptions( open class ListenForNewMailsOptions(
val stopListening: AtomicBoolean = AtomicBoolean(false),
downloadMessageBody: Boolean = false, downloadMessageBody: Boolean = false,
emailFolderName: String = "INBOX", emailFolderName: String = "INBOX",
onError: ((FetchEmailsError) -> Unit)? = null, onError: ((FetchEmailsError) -> Unit)? = null,
onEmailReceived: (EmailWithInvoice) -> Unit onEmailReceived: (EmailWithInvoice) -> Unit
) : FetchEmailsOptions(downloadMessageBody, emailFolderName, onError, onEmailReceived) { ) : FetchEmailsOptions(downloadMessageBody, emailFolderName, onError, onEmailReceived)
}