Ver V0.1.16 Add Android version to project
This commit is contained in:
@@ -0,0 +1,455 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import android.text.Html
|
||||
import android.webkit.MimeTypeMap
|
||||
import com.sun.mail.imap.IMAPFolder
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.Properties
|
||||
import java.util.UUID
|
||||
import javax.mail.Address
|
||||
import javax.mail.Authenticator
|
||||
import javax.mail.Flags
|
||||
import javax.mail.Folder
|
||||
import javax.mail.Message
|
||||
import javax.mail.Multipart
|
||||
import javax.mail.PasswordAuthentication
|
||||
import javax.mail.Session
|
||||
import javax.mail.Store
|
||||
import javax.mail.Transport
|
||||
import javax.mail.UIDFolder
|
||||
import javax.mail.internet.InternetAddress
|
||||
import javax.mail.internet.MimeBodyPart
|
||||
import javax.mail.internet.MimeMessage
|
||||
import javax.mail.internet.MimeMultipart
|
||||
import javax.mail.internet.MimeUtility
|
||||
|
||||
internal object AndroidMailService {
|
||||
data class SyncResult(val payload: JSONObject, val newCount: Int)
|
||||
|
||||
fun connect(account: JSONObject): JSONObject = withStore(account) { session, store ->
|
||||
val inbox = store.getFolder("INBOX")
|
||||
check(inbox.exists()) { "The inbox could not be found." }
|
||||
inbox.open(Folder.READ_ONLY)
|
||||
val count = inbox.messageCount
|
||||
inbox.close(false)
|
||||
val smtpSession = Session.getInstance(smtpProperties(account), credentials(account))
|
||||
val transport = smtpSession.getTransport("smtp")
|
||||
try {
|
||||
transport.connect(
|
||||
account.optString("smtpHost"),
|
||||
account.optInt("smtpPort", 587),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
} finally {
|
||||
if (transport.isConnected) transport.close()
|
||||
}
|
||||
JSONObject().put("mailbox", "INBOX").put("messages", count)
|
||||
}
|
||||
|
||||
fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, requestedFolder)
|
||||
if (folder == null) return@withStore JSONObject()
|
||||
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val total = folder.messageCount
|
||||
val end = (total - offset.coerceAtLeast(0)).coerceAtLeast(0)
|
||||
if (end == 0) {
|
||||
return@withStore JSONObject().put("messages", JSONArray()).put("total", total)
|
||||
.put("start", 0).put("end", 0).put("folder", requestedFolder)
|
||||
}
|
||||
val first = (end - 19).coerceAtLeast(1)
|
||||
val result = JSONArray()
|
||||
val batch = folder.getMessages(first, end).reversed()
|
||||
for (message in batch) {
|
||||
result.put(messageJson(folder, message, requestedFolder))
|
||||
}
|
||||
JSONObject().put("messages", result).put("total", total)
|
||||
.put("start", first).put("end", end).put("folder", requestedFolder)
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
|
||||
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." }
|
||||
val source = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
var expungeDeleted = false
|
||||
source.open(Folder.READ_WRITE)
|
||||
try {
|
||||
val message = (source as? UIDFolder)?.getMessageByUID(uid)
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
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"
|
||||
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)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
source.close(expungeDeleted)
|
||||
}
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
fun send(account: JSONObject, input: JSONObject): JSONObject {
|
||||
val recipient = input.optString("to").trim()
|
||||
require(recipient.isNotEmpty()) { "Add at least one recipient." }
|
||||
val properties = smtpProperties(account)
|
||||
val session = Session.getInstance(properties, credentials(account))
|
||||
val message = MimeMessage(session)
|
||||
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
|
||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
|
||||
val cc = input.optString("cc").trim()
|
||||
if (cc.isNotEmpty()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, true))
|
||||
message.subject = input.optString("subject", "(no subject)")
|
||||
message.setText(input.optString("text"), "UTF-8")
|
||||
message.sentDate = Date()
|
||||
message.saveChanges()
|
||||
|
||||
val transport = session.getTransport("smtp")
|
||||
try {
|
||||
transport.connect(
|
||||
account.optString("smtpHost"),
|
||||
account.optInt("smtpPort", 587),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
transport.sendMessage(message, message.allRecipients)
|
||||
} finally {
|
||||
if (transport.isConnected) transport.close()
|
||||
}
|
||||
|
||||
var savedToSent = false
|
||||
try {
|
||||
withStore(account) { _, store ->
|
||||
val sent = resolveFolder(store, "Sent") ?: store.getFolder("Sent")
|
||||
if (!sent.exists()) sent.create(Folder.HOLDS_MESSAGES)
|
||||
sent.appendMessages(arrayOf(message))
|
||||
savedToSent = true
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
savedToSent = false
|
||||
}
|
||||
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
|
||||
}
|
||||
|
||||
fun saveAttachment(context: Context, account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val uid = input.optLong("uid")
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
val filename = input.optString("filename")
|
||||
val part = findAttachment(message, filename)
|
||||
?: throw IllegalStateException("No attachment was found in this message.")
|
||||
saveAttachmentBytes(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream.readBytes())
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun checkForNewMail(account: JSONObject): Int = withStore(account) { _, store ->
|
||||
val folder = store.getFolder("INBOX")
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val uidFolder = folder as? UIDFolder
|
||||
?: throw IllegalStateException("The mail server does not support stable message IDs.")
|
||||
val validity = uidFolder.uidValidity
|
||||
val latestUid = (uidFolder.uidNext - 1).coerceAtLeast(0)
|
||||
val oldState = account.optJSONObject("androidInboxSyncState")
|
||||
val lastUid = if (oldState == null || oldState.optLong("uidValidity") != validity) {
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
|
||||
return@withStore 0
|
||||
} else oldState.optLong("lastUid")
|
||||
if (latestUid <= lastUid) return@withStore 0
|
||||
val added = uidFolder.getMessagesByUID(lastUid + 1, UIDFolder.LASTUID)
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
|
||||
added.size
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun watchInbox(
|
||||
account: JSONObject,
|
||||
onNewMail: (Int) -> Unit,
|
||||
shouldStop: () -> Boolean,
|
||||
onConnection: (Store?, Folder?) -> Unit
|
||||
) {
|
||||
val props = imapProperties(account).apply {
|
||||
setProperty("mail.imap.timeout", "0")
|
||||
setProperty("mail.imap.writetimeout", "60000")
|
||||
}
|
||||
val session = Session.getInstance(props, credentials(account))
|
||||
val store = session.getStore("imap")
|
||||
try {
|
||||
store.connect(
|
||||
account.optString("imapHost"),
|
||||
account.optInt("imapPort", 143),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
val inbox = store.getFolder("INBOX")
|
||||
inbox.open(Folder.READ_ONLY)
|
||||
var previousCount = inbox.messageCount
|
||||
val uidFolder = inbox as? UIDFolder
|
||||
val uidValidity = uidFolder?.uidValidity ?: 0L
|
||||
val initialUid = uidFolder?.let { (it.uidNext - 1).coerceAtLeast(0) } ?: 0L
|
||||
if (uidValidity > 0) {
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, initialUid)
|
||||
}
|
||||
onConnection(store, inbox)
|
||||
inbox.addMessageCountListener(object : javax.mail.event.MessageCountListener {
|
||||
override fun messagesAdded(event: javax.mail.event.MessageCountEvent) {
|
||||
if (event.type == javax.mail.event.MessageCountEvent.ADDED) {
|
||||
previousCount = maxOf(previousCount, inbox.messageCount)
|
||||
val newestUid = event.messages.maxOfOrNull { message ->
|
||||
try { uidFolder?.getUID(message) ?: 0L } catch (_: Exception) { 0L }
|
||||
} ?: 0L
|
||||
if (uidValidity > 0 && newestUid > 0) {
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, newestUid)
|
||||
}
|
||||
onNewMail(event.messages.size)
|
||||
}
|
||||
}
|
||||
override fun messagesRemoved(event: javax.mail.event.MessageCountEvent) = Unit
|
||||
})
|
||||
try {
|
||||
var supportsIdle = inbox is IMAPFolder
|
||||
while (!shouldStop()) {
|
||||
try {
|
||||
if (supportsIdle && inbox is IMAPFolder) {
|
||||
inbox.idle()
|
||||
} else {
|
||||
Thread.sleep(120_000)
|
||||
val currentCount = inbox.messageCount
|
||||
if (currentCount > previousCount) onNewMail(currentCount - previousCount)
|
||||
previousCount = currentCount
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
if (shouldStop()) break
|
||||
if (error !is javax.mail.MethodNotSupportedException &&
|
||||
!error.javaClass.simpleName.contains("UnsupportedCommand")) throw error
|
||||
supportsIdle = false
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
onConnection(null, null)
|
||||
if (inbox.isOpen) inbox.close(false)
|
||||
}
|
||||
} finally {
|
||||
if (store.isConnected) store.close()
|
||||
}
|
||||
}
|
||||
|
||||
fun accountFingerprint(account: JSONObject): String = listOf(
|
||||
account.optString("email"),
|
||||
account.optString("imapHost"),
|
||||
account.optString("password")
|
||||
).joinToString("|").hashCode().toString()
|
||||
|
||||
private fun messageJson(folder: Folder, message: Message, requestedFolder: String): JSONObject {
|
||||
val uid = (folder as? UIDFolder)?.getUID(message) ?: message.messageNumber.toLong()
|
||||
val sender = (message.from?.firstOrNull() as? InternetAddress)
|
||||
val senderName = decode(sender?.personal).ifBlank { sender?.address ?: "Unknown sender" }
|
||||
val senderEmail = sender?.address ?: ""
|
||||
val subject = decode(message.subject).ifBlank { "(no subject)" }
|
||||
val body = ArrayList<String>()
|
||||
val attachments = JSONArray()
|
||||
collectParts(message, body, attachments)
|
||||
val bodyText = body.joinToString("\n\n").trim()
|
||||
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
||||
val date = message.receivedDate ?: message.sentDate ?: Date()
|
||||
val tags = JSONArray().put(requestedFolder)
|
||||
val files = attachmentList(attachments)
|
||||
val flags = message.flags
|
||||
val id = uid.toDouble()
|
||||
return JSONObject()
|
||||
.put("id", id)
|
||||
.put("uid", uid)
|
||||
.put("initials", senderName.split(Regex("[\\s@]+")).filter(String::isNotBlank)
|
||||
.mapNotNull { it.firstOrNull()?.toString() }.joinToString("").take(2).uppercase(Locale.getDefault()))
|
||||
.put("color", "#dce6df")
|
||||
.put("sender", senderName)
|
||||
.put("email", senderEmail)
|
||||
.put("subject", subject)
|
||||
.put("snippet", snippet)
|
||||
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
|
||||
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
|
||||
.put("unread", !flags.contains(Flags.Flag.SEEN))
|
||||
.put("star", flags.contains(Flags.Flag.FLAGGED))
|
||||
.put("tags", tags)
|
||||
.put("sent", requestedFolder == "Sent")
|
||||
.put("archived", requestedFolder == "Archive")
|
||||
.put("deleted", requestedFolder == "Trash")
|
||||
.put("body", JSONArray().apply {
|
||||
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
||||
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
||||
})
|
||||
.put("attachments", attachments)
|
||||
.put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL)
|
||||
.put("size", files.firstOrNull()?.optString("size") ?: "")
|
||||
}
|
||||
|
||||
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
||||
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
||||
|
||||
private fun collectParts(part: javax.mail.Part, body: MutableList<String>, attachments: JSONArray) {
|
||||
val filename = decode(part.fileName)
|
||||
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
|
||||
val name = filename.ifBlank { "attachment" }
|
||||
val size = part.size.coerceAtLeast(0)
|
||||
attachments.put(JSONObject().put("filename", name).put("size", size))
|
||||
return
|
||||
}
|
||||
val content = try { part.content } catch (_: Exception) { return }
|
||||
when (content) {
|
||||
is String -> if (part.isMimeType("text/plain")) {
|
||||
body.add(content.replace("\r", "").trim())
|
||||
} else if (part.isMimeType("text/html") && body.isEmpty()) {
|
||||
body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
|
||||
}
|
||||
is Multipart -> for (index in 0 until content.count) {
|
||||
collectParts(content.getBodyPart(index), body, attachments)
|
||||
}
|
||||
is javax.mail.BodyPart -> collectParts(content, body, attachments)
|
||||
}
|
||||
}
|
||||
|
||||
private fun findAttachment(part: javax.mail.Part, filename: String): MimeBodyPart? {
|
||||
val name = decode(part.fileName)
|
||||
if ((name == filename || (filename.isBlank() && name.isNotBlank())) && part is MimeBodyPart) return part
|
||||
val content = try { part.content } catch (_: Exception) { return null }
|
||||
if (content is Multipart) {
|
||||
for (index in 0 until content.count) {
|
||||
findAttachment(content.getBodyPart(index), filename)?.let { return it }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
||||
val mimeType = contentType.substringBefore(';').ifBlank {
|
||||
MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, filename)
|
||||
put(MediaStore.Downloads.MIME_TYPE, mimeType)
|
||||
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
}
|
||||
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||
?: throw IllegalStateException("Could not create the attachment in Downloads.")
|
||||
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
?: throw IllegalStateException("Could not write the attachment.")
|
||||
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", filename)
|
||||
}
|
||||
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
|
||||
?: throw IllegalStateException("Downloads storage is not available.")
|
||||
val file = File(directory, filename.replace(Regex("[\\\\/:*?\"<>|]"), "_"))
|
||||
file.writeBytes(bytes)
|
||||
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", filename)
|
||||
}
|
||||
|
||||
private fun resolveFolder(store: Store, requested: String): Folder? {
|
||||
if (requested == "Inbox" || requested == "Starred" || requested == "Snoozed") {
|
||||
return store.getFolder("INBOX")
|
||||
}
|
||||
val (specialUse, candidates) = when (requested) {
|
||||
"Sent" -> "\\Sent" to setOf("sent", "sent items", "sent mail", "sent messages")
|
||||
"Archive" -> "\\Archive" to setOf("archive", "archives", "all mail")
|
||||
"Trash" -> "\\Trash" to setOf("trash", "deleted items", "deleted messages")
|
||||
else -> return store.getFolder(requested).takeIf { it.exists() }
|
||||
}
|
||||
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
|
||||
return folders.firstOrNull { folder ->
|
||||
val imapFolder = folder as? IMAPFolder
|
||||
imapFolder?.attributes?.any { it.equals(specialUse, true) } == true
|
||||
} ?: folders.firstOrNull { folder ->
|
||||
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).lastOrNull() in candidates
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
|
||||
val session = Session.getInstance(imapProperties(account), credentials(account))
|
||||
val store = session.getStore("imap")
|
||||
try {
|
||||
store.connect(
|
||||
account.optString("imapHost"),
|
||||
account.optInt("imapPort", 143),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
return block(session, store)
|
||||
} finally {
|
||||
if (store.isConnected) store.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun credentials(account: JSONObject) = object : Authenticator() {
|
||||
override fun getPasswordAuthentication() = PasswordAuthentication(
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
}
|
||||
|
||||
private fun imapProperties(account: JSONObject) = Properties().apply {
|
||||
setProperty("mail.store.protocol", "imap")
|
||||
setProperty("mail.imap.host", account.optString("imapHost"))
|
||||
setProperty("mail.imap.port", account.optInt("imapPort", 143).toString())
|
||||
setProperty("mail.imap.auth", "true")
|
||||
setProperty("mail.imap.starttls.enable", "true")
|
||||
setProperty("mail.imap.starttls.required", "true")
|
||||
setProperty("mail.imap.ssl.checkserveridentity", "true")
|
||||
setProperty("mail.imap.connectiontimeout", "20000")
|
||||
setProperty("mail.imap.timeout", "30000")
|
||||
setProperty("mail.imap.writetimeout", "30000")
|
||||
}
|
||||
|
||||
private fun smtpProperties(account: JSONObject) = Properties().apply {
|
||||
setProperty("mail.smtp.host", account.optString("smtpHost"))
|
||||
setProperty("mail.smtp.port", account.optInt("smtpPort", 587).toString())
|
||||
setProperty("mail.smtp.auth", "true")
|
||||
setProperty("mail.smtp.starttls.enable", "true")
|
||||
setProperty("mail.smtp.starttls.required", "true")
|
||||
setProperty("mail.smtp.ssl.checkserveridentity", "true")
|
||||
setProperty("mail.smtp.connectiontimeout", "20000")
|
||||
setProperty("mail.smtp.timeout", "30000")
|
||||
setProperty("mail.smtp.writetimeout", "30000")
|
||||
}
|
||||
|
||||
private fun displayName(account: JSONObject) =
|
||||
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
|
||||
|
||||
private fun decode(value: String?): String = try {
|
||||
if (value.isNullOrBlank()) "" else MimeUtility.decodeText(value)
|
||||
} catch (_: Exception) {
|
||||
value.orEmpty()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user