Skip to content

Commit

Permalink
replace play.api.i18n.Lang with lila.common.Lang
Browse files Browse the repository at this point in the history
as to make sure their default implicit doesn't sneak
where it shouldn't.
Using a default lang is now made explicit by
lila.i18n.defaultLang
  • Loading branch information
ornicar committed Dec 5, 2018
1 parent ce487f5 commit 4a2ee05
Show file tree
Hide file tree
Showing 39 changed files with 100 additions and 77 deletions.
2 changes: 1 addition & 1 deletion app/controllers/Bot.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ object Bot extends LilaController {
}
case Array("game", id, "chat") => WithBot(me) {
Env.bot.form.chat.bindFromRequest.fold(
jsonFormError,
jsonFormErrorDefaultLang,
res => WithMyBotGame(id, me) { pov =>
Env.bot.player.chat(pov.gameId, me, res) inject jsonOkResult
}
Expand Down
9 changes: 6 additions & 3 deletions app/controllers/LilaController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import scalatags.Text.{ TypedTag, Frag }

import lila.api.{ PageData, Context, HeaderContext, BodyContext }
import lila.app._
import lila.common.{ LilaCookie, HTTPRequest, ApiVersion, Nonce }
import lila.common.{ LilaCookie, HTTPRequest, ApiVersion, Nonce, Lang }
import lila.notify.Notification.Notifies
import lila.oauth.{ OAuthScope, OAuthServer }
import lila.security.{ Permission, Granter, FingerprintedUser }
Expand Down Expand Up @@ -476,7 +476,7 @@ private[controllers] trait LilaController
) andThen (__ \ "").json.prune
}

