package sqwl.cms
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.headers.ETag
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpHeader, HttpResponse}
import akka.http.scaladsl.server.Directives._
import akka.stream.{ActorMaterializer, Materializer}
import scala.collection.immutable
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
trait Server extends App with Service with config with UrlScheme {
override implicit val system: ActorSystem = ActorSystem()
override implicit val executor: ExecutionContextExecutor = system.dispatcher
override implicit val materializer: Materializer = ActorMaterializer()
protected def content: iContent
val asArticle = Segment.flatMap(content.articleByPath(_))
val asCategory = Segment.flatMap(content.categoryByPath(_))
val asTag = Segment.flatMap(content.tagByPath(_))
private def asHtml(st: ViewState): HttpResponse = {
val s = Layout(content, st).render
HttpResponse(
headers = immutable.Seq[HttpHeader](ETag(MD5(s))),
entity = HttpEntity(ContentTypes.`text/html(UTF-8)`,
"<!DOCTYPE html>" + s))
}
private val routes = get {
pathPrefix(http.prefix) {
pathEnd {
complete(asHtml(Dashboard))
} ~ pathPrefix(asArticle) { article =>
pathEnd {
complete(asHtml(ViewArticle(article)))
} ~ getFromDirectory(article.assets.toString)
} ~ path(asCategory) { category =>
complete(asHtml(ViewCategory(category)))
} ~ path(TAG / asTag) { tag =>
complete(asHtml(ViewTag(tag)))
}
} ~ pathPrefix(http.prefix / ASSETS) {
getFromResourceDirectory("META-INF/resources/webjars")
} ~ pathPrefix(http.prefix / PUBLIC / content.icon._1) {
getFromFile(content.icon._2.toFile)
} ~ pathPrefix(http.prefix / PUBLIC / content.styleSheet._1) {
getFromFile(content.styleSheet._2.toFile)
} ~ pathPrefix(http.prefix / PUBLIC) {
getFromDirectory(content.publicAssets.toString)
}
}
Http().bindAndHandle(routes, http.interface, http.port)
if (run.mode == "devel") {
system.log.info("Click `Enter` to close application...")
StdIn.readLine()
system.terminate()
}
}