|
| 1 | +@file:Suppress("RedundantSuspendModifier", "unused") |
| 2 | + |
| 3 | +package codes.jakob.tstse.example.idiomatic.collections_vs_sequences.shared |
| 4 | + |
| 5 | +import codes.jakob.tstse.example.common.Developer |
| 6 | +import codes.jakob.tstse.example.common.DeveloperType |
| 7 | +import codes.jakob.tstse.example.common.Notification |
| 8 | +import java.time.Clock |
| 9 | +import java.util.* |
| 10 | +import javax.mail.Message |
| 11 | +import javax.mail.Session |
| 12 | +import javax.mail.internet.InternetAddress |
| 13 | +import javax.mail.internet.MimeMessage |
| 14 | + |
| 15 | +abstract class DeveloperNotificationService( |
| 16 | + private val emailSession: Session, |
| 17 | + private val clock: Clock, |
| 18 | +) { |
| 19 | + abstract suspend fun notifyDevelopersByEmail(developerType: DeveloperType, notification: Notification) |
| 20 | + |
| 21 | + protected fun generateEmail(developer: Developer, notification: Notification): Message { |
| 22 | + return MimeMessage(emailSession).apply { |
| 23 | + setRecipients(Message.RecipientType.TO, InternetAddress.parse(developer.emailAddress, false)) |
| 24 | + replyTo = InternetAddress.parse(REPLY_TO_ADDRESS, false) |
| 25 | + subject = generateEmailSubject(developer, notification) |
| 26 | + setText(generateEmailBody(developer, notification)) |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + protected suspend fun sendEmail(email: Message) { |
| 31 | + email.apply { |
| 32 | + sentDate = Date.from(clock.instant()) |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + private fun generateEmailSubject(developer: Developer, notification: Notification): String { |
| 37 | + return notification.info |
| 38 | + } |
| 39 | + |
| 40 | + private fun generateEmailBody(developer: Developer, notification: Notification): String { |
| 41 | + return "Dear ${developer.name}" |
| 42 | + } |
| 43 | + |
| 44 | + companion object { |
| 45 | + private const val REPLY_TO_ADDRESS = "noreply@example.com" |
| 46 | + |
| 47 | + @JvmStatic |
| 48 | + protected fun Message.firstRecipient(): String = allRecipients.map { it.toString() }.first() |
| 49 | + } |
| 50 | +} |
0 commit comments