protected def errorsAsJson(form: Form[_])(implicit lang: play.api.i18n.Lang): JsObject = {
protected def errorsAsJson(form: Form[_])(implicit lang: Lang): JsObject = {
val json = JsObject(
form.errors.groupBy(_.key).mapValues { errors =>
JsArray {
Expand All @@ -489,9 +489,12 @@ private[controllers] trait LilaController
json validate jsonGlobalErrorRenamer getOrElse json
}

protected def jsonFormError(err: Form[_])(implicit lang: play.api.i18n.Lang) =
protected def jsonFormError(err: Form[_])(implicit lang: Lang) =
fuccess(BadRequest(ridiculousBackwardCompatibleJsonError(errorsAsJson(err))))

protected def jsonFormErrorDefaultLang(err: Form[_]) =
jsonFormError(err)(lila.i18n.defaultLang)

protected def pageHit(implicit ctx: lila.api.Context) =
if (HTTPRequest isHuman ctx.req) lila.mon.http.request.path(ctx.req.path)()

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Tournament.scala
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ object Tournament extends LilaController {

private def doApiCreate(me: lila.user.User)(implicit req: Request[_]): Fu[Result] =
env.forms(me).bindFromRequest.fold(
jsonFormError,
jsonFormErrorDefaultLang,
setup => teamsIBelongTo(me) flatMap { teams =>
env.api.createTournament(setup, me, teams, getUserTeamIds) flatMap { tour =>
Env.tournament.jsonView(tour, none, none, getUserTeamIds, none, none, partial = false, lila.i18n.defaultLang)
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/User.scala
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ object User extends LilaController {

def apiWriteNote(username: String) = ScopedBody() { implicit req => me =>
doWriteNote(username, me)(
err = err => _ => jsonFormError(err),
err = err => _ => jsonFormErrorDefaultLang(err),
suc = jsonOkResult
)
}
Expand Down
12 changes: 6 additions & 6 deletions app/templating/DateHelper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,21 @@ trait DateHelper { self: I18nHelper =>

private def dateTimeFormatter(ctx: Context): DateTimeFormatter =
dateTimeFormatters.getOrElseUpdate(
lang(ctx).code,
DateTimeFormat forStyle dateTimeStyle withLocale lang(ctx).toLocale
ctx.lang.code,
DateTimeFormat forStyle dateTimeStyle withLocale ctx.lang.toLocale
)

private def dateFormatter(ctx: Context): DateTimeFormatter =
dateFormatters.getOrElseUpdate(
lang(ctx).code,
DateTimeFormat forStyle dateStyle withLocale lang(ctx).toLocale
ctx.lang.code,
DateTimeFormat forStyle dateStyle withLocale ctx.lang.toLocale
)

private def periodFormatter(ctx: Context): PeriodFormatter =
periodFormatters.getOrElseUpdate(
lang(ctx).code, {
ctx.lang.code, {
Locale setDefault Locale.ENGLISH
PeriodFormat wordBased lang(ctx).toLocale
PeriodFormat wordBased ctx.lang.toLocale
}
)

Expand Down
4 changes: 2 additions & 2 deletions app/templating/I18hHelper.scala
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package lila.app
package templating

import play.api.i18n.Lang
import play.api.libs.json.JsObject
import play.twirl.api.Html

import lila.common.Lang
import lila.i18n.{ LangList, I18nKey, Translator, JsQuantity, I18nDb, JsDump, TimeagoLocales }
import lila.user.UserContext

trait I18nHelper {

implicit def lang(implicit ctx: UserContext) = ctx.lang
implicit def ctxLang(implicit ctx: UserContext): Lang = ctx.lang

def transKey(key: String, db: I18nDb.Ref, args: Seq[Any] = Nil)(implicit lang: Lang): Html =
Translator.html.literal(key, db, args, lang)
Expand Down
6 changes: 3 additions & 3 deletions app/templating/NumberHelper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ trait NumberHelper { self: I18nHelper =>

private def formatter(implicit ctx: UserContext): NumberFormat =
formatters.getOrElseUpdate(
lang(ctx).language,
NumberFormat getInstance new Locale(lang(ctx).language)
ctx.lang.language,
NumberFormat getInstance new Locale(ctx.lang.language)
)

def showMillis(millis: Int)(implicit ctx: UserContext) = formatter format ((millis / 100).toDouble / 10)
def showMillis(millis: Int)(implicit ctx: UserContext) = formatter.format((millis / 100).toDouble / 10)

implicit def richInt(number: Int) = new {
def localize(implicit ctx: UserContext): String = formatter format number
Expand Down
2 changes: 0 additions & 2 deletions app/ui/scalatags.scala
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ trait ScalatagsTemplate extends Styles
with ScalatagsPrefix {

val trans = lila.i18n.I18nKeys

implicit def lang(implicit ctx: lila.user.UserContext) = ctx.lang
}

object ScalatagsTemplate extends ScalatagsTemplate
Expand Down
2 changes: 1 addition & 1 deletion app/views/analyse/embed.scala.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
@title = @{ s"${playerText(pov.game.whitePlayer)} vs ${playerText(pov.game.blackPlayer)} in ${pov.gameId} : ${pov.game.opening.fold(trans.analysis.txt())(_.opening.ecoName)}" }

<!doctype html>
<html lang="@lang.language">
<html lang="@ctx.lang.language">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="@defaultCsp">
Expand Down
2 changes: 1 addition & 1 deletion app/views/board/bits.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ object bits {
"duration" -> ctx.pref.animationFactor * animationDuration.toMillis
),
"is3d" -> ctx.pref.is3d,
"i18n" -> i18nJsObject(translations)
"i18n" -> i18nJsObject(translations)(ctxLang(ctx))
)

def domPreload(pov: Option[lila.game.Pov])(implicit ctx: Context) = {
Expand Down
2 changes: 1 addition & 1 deletion app/views/puzzle/embed.scala.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
@(daily: lila.puzzle.DailyPuzzle)(implicit ctx: Context)

<!doctype html>
<html lang="@lang.language">
<html lang="@ctx.lang.language">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="@defaultCsp">
Expand Down
3 changes: 1 addition & 2 deletions modules/api/src/main/Context.scala
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package lila.api

import play.api.mvc.RequestHeader
import play.api.i18n.Lang

import lila.common.{ HTTPRequest, Nonce }
import lila.common.{ HTTPRequest, Nonce, Lang }
import lila.pref.Pref
import lila.relation.actorApi.OnlineFriends
import lila.user.{ UserContext, HeaderUserContext, BodyUserContext }
Expand Down
4 changes: 2 additions & 2 deletions modules/challenge/src/main/JsonView.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package lila.challenge

import play.api.i18n.Lang
import play.api.libs.json._

import lila.common.Lang
import lila.i18n.{ I18nKeys => trans }
import lila.socket.UserLagCache
import lila.socket.Socket.SocketVersion
import lila.socket.UserLagCache

final class JsonView(
getLightUser: lila.common.LightUser.GetterSync,
Expand Down
7 changes: 4 additions & 3 deletions modules/common/src/main/DetectLanguage.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package lila.common

import play.api.i18n.Lang
import play.api.libs.json._
import play.api.libs.ws.WS
import play.api.Play.current
Expand All @@ -18,8 +17,10 @@ final class DetectLanguage(url: String, key: String) {

private val messageMaxLength = 2000

private val defaultLang = Lang("en")

def apply(message: String): Fu[Option[Lang]] =
if (key.isEmpty) fuccess(Lang("en").some)
if (key.isEmpty) fuccess(defaultLang.some)
else WS.url(url).post(Map(
"key" -> Seq(key),
"q" -> Seq(message take messageMaxLength)
Expand All @@ -35,7 +36,7 @@ final class DetectLanguage(url: String, key: String) {
} recover {
case e: Exception =>
lila.log("DetectLanguage").warn(e.getMessage, e)
Lang("en").some
defaultLang.some
}
}

Expand Down
24 changes: 24 additions & 0 deletions modules/common/src/main/Lang.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package lila.common

import play.api.i18n.{ Lang => PlayLang }

/* Play has an implicit Lang that is made available every-fucking-where
* by the fact that it comes from its companion object.
* Therefore we can't trust any implicit Lang value.
* This type works around that */
case class Lang(value: PlayLang) extends AnyVal {

def language = value.language
def code = value.code
def toLocale = value.toLocale

def is(other: Lang) = other.code == code
}

object Lang {

def apply(language: String): Lang = Lang(PlayLang(language))
def apply(language: String, country: String): Lang = Lang(PlayLang(language, country))

def get(code: String): Option[Lang] = PlayLang get code map apply
}
3 changes: 0 additions & 3 deletions modules/common/src/main/PlayApp.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package lila.common

import com.typesafe.config.Config
import org.joda.time.{ DateTime, Period }
import play.api.i18n.Lang
import play.api.{ Play, Application, Mode }
import scala.collection.JavaConversions._

Expand Down Expand Up @@ -30,8 +29,6 @@ object PlayApp {
play.api.libs.concurrent.Akka.system
}

lazy val langs = loadConfig.getStringList("play.i18n.langs").map(Lang.apply)(scala.collection.breakOut)

private def enableScheduler = !(loadConfig getBoolean "app.scheduler.disabled")

lazy val scheduler = new Scheduler(
Expand Down
2 changes: 1 addition & 1 deletion modules/event/src/main/BsonHandlers.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package lila.event

import reactivemongo.bson._
import play.api.i18n.Lang

import lila.common.Lang
import lila.db.dsl._

private[event] object BsonHandlers {
Expand Down
3 changes: 2 additions & 1 deletion modules/event/src/main/Event.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package lila.event

import org.joda.time.DateTime
import play.api.i18n.Lang

import lila.common.Lang

case class Event(
_id: String,
Expand Down
2 changes: 1 addition & 1 deletion modules/event/src/main/EventForm.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import org.joda.time.DateTime
import play.api.data._
import play.api.data.Forms._
import play.api.data.validation.Constraints._
import play.api.i18n.Lang

import lila.i18n.LangList
import lila.common.Lang

object EventForm {

Expand Down
4 changes: 3 additions & 1 deletion modules/i18n/src/main/I18nDb.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package lila.i18n

import lila.common.Lang

object I18nDb {

sealed trait Ref
Expand All @@ -26,5 +28,5 @@ object I18nDb {
case Coordinates => coordinates
}

val langs = site.keySet
val langs: Set[Lang] = site.keys.map(Lang.apply)(scala.collection.breakOut)
}
3 changes: 2 additions & 1 deletion modules/i18n/src/main/I18nKey.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package lila.i18n

import play.api.i18n.Lang
import play.twirl.api.Html

import lila.user.UserContext
import lila.common.Lang

sealed trait I18nKey {

Expand Down
6 changes: 3 additions & 3 deletions modules/i18n/src/main/I18nLangPicker.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package lila.i18n

import play.api.i18n.Lang
import play.api.mvc.RequestHeader

import lila.common.Lang
import lila.user.User

object I18nLangPicker {
Expand All @@ -18,12 +18,12 @@ object I18nLangPicker {

def bestFromRequestHeaders(req: RequestHeader): Option[Lang] =
req.acceptLanguages.foldLeft(none[Lang]) {
case (None, lang) => findCloser(lang)
case (None, lang) => findCloser(Lang(lang))
case (found, _) => found
}

def allFromRequestHeaders(req: RequestHeader): List[Lang] =
req.acceptLanguages.flatMap(findCloser).distinct.toList
req.acceptLanguages.flatMap(l => findCloser(Lang(l))).distinct.toList

def byStr(str: String): Option[Lang] =
Lang get str flatMap findCloser
Expand Down
2 changes: 1 addition & 1 deletion modules/i18n/src/main/I18nQuantity.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package lila.i18n

import play.api.i18n.Lang
import lila.common.Lang

private sealed trait I18nQuantity

Expand Down
10 changes: 5 additions & 5 deletions modules/i18n/src/main/JsDump.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package lila.i18n
import java.io._
import scala.concurrent.Future
import scala.collection.JavaConversions._

import play.api.i18n.Lang
import play.api.libs.json.{ JsString, JsObject }

import lila.common.Lang

private[i18n] final class JsDump(path: String) {

def apply: Funit = Future {
Expand All @@ -30,7 +30,7 @@ private[i18n] final class JsDump(path: String) {
)

private def writeFullJson = I18nDb.langs foreach { lang =>
val code = dumpFromKey(asScalaSet(I18nDb.site(defaultLang).keySet).toSet, lang)
val code = dumpFromKey(asScalaSet(I18nDb.site(defaultLang.value).keySet).toSet, lang)
val file = new File("%s/%s.all.json".format(pathFile.getCanonicalPath, lang.code))
writeFile(new File("%s/%s.all.json".format(pathFile.getCanonicalPath, lang.code)), code)
}
Expand Down Expand Up @@ -74,9 +74,9 @@ object JsDump {
val emptyMessages: MessageMap = new java.util.HashMap()

def dbToObject(ref: I18nDb.Ref, lang: Lang): JsObject =
I18nDb(ref).get(defaultLang) ?? { defaultMsgs =>
I18nDb(ref).get(defaultLang.value) ?? { defaultMsgs =>
JsObject {
val msgs = I18nDb(ref).get(lang) | emptyMessages
val msgs = I18nDb(ref).get(lang.value) | emptyMessages
defaultMsgs.flatMap {
case (k, v) => translatedJs(k, msgs.getOrDefault(k, v), lang)
}
Expand Down
2 changes: 1 addition & 1 deletion modules/i18n/src/main/JsQuantity.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package lila.i18n

import play.api.i18n.Lang
import lila.common.Lang

object JsQuantity {
private def body(lang: Lang): String = lang.language match {
Expand Down
Loading

0 comments on commit 4a2ee05

Please sign in to comment.