Add Snooze messages until a chosen time and show a follow-up reminder when they return. Bump version V0.1.17
This commit is contained in:
@@ -132,6 +132,61 @@ internal object AndroidAccountVault {
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setSnooze(id: String, uid: Long, folder: String, dueAt: Long?, subject: String) {
|
||||
val store = read()
|
||||
val accounts = store.optJSONArray("accounts") ?: return
|
||||
for (index in 0 until accounts.length()) {
|
||||
val account = accounts.getJSONObject(index)
|
||||
if (account.optString("id") != id) continue
|
||||
val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
val updated = JSONArray()
|
||||
for (itemIndex in 0 until previous.length()) {
|
||||
val item = previous.getJSONObject(itemIndex)
|
||||
if (item.optLong("uid") != uid || item.optString("folder") != folder) updated.put(item)
|
||||
}
|
||||
if (dueAt != null) {
|
||||
updated.put(JSONObject()
|
||||
.put("uid", uid)
|
||||
.put("folder", folder)
|
||||
.put("dueAt", dueAt)
|
||||
.put("subject", subject.take(200)))
|
||||
}
|
||||
account.put("snoozedMessages", updated)
|
||||
write(store)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun takeDueSnoozes(id: String, now: Long): JSONArray {
|
||||
val store = read()
|
||||
val accounts = store.optJSONArray("accounts") ?: return JSONArray()
|
||||
for (index in 0 until accounts.length()) {
|
||||
val account = accounts.getJSONObject(index)
|
||||
if (account.optString("id") != id) continue
|
||||
val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
val remaining = JSONArray()
|
||||
val due = JSONArray()
|
||||
for (itemIndex in 0 until previous.length()) {
|
||||
val item = previous.getJSONObject(itemIndex)
|
||||
if (item.optLong("dueAt") <= now) {
|
||||
due.put(JSONObject(item.toString())
|
||||
.put("accountId", id)
|
||||
.put("email", account.optString("email")))
|
||||
} else {
|
||||
remaining.put(item)
|
||||
}
|
||||
}
|
||||
if (due.length() > 0) {
|
||||
account.put("snoozedMessages", remaining)
|
||||
write(store)
|
||||
}
|
||||
return due
|
||||
}
|
||||
return JSONArray()
|
||||
}
|
||||
|
||||
fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
|
||||
val result = JSONArray()
|
||||
for (index in 0 until accounts.length()) {
|
||||
|
||||
@@ -57,8 +57,9 @@ internal object AndroidMailService {
|
||||
JSONObject().put("mailbox", "INBOX").put("messages", count)
|
||||
}
|
||||
|
||||
fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject {
|
||||
if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
|
||||
return withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, requestedFolder)
|
||||
if (folder == null) return@withStore JSONObject()
|
||||
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
|
||||
@@ -73,7 +74,15 @@ internal object AndroidMailService {
|
||||
val first = (end - 19).coerceAtLeast(1)
|
||||
val result = JSONArray()
|
||||
val batch = folder.getMessages(first, end).reversed()
|
||||
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
for (message in batch) {
|
||||
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
|
||||
val isSnoozed = (0 until snoozed.length()).any { index ->
|
||||
val item = snoozed.getJSONObject(index)
|
||||
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
|
||||
item.optLong("dueAt") > System.currentTimeMillis()
|
||||
}
|
||||
if (isSnoozed) continue
|
||||
result.put(messageJson(folder, message, requestedFolder))
|
||||
}
|
||||
JSONObject().put("messages", result).put("total", total)
|
||||
@@ -82,13 +91,44 @@ internal object AndroidMailService {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
val pending = (0 until snoozes.length())
|
||||
.map { snoozes.getJSONObject(it) }
|
||||
.filter { it.optLong("dueAt") > System.currentTimeMillis() }
|
||||
.sortedBy { it.optLong("dueAt") }
|
||||
val page = pending.drop(offset.coerceAtLeast(0)).take(20)
|
||||
val messages = JSONArray()
|
||||
for (snooze in page) {
|
||||
val sourceFolder = snooze.optString("folder", "Inbox")
|
||||
val folder = resolveFolder(store, sourceFolder) ?: continue
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue
|
||||
messages.put(messageJson(folder, message, "Snoozed")
|
||||
.put("sourceFolder", sourceFolder)
|
||||
.put("snoozedUntil", snooze.optLong("dueAt")))
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
JSONObject()
|
||||
.put("messages", messages)
|
||||
.put("total", pending.size)
|
||||
.put("start", if (page.isEmpty()) 0 else offset + 1)
|
||||
.put("end", offset + messages.length())
|
||||
.put("folder", "Snoozed")
|
||||
}
|
||||
|
||||
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val uid = input.optLong("uid")
|
||||
require(uid > 0) { "That message could not be identified." }
|
||||
val action = input.optString("action")
|
||||
require(action in setOf("star", "unread", "archive", "delete")) { "That mail action is not supported." }
|
||||
require(action in setOf("star", "unread", "archive", "delete", "inbox")) { "That mail action is not supported." }
|
||||
val source = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
var expungeDeleted = false
|
||||
@@ -99,18 +139,38 @@ internal object AndroidMailService {
|
||||
when (action) {
|
||||
"star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled"))
|
||||
"unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled"))
|
||||
"archive", "delete" -> {
|
||||
expungeDeleted = true
|
||||
val targetName = if (action == "archive") "Archive" else "Trash"
|
||||
"archive", "delete", "inbox" -> {
|
||||
val targetName = when (action) {
|
||||
"archive" -> "Archive"
|
||||
"delete" -> "Trash"
|
||||
else -> "Inbox"
|
||||
}
|
||||
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
|
||||
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
|
||||
source.copyMessages(arrayOf(message), target)
|
||||
message.setFlag(Flags.Flag.DELETED, true)
|
||||
if (source.fullName == target.fullName) {
|
||||
if (action == "delete") {
|
||||
expungeDeleted = true
|
||||
message.setFlag(Flags.Flag.DELETED, true)
|
||||
}
|
||||
} else {
|
||||
expungeDeleted = true
|
||||
source.copyMessages(arrayOf(message), target)
|
||||
message.setFlag(Flags.Flag.DELETED, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
source.close(expungeDeleted)
|
||||
}
|
||||
if (action == "archive" || action == "delete" || action == "inbox") {
|
||||
AndroidAccountVault.setSnooze(
|
||||
account.optString("id"),
|
||||
uid,
|
||||
input.optString("folder", "Inbox"),
|
||||
null,
|
||||
""
|
||||
)
|
||||
}
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
|
||||
@@ -159,6 +159,49 @@ class EpMailPlugin : Plugin() {
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun setSnooze(call: PluginCall) {
|
||||
try {
|
||||
val account = AndroidAccountVault.account()
|
||||
?: throw IllegalStateException("Add a mail account before setting a reminder.")
|
||||
val uid = call.getLong("uid") ?: throw IllegalArgumentException("That message could not be identified.")
|
||||
require(uid > 0) { "That message could not be identified." }
|
||||
val folder = call.getString("sourceFolder") ?: call.getString("folder") ?: "Inbox"
|
||||
require(folder in setOf("Inbox", "Sent", "Archive", "Trash")) { "That mailbox cannot be snoozed." }
|
||||
val dueAt = call.getLong("dueAt")
|
||||
if (dueAt != null && dueAt <= System.currentTimeMillis()) {
|
||||
throw IllegalArgumentException("Choose a reminder time in the future.")
|
||||
}
|
||||
AndroidAccountVault.setSnooze(
|
||||
account.optString("id"),
|
||||
uid,
|
||||
folder,
|
||||
dueAt,
|
||||
call.getString("subject").orEmpty()
|
||||
)
|
||||
val update = JSONObject()
|
||||
.put("accountId", account.optString("id"))
|
||||
.put("foldersChanged", JSONArray().put("Snoozed").put(folder))
|
||||
context.sendBroadcast(Intent(MailIdleService.ACTION_MAIL_SYNC)
|
||||
.setPackage(context.packageName)
|
||||
.putExtra(MailIdleService.EXTRA_SYNC_UPDATE, update.toString()))
|
||||
MailIdleService.start(context)
|
||||
call.resolve(JSObject().put("ok", true).put("snoozed", dueAt != null))
|
||||
} catch (error: Exception) {
|
||||
call.reject(error.message ?: "Could not set the reminder.")
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun checkSnoozeReminders(call: PluginCall) {
|
||||
try {
|
||||
MailIdleService.checkSnoozeReminders(context)
|
||||
call.resolve()
|
||||
} catch (error: Exception) {
|
||||
call.reject(error.message ?: "Could not check mail reminders.")
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun saveAttachment(call: PluginCall) {
|
||||
try {
|
||||
|
||||
@@ -14,6 +14,7 @@ class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worke
|
||||
override fun doWork(): Result {
|
||||
return try {
|
||||
AndroidAccountVault.initialize(applicationContext)
|
||||
MailIdleService.checkSnoozeReminders(applicationContext)
|
||||
val accounts = AndroidAccountVault.accounts()
|
||||
for (index in 0 until accounts.length()) {
|
||||
val account = accounts.getJSONObject(index)
|
||||
|
||||
@@ -181,6 +181,21 @@ class MailIdleService : Service() {
|
||||
MailFallbackWorker.cancel(context)
|
||||
}
|
||||
|
||||
fun checkSnoozeReminders(context: Context) {
|
||||
AndroidAccountVault.initialize(context)
|
||||
val accounts = AndroidAccountVault.accounts()
|
||||
for (index in 0 until accounts.length()) {
|
||||
val account = accounts.getJSONObject(index)
|
||||
val reminders = AndroidAccountVault.takeDueSnoozes(
|
||||
account.optString("id"),
|
||||
System.currentTimeMillis()
|
||||
)
|
||||
for (reminderIndex in 0 until reminders.length()) {
|
||||
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
|
||||
if (count <= 0) return
|
||||
val appContext = context.applicationContext
|
||||
@@ -223,5 +238,54 @@ class MailIdleService : Service() {
|
||||
android.util.Log.w(TAG, "Notification permission is unavailable", error)
|
||||
}
|
||||
}
|
||||
|
||||
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
|
||||
val appContext = context.applicationContext
|
||||
val email = account.optString("email")
|
||||
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
|
||||
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
|
||||
manager.createNotificationChannel(NotificationChannel(
|
||||
MAIL_CHANNEL_ID,
|
||||
"Mail reminders",
|
||||
NotificationManager.IMPORTANCE_DEFAULT
|
||||
))
|
||||
}
|
||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||
.setContentTitle("Mail reminder")
|
||||
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setContentIntent(appPendingIntentFor(appContext))
|
||||
.build()
|
||||
try {
|
||||
NotificationManagerCompat.from(appContext).notify(
|
||||
(email + reminder.optLong("uid")).hashCode(),
|
||||
notification
|
||||
)
|
||||
} catch (error: SecurityException) {
|
||||
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
|
||||
}
|
||||
val update = JSONObject()
|
||||
.put("accountId", account.optString("id"))
|
||||
.put("snoozeReminder", true)
|
||||
.put("foldersChanged", org.json.JSONArray()
|
||||
.put("Snoozed")
|
||||
.put(reminder.optString("folder", "Inbox")))
|
||||
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
|
||||
.setPackage(appContext.packageName)
|
||||
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
|
||||
}
|
||||
|
||||
private fun appPendingIntentFor(context: Context): PendingIntent {
|
||||
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
|
||||
?: Intent(context, MainActivity::class.java)
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
return PendingIntent.getActivity(
|
||||
context, 0, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user