more challenges refactoring

pull/1283/head
Thibault Duplessis 2016-02-03 11:10:48 +07:00
parent cefe76e5db
commit 1b399d47a7
9 changed files with 126 additions and 81 deletions

View File

@ -32,9 +32,16 @@ object Challenge extends LilaController {
private[controllers] def reach(id: String)(implicit ctx: Context): Fu[Result] =
env.api byId id flatMap {
case None => notFound
case Some(challenge) if isMine(challenge) => Ok(html.challenge.mine(challenge)).fuccess
case Some(challenge) => Ok(html.challenge.theirs(challenge)).fuccess
_ ?? { c =>
env version c.id flatMap { version =>
negotiate(
html = Ok(isMine(c).fold(
html.challenge.mine.apply _,
html.challenge.theirs.apply _
)(c, env.jsonView(c), version)).fuccess,
api = _ => Ok(env.jsonView(c)).fuccess)
}
}
}
private def isMine(challenge: ChallengeModel)(implicit ctx: Context) = challenge.challenger match {

View File

@ -1,33 +1,73 @@
@(c: lila.challenge.Challenge)(implicit ctx: Context)
@(c: lila.challenge.Challenge, json: play.api.libs.json.JsObject, version: Int)(implicit ctx: Context)
@import lila.challenge.Challenge.Status
@moreJs = {
@jsTag("challenge.js")
@embedJs {
lichess.startChallenge(document.getElementById('my_challenge'), {
socketUrl: '@routes.Challenge.websocket(c.id, apiVersion)',
socketVersion: @version,
xhrUrl: '@routes.Round.watcher(c.id, "white")',
owner: true,
challenge: @Html(toJson(json))
});
}
}
@cancelForm = {
<form method="post" action="@routes.Challenge.cancel(c.id)">
<button type="submit" class="button text" data-icon="L">@trans.cancel()</button>
</form>
}
@round.layout(
title = c.destUserId.isDefined.fold(trans.challengeToPlay,trans.playWithAFriend).str(),
side = Html("")) {
<div class="lichess_game">
side = Html(""),
moreJs = moreJs) {
<div class="lichess_game" id="my_challenge">
<div class="lichess_board_wrap cg-512">
<div class="lichess_board"></div>
</div>
<div class="lichess_overboard" id="my_challenge">
<div class="lichess_overboard">
@c.status match {
case Status.Created | Status.Offline => {
@c.destUserId.map { destId =>
<h2>@trans.challengeToPlay()</h2>
@userIdLink(destId.some, cssClass="target".some)
<span class="loader"><span data-icon="U"></span></span>
<p class="explanations">
@trans.waitingForOpponent()<br />
<a href="@routes.Challenge.cancel(c.id)">@trans.cancel()</a>
</p>
<div id="challenge_declined" class="none">
<h2>Challenge declined</h2>
<a href="@routes.Lobby.home()">@trans.playWithAnotherOpponent()</a>
</div>
}.getOrElse {
@trans.toInviteSomeoneToPlayGiveThisUrl():
<input id="lichess_id_input" class="copyable" spellcheck="false" readonly="true" value="@protocol@commonDomain@routes.Round.watcher(c.id, "white")" />
<button class="copy button" data-rel="lichess_id_input" data-icon="&quot;"></button>
<p class="explanations">
<div class="explanations">
@trans.theFirstPersonToComeOnThisUrlWillPlayWithYou()<br />
<a href="@routes.Challenge.cancel(c.id)">@trans.cancel()</a>
</p>
@cancelForm
</div>
}
<span class="loader" id="ping_challenge"><span data-icon="U"></span></span>
<div class="explanations">
@trans.waitingForOpponent()<br />
@cancelForm
</div>
}
case Status.Declined => {
<div class="declined">
<h2>Challenge declined</h2>
<a class="button" href="@routes.Lobby.home()">@trans.playWithAnotherOpponent()</a>
</div>
}
case Status.Accepted => {
<div class="accepted">
<h2>Challenge accepted!</h2>
<a id="challenge_redirect" href="@routes.Round.watcher(c.id, "white")" class="button">@trans.joinTheGame()</a>
</div>
}
case Status.Canceled => {
<div class="canceled">
<h2>Challenge canceled.</h2>
<a class="button" href="@routes.Lobby.home()">@trans.playWithAnotherOpponent()</a>
</div>
}
}
<p class="explanations">
@trans.variant(): @views.html.game.variantLink(c.variant, variantName(c.variant))<br />

View File

@ -1,4 +1,4 @@
@(c: lila.challenge.Challenge)(implicit ctx: Context)
@(c: lila.challenge.Challenge, json: play.api.libs.json.JsObject, version: Int)(implicit ctx: Context)
@*
@import pov._

View File

@ -40,6 +40,9 @@ case class Challenge(
}
def openDest = destUser.isEmpty
def active = status == Status.Created || status == Status.Offline
def declined = status == Status.Declined
def accepted = status == Status.Accepted
lazy val perfType = perfTypeOf(variant, timeControl)
}

View File

@ -1,10 +1,14 @@
package lila.challenge
import akka.actor._
import akka.pattern.ask
import com.typesafe.config.Config
import scala.concurrent.duration._
import lila.common.PimpedConfig._
import lila.hub.actorApi.map.Ask
import lila.socket.actorApi.GetVersion
import makeTimeout.short
final class Env(
config: Config,
@ -35,6 +39,9 @@ final class Env(
socketTimeout = SocketTimeout)
}), name = SocketName)
def version(challengeId: Challenge.ID): Fu[Int] =
socketHub ? Ask(challengeId, GetVersion) mapTo manifest[Int]
lazy val socketHandler = new SocketHandler(
hub = hub,
socketHub = socketHub,

View File

@ -22,6 +22,7 @@ final class JsonView(getLightUser: String => Option[lila.common.LightUser]) {
"key" -> c.variant.key,
"short" -> c.variant.shortName,
"name" -> c.variant.name),
"initialFen" -> c.initialFen,
"rated" -> c.mode.rated,
"timeControl" -> (c.timeControl match {
case c@TimeControl.Clock(l, i) => Json.obj(

View File

@ -38,7 +38,7 @@ private[challenge] final class SocketHandler(
member: Socket.Member): Handler.Controller = {
case ("p", o) => o int "v" foreach { v =>
socket ! PingVersion(uid, v)
if (member.owner) pingChallenge(challengeId)
}
case ("ping", _) if member.owner => pingChallenge(challengeId)
}
}

View File

@ -701,8 +701,7 @@ lichess.unique = function(xs) {
});
}
if (lichess.challenge) startChallenge(lichess.challenge);
else if (lichess.analyse) startAnalyse(document.getElementById('lichess'), lichess.analyse);
if (lichess.analyse) startAnalyse(document.getElementById('lichess'), lichess.analyse);
else if (lichess.user_analysis) startUserAnalysis(document.getElementById('lichess'), lichess.user_analysis);
else if (lichess.lobby) startLobby(document.getElementById('hooks_wrap'), lichess.lobby);
else if (lichess.tournament) startTournament(document.getElementById('tournament'), lichess.tournament);
@ -1434,48 +1433,6 @@ lichess.unique = function(xs) {
}
}
function startChallenge(data) {
if (data.player.spectator && lichess.openInMobileApp(data.id)) return;
lichess.socket = new lichess.StrongSocket(
data.url.socket,
data.player.version, {
options: {
name: "prelude"
},
params: {
ran: "--ranph--"
},
events: {
declined: function() {
$('#challenge_await').remove();
$('#challenge_declined').show();
}
}
});
Chessground(element.querySelector('.lichess_board'), {
viewOnly: true,
fen: data.game.fen,
orientation: data.player.color,
check: data.game.check,
coordinates: data.pref.coords !== 0,
highlight: {
check: data.pref.highlight
},
disableContextMenu: true
});
setTimeout(function() {
$('.lichess_overboard_wrap', element).addClass('visible');
}, 100);
$('#challenge_await').each(function() {
setInterval(function() {
$('#challenge_await').each(function() {
lichess.socket.send('challenge', $(this).data('user'));
});
}, 1500);
});
}
$.widget("lichess.watchers", {
_create: function() {
this.list = this.element.find("span.list");

View File

@ -1,18 +1,48 @@
$(function() {
// var pingUrl = $('#my_challenge').data('ping');
lichess = lichess || {};
lichess.startChallenge = function(element, opts) {
var challenge = opts.challenge;
if (!opts.owner && lichess.openInMobileApp(challenge.id)) return;
lichess.socket = new lichess.StrongSocket(
opts.socketUrl,
opts.socketVersion, {
options: {
name: "challenge"
},
params: {
ran: "--ranph--"
},
events: {
reload: function() {
console.log('reload');
$.ajax({
url: opts.xhrUrl,
success(html) {
$('.lichess_overboard').replaceWith($(html).find('.lichess_overboard'));
$('#challenge_redirect').each(function() {
location.href = $(this).attr('href');
});
}
});
}
}
});
// var ping = function() {
// $.ajax({
// method:'post',
// url: pingUrl,
// success: function(res) {
// if (res === 'open')
// }
// });
// };
var pingNow = function() {
if (document.getElementById('ping_challenge')) {
lichess.socket.send('ping');
setTimeout(pingNow, 2000);
}
};
pingNow();
// var schedulePing = function() {
// setTimeout(ping, 2000);
// }
});
Chessground(element.querySelector('.lichess_board'), {
viewOnly: true,
fen: challenge.initialFen,
orientation: challenge.color,
coordinates: false,
disableContextMenu: true
});
setTimeout(function() {
$('.lichess_overboard_wrap', element).addClass('visible');
}, 100);
};