Skip to content

Commit 55a345a

Browse files
committed
swiss WIP
1 parent f92322c commit 55a345a

File tree

10 files changed

+189
-13
lines changed

10 files changed

+189
-13
lines changed

app/controllers/Round.scala

+2-2
Original file line numberDiff line numberDiff line change
@@ -233,10 +233,10 @@ final class Round(
233233
(game.tournamentId, game.simulId) match {
234234
case (Some(tid), _) => {
235235
ctx.isAuth && tour.fold(true)(tournamentC.canHaveChat(_, none))
236-
} ?? env.chat.api.userChat.cached.findMine(Chat.Id(tid), ctx.me).map(toEventChat(s"tournament/$tid"))
236+
} ?? env.chat.api.userChat.cached.findMine(Chat.Id(tid), ctx.me).dmap(toEventChat(s"tournament/$tid"))
237237
case (_, Some(_)) =>
238238
game.simulId.?? { sid =>
239-
env.chat.api.userChat.cached.findMine(Chat.Id(sid), ctx.me).map(toEventChat(s"simul/$sid"))
239+
env.chat.api.userChat.cached.findMine(Chat.Id(sid), ctx.me).dmap(toEventChat(s"simul/$sid"))
240240
}
241241
case _ =>
242242
game.hasChat ?? {

app/controllers/Swiss.scala

+35-4
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,38 @@ import play.api.mvc._
44

55
import lila.api.Context
66
import lila.app._
7+
import lila.swiss.{ Swiss => SwissModel }
78
import views._
89

910
final class Swiss(
10-
env: Env
11+
env: Env,
12+
tourC: Tournament
1113
) extends LilaController(env) {
1214

15+
private def swissNotFound(implicit ctx: Context) = NotFound(html.swiss.bits.notFound())
16+
1317
def show(id: String) = Open { implicit ctx =>
14-
???
18+
env.swiss.api.byId(SwissModel.Id(id)) flatMap {
19+
_.fold(swissNotFound.fuccess) { swiss =>
20+
for {
21+
version <- env.swiss.version(swiss.id)
22+
// rounds <- env.swiss.roundsOf(swiss)
23+
json <- env.swiss.json(
24+
swiss = swiss,
25+
// rounds = rounds,
26+
me = ctx.me,
27+
socketVersion = version.some
28+
)
29+
canChat <- canHaveChat(swiss)
30+
chat <- canChat ?? env.chat.api.userChat.cached
31+
.findMine(lila.chat.Chat.Id(swiss.id.value), ctx.me)
32+
.dmap(some)
33+
_ <- chat ?? { c =>
34+
env.user.lightUserApi.preloadMany(c.chat.userIds)
35+
}
36+
} yield Ok(html.swiss.show(swiss, json, chat))
37+
}
38+
}
1539
}
1640

1741
def form(teamId: String) = Auth { implicit ctx => me =>
@@ -27,10 +51,17 @@ final class Swiss(
2751
.fold(
2852
err => BadRequest(html.swiss.form.create(err, teamId)).fuccess,
2953
data =>
30-
env.swiss.api.create(data, me, teamId) map { swiss =>
31-
Redirect(routes.Swiss.show(swiss.id.value))
54+
tourC.rateLimitCreation(me, false, ctx.req) {
55+
env.swiss.api.create(data, me, teamId) map { swiss =>
56+
Redirect(routes.Swiss.show(swiss.id.value))
57+
}
3258
}
3359
)
3460
}
3561
}
62+
63+
private def canHaveChat(swiss: SwissModel)(implicit ctx: Context): Fu[Boolean] =
64+
(swiss.hasChat && ctx.noKid) ?? ctx.userId.?? {
65+
env.team.api.belongsTo(swiss.teamId, _)
66+
}
3667
}

app/controllers/Tournament.scala

+2-2
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ final class Tournament(
9797
)
9898
chat <- canHaveChat(tour, json.some) ?? env.chat.api.userChat.cached
9999
.findMine(Chat.Id(tour.id), ctx.me)
100-
.map(some)
100+
.dmap(some)
101101
_ <- chat ?? { c =>
102102
env.user.lightUserApi.preloadMany(c.chat.userIds)
103103
}
@@ -240,7 +240,7 @@ final class Tournament(
240240
fuccess(Redirect(routes.Tournament.home))
241241
}
242242

243-
private def rateLimitCreation(me: UserModel, isPrivate: Boolean, req: RequestHeader)(
243+
private[controllers] def rateLimitCreation(me: UserModel, isPrivate: Boolean, req: RequestHeader)(
244244
create: => Fu[Result]
245245
): Fu[Result] = {
246246
val cost =

app/views/swiss/show.scala

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package views.html
2+
package swiss
3+
4+
import play.api.libs.json.Json
5+
6+
import lila.api.Context
7+
import lila.app.templating.Environment._
8+
import lila.app.ui.ScalatagsTemplate._
9+
import lila.common.String.html.safeJsonValue
10+
import lila.swiss.Swiss
11+
12+
import controllers.routes
13+
14+
object show {
15+
16+
def apply(
17+
swiss: Swiss,
18+
data: play.api.libs.json.JsObject,
19+
chatOption: Option[lila.chat.UserChat.Mine]
20+
)(implicit ctx: Context): Frag = ???
21+
// views.html.base.layout(
22+
// title = s"${tour.name()} #${tour.id}",
23+
// moreJs = frag(
24+
// jsAt(s"compiled/lichess.tournament${isProd ?? (".min")}.js"),
25+
// embedJsUnsafe(s"""lichess=lichess||{};lichess.tournament=${safeJsonValue(
26+
// Json.obj(
27+
// "data" -> data,
28+
// "i18n" -> bits.jsI18n,
29+
// "userId" -> ctx.userId,
30+
// "chat" -> chatOption.map { c =>
31+
// chat.json(
32+
// c.chat,
33+
// name = trans.chatRoom.txt(),
34+
// timeout = c.timeout,
35+
// public = true,
36+
// resourceId = lila.chat.Chat.ResourceId(s"tournament/${c.chat.id}")
37+
// )
38+
// }
39+
// )
40+
// )}""")
41+
// ),
42+
// moreCss = cssTag {
43+
// if (tour.isTeamBattle) "tournament.show.team-battle"
44+
// else "tournament.show"
45+
// },
46+
// chessground = false,
47+
// openGraph = lila.app.ui
48+
// .OpenGraph(
49+
// title = s"${tour.name()}: ${tour.variant.name} ${tour.clock.show} ${tour.mode.name} #${tour.id}",
50+
// url = s"$netBaseUrl${routes.Tournament.show(tour.id).url}",
51+
// description = s"${tour.nbPlayers} players compete in the ${showEnglishDate(tour.startsAt)} ${tour.name()}. " +
52+
// s"${tour.clock.show} ${tour.mode.name} games are played during ${tour.minutes} minutes. " +
53+
// tour.winnerId.fold("Winner is not yet decided.") { winnerId =>
54+
// s"${usernameOrId(winnerId)} takes the prize home!"
55+
// }
56+
// )
57+
// .some
58+
// )(
59+
// main(cls := s"tour${tour.schedule
60+
// .?? { sched =>
61+
// s" tour-sched tour-sched-${sched.freq.name} tour-speed-${sched.speed.name} tour-variant-${sched.variant.key} tour-id-${tour.id}"
62+
// }}")(
63+
// st.aside(cls := "tour__side")(
64+
// tournament.side(tour, verdicts, streamers, shieldOwner, chatOption.isDefined)
65+
// ),
66+
// div(cls := "tour__main")(div(cls := "box")),
67+
// tour.isCreated option div(cls := "tour__faq")(
68+
// faq(tour.mode.rated.some, tour.isPrivate.option(tour.id))
69+
// )
70+
// )
71+
// )
72+
}

build.sbt

+1-1
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ lazy val tournament = module("tournament",
252252
)
253253

254254
lazy val swiss = module("swiss",
255-
Seq(common, hub, socket, game, round, security, chat, memo, i18n, room),
255+
Seq(common, hub, socket, game, round, security, chat, memo, quote, i18n, room),
256256
Seq(scalatags, lettuce) ++ reactivemongo.bundle
257257
)
258258

modules/security/src/main/SecurityApi.scala

+1-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import play.api.data.Forms._
77
import play.api.data.validation.{ Constraint, Valid => FormValid, Invalid, ValidationError }
88
import play.api.mvc.RequestHeader
99
import reactivemongo.api.bson._
10-
import scala.annotation.nowarn
1110
import scala.concurrent.duration._
1211

1312
import lila.common.{ ApiVersion, EmailAddress, IpAddress }
@@ -71,7 +70,7 @@ final class SecurityApi(
7170
} map loadedLoginForm _
7271

7372
private def authenticateCandidate(candidate: Option[LoginCandidate])(
74-
@nowarn("cat=unused") _username: String,
73+
_username: String,
7574
password: String,
7675
token: Option[String]
7776
): LoginCandidate.Result = candidate.fold[LoginCandidate.Result](LoginCandidate.InvalidUsernameOrPassword) {

modules/swiss/src/main/Env.scala

+9-1
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,25 @@ package lila.swiss
22

33
import com.softwaremill.macwire._
44

5+
import lila.socket.Socket.{ GetVersion, SocketVersion }
56
import lila.common.config._
67

78
@Module
89
final class Env(
9-
db: lila.db.Db
10+
db: lila.db.Db,
11+
lightUserApi: lila.user.LightUserApi
1012
)(implicit ec: scala.concurrent.ExecutionContext) {
1113

1214
private val colls = wire[SwissColls]
1315

1416
val api = wire[SwissApi]
1517

18+
def version(tourId: Swiss.Id): Fu[SocketVersion] =
19+
fuccess(SocketVersion(0))
20+
// socket.rooms.ask[SocketVersion](tourId)(GetVersion)
21+
22+
lazy val json = wire[SwissJson]
23+
1624
lazy val forms = wire[SwissForm]
1725
}
1826

modules/swiss/src/main/SwissApi.scala

+5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ final class SwissApi(
1313

1414
import BsonHandlers._
1515

16+
def byId(id: Swiss.Id) = colls.swiss.byId[Swiss](id.value)
17+
1618
def create(data: SwissForm.SwissData, me: User, teamId: TeamID): Fu[Swiss] = {
1719
val swiss = Swiss(
1820
_id = Swiss.makeId,
@@ -34,6 +36,9 @@ final class SwissApi(
3436
colls.swiss.insert.one(swiss) inject swiss
3537
}
3638

39+
def roundsOf(swiss: Swiss) =
40+
colls.round.ext.find($doc("swissId" $startsWith s"${swiss.id}:")).list[SwissRound]()
41+
3742
def featuredInTeam(teamId: TeamID): Fu[List[Swiss]] =
3843
colls.swiss.ext.find($doc("teamId" -> teamId)).sort($sort desc "startsAt").list[Swiss](5)
3944
}
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package lila.swiss
2+
3+
import org.joda.time.DateTime
4+
import org.joda.time.format.ISODateTimeFormat
5+
import play.api.i18n.Lang
6+
import play.api.libs.json._
7+
import scala.concurrent.duration._
8+
import scala.concurrent.ExecutionContext
9+
10+
import lila.common.{ GreatPlayer, LightUser, Uptime }
11+
import lila.hub.LightTeam.TeamID
12+
import lila.quote.Quote.quoteWriter
13+
import lila.rating.PerfType
14+
import lila.socket.Socket.SocketVersion
15+
import lila.user.User
16+
17+
final class SwissJson(
18+
// lightUserApi: lila.user.LightUserApi
19+
)(implicit ec: ExecutionContext) {
20+
21+
def apply(
22+
swiss: Swiss,
23+
// rounds: List[SwissRound],
24+
me: Option[User],
25+
socketVersion: Option[SocketVersion]
26+
)(implicit lang: Lang): Fu[JsObject] = fuccess {
27+
Json
28+
.obj(
29+
"id" -> swiss.id.value,
30+
"createdBy" -> swiss.createdBy,
31+
"startsAt" -> formatDate(swiss.startsAt),
32+
"name" -> swiss.name,
33+
"perf" -> swiss.perfType,
34+
"clock" -> swiss.clock,
35+
"variant" -> swiss.variant.key,
36+
"nbRounds" -> swiss.nbRounds,
37+
"nbPlayers" -> swiss.nbPlayers
38+
)
39+
.add("isStarted" -> swiss.isStarted)
40+
.add("isFinished" -> swiss.isFinished)
41+
.add("socketVersion" -> socketVersion.map(_.value))
42+
.add("quote" -> swiss.isCreated.option(lila.quote.Quote.one(swiss.id.value)))
43+
.add("description" -> swiss.description)
44+
}
45+
46+
private def formatDate(date: DateTime) = ISODateTimeFormat.dateTime print date
47+
48+
implicit private val clockWrites: OWrites[chess.Clock.Config] = OWrites { clock =>
49+
Json.obj(
50+
"limit" -> clock.limitSeconds,
51+
"increment" -> clock.incrementSeconds
52+
)
53+
}
54+
55+
implicit private def perfTypeWrites(implicit lang: Lang): OWrites[PerfType] = OWrites { pt =>
56+
Json.obj(
57+
"icon" -> pt.iconChar.toString,
58+
"name" -> pt.trans
59+
)
60+
}
61+
}

project/BuildSettings.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ object BuildSettings {
5858
"-deprecation",
5959
"-Xlint:_",
6060
"-Ywarn-macros:after",
61-
"-Ywarn-unused:_",
61+
// "-Ywarn-unused:_",
6262
// "-Xfatal-warnings",
6363
"-Xmaxerrs",
6464
"15",

0 commit comments

Comments
 (0)