Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
ornicar committed Jul 9, 2024
2 parents 1dc1ffd + b6cfd10 commit fd6f524
Show file tree
Hide file tree
Showing 133 changed files with 540 additions and 498 deletions.
11 changes: 3 additions & 8 deletions app/controllers/Report.scala
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,9 @@ final class Report(env: Env, userC: => User, modC: => Mod) extends LilaControlle
val form = env.report.forms.create
val filledForm: Form[lila.report.ReportSetup] = (user, get("postUrl")) match
case (Some(u), Some(pid)) =>
form.fill:
lila.report.ReportSetup(
u.light,
reason = ~get("reason"),
text = s"$pid\n\n"
)
form.fill(lila.report.ReportSetup(u.light, reason = "", text = s"$pid\n\n"))
case _ => form
views.report.ui.form(filledForm, user)
views.report.ui.form(filledForm, user, get("from"))
}
}

Expand All @@ -162,7 +157,7 @@ final class Report(env: Env, userC: => User, modC: => Mod) extends LilaControlle
err =>
for
user <- getUserStr("username").so(env.user.repo.byId)
page <- renderPage(views.report.ui.form(err, user))
page <- renderPage(views.report.ui.form(err, user, none))
yield BadRequest(page),
data =>
if me.is(data.user.id) then BadRequest("You cannot report yourself")
Expand Down
3 changes: 2 additions & 1 deletion app/controllers/Tournament.scala
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ final class Tournament(env: Env, apiC: => Api)(using akka.stream.Materializer) e
fail: => Fu[Result]
)(create: => Fu[Result])(using me: Me, req: RequestHeader): Fu[Result] =
val cost =
if isGranted(_.ManageTournament) then 2
if me.is(UserId.lichess) then 1
else if isGranted(_.ManageTournament) then 2
else if me.hasTitle ||
env.streamer.liveStreamApi.isStreaming(me) ||
me.isVerified ||
Expand Down
2 changes: 1 addition & 1 deletion modules/chat/src/main/Chat.scala
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,10 @@ object Chat:

import BSONFields.*
import reactivemongo.api.bson.BSONDocument
import lila.chat.Line.given
import lila.db.dsl.given

