Skip to content

Commit

Permalink
Merge branch 'master' into user-simuls
Browse files Browse the repository at this point in the history
* master: (287 commits)
  scala tweaks
  New Crowdin updates (#13001)
  upgrade site pgn viewer
  scala tweaks
  expand study chapter pgn in ublogs
  upgrade lichess-pgn-viewer to fix chessops circles
  redirect to the default study chapter when the chapter id is wrong
  ~Fixing missing swiss translations #12961
  fail faster if the study chapter is missing
  restore previous behaviour of study chapter fallback
  highlight the board menu toggle for a little while
  remove unused monitoring
  Revert "rename emoji images - revert after d52a143 lands"
  don't change study chapter names with their Event PGN tag
  refactor/simplify getChapterNameFromPgn
  New Crowdin updates (#12994)
  fix glaring timer bug
  fix round board menu keyboardMove toggle
  make it more obvious that boolPrefXhrToggle reloads the page by default
  Couple lichess study chapter names w/ PGN Event tag
  ...
  • Loading branch information
ornicar committed Jun 12, 2023
2 parents 498d27e + 60223bb commit 1f245e3
Show file tree
Hide file tree
Showing 777 changed files with 16,250 additions and 10,867 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ data/
dist/
node_modules/
local/
lifat/
ui/common/**/*.js
ui/common/**/*.d.ts
ui/chess/**/*.js
Expand Down
58 changes: 25 additions & 33 deletions app/Lila.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,21 @@ object Lila {
* @param process
* The process (real or abstract) to use for starting the server.
*/
def start(process: ServerProcess): Server = try {
def start(process: ServerProcess): Server = try
// Configure logback early - before play invokes Logger
LoggerConfigurator.configure()

val config: ServerConfig = readServerConfigSettings(process)

// Start the application
val application: Application = {
val application: Application =
val environment = Environment(config.rootDir, process.classLoader, config.mode)
LilaComponents(
environment,
DefaultApplicationLifecycle(),
Configuration.load(environment)
).application
}

Play.start(application)

val server = NettyServer(
Expand All @@ -45,58 +45,52 @@ object Lila {
application.actorSystem
)(application.materializer)

process.addShutdownHook {
process.addShutdownHook:
// Only run server stop if the shutdown reason is not defined. That means the
// process received a SIGTERM (or other acceptable signal) instead of being
// stopped because of CoordinatedShutdown, for example when downing a cluster.
// The reason for that is we want to avoid calling coordinated shutdown from
// inside a JVM shutdown hook if the trigger of the JVM shutdown hook was
// coordinated shutdown.
if (application.coordinatedShutdown.shutdownReason().isEmpty) {
server.stop()
}
}
if application.coordinatedShutdown.shutdownReason().isEmpty then server.stop()

lila.common.Lilakka.shutdown(
application.coordinatedShutdown,
_.PhaseBeforeActorSystemTerminate,
"Shut down logging"
) { () => fuccess(LoggerConfigurator.shutdown()) }
): () =>
fuccess(LoggerConfigurator.shutdown())

server
} catch {
catch
case ServerStartException(message, cause) => process.exit(message, cause)
case e: Throwable => process.exit("Oops, cannot start the server.", Some(e))
}

def readServerConfigSettings(process: ServerProcess): ServerConfig = {
val configuration: Configuration = {
def readServerConfigSettings(process: ServerProcess): ServerConfig =
val configuration: Configuration =
val rootDirArg = process.args.headOption.map(new File(_))
val rootDirConfig = rootDirArg.??(ServerConfig.rootDirConfig(_))
Configuration.load(process.classLoader, process.properties, rootDirConfig, true)
}

val rootDir: File = {
val rootDir: File =
val path = configuration
.getOptional[String]("play.server.dir")
.getOrElse(throw ServerStartException("No root server path supplied"))
val file = new File(path)
if (!file.isDirectory)
throw ServerStartException(s"Bad root server path: $path")
val file = File(path)
if !file.isDirectory then throw ServerStartException(s"Bad root server path: $path")
file
}

def parsePort(portType: String): Option[Int] = {
configuration.getOptional[String](s"play.server.$portType.port").filter(_ != "disabled").map { str =>
try Integer.parseInt(str)
catch {
case _: NumberFormatException =>
throw ServerStartException(s"Invalid ${portType.toUpperCase} port: $str")
}
}
}

parsePort("http") match {

def parsePort(portType: String): Option[Int] =
configuration
.getOptional[String](s"play.server.$portType.port")
.filter(_ != "disabled")
.map: str =>
try Integer.parseInt(str)
catch
case _: NumberFormatException =>
throw ServerStartException(s"Invalid ${portType.toUpperCase} port: $str")

parsePort("http") match
case None => throw ServerStartException("Must provide an HTTP port")
case Some(httpPort) =>
val address = configuration.getOptional[String]("play.server.http.address").getOrElse("0.0.0.0")
Expand All @@ -106,6 +100,4 @@ object Lila {
else Mode.Dev

ServerConfig(rootDir, httpPort, address, mode, process.properties, configuration)
}
}
}
30 changes: 14 additions & 16 deletions app/controllers/Account.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import scala.util.chaining.*
import views.html

import lila.api.AnnounceStore
import lila.api.Context
import lila.api.context.*
import lila.app.{ given, * }
import lila.security.SecurityForm.Reopen
import lila.user.{ Holder, TotpSecret, User as UserModel }
Expand Down Expand Up @@ -86,31 +86,29 @@ final class Account(
def nowPlaying = Auth { _ ?=> me =>
negotiate(
html = notFound,
api = _ => doNowPlaying(me, ctx.req)
api = _ => doNowPlaying(me)
)
}

val apiMe =
val rateLimit = lila.memo.RateLimit[UserId](30, 10.minutes, "api.account.user")
Scoped() { req ?=> me =>
Scoped() { ctx ?=> me =>
def limited = rateLimitedFu:
"Please don't poll this endpoint. Stream https://lichess.org/api#tag/Board/operation/apiStreamEvent instead."
rateLimit(me.id, limited):
env.api.userApi.extended(
me,
me.some,
withFollows = apiC.userWithFollows(req),
withFollows = apiC.userWithFollows(ctx.req),
withTrophies = false
)(using reqLang(me)) dmap { JsonOk(_) }
) dmap { JsonOk(_) }
}

def apiNowPlaying = Scoped() { req ?=> me =>
doNowPlaying(me, req)
}
def apiNowPlaying = Scoped() { ctx ?=> doNowPlaying }

private def doNowPlaying(me: lila.user.User, req: RequestHeader) =
private def doNowPlaying(me: lila.user.User)(using AnyContext) =
env.round.proxyRepo.urgentGames(me) map { povs =>
val nb = (getInt("nb", req) | 9) atMost 50
val nb = (getInt("nb") | 9) atMost 50
Ok(Json.obj("nowPlaying" -> JsArray(povs take nb map env.api.lobbyApi.nowPlaying)))
}

Expand Down Expand Up @@ -148,7 +146,7 @@ final class Account(
}
}

private def refreshSessionId(me: UserModel, result: Result)(using ctx: Context): Fu[Result] =
private def refreshSessionId(me: UserModel, result: Result)(using ctx: WebContext): Fu[Result] =
env.security.store.closeAllSessionsOf(me.id) >>
env.push.webSubscriptionApi.unsubscribeByUser(me) >>
env.push.unregisterDevices(me) >>
Expand All @@ -175,7 +173,7 @@ final class Account(
}
}

def renderCheckYourEmail(using Context) =
def renderCheckYourEmail(using WebContext) =
html.auth.checkYourEmail(lila.security.EmailConfirm.cookie get ctx.req)

def emailApply = AuthBody { ctx ?=> me =>
Expand Down Expand Up @@ -315,13 +313,13 @@ final class Account(
}
}

def apiKidPost = Scoped(_.Preference.Write) { req ?=> me =>
getBoolOpt("v", req) match
def apiKidPost = Scoped(_.Preference.Write) { ctx ?=> me =>
getBoolOpt("v") match
case None => BadRequest(jsonError("Missing v parameter")).toFuccess
case Some(v) => env.user.repo.setKid(me, v) inject jsonOkResult
}

private def currentSessionId(using Context) =
private def currentSessionId(using WebContext) =
~env.security.api.reqSessionId(ctx.req)

def security = Auth { _ ?=> me =>
Expand Down Expand Up @@ -351,7 +349,7 @@ final class Account(
}

private def renderReopen(form: Option[play.api.data.Form[Reopen]], msg: Option[String])(using
ctx: Context
ctx: WebContext
) =
env.security.forms.reopen map { baseForm =>
html.account.reopen.form(form.foldLeft(baseForm)(_ withForm _), msg)
Expand Down
18 changes: 9 additions & 9 deletions app/controllers/Analyse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import play.api.libs.json.JsArray
import play.api.mvc.*
import views.*

import lila.api.Context
import lila.api.WebContext
import lila.app.{ given, * }
import lila.common.HTTPRequest
import lila.game.{ PgnDump, Pov }
Expand Down Expand Up @@ -36,7 +36,7 @@ final class Analyse(
}
}

def replay(pov: Pov, userTv: Option[lila.user.User])(using ctx: Context) =
def replay(pov: Pov, userTv: Option[lila.user.User])(using ctx: WebContext) =
if HTTPRequest.isCrawler(ctx.req).yes then replayBot(pov)
else
env.game.gameRepo initialFen pov.gameId flatMap { initialFen =>
Expand Down Expand Up @@ -109,7 +109,7 @@ final class Analyse(
}
}

private def RedirectAtFen(pov: Pov, initialFen: Option[Fen.Epd])(or: => Fu[Result])(using Context) =
private def RedirectAtFen(pov: Pov, initialFen: Option[Fen.Epd])(or: => Fu[Result])(using WebContext) =
(get("fen").map(Fen.Epd.clean): Option[Fen.Epd]).fold(or) { atFen =>
val url = routes.Round.watcher(pov.gameId, pov.color.name)
fuccess {
Expand All @@ -125,7 +125,7 @@ final class Analyse(
}
}

private def replayBot(pov: Pov)(using Context) =
private def replayBot(pov: Pov)(using WebContext) =
for
initialFen <- env.game.gameRepo initialFen pov.gameId
analysis <- env.analyse.analyser get pov.game
Expand Down Expand Up @@ -156,13 +156,13 @@ final class Analyse(
}
}

def externalEngineCreate = ScopedBody(_.Engine.Write) { req ?=> me =>
HTTPRequest.bearer(req) ?? { bearer =>
def externalEngineCreate = ScopedBody(_.Engine.Write) { ctx ?=> me =>
HTTPRequest.bearer(ctx.req) ?? { bearer =>
val tokenId = AccessToken.Id from bearer
lila.analyse.ExternalEngine.form
.bindFromRequest()
.fold(
err => newJsonFormError(err)(using me.realLang | reqLang),
err => newJsonFormError(err),
data =>
env.analyse.externalEngine.create(me, data, tokenId.value) map { engine =>
Created(lila.analyse.ExternalEngine.jsonWrites.writes(engine))
Expand All @@ -171,13 +171,13 @@ final class Analyse(
}
}

def externalEngineUpdate(id: String) = ScopedBody(_.Engine.Write) { req ?=> me =>
def externalEngineUpdate(id: String) = ScopedBody(_.Engine.Write) { ctx ?=> me =>
env.analyse.externalEngine.find(me, id) flatMap {
_.fold(notFoundJson()) { engine =>
lila.analyse.ExternalEngine.form
.bindFromRequest()
.fold(
err => newJsonFormError(err)(using me.realLang | reqLang),
err => newJsonFormError(err),
data =>
env.analyse.externalEngine.update(engine, data) map { engine =>
JsonOk(lila.analyse.ExternalEngine.jsonWrites.writes(engine))
Expand Down
Loading

0 comments on commit 1f245e3

Please sign in to comment.