/akka/src/com/bot4s/telegram/api/WebRoutes.scala

https://github.com/mukel/telegrambot4s · Scala · 56 lines · 44 code · 12 blank · 0 comment · 5 complexity · ed685af369d766b40c4fd2135c4495e0 MD5 · raw file

  1. package com.bot4s.telegram.api
  2. import akka.http.scaladsl.Http
  3. import akka.http.scaladsl.server.Directives._
  4. import akka.http.scaladsl.server.Route
  5. import com.bot4s.telegram.future.BotExecutionContext
  6. import slogging.StrictLogging
  7. import scala.concurrent.{Future, Promise}
  8. trait WebRoutes extends BotBase[Future] with StrictLogging {
  9. _: BotExecutionContext with AkkaImplicits =>
  10. val port: Int
  11. val interfaceIp: String = "::0"
  12. def routes: Route = reject
  13. private var bindingFuture: Future[Http.ServerBinding] = _
  14. @volatile private var eol: Promise[Unit] = _
  15. abstract override def run(): Future[Unit] = synchronized {
  16. if (eol != null) {
  17. throw new RuntimeException("Bot is already running")
  18. }
  19. bindingFuture = Http().bindAndHandle(routes, interfaceIp, port)
  20. bindingFuture.foreach { _ =>
  21. logger.info(s"Listening on $interfaceIp:$port")
  22. }
  23. sys.addShutdownHook {
  24. shutdown()
  25. }
  26. eol = Promise[Unit]()
  27. val t = Future.sequence(Seq(eol.future, super.run()))
  28. t.map(_ => ())
  29. }
  30. abstract override def shutdown(): Unit = synchronized {
  31. if (eol == null) {
  32. throw new RuntimeException("Bot is not running")
  33. }
  34. super.shutdown()
  35. for {
  36. b <- bindingFuture
  37. _ <- b.unbind()
  38. t <- system.terminate()
  39. } /* do */ {
  40. eol.success(())
  41. eol = null
  42. }
  43. }
  44. }