Merge branch 'master' into miniboard-clock

* master:
  java tweaks
  optimize regex
  remove extra "new" and semicolons
  remove superfluous function placeholders
  ensure source is closed
  immutable/mutable call argument list tweaks
  fix actual insight bug
  more code tweaks
  remove debug and re-format
  more code tweaks and reference prefixes
  remove superfluous blocks
  add @tailrec wherever possible
  scalafmt
  name boolean arguments
  code golf
  code tweaks
  update round move tag
  {master} automated code cleanup
  {master} remove temp fix
miniboard-clock
Thibault Duplessis 2020-08-16 15:44:28 +02:00
commit 747ed7a8fd
237 changed files with 566 additions and 544 deletions

View File

@ -23,10 +23,10 @@ final class LilaComponents(ctx: ApplicationLoader.Context) extends BuiltInCompon
lila.log("boot").info {
val java = System.getProperty("java.version")
val mem = Runtime.getRuntime().maxMemory() / 1024 / 1024
val mem = Runtime.getRuntime.maxMemory() / 1024 / 1024
val appVersionCommit = ~configuration.getOptional[String]("app.version.commit")
val appVersionDate = ~configuration.getOptional[String]("app.version.date")
s"lila ${ctx.environment.mode} $appVersionCommit $appVersionDate / java ${java}, memory: ${mem}MB"
s"lila ${ctx.environment.mode} $appVersionCommit $appVersionDate / java $java, memory: ${mem}MB"
}
import _root_.controllers._
@ -58,7 +58,7 @@ final class LilaComponents(ctx: ApplicationLoader.Context) extends BuiltInCompon
implicit def system = actorSystem
implicit lazy val ws: StandaloneWSClient = {
import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClient
import play.api.libs.ws.{ WSConfigParser }
import play.api.libs.ws.WSConfigParser
import play.api.libs.ws.ahc.{ AhcConfigBuilder, AhcWSClientConfigParser, StandaloneAhcWSClient }
new StandaloneAhcWSClient(
new DefaultAsyncHttpClient(

View File

@ -293,7 +293,7 @@ final class Account(
implicit val req = ctx.body
env.security.forms closeAccount me flatMap { form =>
FormFuResult(form) { err =>
fuccess(html.account.close(me, err, false))
fuccess(html.account.close(me, err, managed = false))
} { _ =>
env.closeAccount(me.id, self = true) inject {
Redirect(routes.User show me.username) withCookies env.lilaCookie.newSession
@ -326,7 +326,7 @@ final class Account(
.fold(
err =>
negotiate(
html = BadRequest(html.account.kid(me, err, false)).fuccess,
html = BadRequest(html.account.kid(me, err, managed = false)).fuccess,
api = _ => BadRequest(errorsAsJson(err)).fuccess
),
_ =>
@ -388,7 +388,7 @@ final class Account(
err => BadRequest(renderReopen(err.some, none)).fuccess,
data =>
env.security.reopen
.prepare(data.username, data.realEmail, env.mod.logApi.hasModClose _) flatMap {
.prepare(data.username, data.realEmail, env.mod.logApi.hasModClose) flatMap {
case Left((code, msg)) =>
lila.mon.user.auth.reopenRequest(code).increment()
BadRequest(renderReopen(none, msg.some)).fuccess
@ -413,10 +413,9 @@ final class Account(
def reopenLogin(token: String) =
Open { implicit ctx =>
env.security.reopen confirm token flatMap {
case None => {
case None =>
lila.mon.user.auth.reopenConfirm("token_fail").increment()
notFound
}
case Some(user) =>
env.report.api.reopenReports(lila.report.Suspect(user)) >>
auth.authenticateUser(user) >>-

View File

@ -40,7 +40,7 @@ final class Api(
val status = Action { req =>
val appVersion = get("v", req)
val mustUpgrade = appVersion exists lila.api.Mobile.AppVersion.mustUpgrade _
val mustUpgrade = appVersion exists lila.api.Mobile.AppVersion.mustUpgrade
Ok(apiStatusJson.add("mustUpgrade", mustUpgrade)) as JSON
}
@ -203,7 +203,7 @@ final class Api(
page = page.some,
me = none,
getUserTeamIds = _ => fuccess(Nil),
getTeamName = env.team.getTeamName.apply _,
getTeamName = env.team.getTeamName.apply,
playerInfoExt = none,
socketVersion = none,
partial = false
@ -427,7 +427,7 @@ final class Api(
private[controllers] def GlobalConcurrencyLimitPerUserOption[T](
user: Option[lila.user.User]
): Option[SourceIdentity[T]] =
user.fold(some[SourceIdentity[T]](identity _)) { u =>
user.fold(some[SourceIdentity[T]](identity)) { u =>
GlobalConcurrencyLimitUser.compose[T](u.id)
}

View File

@ -323,7 +323,7 @@ final class Auth(
def passwordReset =
Open { implicit ctx =>
Ok(renderPasswordReset(none, false)).fuccess
Ok(renderPasswordReset(none, fail = false)).fuccess
}
def passwordResetApply =
@ -332,21 +332,19 @@ final class Auth(
forms.passwordReset.form
.bindFromRequest()
.fold(
err => BadRequest(renderPasswordReset(err.some, true)).fuccess,
err => BadRequest(renderPasswordReset(err.some, fail = true)).fuccess,
data =>
env.security.recaptcha.verify(~data.recaptchaResponse, req) flatMap {
_ ?? env.user.repo.enabledWithEmail(data.realEmail.normalize)
} flatMap {
case Some((user, storedEmail)) => {
case Some((user, storedEmail)) =>
lila.mon.user.auth.passwordResetRequest("success").increment()
env.security.passwordReset.send(user, storedEmail) inject Redirect(
routes.Auth.passwordResetSent(storedEmail.conceal)
)
}
case _ => {
case _ =>
lila.mon.user.auth.passwordResetRequest("noEmail").increment()
BadRequest(renderPasswordReset(none, true)).fuccess
}
BadRequest(renderPasswordReset(none, fail = true)).fuccess
}
)
}
@ -361,25 +359,22 @@ final class Auth(
def passwordResetConfirm(token: String) =
Open { implicit ctx =>
env.security.passwordReset confirm token flatMap {
case None => {
case None =>
lila.mon.user.auth.passwordResetConfirm("tokenFail").increment()
notFound
}
case Some(user) => {
case Some(user) =>
authLog(user.username, "-", "Reset password")
lila.mon.user.auth.passwordResetConfirm("tokenOk").increment()
fuccess(html.auth.bits.passwordResetConfirm(user, token, forms.passwdReset, none))
}
}
}
def passwordResetConfirmApply(token: String) =
OpenBody { implicit ctx =>
env.security.passwordReset confirm token flatMap {
case None => {
case None =>
lila.mon.user.auth.passwordResetConfirm("tokenPostFail").increment()
notFound
}
case Some(user) =>
implicit val req = ctx.body
FormFuResult(forms.passwdReset) { err =>
@ -407,7 +402,7 @@ final class Auth(
def magicLink =
Open { implicit ctx =>
Ok(renderMagicLink(none, false)).fuccess
Ok(renderMagicLink(none, fail = false)).fuccess
}
def magicLinkApply =
@ -416,23 +411,21 @@ final class Auth(
forms.magicLink.form
.bindFromRequest()
.fold(
err => BadRequest(renderMagicLink(err.some, true)).fuccess,
err => BadRequest(renderMagicLink(err.some, fail = true)).fuccess,
data =>
env.security.recaptcha.verify(~data.recaptchaResponse, req) flatMap {
_ ?? env.user.repo.enabledWithEmail(data.realEmail.normalize)
} flatMap {
case Some((user, storedEmail)) => {
case Some((user, storedEmail)) =>
MagicLinkRateLimit(user, storedEmail, ctx.req) {
lila.mon.user.auth.magicLinkRequest("success").increment()
env.security.magicLink.send(user, storedEmail) inject Redirect(
routes.Auth.magicLinkSent(storedEmail.value)
)
}(rateLimitedFu)
}
case _ => {
case _ =>
lila.mon.user.auth.magicLinkRequest("no_email").increment()
BadRequest(renderMagicLink(none, true)).fuccess
}
BadRequest(renderMagicLink(none, fail = true)).fuccess
}
)
}
@ -447,15 +440,13 @@ final class Auth(
def magicLinkLogin(token: String) =
Open { implicit ctx =>
env.security.magicLink confirm token flatMap {
case None => {
case None =>
lila.mon.user.auth.magicLinkConfirm("token_fail").increment()
notFound
}
case Some(user) => {
case Some(user) =>
authLog(user.username, "-", "Magic link")
authenticateUser(user) >>-
lila.mon.user.auth.magicLinkConfirm("success").increment()
}
}
}

View File

@ -66,7 +66,7 @@ final class Challenge(
Ok(html.challenge.theirs(c, json, user, get("color") flatMap chess.Color.apply))
},
api = _ => Ok(json).fuccess
) flatMap withChallengeAnonCookie(mine && c.challengerIsAnon, c, true)
) flatMap withChallengeAnonCookie(mine && c.challengerIsAnon, c, owner = true)
} dmap env.lilaCookie.ensure(ctx.req)
private def isMine(challenge: ChallengeModel)(implicit ctx: Context) =
@ -90,7 +90,7 @@ final class Challenge(
negotiate(
html = Redirect(routes.Round.watcher(pov.gameId, cc.fold("white")(_.name))).fuccess,
api = apiVersion => env.api.roundApi.player(pov, none, apiVersion) map { Ok(_) }
) flatMap withChallengeAnonCookie(ctx.isAnon, c, false)
) flatMap withChallengeAnonCookie(ctx.isAnon, c, owner = false)
case None =>
negotiate(
html = Redirect(routes.Round.watcher(c.id, cc.fold("white")(_.name))).fuccess,

View File

@ -81,7 +81,7 @@ final class ForumPost(env: Env) extends LilaController(env) with ForumController
Auth { implicit ctx => me =>
postApi.react(id, me, reaction, v) map {
_ ?? { post =>
Ok(views.html.forum.post.reactions(post, true))
Ok(views.html.forum.post.reactions(post, canReact = true))
}
}
}

View File

@ -523,7 +523,7 @@ abstract private[controllers] class LilaController(val env: Env)
} map {
case (
(pref, hasClas),
(teamNbRequests ~ nbChallenges ~ nbNotifications ~ inquiry)
teamNbRequests ~ nbChallenges ~ nbNotifications ~ inquiry
) =>
PageData(
teamNbRequests,
@ -561,7 +561,7 @@ abstract private[controllers] class LilaController(val env: Env)
case Some(d) =>
env.mod.impersonate.impersonating(d.user) map {
_.fold[RestoredUser](d.some -> None) { impersonated =>
FingerPrintedUser(impersonated, true).some -> d.user.some
FingerPrintedUser(impersonated, hasFingerPrint = true).some -> d.user.some
}
}
}

View File

@ -163,7 +163,7 @@ Allow: /
"icons" -> List(32, 64, 128, 192, 256, 512, 1024).map { size =>
Json.obj(
"src" -> s"//${env.net.assetDomain.value}/assets/logo/lichess-favicon-$size.png",
"sizes" -> s"${size}x${size}",
"sizes" -> s"${size}x$size",
"type" -> "image/png"
)
},

View File

@ -191,7 +191,7 @@ final class Mod(
err => BadRequest(err.toString).fuccess,
rawEmail => {
val email = env.security.emailAddressValidator
.validate(EmailAddress(rawEmail)) err s"Invalid email ${rawEmail}"
.validate(EmailAddress(rawEmail)) err s"Invalid email $rawEmail"
modApi.setEmail(me.id, user.id, email.acceptable) inject redirect(user.username, mod = true)
}
)
@ -268,8 +268,8 @@ final class Mod(
}
}
def communicationPublic(username: String) = communications(username, false)
def communicationPrivate(username: String) = communications(username, true)
def communicationPublic(username: String) = communications(username, priv = false)
def communicationPrivate(username: String) = communications(username, priv = true)
protected[controllers] def redirect(username: String, mod: Boolean = true) =
Redirect(userUrl(username, mod))
@ -296,7 +296,7 @@ final class Mod(
else env.report.api.inquiries.spontaneous _
f(AsMod(me), Suspect(user)) inject {
if (isAppeal) Redirect(routes.Appeal.show(user.username))
else redirect(user.username, true)
else redirect(user.username, mod = true)
}
}
}

View File

@ -54,7 +54,7 @@ final class Msg(
def search(q: String) =
Auth { ctx => me =>
ctx.hasInbox ?? {
q.trim.some.filter(_.size > 1).filter(lila.user.User.couldBeUsername) match {
q.trim.some.filter(_.length > 1).filter(lila.user.User.couldBeUsername) match {
case None => env.msg.json.searchResult(me)(env.msg.search.empty) map { Ok(_) }
case Some(q) => env.msg.search(me, q) flatMap env.msg.json.searchResult(me) map { Ok(_) }
}

View File

@ -180,7 +180,7 @@ final class Plan(env: Env)(implicit system: akka.actor.ActorSystem) extends Lila
lila.plan.Checkout.form
.bindFromRequest()
.fold(
err => badStripeSession(err.toString()).fuccess,
err => badStripeSession(err.toString).fuccess,
checkout =>
env.plan.api.userCustomer(me) flatMap {
case Some(customer) if checkout.freq == Freq.Onetime =>

View File

@ -163,7 +163,7 @@ final class Puzzle(
voted <- ctx.me.?? { env.puzzle.api.vote.value(puzzle.id, _) }
} yield Ok(
Json.obj(
"user" -> lila.puzzle.JsonView.infos(false)(infos),
"user" -> lila.puzzle.JsonView.infos(isOldMobile = false)(infos),
"round" -> lila.puzzle.JsonView.round(round),
"voted" -> voted
)
@ -234,7 +234,7 @@ final class Puzzle(
infos <- env.puzzle userInfos me2
} yield Ok(
Json.obj(
"user" -> lila.puzzle.JsonView.infos(false)(infos)
"user" -> lila.puzzle.JsonView.infos(isOldMobile = false)(infos)
)
)
)

View File

@ -86,7 +86,7 @@ final class Report(
def thenGoTo =
dataOpt.flatMap(_ get "then").flatMap(_.headOption) flatMap {
case "back" => HTTPRequest referer ctx.req
case "profile" => modC.userUrl(prev.user, true).some
case "profile" => modC.userUrl(prev.user, mod = true).some
case url => url.some
}
thenGoTo match {
@ -129,7 +129,7 @@ final class Report(
api.currentCheatReport(lila.report.Suspect(user)) flatMap {
_ ?? { report =>
api.inquiries.toggle(lila.report.Mod(me), report.id).void
} inject modC.redirect(username, true)
} inject modC.redirect(username, mod = true)
}
}
}

View File

@ -140,9 +140,8 @@ final class Round(
case _ =>
Redirect(routes.Round.watcher(gameId, "white")).fuccess
}
case None => {
case None =>
watch(pov)
}
}
case None => challengeC showId gameId
}

View File

@ -54,7 +54,7 @@ final class Setup(
Open { implicit ctx =>
if (HTTPRequest isXhr ctx.req)
fuccess(forms friendFilled get("fen").map(FEN)) flatMap { form =>
val validFen = form("fen").value flatMap ValidFen(false)
val validFen = form("fen").value flatMap ValidFen(strict = false)
userId ?? env.user.repo.named flatMap {
case None => Ok(html.setup.forms.friend(form, none, none, validFen)).fuccess
case Some(user) =>

View File

@ -115,14 +115,14 @@ final class Simul(
def accept(simulId: String, userId: String) =
Open { implicit ctx =>
AsHost(simulId) { simul =>
env.simul.api.accept(simul.id, userId, true) inject jsonOkResult
env.simul.api.accept(simul.id, userId, v = true) inject jsonOkResult
}
}
def reject(simulId: String, userId: String) =
Open { implicit ctx =>
AsHost(simulId) { simul =>
env.simul.api.accept(simul.id, userId, false) inject jsonOkResult
env.simul.api.accept(simul.id, userId, v = false) inject jsonOkResult
}
}

View File

@ -112,7 +112,7 @@ final class Streamer(
}
else {
val next = if (sws.streamer is me) "" else s"?u=${sws.user.id}"
Redirect(s"${routes.Streamer.edit().url}${next}").fuccess
Redirect(s"${routes.Streamer.edit().url}$next").fuccess
}
}
)

View File

@ -92,7 +92,7 @@ final class Swiss(
.fold(
err => BadRequest(html.swiss.form.create(err, teamId)).fuccess,
data =>
tourC.rateLimitCreation(me, false, ctx.req) {
tourC.rateLimitCreation(me, isPrivate = false, ctx.req) {
env.swiss.api.create(data, me, teamId) map { swiss =>
Redirect(routes.Swiss.show(swiss.id.value))
}
@ -113,7 +113,7 @@ final class Swiss(
.fold(
jsonFormErrorDefaultLang,
data =>
tourC.rateLimitCreation(me, false, req) {
tourC.rateLimitCreation(me, isPrivate = false, req) {
JsonOk {
env.swiss.api.create(data, me, teamId) map env.swiss.json.api
}

View File

@ -347,7 +347,7 @@ final class Team(
_ => fuccess(routes.Team.show(team.id).toString),
{
case (decision, url) =>
api.processRequest(team, request, (decision == "accept")) inject url
api.processRequest(team, request, decision == "accept") inject url
}
)
}

View File

@ -94,7 +94,7 @@ final class Tournament(
negotiate(
html = tourOption
.fold(tournamentNotFound.fuccess) { tour =>
(for {
for {
verdicts <- api.verdicts(tour, ctx.me, getUserTeamIds)
version <- env.tournament.version(tour.id)
json <- jsonView(
@ -119,9 +119,9 @@ final class Tournament(
}
streamers <- streamerCache get tour.id
shieldOwner <- env.tournament.shieldApi currentOwner tour
} yield Ok(html.tournament.show(tour, verdicts, json, chat, streamers, shieldOwner)))
} yield Ok(html.tournament.show(tour, verdicts, json, chat, streamers, shieldOwner))
}
.monSuccess(_.tournament.apiShowPartial(false, HTTPRequest clientName ctx.req)),
.monSuccess(_.tournament.apiShowPartial(partial = false, HTTPRequest clientName ctx.req)),
api = _ =>
tourOption
.fold(notFoundJson("No such tournament")) { tour =>

View File

@ -358,7 +358,7 @@ final class User(
}
val spyFu = env.security.userSpy(user, nbOthers)
val others = spyFu flatMap { spy =>
val familyUserIds = user.id :: spy.otherUserIds.toList
val familyUserIds = user.id :: spy.otherUserIds
(isGranted(_.ModNote) ?? env.user.noteApi
.forMod(familyUserIds)
.logTimeIfGt(s"$username noteApi.forMod", 2 seconds)) zip

View File

@ -141,7 +141,7 @@ final class UserAnalysis(
env.importer.importer
.inMemory(data)
.fold(
err => BadRequest(jsonError(err.toString)).fuccess,
err => BadRequest(jsonError(err)).fuccess,
{
case (game, fen) =>
val pov = Pov(game, chess.White)

View File

@ -59,7 +59,7 @@ final class Preload(
data,
povs
) ~ posts ~ tours ~ events ~ simuls ~ feat ~ entries ~ lead ~ tWinners ~ puzzle ~ streams ~ playban ~ blindGames =>
(ctx.me ?? currentGameMyTurn(povs, lightUserApi.sync) _)
(ctx.me ?? currentGameMyTurn(povs, lightUserApi.sync))
.mon(_.lobby segment "currentGame") zip
lightUserApi
.preloadMany {

View File

@ -2,23 +2,25 @@ package lila.app
package templating
import java.util.Locale
import play.api.i18n.Lang
import scala.collection.mutable.AnyRefMap
import play.api.i18n.Lang
import scala.collection.mutable.AnyRefMap
import org.joda.time.format._
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{ DateTime, DateTimeZone, DurationFieldType, Period, PeriodType }
import lila.app.ui.ScalatagsTemplate._
import scala.collection.mutable
trait DateHelper { self: I18nHelper with StringHelper =>
private val dateTimeStyle = "MS"
private val dateStyle = "M-"
private val dateTimeFormatters = AnyRefMap.empty[String, DateTimeFormatter]
private val dateFormatters = AnyRefMap.empty[String, DateTimeFormatter]
private val periodFormatters = AnyRefMap.empty[String, PeriodFormatter]
private val dateTimeFormatters = mutable.AnyRefMap.empty[String, DateTimeFormatter]
private val dateFormatters = mutable.AnyRefMap.empty[String, DateTimeFormatter]
private val periodFormatters = mutable.AnyRefMap.empty[String, PeriodFormatter]
private val periodType = PeriodType forFields Array(
DurationFieldType.days,
DurationFieldType.hours,

View File

@ -191,10 +191,9 @@ trait GameHelper { self: I18nHelper with UserHelper with AiHelper with StringHel
}
case S.Draw => trans.draw.txt()
case S.Outoftime => trans.timeOut.txt()
case S.NoStart => {
case S.NoStart =>
val color = game.loser.fold(Color.white)(_.color).name.capitalize
s"$color didn't move"
}
case S.Cheat => "Cheat detected"
case S.VariantEnd =>
game.variant match {

View File

@ -3,12 +3,15 @@ package templating
import java.text.NumberFormat
import java.util.Locale
import play.api.i18n.Lang
import scala.collection.mutable
import scala.collection.mutable.AnyRefMap
trait NumberHelper { self: I18nHelper =>
private val formatters = AnyRefMap.empty[String, NumberFormat]
private val formatters = mutable.AnyRefMap.empty[String, NumberFormat]
private def formatter(implicit lang: Lang): NumberFormat =
formatters.getOrElseUpdate(

View File

@ -56,7 +56,7 @@ trait SetupHelper { self: I18nHelper =>
"165",
"180"
).map { v =>
(v.toString, v.toString, none)
(v, v, none)
}
val clockIncrementChoices: List[SelectChoice] = {
@ -67,7 +67,7 @@ trait SetupHelper { self: I18nHelper =>
val corresDaysChoices: List[SelectChoice] =
("1", "One day", none) :: List(2, 3, 5, 7, 10, 14).map { d =>
(d.toString, s"${d} days", none)
(d.toString, s"$d days", none)
}
def translatedTimeModeChoices(implicit lang: Lang) =

View File

@ -147,9 +147,7 @@ trait ScalatagsExtensions {
val emptyFrag: Frag = new RawFrag("")
implicit val LilaFragZero: Zero[Frag] = Zero.instance(emptyFrag)
val emptyModifier: Modifier = new Modifier {
def applyTo(t: Builder) = {}
}
val emptyModifier: Modifier = (t: Builder) => {}
def ariaTitle(v: String) =
new Modifier {
@ -161,11 +159,9 @@ trait ScalatagsExtensions {
}
def titleOrText(blind: Boolean, v: String): Modifier =
new Modifier {
def applyTo(t: Builder) = {
if (blind) t.addChild(v)
else t.setAttr("title", Builder.GenericAttrValueSource(v))
}
(t: Builder) => {
if (blind) t.addChild(v)
else t.setAttr("title", Builder.GenericAttrValueSource(v))
}
def titleOrText(v: String)(implicit ctx: Context): Modifier = titleOrText(ctx.blind, v)

View File

@ -64,7 +64,7 @@ object layout {
.map { px =>
s"""<link rel="icon" type="image/png" href="${staticUrl(
s"logo/lichess-favicon-$px.png"
)}" sizes="${px}x${px}">"""
)}" sizes="${px}x$px">"""
}
.mkString(
"",

View File

@ -25,7 +25,7 @@ object show {
csp = bits.csp
)(
main(cls := "page-menu page-small")(
bits.menu(none, false),
bits.menu(none, hasActive = false),
div(cls := s"blog page-menu__content box post ${~doc.getText("blog.cssClasses")}")(
h1(doc.getText("blog.title")),
bits.metas(doc),

View File

@ -21,7 +21,7 @@ object mine {
views.html.base.layout(
title = challengeTitle(c),
openGraph = challengeOpenGraph(c).some,
moreJs = bits.js(c, json, true),
moreJs = bits.js(c, json, owner = true),
moreCss = cssTag("challenge.page")
) {
val challengeLink = s"$netBaseUrl${routes.Round.watcher(c.id, "white")}"
@ -55,7 +55,7 @@ object mine {
spellcheck := "false",
readonly,
value := challengeLink,
size := challengeLink.size
size := challengeLink.length
),
button(
title := "Copy URL",

View File

@ -19,7 +19,7 @@ object theirs {
views.html.base.layout(
title = challengeTitle(c),
openGraph = challengeOpenGraph(c).some,
moreJs = bits.js(c, json, false, color),
moreJs = bits.js(c, json, owner = false, color),
moreCss = cssTag("challenge.page")
) {
main(cls := "page-small challenge-page challenge-theirs box box-pad")(

View File

@ -101,7 +101,7 @@ object clas {
innerForm(form, c.some),
hr,
c.isActive option postForm(
action := routes.Clas.archive(c.id.value, true),
action := routes.Clas.archive(c.id.value, v = true),
cls := "clas-edit__archive"
)(
form3.submit(trans.clas.closeClass(), icon = none)(

View File

@ -33,7 +33,7 @@ object student {
s.student.archived map { archived =>
div(cls := "student-show__archived archived")(
bits.showArchived(archived),
postForm(action := routes.Clas.studentArchive(clas.id.value, s.user.username, false))(
postForm(action := routes.Clas.studentArchive(clas.id.value, s.user.username, v = false))(
form3.submit(trans.clas.inviteTheStudentBack(), icon = none)(cls := "confirm button-empty")
)
)
@ -209,7 +209,7 @@ object student {
s.student.isActive option frag(
hr,
postForm(
action := routes.Clas.studentArchive(clas.id.value, s.user.username, true),
action := routes.Clas.studentArchive(clas.id.value, s.user.username, v = true),
cls := "student-show__archive"
)(
form3.submit(trans.clas.removeStudent(), icon = none)(

View File

@ -39,7 +39,7 @@ object teacherDashboard {
c.archived map { archived =>
div(cls := "clas-show__archived archived")(
bits.showArchived(archived),
postForm(action := routes.Clas.archive(c.id.value, false))(
postForm(action := routes.Clas.archive(c.id.value, v = false))(
form3.submit(trans.clas.reopen(), icon = none)(cls := "confirm button-empty")
)
)

View File

@ -48,9 +48,12 @@ object widget {
pic(c, if (link) 300 else 350),
div(cls := "overview")(
(if (link) h2 else h1)(cls := "coach-name")(titleName(c)),
c.coach.profile.headline.map { h =>
p(cls := s"headline ${if (h.size < 60) "small" else if (h.size < 120) "medium" else "large"}")(h)
},
c.coach.profile.headline
.map { h =>
p(
cls := s"headline ${if (h.length < 60) "small" else if (h.length < 120) "medium" else "large"}"
)(h)
},
table(
tbody(
tr(

View File

@ -106,8 +106,8 @@ object categ {
)
),
tbody(
stickyPosts map showTopic(true),
topics.currentPageResults map showTopic(false)
stickyPosts map showTopic(sticky = true),
topics.currentPageResults map showTopic(sticky = false)
)
),
bar

View File

@ -83,7 +83,7 @@ object side {
game.pgnImport.exists(_.date.isDefined) option small(
"Imported ",
game.pgnImport.flatMap(_.user).map { user =>
trans.by(userIdLink(user.some, None, false))
trans.by(userIdLink(user.some, None, withOnline = false))
}
)
)
@ -94,7 +94,9 @@ object side {
div(cls := s"player color-icon is ${p.color.name} text")(
playerLink(p, withOnline = false, withDiff = true, withBerserk = true)
),
tour.flatMap(_.teamVs).map(_.teams(p.color)) map { teamLink(_, false)(cls := "team") }
tour.flatMap(_.teamVs).map(_.teams(p.color)) map {
teamLink(_, withIcon = false)(cls := "team")
}
)
}
)

View File

@ -31,7 +31,7 @@ object widgets {
frag(
span("IMPORT"),
g.pgnImport.flatMap(_.user).map { user =>
frag(" ", trans.by(userIdLink(user.some, None, false)))
frag(" ", trans.by(userIdLink(user.some, None, withOnline = false)))
},
separator,
if (g.variant.exotic) bits.variantLink(g.variant, g.variant.name.toUpperCase)
@ -138,7 +138,7 @@ object widgets {
} getOrElse {
player.aiLevel map { level =>
frag(
span(aiName(level, false)),
span(aiName(level, withRating = false)),
br,
aiRating(level)
)

View File

@ -30,7 +30,7 @@ object blindLobby {
a(href := gameLink(pov))(
playerText(pov.opponent),
" ",
pov.isMyTurn ?? pov.remainingSeconds map { secondsFromNow(_, true) }
pov.isMyTurn ?? pov.remainingSeconds map { secondsFromNow(_, alwaysRelative = true) }
)
)
}

View File

@ -126,7 +126,7 @@ object inquiry {
div(cls := "links")(
in.report.boostWith
.map { userId =>
a(href := s"${routes.User.games(in.user.id, "search")}?players.b=${userId}")("View", br, "Games")
a(href := s"${routes.User.games(in.user.id, "search")}?players.b=$userId")("View", br, "Games")
}
.getOrElse {
in.report.bestAtomByHuman.map { atom =>
@ -214,7 +214,7 @@ object inquiry {
div(cls := "actions close")(
span(cls := "switcher", title := "Automatically open next report")(
span(cls := "switch")(
form3.cmnToggle("auto-next", "auto-next", true)
form3.cmnToggle("auto-next", "auto-next", checked = true)
)
),
postForm(

View File

@ -37,8 +37,8 @@ object embed {
)
),
jQueryTag,
jsAt("javascripts/vendor/chessground.min.js", false),
jsAt("compiled/puzzle.js", false)
jsAt("javascripts/vendor/chessground.min.js", defer = false),
jsAt("compiled/puzzle.js", defer = false)
)
)
)

View File

@ -51,12 +51,12 @@ object list {
p(
cls := List(
"text" -> true,
"large" -> (atom.text.size > 100 || atom.text.linesIterator.size > 3)
"large" -> (atom.text.length > 100 || atom.text.linesIterator.size > 3)
)
)(shorten(atom.text, 200))
)
},
r.atoms.size > 3 option i(cls := "more")("And ", (r.atoms.size - 3), " more")
r.atoms.size > 3 option i(cls := "more")("And ", r.atoms.size - 3, " more")
),
td(
r.inquiry match {

View File

@ -96,7 +96,7 @@ object bits {
"round-toggle-autoswitch" pipe { id =>
span(cls := "move-on switcher", st.title := trans.automaticallyProceedToNextGameAfterMoving.txt())(
label(`for` := id)(trans.autoSwitch()),
span(cls := "switch")(form3.cmnToggle(id, id, false))
span(cls := "switch")(form3.cmnToggle(id, id, checked = false))
)
}
),
@ -111,11 +111,13 @@ object bits {
playerText(pov.opponent, withRating = false),
span(cls := "indicator")(
if (pov.isMyTurn)
pov.remainingSeconds.fold[Frag](trans.yourTurn())(secondsFromNow(_, true))
pov.remainingSeconds
.fold[Frag](trans.yourTurn())(secondsFromNow(_, alwaysRelative = true))
else nbsp
)
)
)
)
}
}
)

View File

@ -69,7 +69,7 @@ LichessRound.boot(${safeJsonValue(
bits.side(pov, data, tour.map(_.tourAndTeamVs), simul, bookmarked = bookmarked),
chatOption.map(_ => chat.frag)
),
bits.roundAppPreload(pov, true),
bits.roundAppPreload(pov, controls = true),
div(cls := "round__underboard")(
bits.crosstable(cross, pov.game),
(playing.nonEmpty || simul.exists(_ isHost ctx.me)) option

View File

@ -57,7 +57,7 @@ LichessRound.boot(${safeJsonValue(
bits.side(pov, data, tour, simul, userTv, bookmarked),
chatOption.map(_ => chat.frag)
),
bits.roundAppPreload(pov, false),
bits.roundAppPreload(pov, controls = false),
div(cls := "round__underboard")(bits.crosstable(cross, pov.game)),
div(cls := "round__underchat")(bits underchat pov.game)
)

View File

@ -14,7 +14,7 @@ private object bits {
import trans.search._
private val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
private val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd")
private val dateMin = "2011-01-01"
private def dateMinMax: List[Modifier] =
List(min := dateMin, max := dateFormatter.print(DateTime.now.plusDays(1)))

View File

@ -75,7 +75,7 @@ private object bits {
div(
input(
`type` := "radio",
id := s"$prefix${field.id}_${key}",
id := s"$prefix${field.id}_$key",
st.name := field.name,
value := key,
field.value.has(key) option checked

View File

@ -51,7 +51,7 @@ object forms {
layout("ai", trans.playWithTheMachine(), routes.Setup.ai()) {
frag(
renderVariant(form, translatedAiVariantChoices),
fenInput(form("fen"), true, validFen),
fenInput(form("fen"), strict = true, validFen),
renderTimeMode(form),
if (ctx.blind)
frag(
@ -95,7 +95,7 @@ object forms {
userLink(u, cssClass = "target".some)
},
renderVariant(form, translatedVariantChoicesWithVariantsAndFen),
fenInput(form("fen"), false, validFen),
fenInput(form("fen"), strict = false, validFen),
renderTimeMode(form),
ctx.isAuth option div(cls := "mode_choice buttons")(
renderRadios(form("mode"), translatedModeChoices)

View File

@ -106,7 +106,7 @@ object form {
)
),
form3.split(
(teams.size > 0) ?? {
teams.nonEmpty ?? {
form3.group(form("team"), raw("Only members of team"), half = true)(
form3.select(_, List(("", "No Restriction")) ::: teams.map(_.pair))
)

View File

@ -18,7 +18,9 @@ object header {
s.streamer.name
),
s.streamer.headline.map(_.value).map { d =>
p(cls := s"headline ${if (d.size < 60) "small" else if (d.size < 120) "medium" else "large"}")(d)
p(cls := s"headline ${if (d.length < 60) "small" else if (d.length < 120) "medium" else "large"}")(
d
)
},
div(cls := "services")(
s.streamer.twitch.map { twitch =>

View File

@ -34,7 +34,9 @@ object index {
div(cls := "overview")(
h1(dataIcon := "")(titleTag(s.user.title), stringValueFrag(s.streamer.name)),
s.streamer.headline.map(_.value).map { d =>
p(cls := s"headline ${if (d.size < 60) "small" else if (d.size < 120) "medium" else "large"}")(d)
p(
cls := s"headline ${if (d.length < 60) "small" else if (d.length < 120) "medium" else "large"}"
)(d)
},
div(cls := "services")(
s.streamer.twitch.map { twitch =>

View File

@ -70,5 +70,5 @@ object show {
)
)
def socketUrl(id: String) = s"/study/$id/socket/v${apiVersion}"
def socketUrl(id: String) = s"/study/$id/socket/v$apiVersion"
}

View File

@ -34,7 +34,7 @@ object list {
h1(myTeams()),
standardFlash(),
table(cls := "slist slist-pad")(
if (teams.size > 0) tbody(teams.map(bits.teamTr(_)))
if (teams.nonEmpty) tbody(teams.map(bits.teamTr(_)))
else noTeam()
)
)
@ -49,7 +49,7 @@ object list {
h1(teamsIlead()),
standardFlash(),
table(cls := "slist slist-pad")(
if (teams.size > 0) tbody(teams.map(bits.teamTr(_)))
if (teams.nonEmpty) tbody(teams.map(bits.teamTr(_)))
else noTeam()
)
)

View File

@ -118,7 +118,7 @@ object form {
frag(
form3.split(
fields.password,
(auto && tour.isEmpty && teams.size > 0) option {
(auto && tour.isEmpty && teams.nonEmpty) option {
val baseField = form("conditions.teamMember.teamId")
val field = ctx.req.queryString get "team" flatMap (_.headOption) match {
case None => baseField

View File

@ -74,7 +74,7 @@ var d=lichess.StrongSocket.defaults;d.params.flag="tournament";d.events.reload=a
scheduled.map { tour =>
tour.schedule.filter(s => s.freq != lila.tournament.Schedule.Freq.Hourly) map { s =>
a(href := routes.Tournament.show(tour.id), dataIcon := tournamentIconChar(tour))(
strong(tour.name(false)),
strong(tour.name(full = false)),
momentFromNow(s.at)
)
}

View File

@ -11,7 +11,7 @@ object homepageSpotlight {
def apply(tour: lila.tournament.Tournament)(implicit ctx: Context) = {
val schedClass = tour.schedule ?? { sched =>
val invert = (sched.freq.isWeeklyOrBetter && tour.isNowOrSoon) ?? " invert"
val distant = (tour.isDistant) ?? " distant little"
val distant = tour.isDistant ?? " distant little"
s"${sched.freq} ${sched.speed} ${sched.variant.key}$invert$distant"
}
val tourClass = s"tour-spotlight id_${tour.id} $schedClass"

View File

@ -23,7 +23,7 @@ object shields {
h1("Tournament shields"),
div(cls := "tournament-shields")(
history.sorted.map {
case (categ, awards) => {
case (categ, awards) =>
section(
h2(
a(href := routes.Tournament.categShields(categ.key))(
@ -38,7 +38,6 @@ object shields {
)
})
)
}
}
)
)

View File

@ -30,8 +30,8 @@ object embed {
views.html.game.mini.noCtx(pov, tv = true, blank = true)
),
jQueryTag,
jsAt("javascripts/vendor/chessground.min.js", false),
jsAt("compiled/tv.js", false)
jsAt("javascripts/vendor/chessground.min.js", defer = false),
jsAt("compiled/tv.js", defer = false)
)
)
)

View File

@ -51,7 +51,7 @@ object index {
side.meta(pov),
side.channels(channel, champions, "/tv")
),
views.html.round.bits.roundAppPreload(pov, false),
views.html.round.bits.roundAppPreload(pov, controls = false),
div(cls := "round__underboard")(
views.html.round.bits.crosstable(cross, pov.game),
div(cls := "tv-history")(

View File

@ -24,7 +24,7 @@ object mini {
div(cls := "left")(
userLink(u, withPowerTip = false),
u.profileOrDefault.countryInfo map { c =>
val hasRoomForNameText = u.username.size + c.shortName.size < 20
val hasRoomForNameText = u.username.length + c.shortName.length < 20
span(
cls := "upt__info__top__country",
title := (!hasRoomForNameText).option(c.name)

View File

@ -135,11 +135,11 @@ object header {
div(cls := "mod-note")(
submitButton(cls := "button")(trans.send()),
div(
div(form3.cmnToggle("note-mod", "mod", true)),
div(form3.cmnToggle("note-mod", "mod", checked = true)),
label(`for` := "note-mod")("For moderators only")
),
isGranted(_.Doxing) option div(
div(form3.cmnToggle("note-dox", "dox", false)),
div(form3.cmnToggle("note-dox", "dox", checked = false)),
label(`for` := "note-dox")("Doxing info")
)
)

View File

@ -39,7 +39,7 @@ object chart {
),
tbody(
data.perfResults.map {
case (pt, res) => {
case (pt, res) =>
tr(
th(iconTag(pt.iconChar, pt.trans)),
td(res.nb.localize),
@ -47,7 +47,6 @@ object chart {
td(res.points.sum.localize),
td(res.rankPercentMedian, "%")
)
}
},
tr(
th("Total"),

View File

@ -50,7 +50,7 @@ object bits {
videos.currentPageResults.map { card(_, control) },
videos.nextPage.map { next =>
div(cls := "pager none")(
a(rel := "next", href := s"${routes.Video.author(name)}?${control.queryString}&page=${next}")(
a(rel := "next", href := s"${routes.Video.author(name)}?${control.queryString}&page=$next")(
"Next"
)
)

View File

@ -42,7 +42,7 @@ lazy val modules = Seq(
)
lazy val moduleRefs = modules map projectToRef
lazy val moduleCPDeps = moduleRefs map { new sbt.ClasspathDependency(_, None) }
lazy val moduleCPDeps = moduleRefs map { sbt.ClasspathDependency(_, None) }
lazy val api = module("api",
moduleCPDeps,

View File

@ -46,7 +46,7 @@ object Activity {
val genesis = new DateTime(2010, 1, 1, 0, 0).withTimeAtStartOfDay
def today = Day(Days.daysBetween(genesis, DateTime.now.withTimeAtStartOfDay).getDays)
def recent(nb: Int): List[Day] =
(0 to (nb - 1)).toList.map { delta =>
(0 until nb).toList.map { delta =>
Day(Days.daysBetween(genesis, DateTime.now.minusDays(delta).withTimeAtStartOfDay).getDays)
}
}

View File

@ -29,7 +29,7 @@ final class ActivityWriteApi(
.add(pt, Score.make(game wonBy player.color, RatingProg make player))
)
setCorres = game.hasCorrespondenceClock ?? $doc(
ActivityFields.corres -> a.corres.orDefault.add(GameId(game.id), false, true)
ActivityFields.corres -> a.corres.orDefault.add(GameId(game.id), moved = false, ended = true)
)
setters = setGames ++ setCorres
_ <-
@ -89,7 +89,7 @@ final class ActivityWriteApi(
def corresMove(gameId: Game.ID, userId: User.ID) =
update(userId) { a =>
a.copy(corres = Some((~a.corres).add(GameId(gameId), true, false))).some
a.copy(corres = Some((~a.corres).add(GameId(gameId), moved = true, ended = false))).some
}
def plan(userId: User.ID, months: Int) =

View File

@ -43,7 +43,7 @@ final class Annotator(netDomain: lila.common.config.NetDomain) {
move =>
move.copy(
glyphs = Glyphs.fromList(advice.judgment.glyph :: Nil),
comments = advice.makeComment(true, true) :: move.comments,
comments = advice.makeComment(withEval = true, withBestMove = true) :: move.comments,
variations = makeVariation(turn, advice) :: Nil
)
)

View File

@ -20,7 +20,7 @@ object JsonView {
Json
.obj(
"name" -> a.judgment.name,
"comment" -> a.makeComment(false, true)
"comment" -> a.makeComment(withEval = false, withBestMove = true)
)
.add(
"glyph" -> withGlyph.option(

View File

@ -101,7 +101,7 @@ final class PersonalDataExport(
private val bigSep = "\n\n------------------------------------------\n\n"
private def textTitle(t: String) = s"\n\n${"=" * t.size}\n$t\n${"=" * t.size}\n\n\n"
private def textTitle(t: String) = s"\n\n${"=" * t.length}\n$t\n${"=" * t.length}\n\n\n"
private val englishDateTimeFormatter = DateTimeFormat forStyle "MS"
private def textDate(date: DateTime) = englishDateTimeFormatter print date

View File

@ -54,12 +54,12 @@ final private[api] class RoundApi(
case json ~ simul ~ swiss ~ note ~ forecast ~ bookmarked =>
(
withTournament(pov, tour) _ compose
withSwiss(swiss) _ compose
withSimul(simul) _ compose
withSteps(pov, initialFen) _ compose
withNote(note) _ compose
withBookmark(bookmarked) _ compose
withForecastCount(forecast.map(_.steps.size)) _
withSwiss(swiss) compose
withSimul(simul) compose
withSteps(pov, initialFen) compose
withNote(note) compose
withBookmark(bookmarked) compose
withForecastCount(forecast.map(_.steps.size))
)(json)
}
}
@ -92,11 +92,11 @@ final private[api] class RoundApi(
case json ~ simul ~ swiss ~ note ~ bookmarked =>
(
withTournament(pov, tour) _ compose
withSwiss(swiss) _ compose
withSimul(simul) _ compose
withNote(note) _ compose
withBookmark(bookmarked) _ compose
withSteps(pov, initialFen) _
withSwiss(swiss) compose
withSimul(simul) compose
withNote(note) compose
withBookmark(bookmarked) compose
withSteps(pov, initialFen)
)(json)
}
}
@ -131,12 +131,12 @@ final private[api] class RoundApi(
case json ~ tour ~ simul ~ swiss ~ note ~ bookmarked =>
(
withTournament(pov, tour) _ compose
withSwiss(swiss) _ compose
withSimul(simul) _ compose
withNote(note) _ compose
withBookmark(bookmarked) _ compose
withTree(pov, analysis, initialFen, withFlags) _ compose
withAnalysis(pov.game, analysis) _
withSwiss(swiss) compose
withSimul(simul) compose
withNote(note) compose
withBookmark(bookmarked) compose
withTree(pov, analysis, initialFen, withFlags) compose
withAnalysis(pov.game, analysis)
)(json)
}
}
@ -163,7 +163,7 @@ final private[api] class RoundApi(
) map { json =>
(
withTree(pov, analysis, initialFen, withFlags) _ compose
withAnalysis(pov.game, analysis) _
withAnalysis(pov.game, analysis)
)(json)
}
}
@ -256,7 +256,7 @@ final private[api] class RoundApi(
Json
.obj(
"id" -> v.tour.id,
"name" -> v.tour.name(false),
"name" -> v.tour.name(full = false),
"running" -> v.tour.isStarted
)
.add("secondsToFinish" -> v.tour.isStarted.option(v.tour.secondsToFinish))

View File

@ -15,6 +15,6 @@ private[appeal] object BsonHandlers {
s => BSONString(s.key)
)
implicit val appealMsgHandler = Macros.handler[AppealMsg]
implicit val appealHandler = Macros.handler[Appeal]
implicit val appealMsgHandler = Macros.handler[AppealMsg]
implicit val appealHandler = Macros.handler[Appeal]
}

View File

@ -7,7 +7,7 @@ import lila.common.config._
@Module
final class Env(
db: lila.db.Db,
userRepo: lila.user.UserRepo,
userRepo: lila.user.UserRepo
)(implicit ec: scala.concurrent.ExecutionContext) {
private val coll = db(CollName("appeal"))

View File

@ -26,7 +26,7 @@ final class BlogApi(
.pageSize(maxPerPage.value)
.page(page)
.submit()
.fold(_ => none, some _)
.fold(_ => none, some)
.dmap2 { PrismicPaginator(_, page, maxPerPage) }
def recent(

View File

@ -1,5 +1,7 @@
package lila.blog
import java.util
import com.github.blemale.scaffeine.LoadingCache
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension
import com.vladsch.flexmark.ext.tables.TablesExtension
@ -7,6 +9,7 @@ import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.util.data.MutableDataSet
import java.util.Arrays
import scala.concurrent.duration._
import scala.util.matching.Regex
@ -25,7 +28,10 @@ object BlogTransform {
private val PreRegex = """<pre>markdown(.+)</pre>""".r
private val options = new MutableDataSet()
options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()))
options.set(
Parser.EXTENSIONS,
util.Arrays.asList(TablesExtension.create(), StrikethroughExtension.create())
)
options.set(HtmlRenderer.SOFT_BREAK, "<br>\n")
options.set(TablesExtension.CLASS_NAME, "slist")
private val parser = Parser.builder(options).build()

View File

@ -50,9 +50,9 @@ final class BotPlayer(
chatApi.userChat.write(chatId, me.id, d.text, publicSource = source, _.Round)
}
def rematchAccept(id: Game.ID, me: User): Fu[Boolean] = rematch(id, me, true)
def rematchAccept(id: Game.ID, me: User): Fu[Boolean] = rematch(id, me, accept = true)
def rematchDecline(id: Game.ID, me: User): Fu[Boolean] = rematch(id, me, false)
def rematchDecline(id: Game.ID, me: User): Fu[Boolean] = rematch(id, me, accept = false)
private def rematch(id: Game.ID, me: User, accept: Boolean): Fu[Boolean] =
gameRepo game id map {

View File

@ -64,7 +64,7 @@ final class GameStateStream(
private val classifiers = List(
MoveGameEvent makeChan id,
s"boardDrawOffer:${id}",
s"boardDrawOffer:$id",
"finishGame",
"abortGame",
uniqChan(init.game pov as),
@ -83,7 +83,7 @@ final class GameStateStream(
else self ! SetOnline
}
lila.mon.bot.gameStream("start").increment()
Bus.publish(Tell(init.game.id, BotConnected(as, true)), "roundSocket")
Bus.publish(Tell(init.game.id, BotConnected(as, v = true)), "roundSocket")
}
override def postStop(): Unit = {
@ -92,7 +92,7 @@ final class GameStateStream(
// hang around if game is over
// so the opponent has a chance to rematch
context.system.scheduler.scheduleOnce(if (gameOver) 10 second else 1 second) {
Bus.publish(Tell(init.game.id, BotConnected(as, false)), "roundSocket")
Bus.publish(Tell(init.game.id, BotConnected(as, v = false)), "roundSocket")
}
queue.complete()
lila.mon.bot.gameStream("stop").increment()
@ -101,7 +101,7 @@ final class GameStateStream(
def receive = {
case MoveGameEvent(g, _, _) if g.id == id => pushState(g)
case lila.chat.actorApi.ChatLine(chatId, UserLine(username, _, text, false, false)) =>
pushChatLine(username, text, chatId.value.size == Game.gameIdSize)
pushChatLine(username, text, chatId.value.length == Game.gameIdSize)
case FinishGame(g, _, _) if g.id == id => onGameOver(g.some)
case AbortedBy(pov) if pov.gameId == id => onGameOver(pov.game.some)
case lila.game.actorApi.BoardDrawOffer(pov) if pov.gameId == id => pushState(pov.game)

View File

@ -12,14 +12,14 @@ final class OnlineApiUsers(
private val cache = new ExpireCallbackMemo(
10.seconds,
userId => publish(userId, false)
userId => publish(userId, isOnline = false)
)
def setOnline(userId: lila.user.User.ID): Unit = {
// We must delay the event publication, because caffeine
// delays the removal listener, therefore when a bot reconnects,
// the offline event is sent after the online event.
if (!cache.get(userId)) scheduler.scheduleOnce(1 second) { publish(userId, true) }
if (!cache.get(userId)) scheduler.scheduleOnce(1 second) { publish(userId, isOnline = true) }
cache.put(userId)
}

View File

@ -42,7 +42,7 @@ final class ChatApi(
def findMine(chatId: Chat.Id, me: Option[User]): Fu[UserChat.Mine] =
me match {
case Some(user) => findMine(chatId, user)
case None => cache.get(chatId) dmap { UserChat.Mine(_, false) }
case None => cache.get(chatId) dmap { UserChat.Mine(_, timeout = false) }
}
private def findMine(chatId: Chat.Id, me: User): Fu[UserChat.Mine] =
@ -62,14 +62,14 @@ final class ChatApi(
def findAll(chatIds: List[Chat.Id]): Fu[List[UserChat]] =
coll.byIds[UserChat](chatIds.map(_.value), ReadPreference.secondaryPreferred)
def findMine(chatId: Chat.Id, me: Option[User]): Fu[UserChat.Mine] = findMineIf(chatId, me, true)
def findMine(chatId: Chat.Id, me: Option[User]): Fu[UserChat.Mine] = findMineIf(chatId, me, cond = true)
def findMineIf(chatId: Chat.Id, me: Option[User], cond: Boolean): Fu[UserChat.Mine] =
me match {
case Some(user) if cond => findMine(chatId, user)
case Some(user) => fuccess(UserChat.Mine(Chat.makeUser(chatId) forUser user.some, false))
case None if cond => find(chatId) dmap { UserChat.Mine(_, false) }
case None => fuccess(UserChat.Mine(Chat.makeUser(chatId), false))
case Some(user) => fuccess(UserChat.Mine(Chat.makeUser(chatId) forUser user.some, timeout = false))
case None if cond => find(chatId) dmap { UserChat.Mine(_, timeout = false) }
case None => fuccess(UserChat.Mine(Chat.makeUser(chatId), timeout = false))
}
private def findMine(chatId: Chat.Id, me: User): Fu[UserChat.Mine] =
@ -243,7 +243,7 @@ final class ChatApi(
makeLine(chatId, color, text) ?? { line =>
pushLine(chatId, line) >>- {
publish(chatId, actorApi.ChatLine(chatId, line), busChan)
lila.mon.chat.message("anonPlayer", false).increment()
lila.mon.chat.message("anonPlayer", troll = false).increment()
}
}
@ -288,7 +288,8 @@ final class ChatApi(
def cut(text: String) = Some(text.trim take Line.textMaxSize) filter (_.nonEmpty)
private val gameUrlRegex = (Pattern.quote(netDomain.value) + """\b/(\w{8})\w{4}\b""").r
private val gameUrlReplace = Matcher.quoteReplacement(netDomain.value) + "/$1";
private val gameUrlReplace = Matcher.quoteReplacement(netDomain.value) + "/$1"
private def noPrivateUrl(str: String): String = gameUrlRegex.replaceAllIn(str, gameUrlReplace)
private val multilineRegex = """\n\n{2,}+""".r
private def multiline(str: String) = multilineRegex.replaceAllIn(str, """\n\n""")

View File

@ -12,7 +12,7 @@ final class ChatPanic {
!(enabled || tighter) || {
(u.count.gameH > 10 && u.createdSinceDays(1)) || u.isVerified
}
def allowed(u: User): Boolean = allowed(u, false)
def allowed(u: User): Boolean = allowed(u, tighter = false)
def allowed(id: User.ID, fetch: User.ID => Fu[Option[User]]): Fu[Boolean] =
if (enabled) fetch(id) dmap { _ ?? allowed }

View File

@ -77,7 +77,7 @@ object ChatTimeout {
def apply(key: String) = all.find(_.key == key)
}
implicit val ReasonBSONHandler: BSONHandler[Reason] = tryHandler[Reason](
{ case BSONString(value) => Reason(value) toTry s"Invalid reason ${value}" },
{ case BSONString(value) => Reason(value) toTry s"Invalid reason $value" },
x => BSONString(x.key)
)

View File

@ -195,7 +195,7 @@ final class ClasApi(
)
.orFail(s"No user could be created for ${data.username}")
.flatMap { user =>
userRepo.setKid(user, true) >>
userRepo.setKid(user, v = true) >>
userRepo.setManagedUserInitialPerfs(user.id) >>
coll.insert.one(Student.make(user, clas, teacher.id, data.realName, managed = true)) >>
sendWelcomeMessage(teacher.id, user, clas) inject
@ -251,7 +251,7 @@ ${clas.desc}""",
def create(clas: Clas, user: User, realName: String, teacher: User): Fu[ClasInvite.Feedback] =
student
.archive(Student.id(user.id, clas.id), user, false)
.archive(Student.id(user.id, clas.id), user, v = false)
.map2[ClasInvite.Feedback](_ => Already) getOrElse {
lila.mon.clas.studentInvite(teacher.id)
val invite = ClasInvite.make(clas, user, realName, teacher)

View File

@ -69,7 +69,7 @@ final class ClasForm(
mapping(
"username" -> lila.user.DataForm.historicalUsernameField
.verifying("Unknown username", { blockingFetchUser(_).isDefined })
.verifying("This is a teacher", u => !c.teachers.toList.exists(_ == u.toLowerCase)),
.verifying("This is a teacher", u => !c.teachers.toList.contains(u.toLowerCase)),
"realName" -> nonEmptyText
)(NewStudent.apply)(NewStudent.unapply)
)

View File

@ -1,5 +1,7 @@
package lila.clas
import java.util
import com.github.blemale.scaffeine.LoadingCache
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension
import com.vladsch.flexmark.ext.tables.TablesExtension
@ -8,6 +10,7 @@ import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.util.data.MutableDataSet
import java.util.Arrays
import scala.concurrent.duration._
final class ClasMarkup {
@ -18,7 +21,7 @@ final class ClasMarkup {
private val options = new MutableDataSet()
options.set(
Parser.EXTENSIONS,
Arrays.asList(
util.Arrays.asList(
TablesExtension.create(),
StrikethroughExtension.create(),
AutolinkExtension.create()

View File

@ -7,7 +7,7 @@ final class NameGenerator(userRepo: lila.user.UserRepo)(implicit ec: ExecutionCo
def apply(maxSize: Int = 16, triesLeft: Int = 100): Fu[Option[String]] = {
val name = anyOf(combinations).map(anyOf).mkString
if (name.size <= maxSize) userRepo.nameExists(name) flatMap {
if (name.length <= maxSize) userRepo.nameExists(name) flatMap {
case true => apply(maxSize, triesLeft - 1)
case _ => fuccess(name.some)
}

View File

@ -26,7 +26,7 @@ case class Student(
object Student {
def id(userId: User.ID, clasId: Clas.Id) = Id(s"${userId}:${clasId}")
def id(userId: User.ID, clasId: Clas.Id) = Id(s"$userId:$clasId")
def make(user: User, clas: Clas, teacherId: User.ID, realName: String, managed: Boolean) =
Student(
@ -50,7 +50,7 @@ object Student {
private val random = new java.security.SecureRandom()
private val chars = ('2' to '9') ++ (('a' to 'z').toSet - 'l') mkString
private val nbChars = chars.size
private val nbChars = chars.length
private def secureChar = chars(random nextInt nbChars)
def generate =

View File

@ -5,7 +5,7 @@ import play.api.i18n.Lang
import lila.common.paginator.Paginator
import lila.db.dsl._
import lila.db.paginator.{ Adapter }
import lila.db.paginator.Adapter
import lila.user.{ User, UserRepo }
final class CoachPager(

View File

@ -52,7 +52,7 @@ object CoachProfileForm {
available = Coach.Available(available),
profile = profile,
languages = Json.parse(languages).validate[List[TagifyLang]] match {
case JsSuccess(langs, _) => langs.take(10).toList.map(_.code).flatMap(Lang.get).map(_.code).distinct
case JsSuccess(langs, _) => langs.take(10).map(_.code).flatMap(Lang.get).map(_.code).distinct
case _ => Nil
},
updatedAt = DateTime.now

View File

@ -42,10 +42,10 @@ final class Env(
lila.common.Bus.subscribeFun("adjustCheater", "finishGame", "shadowban", "setPermissions") {
case lila.hub.actorApi.mod.Shadowban(userId, true) =>
api.toggleApproved(userId, false)
api.toggleApproved(userId, value = false)
api.reviews deleteAllBy userId
case lila.hub.actorApi.mod.MarkCheater(userId, true) =>
api.toggleApproved(userId, false)
api.toggleApproved(userId, value = false)
api.reviews deleteAllBy userId
case lila.hub.actorApi.mod.SetPermissions(userId, permissions) =>
api.toggleApproved(userId, permissions.has(Permission.Coach.dbKey))
@ -60,8 +60,8 @@ final class Env(
def cli =
new lila.common.Cli {
def process = {
case "coach" :: "enable" :: username :: Nil => api.toggleApproved(username, true)
case "coach" :: "disable" :: username :: Nil => api.toggleApproved(username, false)
case "coach" :: "enable" :: username :: Nil => api.toggleApproved(username, value = true)
case "coach" :: "disable" :: username :: Nil => api.toggleApproved(username, value = false)
}
}
}

View File

@ -95,11 +95,11 @@ object Form {
import play.api.data.{ validation => V }
def minLength[A](from: A => String)(length: Int): Constraint[A] =
Constraint[A]("constraint.minLength", length) { o =>
if (from(o).size >= length) V.Valid else V.Invalid(V.ValidationError("error.minLength", length))
if (from(o).length >= length) V.Valid else V.Invalid(V.ValidationError("error.minLength", length))
}
def maxLength[A](from: A => String)(length: Int): Constraint[A] =
Constraint[A]("constraint.maxLength", length) { o =>
if (from(o).size <= length) V.Valid else V.Invalid(V.ValidationError("error.maxLength", length))
if (from(o).length <= length) V.Valid else V.Invalid(V.ValidationError("error.maxLength", length))
}
}

View File

@ -83,7 +83,7 @@ object HTTPRequest {
def hasFileExtension(req: RequestHeader) = fileExtensionRegex.find(req.path)
def weirdUA(req: RequestHeader) = userAgent(req).fold(true)(_.size < 30)
def weirdUA(req: RequestHeader) = userAgent(req).fold(true)(_.length < 30)
def print(req: RequestHeader) = s"${printReq(req)} ${printClient(req)}"

View File

@ -38,7 +38,7 @@ object Iso {
strs => strs.value mkString sep
)
implicit def isoIdentity[A]: Iso[A, A] = apply(identity[A] _, identity[A] _)
implicit def isoIdentity[A]: Iso[A, A] = apply(identity[A], identity[A])
implicit val stringIsoIdentity: Iso[String, String] = isoIdentity[String]

View File

@ -12,7 +12,7 @@ object Maths {
a.nonEmpty option {
val arr = a.toArray
Sorting.stableSort(arr)
val size = arr.size
val size = arr.length
val mid = size / 2
if (size % 2 == 0) n.toDouble(arr(mid) + arr(mid - 1)) / 2
else n.toDouble(arr(mid))

View File

@ -32,7 +32,7 @@ object String {
def shorten(text: String, length: Int, sep: String = "…") = {
val t = text.replace('\n', ' ')
if (t.size > (length + sep.size)) (t take length) ++ sep
if (t.length > (length + sep.length)) (t take length) ++ sep
else t
}
@ -107,13 +107,12 @@ object String {
case JsNumber(n) => n.toString
case JsBoolean(b) => if (b) "true" else "false"
case JsArray(items) => items.map(safeJsonValue).mkString("[", ",", "]")
case JsObject(fields) => {
case JsObject(fields) =>
fields
.map {
case (k, v) => s"${safeJsonString(k)}:${safeJsonValue(v)}"
}
.mkString("{", ",", "}")
}
}
}
}

View File

@ -73,13 +73,13 @@ object WMMatching {
private[this] def minWeightMatching(endpoint: Array[Int], weights: Array[Int]): List[(Int, Int)] = {
val maxweight = weights.max
maxWeightMatching(endpoint, weights.map { maxweight - _ }, true)
maxWeightMatching(endpoint, weights.map { maxweight - _ }, maxcardinality = true)
}
private[this] def mateToList(endpoint: Array[Int], mate: Array[Int]): List[(Int, Int)] = {
// Transform mate such that mate(v) is the vertex to which v is paired.
var l: List[(Int, Int)] = Nil
for (v <- Range(mate.size - 2, -1, -1)) {
for (v <- Range(mate.length - 2, -1, -1)) {
val k = mate(v)
if (k >= 0) {
val e = endpoint(k)
@ -458,9 +458,9 @@ object WMMatching {
val l1 = blossomchilds(b).length - 1
val (jstep, endptrick) =
// Start index is odd; go forward and wrap.
if ((j & 1) != 0) ((j: Int) => { if (j == l1) 0 else (j + 1) }, 0)
if ((j & 1) != 0) ((j: Int) => { if (j == l1) 0 else j + 1 }, 0)
// Start index is even; go backward.
else ((j: Int) => { if (j == 0) l1 else (j - 1) }, 1)
else ((j: Int) => { if (j == 0) l1 else j - 1 }, 1)
// Move along the blossom until we get to the base.
var p = labelend(b)
while (j != 0) {
@ -534,8 +534,8 @@ object WMMatching {
val i = blossomchilds(b).indexOf(t)
var j = i
val (jstep, endptrick) =
if ((j & 1) != 0) ((j: Int) => { if (j == l1) 0 else (j + 1) }, 0)
else ((j: Int) => { if (j == 0) l1 else (j - 1) }, 1)
if ((j & 1) != 0) ((j: Int) => { if (j == l1) 0 else j + 1 }, 0)
else ((j: Int) => { if (j == 0) l1 else j - 1 }, 1)
// Move along the blossom until we get to the base.
while (j != 0) {
// Step to the next sub-blossom and augment it recursively.
@ -744,14 +744,12 @@ object WMMatching {
for (v <- vertices) {
label(inblossom(v)) match {
case 0 => ()
case 1 => {
case 1 =>
//S-vertex: 2*u = 2*u - 2*delta
dualvar(v) -= dt.delta
}
case 2 => {
case 2 =>
//T-vertex: 2*u = 2*u + 2*delta
dualvar(v) += dt.delta
}
}
}
@ -768,24 +766,21 @@ object WMMatching {
// Take action at the point where minimum delta occurred.
dt.tp match {
case 0 => false
case 1 => {
case 1 =>
// Use the least-slack edge to continue the search.
allowedge(dt.extra) = true
val kk = 2 * dt.extra
val ei = endpoint(kk)
queue ::= (if (label(inblossom(ei)) == 0) endpoint(kk + 1) else ei)
true
}
case 2 => {
case 2 =>
// Use the least-slack edge to continue the search.
allowedge(dt.extra) = true
queue ::= endpoint(2 * dt.extra)
true
}
case 3 => {
expandBlossom(dt.extra, false)
case 3 =>
expandBlossom(dt.extra, endstage = false)
true
}
}
}
}

View File

@ -12,6 +12,7 @@ object Levenshtein {
val i = j - dd
((i - (threshold - 1)) max 0) until (1 + ((i + t) min a.length))
}
@scala.annotation.tailrec
def loop(j: Int, prev: Array[Int], prevr: Range, next: Array[Int]): Int = {
if (j > b.length) prev.last
else {
@ -22,7 +23,7 @@ object Levenshtein {
if (i == 0) j
else {
val t0 = if (i < prevr.end) prev(i) else inf
val t1 = 1 + (if (i > q.start) t0 min (next(i - 1)) else t0)
val t1 = 1 + (if (i > q.start) t0 min next(i - 1) else t0)
if (prevr.start < i) {
val t = prev(i - 1)
t1 min (if (c != a(i - 1)) 1 + t else t)

View File

@ -59,7 +59,7 @@ final class PimpedFuture[A](private val fua: Fu[A]) extends AnyVal {
def addFailureEffect(effect: Throwable => Unit)(implicit ec: EC) = {
fua.failed.foreach {
case e: Throwable => effect(e)
e: Throwable => effect(e)
}
fua
}

View File

@ -159,8 +159,8 @@ final object RawHtml {
while (
(sArr(last): @switch) match {
case '.' | ',' | '?' | '!' | ':' | ';' | '' | '—' | '@' | '\'' => true
case '(' => { parenCnt -= 1; true }
case ')' => { parenCnt += 1; parenCnt <= 0 }
case '(' => parenCnt -= 1; true
case ')' => parenCnt += 1; parenCnt <= 0
case _ => false
}
) { last -= 1 }

View File

@ -40,7 +40,7 @@ case class NormalizedEmailAddress(value: String) extends AnyVal with StringValue
case class EmailAddress(value: String) extends AnyVal with StringValue {
def conceal =
value split '@' match {
case Array(user, domain) => s"${user take 3}*****@${domain}"
case Array(user, domain) => s"${user take 3}*****@$domain"
case _ => value
}
def normalize =

View File

@ -6,7 +6,7 @@ import reactivemongo.api.bson._
case class ByteArray(value: Array[Byte]) {
def isEmpty = value.size == 0
def isEmpty = value.length == 0
def toHexStr = ByteArray.hex hex2Str value

Some files were not shown because too many files have changed in this diff Show More