Skip to content

Commit

Permalink
Merge branch 'lichess-org:master' into patch-7
Browse files Browse the repository at this point in the history
  • Loading branch information
Carbrex authored Jan 23, 2024
2 parents 4159968 + e64c1f8 commit f65bc4d
Show file tree
Hide file tree
Showing 17 changed files with 50 additions and 54 deletions.
15 changes: 5 additions & 10 deletions app/controllers/BulkPairing.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,18 @@ import lila.setup.SetupBulk
final class BulkPairing(env: Env) extends LilaController(env):

def list = ScopedBody(_.Challenge.Bulk) { _ ?=> me ?=>
env.challenge.bulk.scheduledBy(me) map { list =>
env.challenge.bulk.scheduledBy(me) map: list =>
JsonOk(Json.obj("bulks" -> list.map(SetupBulk.toJson)))
}
}

def delete(id: String) = ScopedBody(_.Challenge.Bulk) { _ ?=> me ?=>
env.challenge.bulk.deleteBy(id, me) flatMap {
env.challenge.bulk.deleteBy(id, me) flatMap:
if _ then jsonOkResult else notFoundJson()
}
}

def startClocks(id: String) = ScopedBody(_.Challenge.Bulk) { _ ?=> me ?=>
env.challenge.bulk.startClocks(id, me) flatMap {
env.challenge.bulk.startClocksAsap(id, me) flatMap:
if _ then jsonOkResult else notFoundJson()
}
}

