lila/app/controllers/Export.scala

80 lines
2.4 KiB
Scala
Raw Normal View History

package controllers
2019-12-04 16:39:16 -07:00
import akka.stream.scaladsl._
import akka.util.ByteString
2016-08-13 08:25:09 -06:00
import scala.concurrent.duration._
2020-02-26 11:19:19 -07:00
import play.api.mvc.Result
import lila.app._
import lila.common.HTTPRequest
2019-12-04 16:39:16 -07:00
final class Export(env: Env) extends LilaController(env) {
2020-02-25 14:25:09 -07:00
private val ExportRateLimitGlobal = new lila.memo.RateLimit[String](
2018-03-30 09:25:35 -06:00
credits = 240,
2016-08-13 08:25:09 -06:00
duration = 1 minute,
2020-02-26 11:19:19 -07:00
name = "export image global",
key = "export.image.global"
)
2016-08-13 08:25:09 -06:00
def png(id: String) = Open { implicit ctx =>
OnlyHumansAndFacebookOrTwitter {
2020-02-25 14:25:09 -07:00
ExportRateLimitGlobal(
2019-12-13 07:30:20 -07:00
"-",
msg = s"${HTTPRequest.lastRemoteAddress(ctx.req).value} ${~HTTPRequest.userAgent(ctx.req)}"
) {
2019-12-10 14:01:18 -07:00
lila.mon.export.png.game.increment()
2019-12-04 16:39:16 -07:00
OptionFuResult(env.game.gameRepo game id) { game =>
2020-02-26 11:19:19 -07:00
env.game.pngExport fromGame game map
stream("image/png") map
gameImageCacheSeconds(game)
2020-02-25 14:25:09 -07:00
}
}
}
}
def gif(id: String) = Open { implicit ctx =>
OnlyHumansAndFacebookOrTwitter {
ExportRateLimitGlobal("-", msg = HTTPRequest.lastRemoteAddress(ctx.req).value) {
OptionFuResult(env.game.gameRepo gameWithInitialFen id) {
case (game, initialFen) =>
2020-02-26 11:19:19 -07:00
env.game.gifExport.fromGame(game, initialFen) map
stream("image/gif") map
gameImageCacheSeconds(game)
2016-08-13 08:25:09 -06:00
}
}
}
}
2020-02-26 11:19:19 -07:00
private def gameImageCacheSeconds(game: lila.game.Game)(res: Result): Result = {
val cacheSeconds =
if (game.finishedOrAborted) 3600 * 24
else 10
res.withHeaders(CACHE_CONTROL -> s"max-age=$cacheSeconds")
}
def puzzlePng(id: Int) = Open { implicit ctx =>
OnlyHumansAndFacebookOrTwitter {
2020-02-25 14:25:09 -07:00
ExportRateLimitGlobal("-", msg = HTTPRequest.lastRemoteAddress(ctx.req).value) {
2019-12-10 14:01:18 -07:00
lila.mon.export.png.puzzle.increment()
2019-12-04 16:39:16 -07:00
OptionFuResult(env.puzzle.api.puzzle find id) { puzzle =>
env.game.pngExport(
2018-05-08 20:38:45 -06:00
fen = chess.format.FEN(puzzle.fenAfterInitialMove | puzzle.fen),
lastMove = puzzle.initialMove.uci.some,
check = none,
orientation = puzzle.color.some,
logHint = s"puzzle $id"
2020-02-25 14:25:09 -07:00
) map stream("image/png")
2016-08-13 08:25:09 -06:00
}
}
}
}
2020-02-25 14:25:09 -07:00
private def stream(contentType: String)(stream: Source[ByteString, _]) =
2019-12-13 07:30:20 -07:00
Ok.chunked(stream)
.withHeaders(
noProxyBufferHeader,
CACHE_CONTROL -> "max-age=7200"
2020-02-25 14:25:09 -07:00
) as contentType
}