given BSONDocumentHandler[MixedChat] = new BSON[MixedChat]:
import lila.chat.Line.given
def reads(r: BSON.Reader): MixedChat =
MixedChat(
id = r.get[ChatId](id),
Expand Down
19 changes: 10 additions & 9 deletions modules/chat/src/main/Line.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package lila.chat

import reactivemongo.api.bson.*

import chess.{ Color, PlayerTitle }

case class UserLine(
Expand All @@ -23,6 +25,12 @@ case class UserLine(

def isLichess = userId.is(UserId.lichess)

object UserLine:
private[chat] given BSONHandler[UserLine] = BSONStringHandler.as[UserLine](
v => Line.strToUserLine(v).getOrElse(Line.invalidLine),
Line.userLineToStr
)

case class PlayerLine(color: Color, text: String) extends Line:
def deleted = false
def author = color.name
Expand All @@ -35,16 +43,9 @@ object Line:
val textMaxSize = 140
val titleSep = '~'

import reactivemongo.api.bson.*

private val invalidLine =
private[chat] val invalidLine =
UserLine(UserName(""), None, false, false, "[invalid character]", troll = false, deleted = true)

private[chat] given BSONHandler[UserLine] = BSONStringHandler.as[UserLine](
v => strToUserLine(v).getOrElse(invalidLine),
userLineToStr
)

private[chat] given lineHandler: BSONHandler[lila.core.chat.Line] =
BSONStringHandler.as[lila.core.chat.Line](
v => strToLine(v).getOrElse(invalidLine),
Expand All @@ -59,7 +60,7 @@ object Line:
private val UserLineRegex = {
"""(?s)([\w-~]{2,}+)([ """ + s"$trollChar$deletedChar$patronChar$flairChar$patronFlairChar" + """])(.++)"""
}.r
private def strToUserLine(str: String): Option[UserLine] = str match
private[chat] def strToUserLine(str: String): Option[UserLine] = str match
case UserLineRegex(username, sep, text) =>
val troll = sep == trollChar
val deleted = sep == deletedChar
Expand Down
8 changes: 5 additions & 3 deletions modules/common/src/main/Json.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package lila.common

import play.api.libs.json.{ Json as PlayJson, * }
import scala.util.NotGiven
import io.mola.galimatias.URL

object Json:
Expand All @@ -20,11 +19,14 @@ object Json:

given Writes[URL] = url => JsString(url.toString)

given [A](using Show[A]): KeyWrites[A] with
def writeKey(key: A) = key.show
given Writes[chess.PlayerTitle] = tile => JsString(tile.value)

given NoJsonHandler[chess.Square] with {}

// could be in scalalib
given [A](using sr: SameRuntime[A, String]): KeyWrites[A] with
def writeKey(key: A) = sr(key)

import lila.core.LightUser
given lightUserWrites: OWrites[LightUser] = OWrites(lightUser.write)
object lightUser:
Expand Down
3 changes: 2 additions & 1 deletion modules/core/src/main/perf.scala
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ object perf:
def value: String = key
def id: PerfId = keyIdMap(key)

given Show[PerfKey] = _.value
given Show[PerfKey] = _.value
given SameRuntime[PerfKey, String] = _.value

def apply(key: String): Option[PerfKey] = Option.when(all.contains(key))(key)
def apply(variant: Variant, speed: Speed): PerfKey = byVariant(variant) | standardBySpeed(speed)
Expand Down
51 changes: 24 additions & 27 deletions modules/db/src/main/Handlers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,24 @@ trait Handlers:

// free handlers for all types with TotalWrapper
// unless they are given an instance of lila.db.NoDbHandler[T]
given opaqueHandler[T, A](using
sr: SameRuntime[A, T],
given opaqueWriter[T, A](using
rs: SameRuntime[T, A],
handler: BSONHandler[A]
)(using NotGiven[NoDbHandler[T]]): BSONHandler[T] =
handler.as(sr.apply, rs.apply)
writer: BSONWriter[A]
)(using NotGiven[NoDbHandler[T]]): BSONWriter[T] with
def writeTry(t: T) = writer.writeTry(rs(t))

given listHandler[T: BSONHandler]: BSONHandler[List[T]] with
val reader = collectionReader[List, T]
val writer = BSONWriter.collectionWriter[T, List[T]]
def readTry(bson: BSONValue): Try[List[T]] = reader.readTry(bson)
def writeTry(t: List[T]): Try[BSONValue] = writer.writeTry(t)
given opaqueReader[T, A](using
sr: SameRuntime[A, T],
reader: BSONReader[A]
): BSONReader[T] with
def readTry(bson: BSONValue) = reader.readTry(bson).map(sr.apply)

given userIdOfWriter[U: UserIdOf, T](using writer: BSONWriter[UserId]): BSONWriter[U] with
given userIdOfWriter[U: UserIdOf](using writer: BSONWriter[UserId]): BSONWriter[U] with
inline def writeTry(u: U) = writer.writeTry(u.id)
given noUserIdOf[A: lila.core.userId.UserIdOf]: NoDbHandler[A] with {}

given NoDbHandler[UserId] with {}
given userIdHandler: BSONHandler[UserId] = stringIsoHandler

given dateTimeHandler: BSONHandler[LocalDateTime] = quickHandler[LocalDateTime](
{ case v: BSONDateTime => millisToDateTime(v.value) },
Expand Down Expand Up @@ -108,18 +111,18 @@ trait Handlers:
leftHandler.readTry(bson).map(Left.apply).orElse(rightHandler.readTry(bson).map(Right.apply))
def writeTry(e: Either[L, R]) = e.fold(leftHandler.writeTry, rightHandler.writeTry)

def stringMapHandler[V](using
reader: BSONReader[Map[String, V]],
writer: BSONWriter[Map[String, V]]
): BSONHandler[Map[String, V]] = new:
def readTry(bson: BSONValue) = reader.readTry(bson)
def writeTry(v: Map[String, V]) = writer.writeTry(v)
given mapHandler[V: BSONHandler]: BSONHandler[Map[String, V]] = new:
def readTry(bson: BSONValue) = BSONReader.mapReader.readTry(bson)
def writeTry(v: Map[String, V]) = BSONWriter.mapWriter.writeTry(v)

def typedMapHandler[K, V: BSONHandler](using sr: SameRuntime[K, String], rs: SameRuntime[String, K]) =
stringMapHandler[V].as[Map[K, V]](_.mapKeys(rs(_)), _.mapKeys(sr(_)))
def typedMapHandler[K, V: BSONHandler](using
sr: SameRuntime[K, String],
rs: SameRuntime[String, K]
): BSONHandler[Map[K, V]] =
mapHandler[V].as[Map[K, V]](_.mapKeys(rs(_)), _.mapKeys(sr(_)))

def typedMapHandlerIso[K, V: BSONHandler](using keyIso: StringIso[K]) =
stringMapHandler[V].as[Map[K, V]](_.mapKeys(keyIso.from), _.mapKeys(keyIso.to))
def typedMapHandlerIso[K, V: BSONHandler](using keyIso: StringIso[K]): BSONHandler[Map[K, V]] =
mapHandler[V].as[Map[K, V]](_.mapKeys(keyIso.from), _.mapKeys(keyIso.to))

def ifPresentHandler[A](a: A) = quickHandler({ case BSONBoolean(true) => a }, _ => BSONBoolean(true))

Expand All @@ -135,12 +138,6 @@ trait Handlers:
nel => listWriter.writeTry(nel.toList).get
)

given vectorHandler[T: BSONHandler]: BSONHandler[Vector[T]] with
val reader = collectionReader[Vector, T]
val writer = BSONWriter.collectionWriter[T, Vector[T]]
def readTry(bson: BSONValue): Try[Vector[T]] = reader.readTry(bson)
def writeTry(t: Vector[T]): Try[BSONValue] = writer.writeTry(t)

given BSONWriter[BSONNull.type] with
def writeTry(n: BSONNull.type) = Success(BSONNull)

Expand Down
2 changes: 1 addition & 1 deletion modules/forum/src/main/ui/PostUi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ final class PostUi(helpers: Helpers, bits: ForumBits):
cls := "mod report button button-empty",
href := addQueryParams(
routes.Report.form.url,
Map("username" -> userId.value, "postUrl" -> postUrl, "reason" -> "comm")
Map("username" -> userId.value, "postUrl" -> postUrl, "from" -> "forum")
),
dataIcon := Icon.CautionTriangle
)
Expand Down
2 changes: 1 addition & 1 deletion modules/notify/src/main/NotificationPref.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ object NotificationPref:
)(NotificationPref.apply)(lila.notify.unapply)
)

import lila.db.dsl.opaqueHandler
import lila.db.dsl.given
given BSONDocumentHandler[NotificationPref] = Macros.handler

import play.api.libs.json.{ Json, Writes, OWrites }
Expand Down
1 change: 1 addition & 0 deletions modules/plan/src/main/Currency.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import scala.util.Try
import lila.common.autoconfig.AutoConfig
import lila.common.config.given
import lila.core.config.Secret
import lila.db.dsl.mapHandler

case class CurrencyWithRate(currency: Currency, rate: Double)

Expand Down
2 changes: 1 addition & 1 deletion modules/relay/src/main/BSONHandlers.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package lila.relay

import reactivemongo.api.bson.*
import reactivemongo.api.bson.{ BSONDocumentHandler, BSONHandler, Macros }

import lila.db.BSON
import lila.db.dsl.{ *, given }
Expand Down
7 changes: 5 additions & 2 deletions modules/relay/src/main/ui/FormUi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ final class FormUi(helpers: Helpers, ui: RelayUi, tourUi: RelayTourUi):
url: play.api.mvc.Call,
nav: FormNavigation
)(using ctx: Context) =
val broadcastEmailContact = a(href := "mailto:[email protected]")("[email protected]")
val lccWarning = nav.round
.flatMap(_.sync.upstream)
.exists(_.hasLcc)
Expand All @@ -163,7 +164,9 @@ final class FormUi(helpers: Helpers, ui: RelayUi, tourUi: RelayTourUi):
p(
"LiveChessCloud support is deprecated and will be removed soon.",
br,
"If you need help, please contact us at [email protected]."
s"If you need help, please contact us at ",
broadcastEmailContact,
"."
)
)
val contactUsForOfficial = nav.featurableRound.isDefined
Expand All @@ -174,7 +177,7 @@ final class FormUi(helpers: Helpers, ui: RelayUi, tourUi: RelayTourUi):
a(href := routes.RelayTour.index(1))("broadcast page"),
"?"
),
p(trans.contact.sendEmailAt("[email protected]"))
p(trans.contact.sendEmailAt(broadcastEmailContact))
)
postForm(cls := "form3", action := url)(
(!Granter.opt(_.StudyAdmin)).option:
Expand Down
11 changes: 9 additions & 2 deletions modules/report/src/main/ui/ReportUi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ final class ReportUi(helpers: Helpers):
import helpers.{ given, * }
import ReportUi.*

def form(form: Form[?], reqUser: Option[User] = None)(using ctx: Context) =
def filterReason(from: Option[String])(reason: Reason): Boolean = from match
case Some("forum") => reason.isComm
case _ => true

def form(form: Form[?], reqUser: Option[User] = None, from: Option[String])(using ctx: Context) =
Page(trans.site.reportAUser.txt())
.css("bits.form3")
.js(
Expand Down Expand Up @@ -65,7 +69,8 @@ final class ReportUi(helpers: Helpers):
form3.group(form("reason"), trans.site.reason()): f =>
form3.select(
f,
translatedReasonChoices.map((r, t) => (r.key, t)),
translatedReasonChoices.collect:
case (r, t) if filterReason(from)(r) => (r.key, t),
trans.site.whatIsIheMatter.txt().some
)
,
Expand Down Expand Up @@ -95,7 +100,9 @@ final class ReportUi(helpers: Helpers):
else
"Please provide as much information as possible, including relevant game links, posts, and messages."
,
" ",
englishPlease,
" ",
maxLength
)

Expand Down
16 changes: 7 additions & 9 deletions modules/security/src/main/GarbageCollector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,12 @@ final class GarbageCollector(
logger.debug(s"other ${data.user.username} others=${others.map(_.username)}")
spy.ips
.existsM(ipTrust.isSuspicious)
.map:
_.so(
collect(
user,
email,
msg = s"Prev users: ${others.map(o => "@" + o.username).mkString(", ")}",
quickly = quickly
)
.mapz:
collect(
user,
email,
msg = s"Prev users: ${others.map(o => "@" + o.username).mkString(", ")}",
quickly = quickly
)
yield ()

Expand All @@ -98,7 +96,7 @@ final class GarbageCollector(
hasBeenCollectedBefore(user).not.map {
if _ then
val armed = isArmed()
val wait = if quickly then 3.seconds else (30 + ThreadLocalRandom.nextInt(300)).seconds
val wait = if quickly then 3.seconds else (30 + ThreadLocalRandom.nextInt(240)).seconds
val message =
s"Will dispose of https://lichess.org/${user.username} in $wait. Email: ${email.value}. $msg${(!armed)
.so(" [SIMULATION]")}"
Expand Down
2 changes: 2 additions & 0 deletions modules/study/src/main/BSONHandlers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ object BSONHandlers:
private[study] given dbMemberHandler: BSONDocumentHandler[DbMember] = Macros.handler
private[study] given BSONDocumentWriter[StudyMember] with
def writeTry(x: StudyMember) = Success($doc("role" -> x.role))

private[study] given (using handler: BSONHandler[Map[String, DbMember]]): BSONHandler[StudyMembers] =
handler.as[StudyMembers](
members =>
Expand All @@ -367,6 +368,7 @@ object BSONHandlers:
}),
_.members.view.map((id, m) => id.value -> DbMember(m.role)).toMap
)

import lila.core.study.Visibility
private[study] given BSONHandler[Visibility] = tryHandler[Visibility](
{ case BSONString(v) => Visibility.byKey.get(v).toTry(s"Invalid visibility $v") },
Expand Down
2 changes: 1 addition & 1 deletion modules/study/src/main/StudyMember.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ case class StudyMembers(members: StudyMember.MemberMap):
}.toMap
)

def contains[U: UserIdOf](u: U): Boolean = members contains u.id
def contains[U: UserIdOf](u: U): Boolean = members.contains(u.id)

export members.{ get, keys as ids, keySet as idSet }

Expand Down
1 change: 1 addition & 0 deletions modules/team/src/main/JsonView.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ final class JsonView(lightUserApi: LightUserApi, userJson: lila.core.user.JsonVi
"leader" -> lightUserApi.sync(team.createdBy), // for BC
"nbMembers" -> team.nbMembers
)
.add("flair" -> team.flair)

given memberWithPermsWrites: OWrites[TeamMember] = OWrites: m =>
Json.obj("user" -> lightUserApi.syncFallback(m.user), "perms" -> m.perms.map(_.key))
Expand Down
Loading

0 comments on commit fd6f524

Please sign in to comment.