def create = ScopedBody(_.Challenge.Bulk) { ctx ?=> me ?=>
Expand All @@ -32,7 +29,7 @@ final class BulkPairing(env: Env) extends LilaController(env):
.fold(
jsonFormError,
data =>
env.setup.bulk(data, me) flatMap {
env.setup.bulk(data, me) flatMap:
case Left(SetupBulk.ScheduleError.RateLimited) =>
TooManyRequests:
jsonError(s"Ratelimited! Max games per 10 minutes: ${SetupBulk.maxGames}")
Expand All @@ -47,10 +44,8 @@ final class BulkPairing(env: Env) extends LilaController(env):
case Left(SetupBulk.ScheduleError.DuplicateUsers(users)) =>
BadRequest(Json.obj("duplicateUsers" -> users))
case Right(bulk) =>
env.challenge.bulk.schedule(bulk) map {
env.challenge.bulk.schedule(bulk) map:
case Left(error) => BadRequest(jsonError(error))
case Right(bulk) => JsonOk(SetupBulk toJson bulk)
}
}
)
}
2 changes: 1 addition & 1 deletion app/views/board/editor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ object editor:
.OpenGraph(
title = "Chess board editor",
url = s"$netBaseUrl${routes.Editor.index.url}",
description = "Load opening positions or create your own chess.Position on a chess board editor"
description = "Load opening positions or create your own chess position on a chess board editor"
)
.some
)(
Expand Down
9 changes: 3 additions & 6 deletions app/views/round/player.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,9 @@ object player:
div(cls := "round__underboard")(
bits.crosstable(cross, pov.game),
(playing.nonEmpty || simul.exists(_ isHost ctx.me)) option
div(
cls := List(
"round__now-playing" -> true,
"blindfold" -> pov.player.blindfold
)
)(bits.others(playing, simul.filter(_ isHost ctx.me)))
div(cls := "round__now-playing")(
bits.others(playing, simul.filter(_ isHost ctx.me))
)
),
div(cls := "round__underchat")(bits underchat pov.game)
)
2 changes: 2 additions & 0 deletions app/views/site/help.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ object help:
header(trans.other()),
flip,
zen,
row(frag(kbd("shift"), kbd("B")), "Toggle blindfold mode"),
helpDialog
)
)
Expand All @@ -60,6 +61,7 @@ object help:
header(trans.other()),
flip,
zen,
row(frag(kbd("shift"), kbd("B")), "Toggle blindfold mode"),
helpDialog
)
)
Expand Down
1 change: 1 addition & 0 deletions modules/api/src/main/GameApiV2.scala
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ final class GameApiV2(
.sortedCursor(
$inIds(config.ids),
Query.sortCreated,
hint = $id(1).some,
batchSize = config.perSecond.value
)
.documentSource()
Expand Down
25 changes: 9 additions & 16 deletions modules/challenge/src/main/ChallengeBulk.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import lila.setup.SetupBulk.{ ScheduledBulk, ScheduledGame, maxBulks }
import lila.user.User
import chess.{ Clock, ByColor, Speed }
import lila.common.config.Max
import lila.round.actorApi.round.StartClock

final class ChallengeBulkApi(
colls: ChallengeColls,
Expand Down Expand Up @@ -46,20 +47,19 @@ final class ChallengeBulkApi(
def deleteBy(id: String, me: User): Fu[Boolean] =
coll.delete.one($doc("_id" -> id, "by" -> me.id)).map(_.n == 1)

def startClocks(id: String, me: User): Fu[Boolean] =
def startClocksAsap(id: String, me: User): Fu[Boolean] =
coll
.updateField($doc("_id" -> id, "by" -> me.id, "pairedAt" $exists true), "startClocksAt", nowInstant)
.map(_.n == 1)

def schedule(bulk: ScheduledBulk): Fu[Either[String, ScheduledBulk]] = workQueue(bulk.by):
coll.list[ScheduledBulk]($doc("by" -> bulk.by, "pairedAt" $exists false)) flatMap { bulks =>
coll.list[ScheduledBulk]($doc("by" -> bulk.by, "pairedAt" $exists false)) flatMap: bulks =>
if bulks.sizeIs >= maxBulks then fuccess(Left("Already too many bulks queued"))
else if bulks.map(_.games.size).sum >= 1000
then fuccess(Left("Already too many games queued"))
else if bulks.exists(_ collidesWith bulk)
then fuccess(Left("A bulk containing the same players is scheduled at the same time"))
else coll.insert.one(bulk) inject Right(bulk)
}

private[challenge] def tick: Funit =
checkForPairing >> checkForClocks
Expand All @@ -72,14 +72,10 @@ final class ChallengeBulkApi(
makePairings(bulk).void

private def checkForClocks: Funit =
coll.one[ScheduledBulk]($doc("startClocksAt" $lte nowInstant, "pairedAt" $exists true)) flatMapz { bulk =>
coll.one[ScheduledBulk]($doc("startClocksAt" $lte nowInstant, "pairedAt" $exists true)) flatMapz: bulk =>
workQueue(bulk.by):
startClocksNow(bulk)
}

private def startClocksNow(bulk: ScheduledBulk): Funit =
Bus.publish(TellMany(bulk.games.map(_.id.value), lila.round.actorApi.round.StartClock), "roundSocket")
coll.delete.one($id(bulk._id)).void
fuccess:
Bus.publish(TellMany(bulk.games.map(_.id.value), StartClock), "roundSocket")

private def makePairings(bulk: ScheduledBulk): Funit =
def timeControl =
Expand All @@ -88,9 +84,8 @@ final class ChallengeBulkApi(
val perfType = PerfType(bulk.variant, Speed(bulk.clock.left.toOption))
Source(bulk.games)
.mapAsyncUnordered(8): game =>
userApi.gamePlayers.loggedIn(game.userIds, bulk.perfType, useCache = false) map2 { users =>
userApi.gamePlayers.loggedIn(game.userIds, bulk.perfType, useCache = false) map2: users =>
(game.id, users)
}
.mapConcat(_.toList)
.map: (id, users) =>
val game = Game
Expand Down Expand Up @@ -120,8 +115,6 @@ final class ChallengeBulkApi(
.toMat(LilaStream.sinkCount)(Keep.right)
.run()
.addEffect(lila.mon.api.challenge.bulk.createNb(bulk.by.value).increment(_))
.logFailure(logger, e => s"Bulk.makePairings ${bulk._id} ${e.getMessage}") >> {
if bulk.startClocksAt.isDefined
then coll.updateField($id(bulk._id), "pairedAt", nowInstant)
else coll.delete.one($id(bulk._id))
.logFailure(logger, e => s"Bulk.makePairings ${bulk.id} ${e.getMessage}") >> {
coll.updateField($id(bulk.id), "pairedAt", nowInstant)
}.void
4 changes: 3 additions & 1 deletion modules/game/src/main/GameRepo.scala
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,11 @@ final class GameRepo(val coll: Coll)(using Executor):
selector: Bdoc,
sort: Bdoc,
batchSize: Int = 0,
hint: Option[Bdoc] = none,
readPref: ReadPref = _.priTemp
): AkkaStreamCursor[Game] =
coll.find(selector).sort(sort).batchSize(batchSize).cursor[Game](readPref)
val query = coll.find(selector).sort(sort).batchSize(batchSize)
hint.map(coll.hint).foldLeft(query)(_ hint _).cursor[Game](readPref)

def byIdsCursor(ids: Iterable[GameId]): Cursor[Game] = coll.find($inIds(ids)).cursor[Game]()

Expand Down
2 changes: 1 addition & 1 deletion modules/game/src/main/JsonView.scala
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ final class JsonView(rematches: Rematches):
.add("ratingDiff" -> pov.player.ratingDiff)

def maybeFen(pov: Pov): Fen.Epd =
Fen.write(pov.game.chess)
if pov.player.blindfold then Fen.Epd("8/8/8/8/8/8/8/8") else Fen.write(pov.game.chess)

def player(p: Player, user: Option[LightUser]) =
Json
Expand Down
7 changes: 3 additions & 4 deletions modules/round/src/main/Finisher.scala
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,8 @@ final private class Finisher(
stats = lt.lagStats
moves = lt.moves if moves > 4
sd <- stats.stdDev
mean = stats.mean if mean > 0
uncompStats = lt.uncompStats
uncompAvg = Math.round(10 * uncompStats.mean)
mean = stats.mean if mean > 0
uncompAvg = Math.round(10 * lt.uncompStats.mean)
compEstStdErr <- lt.compEstStdErr
quotaStr = f"${lt.quotaGain.centis / 10}%02d"
compEstOvers = lt.compEstOvers.centis
Expand All @@ -87,7 +86,7 @@ final private class Finisher(
// wikipedia.org/wiki/Coefficient_of_variation#Estimation
lRec.coefVar.record(Math.round((1000f + 250f / moves) * sd / mean))
lRec.uncomped(quotaStr).record(uncompAvg)
uncompStats.stdDev foreach { v =>
lt.uncompStats.stdDev foreach { v =>
lRec.uncompStdDev(quotaStr).record(Math.round(10 * v))
}
lt.lagEstimator match
Expand Down
8 changes: 5 additions & 3 deletions modules/setup/src/main/SetupBulk.scala
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,10 @@ object SetupBulk:
case class ScheduledGame(id: GameId, white: UserId, black: UserId):
def userIds = ByColor(white, black)

type ID = String
import reactivemongo.api.bson.Macros.Annotations.Key
case class ScheduledBulk(
_id: String,
@Key("_id") id: ID,
by: UserId,
games: List[ScheduledGame],
variant: Variant,
Expand Down Expand Up @@ -152,7 +154,7 @@ object SetupBulk:
import lila.game.JsonView.given
Json
.obj(
"id" -> _id,
"id" -> id,
"games" -> games.map: g =>
Json.obj(
"id" -> g.id,
Expand Down Expand Up @@ -235,7 +237,7 @@ final class SetupBulkApi(oauthServer: OAuthServer, idGenerator: IdGenerator)(usi
case (id, (w, b)) => ScheduledGame(id, w, b)
.dmap:
ScheduledBulk(
_id = ThreadLocalRandom nextString 8,
id = ThreadLocalRandom nextString 8,
by = me.id,
_,
data.variant,
Expand Down
7 changes: 4 additions & 3 deletions modules/shutup/src/main/Dictionary.scala
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ milf
molest(er|ed|)
mong
monkey
moron
morr?on
mother(fuc?k(er|)|)
mthrfckr
nazi
Expand Down Expand Up @@ -263,6 +263,7 @@ mierda
moduler[ao]
payas[ao]
pendejo
po(ll|y)a
put[ao]
trampa
trampos[ao]
Expand Down Expand Up @@ -320,7 +321,7 @@ schwanzlutscher
schwuchtel
trottel
untermensch
wichser
wi(chs|x++)er
""")

def tr = dict("""
Expand Down Expand Up @@ -360,7 +361,7 @@ get bombed
k y s
ky5
(l|1|ı|\|)<ys
nigg?er
n[1i]gg?er
rap(ed?|e?ing)
subhuman
""")
Expand Down
2 changes: 1 addition & 1 deletion project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ object Dependencies {
val scalatags = "com.lihaoyi" %% "scalatags" % "0.12.0"
val lettuce = "io.lettuce" % "lettuce-core" % "6.3.1.RELEASE"
val nettyTransport =
"io.netty" % s"netty-transport-native-$notifier" % "4.1.105.Final" classifier s"$os-$arch"
"io.netty" % s"netty-transport-native-$notifier" % "4.1.106.Final" classifier s"$os-$arch"
val munit = "org.scalameta" %% "munit" % "1.0.0-M10" % Test
val uaparser = "org.uaparser" %% "uap-scala" % "0.16.0"
val apacheText = "org.apache.commons" % "commons-text" % "1.11.0"
Expand Down
7 changes: 5 additions & 2 deletions ui/analyse/src/view/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,11 @@ function controls(ctrl: AnalyseCtrl) {
else if (action === 'explorer') ctrl.toggleExplorer();
else if (action === 'practice') ctrl.togglePractice();
else if (action === 'menu') ctrl.actionMenu.toggle();
else if (action === 'analysis' && ctrl.studyPractice)
window.open(ctrl.studyPractice.analysisUrl(), '_blank', 'noopener');
else if (action === 'analysis' && ctrl.studyPractice) {
if (!window.open(ctrl.studyPractice.analysisUrl(), '_blank', 'noopener')) {
window.location.href = ctrl.studyPractice.analysisUrl(); //safari
}
}
}, ctrl.redraw),
),
},
Expand Down
6 changes: 4 additions & 2 deletions ui/ceval/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,18 @@ export const sharedWasmMemory = (lo: number, hi = 32767): WebAssembly.Memory =>
};

export function showEngineError(engine: string, error: string) {
console.log(error);
domDialog({
class: 'engine-error',
htmlText:
`<h2>${lichess.escapeHtml(engine)} <bad>error</bad></h2>` + error.includes('Status 503')
`<h2>${lichess.escapeHtml(engine)} <bad>error</bad></h2>` +
(error.includes('Status 503')
? `<p>Your external engine does not appear to be connected.</p>
<p>Please check the network and restart your provider if possible.</p>`
: `${lichess.escapeHtml(error)}</pre><h2>Things to try</h2><ul>
<li>Decrease memory slider in engine settings</li>
<li>Clear site settings for lichess.org</li>
<li>Select another engine</li><li>Update your browser</li></ul>`,
<li>Select another engine</li><li>Update your browser</li></ul>`),
}).then((dlg: Dialog) => {
const select = () =>
setTimeout(() => {
Expand Down
4 changes: 1 addition & 3 deletions ui/lobby/src/ctrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ export default class LobbyController {

const locationHash = location.hash.replace('#', '');
if (['ai', 'friend', 'hook'].includes(locationHash)) {
let friendUser: string;
const forceOptions: ForceSetupOptions = {};
const urlParams = new URLSearchParams(location.search);
const friendUser = urlParams.get('user') ?? undefined;
if (locationHash === 'hook') {
if (urlParams.get('time') === 'realTime') {
this.tab = 'real_time';
Expand All @@ -88,8 +88,6 @@ export default class LobbyController {
} else if (urlParams.get('fen')) {
forceOptions.fen = urlParams.get('fen')!;
forceOptions.variant = 'fromPosition';
} else {
friendUser = urlParams.get('user')!;
}

loadDialogPolyfill.then(() => {
Expand Down
2 changes: 1 addition & 1 deletion ui/puzzle/src/keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default (ctrl: PuzzleCtrl) =>
.bind('?', () => ctrl.keyboardHelp(!ctrl.keyboardHelp()))
.bind('f', ctrl.flip)
.bind('n', ctrl.nextPuzzle)
.bind('b', () => ctrl.blindfold(!ctrl.blindfold()));
.bind('B', () => ctrl.blindfold(!ctrl.blindfold()));

export const view = (ctrl: PuzzleCtrl) =>
snabDialog({
Expand Down
1 change: 1 addition & 0 deletions ui/round/src/keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const init = (ctrl: RoundController) =>
})
.bind('f', ctrl.flipNow)
.bind('z', () => lichess.pubsub.emit('zen'))
.bind('B', () => ctrl.blindfold(!ctrl.blindfold()))
.bind('?', () => {
ctrl.keyboardHelp = !ctrl.keyboardHelp;
ctrl.redraw();
Expand Down

0 comments on commit f65bc4d

Please sign in to comment.