Private
Public Access
feat: primera iteracion del servicio de comunicaciones externas
This commit is contained in:
1 parent
73f9cef8ce
commit
4c0dbaa91c
15 files changed
+429
No files matched your search
@@ -0,0 +1,16 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<!-- On Windows machines setting withJansi to true enables ANSI
|
||||
color code interpretation by the Jansi library. This requires
|
||||
org.fusesource.jansi:jansi:1.8 on the class path. Note that
|
||||
Unix-based operating systems such as Linux and Mac OS X
|
||||
support ANSI color codes by default. -->
|
||||
<withJansi>true</withJansi>
|
||||
<encoder>
|
||||
<pattern>[%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.Concurrent
|
||||
import cats.syntax.all._
|
||||
import com.fede.comms.emails.{Email, Mensaje}
|
||||
import org.http4s.HttpRoutes
|
||||
import org.http4s.circe.CirceEntityDecoder._
|
||||
import org.http4s.dsl.Http4sDsl
|
||||
|
||||
object CommsRoutes {
|
||||
|
||||
def emailRoutes[F[_]: Concurrent](email: Email[F]): HttpRoutes[F] = {
|
||||
val dsl = new Http4sDsl[F] {}
|
||||
import dsl._
|
||||
HttpRoutes.of[F] {
|
||||
case req @ POST -> Root / "email" =>
|
||||
req.attemptAs[Mensaje].foldF(
|
||||
_ => BadRequest(),
|
||||
mensaje => email.enviar(mensaje) *> Ok()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.{Async, Resource}
|
||||
import com.comcast.ip4s._
|
||||
import com.fede.comms.config.SmtpConfig
|
||||
import com.fede.comms.emails.SmtpEmail
|
||||
import fs2.io.net.Network
|
||||
import org.http4s.ember.server.EmberServerBuilder
|
||||
import org.http4s.implicits._
|
||||
import org.http4s.server.middleware.Logger
|
||||
|
||||
object CommsServer {
|
||||
|
||||
def run[F[_]: Async: Network]: F[Nothing] = {
|
||||
for {
|
||||
smtpConfig <- Resource.eval(SmtpConfig.load[F]())
|
||||
email = new SmtpEmail[F](smtpConfig)
|
||||
|
||||
httpApp = CommsRoutes.emailRoutes[F](email).orNotFound
|
||||
|
||||
finalHttpApp = Logger.httpApp(true, true)(httpApp)
|
||||
|
||||
_ <-
|
||||
EmberServerBuilder.default[F]
|
||||
.withHost(ipv4"0.0.0.0")
|
||||
.withPort(port"8088")
|
||||
.withHttpApp(finalHttpApp)
|
||||
.build
|
||||
} yield ()
|
||||
}.useForever
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.{IO, IOApp}
|
||||
|
||||
object Main extends IOApp.Simple {
|
||||
val run = CommsServer.run[IO]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.fede.comms.config
|
||||
|
||||
import cats.effect.Sync
|
||||
|
||||
import java.io.File
|
||||
import scala.io.Source
|
||||
|
||||
final case class SmtpConfig(
|
||||
host: String,
|
||||
port: Int,
|
||||
user: String,
|
||||
password: String,
|
||||
from: String,
|
||||
to: String
|
||||
)
|
||||
|
||||
object SmtpConfig {
|
||||
|
||||
def load[F[_]: Sync](envFile: String = ".env"): F[SmtpConfig] =
|
||||
Sync[F].delay {
|
||||
val env = EnvFile.load(envFile)
|
||||
|
||||
def required(key: String): String =
|
||||
env.getOrElse(key, sys.error(s"Falta $key en $envFile"))
|
||||
|
||||
SmtpConfig(
|
||||
host = required("SMTP_HOST"),
|
||||
port = env.get("SMTP_PORT").flatMap(_.toIntOption).getOrElse(587),
|
||||
user = required("SMTP_USER"),
|
||||
password = required("SMTP_PASSWORD"),
|
||||
from = required("SMTP_FROM"),
|
||||
to = required("SMTP_TO")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
object EnvFile {
|
||||
|
||||
def load(path: String): Map[String, String] = {
|
||||
val file = new File(path)
|
||||
if (!file.exists()) Map.empty
|
||||
else {
|
||||
val lines = Source.fromFile(file).getLines().toList
|
||||
lines.flatMap(parseLine).toMap
|
||||
}
|
||||
}
|
||||
|
||||
private def parseLine(line: String): Option[(String, String)] = {
|
||||
val trimmed = line.trim
|
||||
if (trimmed.isEmpty || trimmed.startsWith("#")) None
|
||||
else {
|
||||
val withoutExport = trimmed.stripPrefix("export").trim
|
||||
val idx = withoutExport.indexOf('=')
|
||||
if (idx <= 0) None
|
||||
else {
|
||||
val key = withoutExport.substring(0, idx).trim
|
||||
val raw = withoutExport.substring(idx + 1).trim
|
||||
val value = raw match {
|
||||
case q if q.length >= 2 && q.head == '"' && q.last == '"' =>
|
||||
q.substring(1, q.length - 1)
|
||||
case q if q.length >= 2 && q.head == '\'' && q.last == '\'' =>
|
||||
q.substring(1, q.length - 1)
|
||||
case other => other
|
||||
}
|
||||
Some(key -> value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.fede.comms.emails
|
||||
|
||||
import cats.effect.Concurrent
|
||||
import io.circe.{Decoder, Encoder}
|
||||
import io.circe.generic.semiauto._
|
||||
import org.http4s.{EntityDecoder, EntityEncoder}
|
||||
import org.http4s.circe._
|
||||
|
||||
final case class Mensaje(titulo: String, descripcion: String, items: List[String], to: String)
|
||||
|
||||
object Mensaje {
|
||||
implicit val mensajeDecoder: Decoder[Mensaje] = deriveDecoder
|
||||
implicit def mensajeEntityDecoder[F[_]: Concurrent]: EntityDecoder[F, Mensaje] = jsonOf
|
||||
|
||||
implicit val mensajeEncoder: Encoder[Mensaje] = deriveEncoder
|
||||
implicit def mensajeEntityEncoder[F[_]]: EntityEncoder[F, Mensaje] = jsonEncoderOf
|
||||
}
|
||||
|
||||
trait Email[F[_]] {
|
||||
def enviar(m: Mensaje): F[Unit]
|
||||
}
|
||||
|
||||
object Email {
|
||||
def apply[F[_]](implicit ev: Email[F]): Email[F] = ev
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.fede.comms.emails
|
||||
|
||||
import cats.effect.Sync
|
||||
import jakarta.mail.internet.{InternetAddress, MimeMessage}
|
||||
import jakarta.mail.{Authenticator, Message, PasswordAuthentication, Session, Transport}
|
||||
|
||||
import java.util.Properties
|
||||
|
||||
final class SmtpEmail[F[_]: Sync](config: com.fede.comms.config.SmtpConfig) extends Email[F] {
|
||||
|
||||
def enviar(m: Mensaje): F[Unit] =
|
||||
Sync[F].blocking {
|
||||
val props = new Properties()
|
||||
props.put("mail.transport.protocol", "smtp")
|
||||
props.put("mail.smtp.host", config.host)
|
||||
props.put("mail.smtp.port", config.port.toString)
|
||||
props.put("mail.smtp.auth", "true")
|
||||
if (config.port == 465) {
|
||||
props.put("mail.smtp.ssl.enable", "true")
|
||||
} else {
|
||||
props.put("mail.smtp.starttls.enable", "true")
|
||||
}
|
||||
|
||||
val session = Session.getInstance(props, new Authenticator {
|
||||
override def getPasswordAuthentication: PasswordAuthentication =
|
||||
new PasswordAuthentication(config.user, config.password)
|
||||
})
|
||||
|
||||
val message = new MimeMessage(session)
|
||||
message.setFrom(new InternetAddress(config.from))
|
||||
message.setRecipients(Message.RecipientType.TO, m.to)
|
||||
message.setSubject(m.titulo, "UTF-8")
|
||||
message.setContent(htmlBody(m), "text/html; charset=utf-8")
|
||||
Transport.send(message)
|
||||
}
|
||||
|
||||
private def htmlBody(m: Mensaje): String = {
|
||||
val itemsHtml =
|
||||
if (m.items.isEmpty) ""
|
||||
else
|
||||
m.items.zipWithIndex
|
||||
.map { case (item, i) =>
|
||||
s"""<tr><td>${i + 1}</td><td>${escape(item)}</td></tr>"""
|
||||
}
|
||||
.mkString(
|
||||
"""<table border="1" cellpadding="6" cellspacing="0" style="border-collapse: collapse;">
|
||||
|<thead><tr><th>#</th><th>Item</th></tr></thead>
|
||||
|<tbody>""".stripMargin,
|
||||
"",
|
||||
"</tbody></table>"
|
||||
)
|
||||
s"""<html><body>
|
||||
|${m.descripcion}
|
||||
|$itemsHtml
|
||||
|</body></html>""".stripMargin
|
||||
}
|
||||
|
||||
private def escape(s: String): String =
|
||||
s.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.IO
|
||||
import cats.effect.kernel.Ref
|
||||
import com.fede.comms.emails.{Email, Mensaje}
|
||||
import org.http4s._
|
||||
import org.http4s.implicits._
|
||||
import munit.CatsEffectSuite
|
||||
|
||||
class CommsRoutesSpec extends CatsEffectSuite {
|
||||
|
||||
test("POST /email returns 200 and calls enviar") {
|
||||
val testIO = for {
|
||||
ref <- Ref.of[IO, List[Mensaje]](Nil)
|
||||
email = new Email[IO] {
|
||||
def enviar(m: Mensaje): IO[Unit] = ref.update(_ :+ m)
|
||||
}
|
||||
req = Request[IO](Method.POST, uri"/email")
|
||||
.withEntity(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com"))
|
||||
resp <- CommsRoutes.emailRoutes[IO](email).orNotFound(req)
|
||||
sent <- ref.get
|
||||
} yield (resp.status, sent)
|
||||
|
||||
for {
|
||||
r <- testIO
|
||||
_ <- assertIO(IO.pure(r._1), Status.Ok)
|
||||
_ <- assertIO(IO.pure(r._2), List(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com")))
|
||||
} yield ()
|
||||
}
|
||||
|
||||
test("POST /email with invalid json returns 400") {
|
||||
val email = new Email[IO] {
|
||||
def enviar(m: Mensaje): IO[Unit] = IO.unit
|
||||
}
|
||||
val req = Request[IO](Method.POST, uri"/email").withEntity("{}")
|
||||
assertIO(
|
||||
CommsRoutes.emailRoutes[IO](email).orNotFound(req).map(_.status),
|
||||
Status.BadRequest
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.IO
|
||||
import com.fede.comms.config.SmtpConfig
|
||||
import com.fede.comms.emails.{Mensaje, SmtpEmail}
|
||||
import munit.CatsEffectSuite
|
||||
|
||||
class SmtpEmailSpec extends CatsEffectSuite {
|
||||
|
||||
test("envia un email real usando el .env") {
|
||||
for {
|
||||
config <- SmtpConfig.load[IO]()
|
||||
email = new SmtpEmail[IO](config)
|
||||
to = sys.env.getOrElse("SMTP_TO", config.from)
|
||||
_ <- email.enviar(
|
||||
Mensaje(
|
||||
titulo = "[comms] prueba",
|
||||
descripcion = "Email de prueba desde el servicio comms",
|
||||
items = List("item 1", "item 2"),
|
||||
to = to
|
||||
)
|
||||
)
|
||||
} yield ()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user