Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dankorjunk
- import filestorage.{Elo, FileStorage, ImageMeme}
- import akka.actor.ActorSystem
- import akka.http.scaladsl.Http
- import akka.http.scaladsl.model._
- import akka.http.scaladsl.server.Directives._
- import akka.stream.ActorMaterializer
- import scala.io.StdIn
- object WebServer {
- def main(args: Array[String]) {
- implicit val system = ActorSystem("doj-system")
- implicit val materializer = ActorMaterializer()
- // needed for the future flatMap/onComplete in the end
- implicit val executionContext = system.dispatcher
- val route =
- path("api" / "suggest") {
- get {
- val (id1, id2) = FileStorage.retrieveForRate()
- complete(HttpEntity(ContentTypes.`application/json`,
- upickle.default.write(Map("id1" -> id1, "id2" -> id2))))
- }
- } ~
- path("api" / "top") {
- get {
- parameters('offset.as[Int], 'size.as[Int]) { (offset, size) =>
- val top = FileStorage.getTop(offset, size)
- complete(HttpEntity(ContentTypes.`application/json`,
- upickle.default.write(Map("top" -> top))))
- }
- }
- } ~
- path("api" / "upload") {
- post {
- extractRequestContext { ctx =>
- implicit val materializer = ctx.materializer
- implicit val ec = ctx.executionContext
- fileUpload("image") {
- case (metadata, byteSource) =>
- val f = byteSource.runFold(Array[Byte]())((file, part) => file ++ part.toArray[Byte])
- onSuccess(f) { (file) => {
- FileStorage.uploadImage(file)
- complete("Image uploaded")
- } }
- }
- }
- } ~
- get {
- complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
- """
- |<form method="post" enctype="multipart/form-data">
- | <input type="file" name="image" />
- | <input type="submit" />
- |</form>
- """.stripMargin))
- }
- } ~
- path("api" / "rate") {
- post {
- formFields('id1, 'id2, 'winner) { (id1, id2, winner) =>
- for {
- img1 <- FileStorage.getImage(id1)
- img2 <- FileStorage.getImage(id2)
- } {
- val firstWin = winner match {
- case "win1" => 1.0
- case "draw" => 0.5
- case "win2" => 0.0
- case _ => 0.0
- }
- val (newRank1, newRank2) = Elo.getNewRanks(img1.rank, img2.rank, firstWin)
- FileStorage.updateImage(
- id1, ImageMeme(id1, newRank1, img1.timestamp, img1.numOfShows + 1))
- FileStorage.updateImage(
- id2, ImageMeme(id2, newRank2, img2.timestamp, img2.numOfShows + 1))
- }
- complete("Ranks updated")
- }
- }
- }
- val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
- println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
- StdIn.readLine() // let it run until user presses return
- bindingFuture
- .flatMap(_.unbind()) // trigger unbinding from the port
- .onComplete(_ => system.terminate()) // and shutdown when done
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement