mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
4
Commits
2f3f39a21d
...
bd8be4d10d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd8be4d10d | ||
|
|
6a4288bb6c
|
||
|
|
dda588da06 | ||
|
|
2c5e290e66
|
-36
@@ -1,36 +0,0 @@
|
||||
# Project Roadmap
|
||||
|
||||
High-level implementation milestones and strategic direction
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: MVP & Core Functionality (Current Focus)
|
||||
Target: Q1 2027
|
||||
|
||||
- [ ] **Initial UI / Interface**
|
||||
- [ ] Create front page and settle on colour scheme
|
||||
- [ ] Apply colour scheme across the site
|
||||
- [ ] Allow colour theme to be changed on chessboard
|
||||
- [ ] **Core Features**
|
||||
- [x] Log in
|
||||
- [x] Rating of user and puzzles
|
||||
- [x] Implement core API endpoints with input validation.
|
||||
- [x] Traverse puzzles in easy/medium/hard mode with session timer/rating+/-
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Polish & Reliability
|
||||
Target: Q2 2027
|
||||
|
||||
- [ ] **Security & Compliance**
|
||||
- [ ] Complete security hardening and dependency vulnerability auditing.
|
||||
- [ ] **Testing & Quality Control**
|
||||
- [ ] Expand integration test suite for critical API paths.
|
||||
- [ ] Set up automated WCAG accessibility audits in CI.
|
||||
- [ ] **Performance & Caching**
|
||||
- [ ] Optimize database indexes and payload response sizes.
|
||||
- [x] Implement local caching strategy for high-frequency queries.
|
||||
- [ ] **Logged in user features**
|
||||
- [ ] Allow logged in users to see their progrees on a profile page
|
||||
|
||||
---
|
||||
@@ -1,33 +0,0 @@
|
||||
# Immediate TODOs
|
||||
|
||||
Granular tasks and operational scratchpad for active development.
|
||||
|
||||
---
|
||||
|
||||
## In Progress 🟡
|
||||
- [x] Basic design and colour scheme
|
||||
- [x] Apply design to the rest of the site
|
||||
- [x] Create reusable components such as button
|
||||
- [x] Organise nav bar
|
||||
- [x] Display puzzles and move to next
|
||||
- [x] Create footer
|
||||
|
||||
---
|
||||
|
||||
## Next Up (Sprint Backlog) 🟢
|
||||
- [ ] Forgot password
|
||||
- [ ] Anonymous trial of 10 puzzles without logging in
|
||||
- [x] Light / Dark mode
|
||||
- [ ] WCAG compliance
|
||||
- [x] Self host font - google fonts not gdpr compliant
|
||||
---
|
||||
|
||||
## Tech Debt & Refactoring 🧹
|
||||
- [ ] Split CSS into modules (ongoing)
|
||||
|
||||
---
|
||||
|
||||
## Deferred / Parking Lot 🧊
|
||||
- [ ] Profile page
|
||||
- [ ] Visual guide to user progress / attemps
|
||||
- [ ] Export user data
|
||||
@@ -22,6 +22,7 @@
|
||||
@import "./components/_learning-strip.css";
|
||||
@import "./components/_board.css";
|
||||
@import "./components/_promotion.css";
|
||||
@import "./pages/_legal.css";
|
||||
|
||||
@source "../css";
|
||||
@source "../js";
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
.legal {
|
||||
width: min(760px, calc(100% - 48px));
|
||||
margin: 0 auto;
|
||||
padding: 84px 0 120px;
|
||||
}
|
||||
|
||||
.legal h1 {
|
||||
max-width: none;
|
||||
font-size: clamp(42px, 5vw, 62px);
|
||||
line-height: 1.02;
|
||||
}
|
||||
|
||||
.legal-meta {
|
||||
margin-top: 14px;
|
||||
color: var(--color-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.legal h2 {
|
||||
margin: 42px 0 12px;
|
||||
font-size: 26px;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.legal p,
|
||||
.legal li {
|
||||
color: var(--color-muted);
|
||||
font-size: 15px;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.legal p + p {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.legal ul {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 12px 0 0 20px;
|
||||
list-style: disc;
|
||||
}
|
||||
|
||||
.legal strong {
|
||||
color: var(--color-body);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal a {
|
||||
color: var(--color-coral-text);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.legal a:hover {
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.legal {
|
||||
width: calc(100% - 36px);
|
||||
padding: 56px 0 84px;
|
||||
}
|
||||
|
||||
.legal h1 {
|
||||
font-size: clamp(34px, 11vw, 44px);
|
||||
}
|
||||
|
||||
.legal h2 {
|
||||
margin-top: 34px;
|
||||
font-size: 23px;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,15 @@
|
||||
# General application configuration
|
||||
import Config
|
||||
|
||||
# Public-facing branding. Change these values to rename the site without
|
||||
# touching templates. The OTP app (`:chesstrainer`) and module namespaces are
|
||||
# identity, not branding, and stay as they are.
|
||||
config :chesstrainer, :branding,
|
||||
name: "Lucid Chess",
|
||||
wordmark: "LUCID",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@lucidchess.app"
|
||||
|
||||
config :chesstrainer, :scopes,
|
||||
user: [
|
||||
default: true,
|
||||
|
||||
@@ -81,6 +81,13 @@ config :chesstrainer, Chesstrainer.Cache,
|
||||
max_size: cache_max_size,
|
||||
backup_time: cache_backup_time
|
||||
|
||||
# Guest puzzle limit: free puzzles per UTC day for anonymous visitors. The
|
||||
# visitor is identified by a keyed hash of their address held in memory only.
|
||||
# Enable TRUST_FORWARDED_FOR only behind a proxy that sets the header.
|
||||
config :chesstrainer, Chesstrainer.GuestLimits,
|
||||
limit: String.to_integer(System.get_env("GUEST_PUZZLE_LIMIT", "5")),
|
||||
trust_forwarded_for: System.get_env("TRUST_FORWARDED_FOR") in ~w(true 1)
|
||||
|
||||
config :chesstrainer, ChesstrainerWeb.Endpoint,
|
||||
http: [port: String.to_integer(System.get_env("PORT", "4000"))]
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Guest puzzles are capped per UTC day by a hashed address
|
||||
|
||||
`/guest-train` gives anonymous visitors 5 puzzles per UTC day. The budget is per
|
||||
client address, but the address is never stored: the limiter keys an in-memory
|
||||
ETS table by `HMAC-SHA256(boot_secret, "<gregorian_day>|<address>")`. The secret
|
||||
is generated when the node boots, so digests are not stable across restarts and
|
||||
cannot be correlated with anything else. The table is swept when the day rolls
|
||||
over, and no entry is ever written to the database, a log, or a backup.
|
||||
|
||||
## Why a daily UTC reset
|
||||
|
||||
A fixed 00:00 UTC boundary makes the rule easy to state ("5 free puzzles a
|
||||
day"), gives every visitor the same reset instant, and removes the need for
|
||||
per-entry timestamps: the UTC date is part of the key, so yesterday's entries
|
||||
simply stop matching. That also means the stored data's lifetime is bounded by
|
||||
the calendar day.
|
||||
|
||||
## Why not an IP address
|
||||
|
||||
The raw address is never persisted; only the digest is, and only until the day
|
||||
rolls over or the node restarts. This is abuse prevention with data
|
||||
minimisation, not tracking, and needs no cookie or client-side storage. The
|
||||
processing is disclosed in the privacy policy (see #87).
|
||||
|
||||
## Consequences
|
||||
|
||||
- Visitors behind one NAT share a budget. Masking to a subnet would make that
|
||||
worse, so the full address is hashed.
|
||||
- The budget lives in one node's memory: a restart resets it, and a second node
|
||||
would keep its own. Move the counter to Postgres or Redis if that matters.
|
||||
- The unit being metered is a puzzle load, not a move. A LiveView reconnect
|
||||
re-runs the connected mount and therefore consumes one puzzle.
|
||||
- Retry and review never consume a puzzle because they reuse the loaded
|
||||
position.
|
||||
- Signed-in visitors are redirected to `/train` and are never metered.
|
||||
- Behind a proxy, set `TRUST_FORWARDED_FOR=1` and make sure the proxy overwrites
|
||||
or appends `X-Forwarded-For`; otherwise every visitor shares the proxy's
|
||||
budget. `GUEST_PUZZLE_LIMIT` changes the daily allowance.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Eight-or-more-piece endgames are trained from engine-sourced corridors that hand off to the tablebase at seven
|
||||
|
||||
_Status: proposed. Extends ADR-0005: the ≤7-piece source split stands; this adds a source for 8+._
|
||||
|
||||
Syzygy stops at seven pieces and there is no tablebase for eight or more. To
|
||||
train such endgames without pretending to a completeness they lack, each 8+
|
||||
endgame is backed by a **corridor**: one or two winning lines, generated offline
|
||||
with a chess engine (Stockfish), that stay clearly winning at every step. The
|
||||
corridor is stored as solved positions keyed by position key and served by a new
|
||||
tablebase backend, so the play loop and grading are unchanged.
|
||||
|
||||
The corridor ends at the first capture that brings the board to seven pieces or
|
||||
fewer. From that position the existing router answers from Syzygy (≤5, local) or
|
||||
Lichess (6–7), so the tail of every puzzle is tablebase-optimal. Generation
|
||||
verifies the handoff: it probes the ≤7 position and asserts it is still a win for
|
||||
the winning side. A promotion does not end the corridor, because it does not
|
||||
reduce the piece count; only a capture does.
|
||||
|
||||
A second line is stored only when both lines are clearly winning — the engine's
|
||||
evaluation stays above the winning threshold throughout. A line that dips is
|
||||
discarded rather than shipped as a dubious alternative.
|
||||
|
||||
## Grading
|
||||
|
||||
Inside the corridor grading is binary: a move on a stored line passes, a move
|
||||
off the lines fails. The stored move list is deliberately incomplete, so it
|
||||
cannot support the "any winning move passes" rule the tablebase enables; the
|
||||
user must find the technique the corridor encodes. Once the position reaches
|
||||
seven pieces, grading returns to the existing optimal/winning/losing model.
|
||||
|
||||
## Why not the alternatives
|
||||
|
||||
- **Engine at runtime.** Removes the offline step but adds per-move latency, a
|
||||
rate limit if it is a remote service, and non-determinism in what counts as
|
||||
"winning". The corridor is deterministic and free at play time.
|
||||
- **Hand-authored book.** The same shape without an engine to generate it:
|
||||
fragile, narrow, and prone to grading a move as losing only because nobody
|
||||
wrote it down.
|
||||
- **Solving the whole 8+ region.** Infeasible. The corridor trades completeness
|
||||
for a short, verified path to a position the tablebase can finish.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Endgames gain an `oracle` (`:tablebase` or `:corridor`). The changeset admits
|
||||
8+ FENs only for corridor endgames.
|
||||
- A corridor-position store (keyed by position key) and a tree backend join the
|
||||
existing Fathom/Lichess backends. Eight-plus positions without a corridor are
|
||||
still rejected.
|
||||
- Generation depends on a Stockfish binary at build/curation time, not at
|
||||
runtime.
|
||||
- The corridor is engine-best, not proven-optimal. Honest wording ("engine-best
|
||||
defence") is required in player-facing copy, and GLOSSARY's *optimal move* and
|
||||
*winning move* need a corridor-aware distinction.
|
||||
- An off-corridor legal move fails the attempt; this is a deliberate departure
|
||||
from tablebase grading and must be reflected in the play surface.
|
||||
@@ -1,6 +1,7 @@
|
||||
defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
|
||||
# Delivers the email using the application mailer.
|
||||
@@ -8,7 +9,7 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({"Chesstrainer", "contact@example.com"})
|
||||
|> from({Branding.name(), Branding.support_email()})
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ defmodule Chesstrainer.Application do
|
||||
{Phoenix.PubSub, name: Chesstrainer.PubSub},
|
||||
# Start a worker by calling: Chesstrainer.Worker.start_link(arg)
|
||||
# {Chesstrainer.Worker, arg},
|
||||
Chesstrainer.GuestLimits,
|
||||
# Start to serve requests, typically the last entry
|
||||
ChesstrainerWeb.Endpoint,
|
||||
{Registry, keys: :unique, name: Chesstrainer.CacheRegistry},
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
defmodule Chesstrainer.Branding do
|
||||
@moduledoc """
|
||||
Public-facing branding, read from `config :chesstrainer, :branding`.
|
||||
|
||||
Keeps display names out of templates and controllers so the site can be
|
||||
renamed in one place. Values are read at runtime, so a deploy can override
|
||||
them without recompiling.
|
||||
"""
|
||||
|
||||
@defaults [
|
||||
name: "Lucid Chess",
|
||||
wordmark: "LUCID",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@lucidchess.app"
|
||||
]
|
||||
|
||||
@doc "The display name, e.g. `\"Lucid Chess\"`."
|
||||
def name, do: get(:name)
|
||||
|
||||
@doc "The short wordmark used in the navbar and footer."
|
||||
def wordmark, do: get(:wordmark)
|
||||
|
||||
@doc "The tagline appended to the home title, e.g. `\"Endgame Trainer\"`."
|
||||
def tagline, do: get(:tagline)
|
||||
|
||||
@doc "The address shown in legal pages and used as the mailer `from`."
|
||||
def support_email, do: get(:support_email)
|
||||
|
||||
@doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`."
|
||||
def home_title, do: "#{name()} — #{tagline()}"
|
||||
|
||||
@doc "Builds a page title, e.g. `title(\"Privacy Policy\")`."
|
||||
def title(page), do: "#{page} — #{name()}"
|
||||
|
||||
defp get(key) do
|
||||
config = Application.get_env(:chesstrainer, :branding) || []
|
||||
Keyword.get(config, key, Keyword.fetch!(@defaults, key))
|
||||
end
|
||||
end
|
||||
@@ -23,11 +23,23 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns a random endgame, or `nil` when none exist.
|
||||
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating
|
||||
the puzzle just played.
|
||||
"""
|
||||
def random_endgame do
|
||||
Repo.one(from e in Endgame, order_by: fragment("RANDOM()"), limit: 1)
|
||||
def random_endgame(opts \\ []) do
|
||||
exclude_ids = Keyword.get(opts, :exclude_ids, [])
|
||||
|
||||
Endgame
|
||||
|> skip_ids(exclude_ids)
|
||||
|> order_by([e], fragment("RANDOM()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp skip_ids(query, []), do: query
|
||||
defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids)
|
||||
|
||||
@doc """
|
||||
Returns the number of stored endgames, each of which is played as a puzzle.
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
defmodule Chesstrainer.GuestLimits do
|
||||
@moduledoc """
|
||||
Daily puzzle budget for anonymous visitors.
|
||||
|
||||
Each visitor gets a fixed number of puzzles per UTC day. Visitors are
|
||||
identified by an HMAC of their client address — the address itself is never
|
||||
stored, logged, or persisted. The digest lives only in ETS, is scoped to the
|
||||
current UTC date, and is swept away when the day rolls over. The HMAC secret
|
||||
is generated at boot, so digests are not stable across restarts.
|
||||
|
||||
Budgets reset for everyone at 00:00 UTC: the date is part of the key, so a
|
||||
new day simply starts a new entry.
|
||||
"""
|
||||
|
||||
use GenServer
|
||||
|
||||
@table :guest_limits
|
||||
@default_limit 5
|
||||
@sweep_interval :timer.minutes(10)
|
||||
|
||||
@typedoc "An IPv4/IPv6 address, or `nil` when the socket has no peer data."
|
||||
@type address :: :inet.ip_address() | nil
|
||||
|
||||
@doc "Starts the limiter."
|
||||
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
|
||||
|
||||
@doc """
|
||||
Consumes one puzzle from `address`'s budget for `today`.
|
||||
|
||||
Returns `{:ok, remaining}` with the puzzles left today, or
|
||||
`{:limit_reached, retry_in_ms}` when the budget is spent. A `nil` address is
|
||||
not limited and returns `{:ok, nil}`.
|
||||
"""
|
||||
@spec take(address, Date.t()) ::
|
||||
{:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer}
|
||||
def take(address, today \\ Date.utc_today()) do
|
||||
GenServer.call(__MODULE__, {:take, address, today})
|
||||
end
|
||||
|
||||
@doc "Clears every budget. Intended for tests."
|
||||
def reset, do: GenServer.call(__MODULE__, :reset)
|
||||
|
||||
@doc "The daily puzzle allowance for a guest."
|
||||
def limit, do: config() |> Keyword.get(:limit, @default_limit)
|
||||
|
||||
@doc """
|
||||
Whether to read the client address from `X-Forwarded-For`.
|
||||
|
||||
Enable only behind a proxy that overwrites or appends the header.
|
||||
"""
|
||||
def trust_forwarded_for?, do: config() |> Keyword.get(:trust_forwarded_for, false)
|
||||
|
||||
defp config, do: Application.get_env(:chesstrainer, __MODULE__, [])
|
||||
|
||||
@impl true
|
||||
def init(opts) do
|
||||
:ets.new(@table, [:named_table, :set])
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
limit: Keyword.get(opts, :limit, limit()),
|
||||
secret: :crypto.strong_rand_bytes(32)
|
||||
}}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
|
||||
|
||||
def handle_call({:take, address, today}, _from, state) do
|
||||
day = Date.to_gregorian_days(today)
|
||||
key = key(state.secret, day, address)
|
||||
|
||||
case count(key, day) do
|
||||
used when used >= state.limit ->
|
||||
{:reply, {:limit_reached, ms_until_utc_midnight()}, state}
|
||||
|
||||
used ->
|
||||
:ets.insert(@table, {key, day, used + 1})
|
||||
{:reply, {:ok, state.limit - used - 1}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call(:reset, _from, state) do
|
||||
:ets.delete_all_objects(@table)
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info(:sweep, state) do
|
||||
sweep(Date.to_gregorian_days(Date.utc_today()))
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
defp count(key, day) do
|
||||
case :ets.lookup(@table, key) do
|
||||
[{^key, ^day, used}] -> used
|
||||
_ -> 0
|
||||
end
|
||||
end
|
||||
|
||||
defp key(secret, day, address) do
|
||||
:crypto.mac(:hmac, :sha256, secret, [Integer.to_string(day), "|", address_binary(address)])
|
||||
end
|
||||
|
||||
defp address_binary(address) when is_tuple(address), do: :erlang.term_to_binary(address)
|
||||
|
||||
defp sweep(day) do
|
||||
:ets.select_delete(@table, [{{:_, :"$1", :_}, [{:<, :"$1", day}], [true]}])
|
||||
end
|
||||
|
||||
defp ms_until_utc_midnight do
|
||||
now = DateTime.utc_now()
|
||||
midnight = now |> DateTime.to_date() |> Date.add(1) |> DateTime.new!(~T[00:00:00], "Etc/UTC")
|
||||
|
||||
max(DateTime.diff(midnight, now, :millisecond), 0)
|
||||
end
|
||||
end
|
||||
@@ -91,6 +91,7 @@ defmodule ChesstrainerWeb do
|
||||
|
||||
# Common modules used in templates
|
||||
alias Phoenix.LiveView.JS
|
||||
alias Chesstrainer.Branding
|
||||
alias ChesstrainerWeb.Layouts
|
||||
|
||||
# Routes generation with the ~p sigil
|
||||
|
||||
@@ -70,9 +70,9 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
~H"""
|
||||
<header>
|
||||
<nav class="nav-wrap" aria-label="Main navigation">
|
||||
<a class="brand" href="/" aria-label="Lucid Chess home">
|
||||
<a class="brand" href="/" aria-label={"#{Branding.name()} home"}>
|
||||
<span class="brand-mark">♞</span>
|
||||
<span>LUCID</span>
|
||||
<span>{Branding.wordmark()}</span>
|
||||
</a>
|
||||
|
||||
<div class="nav-right">
|
||||
@@ -151,7 +151,7 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
|
||||
# Signed-in users start a puzzle session; visitors browse the public list.
|
||||
defp start_href(%{user: %{}}), do: ~p"/train"
|
||||
defp start_href(_scope), do: ~p"/endgames"
|
||||
defp start_href(_scope), do: ~p"/guest-train"
|
||||
|
||||
@doc """
|
||||
Renders the site-wide footer.
|
||||
@@ -166,19 +166,19 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
~H"""
|
||||
<footer class="site-footer">
|
||||
<div class="footer-brand">
|
||||
<a class="brand" href="/" aria-label="Lucid Chess home">
|
||||
<a class="brand" href="/" aria-label={"#{Branding.name()} home"}>
|
||||
<span class="brand-mark">♞</span>
|
||||
<span>LUCID</span>
|
||||
<span>{Branding.wordmark()}</span>
|
||||
</a>
|
||||
<p>Short, focused endgame training.</p>
|
||||
</div>
|
||||
|
||||
<nav class="footer-links" aria-label="Footer">
|
||||
<a href="/#privacy">Privacy Policy</a>
|
||||
<a href="/#terms-conditions">Terms & Conditions</a>
|
||||
<a href="/privacy">Privacy Policy</a>
|
||||
<a href="/terms-conditions">Terms & Conditions</a>
|
||||
</nav>
|
||||
|
||||
<small>© {@year} Lucid Chess</small>
|
||||
<small>© {@year} {Branding.name()}</small>
|
||||
</footer>
|
||||
"""
|
||||
end
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
|
||||
<meta name="csrf-token" content={get_csrf_token()} />
|
||||
<.live_title
|
||||
default="Lucid Chess — Endgame Trainer"
|
||||
suffix={assigns[:title_suffix] || " · Lucid Chess"}
|
||||
default={Branding.home_title()}
|
||||
suffix={assigns[:title_suffix] || " · #{Branding.name()}"}
|
||||
phx-no-format
|
||||
>{assigns[:page_title]}</.live_title>
|
||||
<meta
|
||||
@@ -17,11 +17,11 @@
|
||||
/>
|
||||
<link :if={assigns[:canonical_url]} rel="canonical" href={assigns[:canonical_url]} />
|
||||
<meta :if={assigns[:meta_description]} property="og:type" content="website" />
|
||||
<meta :if={assigns[:meta_description]} property="og:site_name" content="Lucid Chess" />
|
||||
<meta :if={assigns[:meta_description]} property="og:site_name" content={Branding.name()} />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
property="og:title"
|
||||
content={assigns[:page_title] || "Lucid Chess — Endgame Trainer"}
|
||||
content={assigns[:page_title] || Branding.home_title()}
|
||||
/>
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
@@ -33,7 +33,7 @@
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
name="twitter:title"
|
||||
content={assigns[:page_title] || "Lucid Chess — Endgame Trainer"}
|
||||
content={assigns[:page_title] || Branding.home_title()}
|
||||
/>
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
|
||||
@@ -2,6 +2,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.DailyPuzzles
|
||||
alias Chesstrainer.Endgames
|
||||
|
||||
@@ -13,7 +14,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
|
||||
conn
|
||||
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|
||||
|> assign(:page_title, "Lucid Chess — Endgame Trainer")
|
||||
|> assign(:page_title, Branding.home_title())
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, @description)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
@@ -25,4 +26,27 @@ defmodule ChesstrainerWeb.PageController do
|
||||
today: Date.utc_today()
|
||||
)
|
||||
end
|
||||
|
||||
def privacy(conn, _params) do
|
||||
conn
|
||||
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|
||||
|> assign(:page_title, Branding.title("Privacy Policy"))
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(
|
||||
:meta_description,
|
||||
"How #{Branding.name()} collects, uses, and protects your personal data."
|
||||
)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> render(:privacy)
|
||||
end
|
||||
|
||||
def terms_conditions(conn, _params) do
|
||||
conn
|
||||
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|
||||
|> assign(:page_title, Branding.title("Terms & Conditions"))
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, "The terms that apply when you use #{Branding.name()}.")
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> render(:terms_conditions)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="progress-banner" id="progress">
|
||||
<%!-- <section class="progress-banner" id="progress">
|
||||
<div>
|
||||
<span class="section-kicker">A calmer way to improve</span>
|
||||
<h2>
|
||||
@@ -85,5 +85,5 @@
|
||||
<.pill_button variant={:light} navigate={play_path(@active_endgame)}>
|
||||
Begin with the basics <.icon_arrow />
|
||||
</.pill_button>
|
||||
</section>
|
||||
</section> --%>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
<Layouts.flash_group flash={@flash} />
|
||||
|
||||
<main>
|
||||
<article class="legal">
|
||||
<h1>Privacy Policy</h1>
|
||||
<p class="legal-meta">Last updated: 6 November 2026</p>
|
||||
|
||||
<p>
|
||||
{Branding.name()} is an endgame training site. This policy explains what
|
||||
information we collect when you use it, why we collect it, and the choices
|
||||
you have. It covers the website and every page under it, including the
|
||||
guest trainer.
|
||||
</p>
|
||||
|
||||
<h2>What we collect</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Account details.</strong>
|
||||
If you register, we store your username, email address, and a hashed
|
||||
password. We never store passwords in plain text.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Training activity.</strong>
|
||||
We record the puzzles you attempt and whether you solved them, so we can
|
||||
show your progress and keep the daily puzzle meaningful.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Technical data.</strong>
|
||||
Our hosting and server infrastructure may keep standard request logs
|
||||
(IP address, browser, timestamps) for security and troubleshooting.
|
||||
These logs are rotated regularly.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Messages you send us.</strong>
|
||||
If you contact us, we keep the message and our reply for as long as
|
||||
needed to help you.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h2>Cookies and local storage</h2>
|
||||
<p>
|
||||
We use a small number of cookies and local storage entries that are
|
||||
required for the site to work:
|
||||
</p>
|
||||
<ul>
|
||||
<li>a session cookie that keeps you signed in;</li>
|
||||
<li>a CSRF token that protects forms from cross-site requests;</li>
|
||||
<li>a colour-mode preference stored in your browser.</li>
|
||||
</ul>
|
||||
<p>
|
||||
We do not use advertising cookies, third-party analytics, or cross-site
|
||||
tracking. You can clear these entries at any time in your browser
|
||||
settings; doing so will sign you out and reset your colour mode.
|
||||
</p>
|
||||
|
||||
<h2>How we use your information</h2>
|
||||
<ul>
|
||||
<li>To create and secure your account and sign you in.</li>
|
||||
<li>To run the trainer and remember your progress.</li>
|
||||
<li>To send service emails, such as confirmation and password reset links.</li>
|
||||
<li>To keep the site available, prevent abuse, and fix faults.</li>
|
||||
<li>To respond when you ask for help.</li>
|
||||
</ul>
|
||||
<p>
|
||||
We rely on our contract with you to provide the service, our legitimate
|
||||
interests in keeping it secure and improving it, and your consent where we
|
||||
ask for it. You can withdraw consent at any time.
|
||||
</p>
|
||||
|
||||
<h2>Guest puzzle limit</h2>
|
||||
<p>
|
||||
Visitors who use the guest trainer without an account get a limited number
|
||||
of free puzzles per UTC day. To enforce that limit and prevent abuse, we
|
||||
identify each visitor by a keyed hash (HMAC-SHA256) of their IP address.
|
||||
The limiter itself never stores, logs, or shares the raw address.
|
||||
</p>
|
||||
<p>
|
||||
The hash exists only in the memory of the server that handled your request.
|
||||
It is tied to the current UTC day, stops being usable at 00:00 UTC, and is
|
||||
deleted by a periodic sweep shortly afterwards; it is also discarded when
|
||||
the server restarts. It is never written to a database, a log, or a
|
||||
backup, and no cookie or other client-side storage is involved. Signed-in
|
||||
accounts are not metered this way.
|
||||
</p>
|
||||
<p>
|
||||
We process this hash on the basis of our legitimate interests
|
||||
(Article 6(1)(f) GDPR) in keeping the service available and preventing
|
||||
abuse of the free tier. We do not share it with anyone. You have the right
|
||||
to object to this processing; to do so, contact us using the address below.
|
||||
</p>
|
||||
|
||||
<h2>Sharing</h2>
|
||||
<p>
|
||||
We do not sell your personal information. We share it only with providers
|
||||
who help us run the site — for example hosting, database, and email
|
||||
delivery providers — and only as far as they need it to perform that work.
|
||||
We may also disclose information where the law requires it or to protect
|
||||
the rights and safety of our users.
|
||||
</p>
|
||||
|
||||
<h2>Retention</h2>
|
||||
<p>
|
||||
We keep account and training data while your account is open. If you
|
||||
delete your account, we remove your personal information within a
|
||||
reasonable period, except where we must keep records for legal, security,
|
||||
or accounting reasons.
|
||||
</p>
|
||||
|
||||
<h2>Your rights</h2>
|
||||
<p>
|
||||
Depending on where you live, you may have the right to access, correct,
|
||||
delete, restrict, or export your personal information, and to object to
|
||||
some uses of it. To make a request, contact us using the address below. If
|
||||
you are in the UK or EU and are unhappy with our response, you can complain
|
||||
to your local data protection authority.
|
||||
</p>
|
||||
|
||||
<h2>Children</h2>
|
||||
<p>
|
||||
The service is not directed at children under 13, and we do not knowingly
|
||||
collect their personal information. If you believe a child has created an
|
||||
account, contact us and we will remove it.
|
||||
</p>
|
||||
|
||||
<h2>Changes</h2>
|
||||
<p>
|
||||
We may update this policy as the service changes. When we do, we will
|
||||
change the date at the top of this page and, for significant changes,
|
||||
notify signed-in users by email or on the site.
|
||||
</p>
|
||||
|
||||
<h2>Contact</h2>
|
||||
<p>
|
||||
Questions about this policy or your data can be sent to <a href={"mailto:" <> Branding.support_email()}>{Branding.support_email()}</a>.
|
||||
</p>
|
||||
</article>
|
||||
</main>
|
||||
@@ -0,0 +1,118 @@
|
||||
<Layouts.flash_group flash={@flash} />
|
||||
|
||||
<main>
|
||||
<article class="legal">
|
||||
<h1>Terms & Conditions</h1>
|
||||
<p class="legal-meta">Last updated: 6 November 2026</p>
|
||||
|
||||
<p>
|
||||
These terms govern your use of {Branding.name()}. By browsing the site, using
|
||||
the guest trainer, or creating an account, you agree to them. If you do not
|
||||
agree, please do not use the service.
|
||||
</p>
|
||||
|
||||
<h2>The service</h2>
|
||||
<p>
|
||||
{Branding.name()} provides short endgame puzzles and training tools. Some
|
||||
features are available without an account; others, such as saved progress
|
||||
and the full puzzle list, require you to register. We may add, change, or
|
||||
remove features over time.
|
||||
</p>
|
||||
<p>
|
||||
The guest trainer is limited to a fixed number of puzzles per UTC day,
|
||||
which we may change. The limit is enforced as described in our <a href="/privacy">Privacy Policy</a>.
|
||||
</p>
|
||||
|
||||
<h2>Accounts</h2>
|
||||
<ul>
|
||||
<li>You must be at least 13 years old to create an account.</li>
|
||||
<li>Give accurate information and keep it up to date.</li>
|
||||
<li>Keep your password private and tell us promptly about unauthorised use.</li>
|
||||
<li>You are responsible for activity that happens under your account.</li>
|
||||
<li>Do not share, sell, or transfer your account to someone else.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Acceptable use</h2>
|
||||
<p>You agree not to:</p>
|
||||
<ul>
|
||||
<li>break the law or infringe anyone else's rights;</li>
|
||||
<li>interfere with the site, its servers, or other users;</li>
|
||||
<li>attempt to gain access to accounts or data that are not yours;</li>
|
||||
<li>scrape, crawl, or bulk-download the site without our permission;</li>
|
||||
<li>copy, resell, or redistribute the service or its content;</li>
|
||||
<li>use the service to send spam or malicious code.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Our content and your licence</h2>
|
||||
<p>
|
||||
The site, its design, text, and software are owned by {Branding.name()} or its
|
||||
licensors and are protected by copyright and other laws. We grant you a
|
||||
personal, non-exclusive, non-transferable licence to use the service for
|
||||
your own training. You may not reproduce, modify, distribute, or create
|
||||
derivative works from our content without written permission.
|
||||
</p>
|
||||
<p>
|
||||
Chess positions and puzzle data are drawn from public sources and
|
||||
tablebase material. You may use the training output for your own study,
|
||||
but not to build a competing product.
|
||||
</p>
|
||||
|
||||
<h2>Your data</h2>
|
||||
<p>
|
||||
You keep ownership of the information you provide. You give us permission
|
||||
to store and use it as described in our <a href="/privacy">Privacy Policy</a>
|
||||
so that we can run the service.
|
||||
</p>
|
||||
|
||||
<h2>Paid plans</h2>
|
||||
<p>
|
||||
Some features may be offered as part of a paid plan. Prices, billing
|
||||
periods, and cancellation terms will be shown before you purchase. Unless
|
||||
the law requires otherwise, payments are non-refundable once a billing
|
||||
period has started. We may change prices with reasonable notice.
|
||||
</p>
|
||||
|
||||
<h2>Availability and changes</h2>
|
||||
<p>
|
||||
We aim to keep the site available, but we do not guarantee uninterrupted
|
||||
access. Maintenance, faults, or circumstances outside our control may
|
||||
interrupt it. We may suspend or discontinue the service, in whole or in
|
||||
part, with reasonable notice where practical.
|
||||
</p>
|
||||
|
||||
<h2>Disclaimer</h2>
|
||||
<p>
|
||||
{Branding.name()} is an educational tool. We do not promise that using it will
|
||||
improve your rating or results, and puzzle solutions are provided for
|
||||
training purposes only. The service is provided "as is" to the extent
|
||||
permitted by law.
|
||||
</p>
|
||||
|
||||
<h2>Limitation of liability</h2>
|
||||
<p>
|
||||
To the extent permitted by law, {Branding.name()} is not liable for indirect or
|
||||
consequential losses, loss of data, or loss of profits arising from your
|
||||
use of the service. Nothing in these terms limits liability that cannot be
|
||||
limited by law, including for death, personal injury, or fraud.
|
||||
</p>
|
||||
|
||||
<h2>Termination</h2>
|
||||
<p>
|
||||
You may stop using the service and delete your account at any time. We may
|
||||
suspend or close an account that breaches these terms, that we reasonably
|
||||
believe is being misused, or where we are required to do so by law.
|
||||
</p>
|
||||
|
||||
<h2>Governing law</h2>
|
||||
<p>
|
||||
These terms are governed by the laws of France. Any dispute
|
||||
will be handled by the courts of France, unless the law where
|
||||
you live gives you the right to bring it elsewhere.
|
||||
</p>
|
||||
|
||||
<h2>Contact</h2>
|
||||
<p>
|
||||
Questions about these terms can be sent to <a href={"mailto:" <> Branding.support_email()}>{Branding.support_email()}</a>.
|
||||
</p>
|
||||
</article>
|
||||
</main>
|
||||
@@ -12,8 +12,8 @@ defmodule ChesstrainerWeb.Endpoint do
|
||||
]
|
||||
|
||||
socket "/live", Phoenix.LiveView.Socket,
|
||||
websocket: [connect_info: [session: @session_options]],
|
||||
longpoll: [connect_info: [session: @session_options]]
|
||||
websocket: [connect_info: [:peer_data, :x_headers, session: @session_options]],
|
||||
longpoll: [connect_info: [:peer_data, :x_headers, session: @session_options]]
|
||||
|
||||
# Serve at "/" the static files from "priv/static" directory.
|
||||
#
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
defmodule ChesstrainerWeb.ChessTestLive do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
{:ok, assign(socket, last_move: "None yet", san: "None yet", move_list: [])}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<div class="mx-auto max-w-2xl p-6">
|
||||
<h1 class="text-2xl font-bold mb-4">Chessground LiveView Test</h1>
|
||||
|
||||
<form phx-submit="load_fen" class="mb-6 flex gap-2 bg-gray-50 p-4 rounded-lg shadow-sm">
|
||||
<div class="flex-1">
|
||||
<input
|
||||
type="text"
|
||||
name="fen"
|
||||
placeholder="Paste FEN string here (e.g., rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1)"
|
||||
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="px-4 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700 transition"
|
||||
>
|
||||
Load FEN
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="bg-gray-100 p-4 rounded mb-4 flex justify-between items-center shadow-sm">
|
||||
<div>
|
||||
<p class="text-sm text-gray-600 font-semibold">Last Played Move:</p>
|
||||
<p class="text-lg font-mono text-blue-600">{@last_move}</p>
|
||||
<p class="text-lg font-mono text-blue-600">{@san}</p>
|
||||
<p class="text-lg font-mono text-emerald-600">
|
||||
{if length(@move_list) == 0 do
|
||||
"No Moves"
|
||||
else
|
||||
Enum.reverse(@move_list) |> Enum.join(", ")
|
||||
end}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-center bg-gray-200 p-4 rounded-xl shadow-inner">
|
||||
<div
|
||||
id="chessground-board"
|
||||
phx-hook="ChessBoard"
|
||||
phx-update="ignore"
|
||||
class="w-[400px] h-[400px]"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("load_fen", %{"fen" => fen}, socket) do
|
||||
clean_fen = String.trim(fen)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:last_move, "Position Loaded")
|
||||
|> assign(:san, "None yet")
|
||||
|> assign(:move_list, [])
|
||||
|> push_event("set_fen", %{fen: clean_fen})}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event(
|
||||
"move_played",
|
||||
%{"from" => from, "to" => to, "fen" => _fen, "san" => san},
|
||||
socket
|
||||
) do
|
||||
current_moves = socket.assigns.move_list
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:last_move, "#{from} ➔ #{to}")
|
||||
|> assign(:san, san)
|
||||
|> assign(:move_list, [san | current_moves])}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,266 @@
|
||||
defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
@moduledoc """
|
||||
Public training: play random endgame puzzles without an account.
|
||||
|
||||
There is no difficulty selection and no session — each puzzle is drawn from
|
||||
the whole pool and "Next puzzle" draws another. Anonymous visitors get a
|
||||
daily budget of puzzles (see `Chesstrainer.GuestLimits`); when it runs out the
|
||||
page asks them to sign up. Signed-in visitors are sent to `/train`, where they
|
||||
can pick a difficulty. Move grading, opponent replies and review come from
|
||||
`ChesstrainerWeb.EndgameLive.PlayCore`.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.GuestLimits
|
||||
alias ChesstrainerWeb.EndgameLive.PlayCore
|
||||
alias ChesstrainerWeb.PlayComponents
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash}>
|
||||
<.header>
|
||||
Train
|
||||
<:subtitle>
|
||||
<%= if @endgame do %>
|
||||
A random endgame puzzle — {@endgame.color
|
||||
|> Atom.to_string()
|
||||
|> String.capitalize()} to move, rating {round(@endgame.rating)}.
|
||||
<% else %>
|
||||
Random endgame puzzles.
|
||||
<% end %>
|
||||
<span
|
||||
:if={@guest_remaining != nil}
|
||||
id="guest-remaining"
|
||||
class="mt-1 block text-xs text-muted"
|
||||
>
|
||||
{remaining_label(@guest_remaining, @limit)}
|
||||
</span>
|
||||
<span class="mt-1 block text-xs text-muted">
|
||||
<.link navigate={~p"/users/register"}>Create a free account</.link>
|
||||
to track your rating and train at your level.
|
||||
</span>
|
||||
</:subtitle>
|
||||
</.header>
|
||||
|
||||
<section
|
||||
:if={@limit_reached}
|
||||
id="guest-limit"
|
||||
class="rounded-xl border border-hairline bg-canvas-raised p-6"
|
||||
>
|
||||
<h2 class="text-lg font-semibold">
|
||||
You've used your {@limit} free puzzles today
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Sign up for a free account to keep training. Your rating is tracked, so
|
||||
the puzzles match your level.
|
||||
</p>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Free guest puzzles reset at 00:00 UTC (in {format_wait(@limit_reached)}).
|
||||
</p>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<.button id="guest-sign-up" navigate={~p"/users/register"} variant="primary">
|
||||
<.icon name="hero-user-plus" /> Sign up free
|
||||
</.button>
|
||||
<.button navigate={~p"/users/log-in"}>Log in</.button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<PlayComponents.play_surface
|
||||
:if={@endgame}
|
||||
session={is_nil(@limit_reached)}
|
||||
endgame={@endgame}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
review_tablebase={@review_tablebase}
|
||||
review_blocked={@review_blocked}
|
||||
awaiting_reply={@awaiting_reply}
|
||||
last_grade={@last_grade}
|
||||
awaiting_best_line={@awaiting_best_line}
|
||||
/>
|
||||
|
||||
<p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p>
|
||||
|
||||
<p
|
||||
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
|
||||
class="text-base-content/70"
|
||||
>
|
||||
No endgames are available yet. Please check back soon.
|
||||
</p>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
socket = assign(socket, :limit, GuestLimits.limit())
|
||||
|
||||
cond do
|
||||
signed_in?(socket) ->
|
||||
{:ok, redirect(socket, to: ~p"/train")}
|
||||
|
||||
connected?(socket) ->
|
||||
take_puzzle(socket, client_address(socket))
|
||||
|
||||
true ->
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:loading, true)
|
||||
|> assign(:endgame, nil)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, nil)
|
||||
|> assign(:guest_address, nil)}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("next_puzzle", _params, socket) do
|
||||
case GuestLimits.take(socket.assigns.guest_address) do
|
||||
{:ok, remaining} ->
|
||||
endgame =
|
||||
Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) ||
|
||||
Endgames.random_endgame()
|
||||
|
||||
case endgame do
|
||||
nil ->
|
||||
{:noreply, put_flash(socket, :info, "No more puzzles are available right now.")}
|
||||
|
||||
endgame ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:guest_remaining, remaining)
|
||||
|> PlayCore.init(endgame, page_title: "Train")}
|
||||
end
|
||||
|
||||
{:limit_reached, retry_ms} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, retry_ms)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("endgame_move_played", params, socket),
|
||||
do: PlayCore.move_played(socket, params)
|
||||
|
||||
def handle_event("opponent_reply_applied", params, socket),
|
||||
do: PlayCore.opponent_reply_applied(socket, params)
|
||||
|
||||
def handle_event("chess_fen_invalid", params, socket),
|
||||
do: PlayCore.fen_invalid(socket, params)
|
||||
|
||||
def handle_event("reset", _params, socket), do: PlayCore.reset(socket)
|
||||
|
||||
def handle_event("review", _params, socket), do: PlayCore.review(socket)
|
||||
|
||||
def handle_event("review_prev", _params, socket), do: PlayCore.review_prev(socket)
|
||||
|
||||
def handle_event("review_next", _params, socket), do: PlayCore.review_next(socket)
|
||||
|
||||
def handle_event("review_step", %{"index" => index}, socket),
|
||||
do: PlayCore.review_step(socket, index)
|
||||
|
||||
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
||||
|
||||
def handle_event("best_line_move_applied", params, socket),
|
||||
do: PlayCore.best_line_move_applied(socket, params)
|
||||
|
||||
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
|
||||
|
||||
defp take_puzzle(socket, address) do
|
||||
case GuestLimits.take(address) do
|
||||
{:ok, remaining} ->
|
||||
socket =
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, remaining)
|
||||
|> assign(:limit_reached, nil)
|
||||
|
||||
{:ok, load_random_endgame(socket)}
|
||||
|
||||
{:limit_reached, retry_ms} ->
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, retry_ms)
|
||||
|> assign(:endgame, nil)}
|
||||
end
|
||||
end
|
||||
|
||||
defp load_random_endgame(socket) do
|
||||
case Endgames.random_endgame() do
|
||||
nil -> assign(socket, :endgame, nil)
|
||||
endgame -> PlayCore.init(socket, endgame, page_title: "Train")
|
||||
end
|
||||
end
|
||||
|
||||
defp client_address(socket) do
|
||||
if GuestLimits.trust_forwarded_for?() do
|
||||
forwarded_address(socket) || peer_address(socket)
|
||||
else
|
||||
peer_address(socket)
|
||||
end
|
||||
end
|
||||
|
||||
defp peer_address(socket) do
|
||||
case get_connect_info(socket, :peer_data) do
|
||||
%{address: address} -> address
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp forwarded_address(socket) do
|
||||
with headers when is_list(headers) <- get_connect_info(socket, :x_headers),
|
||||
{_, value} <- List.keyfind(headers, "x-forwarded-for", 0),
|
||||
address when address != nil <- parse_address(value) do
|
||||
address
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
# The rightmost entry is the one our own proxy appended.
|
||||
defp parse_address(value) do
|
||||
value
|
||||
|> String.split(",")
|
||||
|> List.last()
|
||||
|> to_string()
|
||||
|> String.trim()
|
||||
|> String.to_charlist()
|
||||
|> :inet.parse_address()
|
||||
|> case do
|
||||
{:ok, address} -> address
|
||||
{:error, _} -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp signed_in?(socket) do
|
||||
case socket.assigns.current_scope do
|
||||
%{user: %{}} -> true
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp remaining_label(0, _limit), do: "Last free puzzle today"
|
||||
|
||||
defp remaining_label(remaining, limit),
|
||||
do: "#{remaining} of #{limit} free puzzles left today"
|
||||
|
||||
defp format_wait(ms) when is_integer(ms) do
|
||||
minutes = max(div(ms + 59_999, 60_000), 1)
|
||||
hours = div(minutes, 60)
|
||||
mins = rem(minutes, 60)
|
||||
|
||||
if hours > 0, do: "#{hours}h #{mins}m", else: "#{mins}m"
|
||||
end
|
||||
end
|
||||
@@ -21,10 +21,8 @@ defmodule ChesstrainerWeb.Router do
|
||||
pipe_through :browser
|
||||
|
||||
get "/", PageController, :home
|
||||
|
||||
live "/chess-test", ChessTestLive
|
||||
|
||||
live "/endgames", EndgameLive.PlayerIndex, :index
|
||||
get "/privacy", PageController, :privacy
|
||||
get "/terms-conditions", PageController, :terms_conditions
|
||||
end
|
||||
|
||||
scope "/admin", ChesstrainerWeb do
|
||||
@@ -68,6 +66,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
|
||||
live_session :require_authenticated_user,
|
||||
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
|
||||
live "/endgames", EndgameLive.PlayerIndex, :index
|
||||
live "/train", EndgameLive.Train, :train
|
||||
live "/users/settings", UserLive.Settings, :edit
|
||||
live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email
|
||||
@@ -81,6 +80,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
|
||||
live_session :current_user,
|
||||
on_mount: [{ChesstrainerWeb.UserAuth, :mount_current_scope}] do
|
||||
live "/guest-train", EndgameLive.GuestTrain, :play
|
||||
live "/endgames/:public_code/play", EndgameLive.Play, :play
|
||||
live "/users/register", UserLive.Registration, :new
|
||||
live "/users/log-in", UserLive.Login, :new
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
# We recommend using the bang functions (`insert!`, `update!`
|
||||
# and so on) as they will fail if something goes wrong.
|
||||
|
||||
Code.require_file("seeds/endgames/win.ex", __DIR__)
|
||||
Code.require_file("seeds/endgames/draw.ex", __DIR__)
|
||||
Code.require_file("seeds/endgames.ex", __DIR__)
|
||||
Code.require_file("seeds/themes.ex", __DIR__)
|
||||
|
||||
|
||||
@@ -1,43 +1,7 @@
|
||||
alias Chesstrainer.Repo.Seeds.Endgames.{Win, Draw}
|
||||
|
||||
defmodule Chesstrainer.Repo.Seeds.Endgames do
|
||||
def all do
|
||||
[
|
||||
%{
|
||||
fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1",
|
||||
color: :white,
|
||||
message: "Rook vs king endgame",
|
||||
notes: "Basic rook endgame",
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "r7/4R2P/3p4/3k1K2/2p5/8/8/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/5p2/1P1K1k2/8/2r5/8/7R w - - 0 0",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "5n2/R7/4pk2/8/5PK1/8/8/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "5k2/R7/3K4/4p3/5P2/8/8/5r2 w - - 0 1",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "5k2/8/p7/4K1P1/P4R2/6r1/8/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :win
|
||||
}
|
||||
]
|
||||
Win.all() ++ Draw.all()
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
defmodule Chesstrainer.Repo.Seeds.Endgames.Draw do
|
||||
def all do
|
||||
[
|
||||
%{
|
||||
fen: "r7/4R2P/3p4/3k1K2/2p5/8/8/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/5p2/1P1K1k2/8/2r5/8/7R w - - 0 0",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "5n2/R7/4pk2/8/5PK1/8/8/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "5k2/R7/3K4/4p3/5P2/8/8/5r2 w - - 0 1",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "5k2/8/p7/4K1P1/P4R2/6r1/8/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "6k1/8/6r1/8/5b2/2PR4/4K3/8 w - - 0 1",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/1p3k2/3B4/8/3b2P1/1P6/6K1/8 b - - 0 1",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/k5r1/2N5/PK6/2B5/8/8/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "6k1/8/5K2/8/5P1R/r6P/8/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/4k1KP/p5P1/r7/8/8/8 w - - 0 1",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/5K2/3kn3/6B1/7P/8/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/6k1/8/R7/7K/1P6/5r2/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/7p/6p1/5k2/7N/8/4KP2/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/6Rp/8/5k2/5p2/5K2/7r/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "6k1/3R4/5Kp1/6r1/4P3/8/8/8 b - - 0 1",
|
||||
color: :black,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/7B/8/8/3p4/6Kp/3k1n2 w - - 0 0",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "7r/8/8/6k1/R6p/6pK/8/8 w - - 0 52",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "R7/8/8/8/6K1/5p2/5Pk1/4r3 w - - 0 1",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/8/5n2/1P1k4/3p1P2/3P1K2/8/8 w - - 0 0",
|
||||
color: :white,
|
||||
result: :draw
|
||||
},
|
||||
%{
|
||||
fen: "8/5k2/6R1/4r2p/8/6KP/6P1/8 w - - 5 49",
|
||||
color: :white,
|
||||
result: :draw
|
||||
}
|
||||
]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,58 @@
|
||||
defmodule Chesstrainer.Repo.Seeds.Endgames.Win do
|
||||
def all do
|
||||
[
|
||||
%{
|
||||
fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1",
|
||||
color: :white,
|
||||
message: "Rook vs king endgame",
|
||||
notes: "Basic rook endgame",
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/8/8/2p1k3/P6R/1K6/6rP/8 w - - 0 0",
|
||||
color: :white,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/7p/6p1/8/k7/8/2K3P1/8 b - - 0 0",
|
||||
color: :black,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "R7/8/8/6p1/4k3/3rPp1P/8/6K1 b - - 0 1",
|
||||
color: :black,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/8/7k/8/8/8/5q2/3B2RK b - - 0 1",
|
||||
color: :black,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "6K1/8/5P1k/2R5/1r6/8/2p5/8 w - - 0 0",
|
||||
color: :white,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/r7/5PK1/3k4/p7/8/1R6/8 w - - 0 1",
|
||||
color: :white,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "R7/P4r2/5k2/3Kp3/8/8/8/8 w - - 0 0",
|
||||
color: :white,
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/B2k4/1P3K2/3bP3/8/8/8/8 w - - 0 1",
|
||||
color: :white,
|
||||
result: :win
|
||||
},
|
||||
]
|
||||
end
|
||||
end
|
||||
@@ -322,7 +322,7 @@ defmodule Chesstrainer.EndgamesTest do
|
||||
end
|
||||
end
|
||||
|
||||
describe "random_endgame/0" do
|
||||
describe "random_endgame/1" do
|
||||
test "returns nil when there are no endgames" do
|
||||
assert Endgames.random_endgame() == nil
|
||||
end
|
||||
@@ -333,6 +333,13 @@ defmodule Chesstrainer.EndgamesTest do
|
||||
|
||||
assert Endgames.random_endgame().id in [kr.id, kq.id]
|
||||
end
|
||||
|
||||
test "skips excluded endgames" do
|
||||
kr = create_endgame!(@kr)
|
||||
kq = create_endgame!(@kq)
|
||||
|
||||
assert Endgames.random_endgame(exclude_ids: [kr.id]).id == kq.id
|
||||
end
|
||||
end
|
||||
|
||||
describe "curated_endgames/1" do
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
defmodule Chesstrainer.GuestLimitsTest do
|
||||
use ExUnit.Case, async: false
|
||||
|
||||
alias Chesstrainer.GuestLimits
|
||||
|
||||
@address {203, 0, 113, 7}
|
||||
@other {198, 51, 100, 9}
|
||||
@today ~D[2026-11-06]
|
||||
|
||||
setup do
|
||||
GuestLimits.reset()
|
||||
:ok
|
||||
end
|
||||
|
||||
test "allows five puzzles a day and blocks the sixth" do
|
||||
assert {:ok, 4} = GuestLimits.take(@address, @today)
|
||||
assert {:ok, 3} = GuestLimits.take(@address, @today)
|
||||
assert {:ok, 2} = GuestLimits.take(@address, @today)
|
||||
assert {:ok, 1} = GuestLimits.take(@address, @today)
|
||||
assert {:ok, 0} = GuestLimits.take(@address, @today)
|
||||
|
||||
assert {:limit_reached, retry_ms} = GuestLimits.take(@address, @today)
|
||||
assert retry_ms > 0
|
||||
end
|
||||
|
||||
test "resets on the next UTC day" do
|
||||
for _ <- 1..5, do: assert({:ok, _} = GuestLimits.take(@address, @today))
|
||||
assert {:limit_reached, _} = GuestLimits.take(@address, @today)
|
||||
|
||||
assert {:ok, 4} = GuestLimits.take(@address, ~D[2026-11-07])
|
||||
end
|
||||
|
||||
test "tracks addresses independently" do
|
||||
for _ <- 1..5, do: assert({:ok, _} = GuestLimits.take(@address, @today))
|
||||
|
||||
assert {:limit_reached, _} = GuestLimits.take(@address, @today)
|
||||
assert {:ok, 4} = GuestLimits.take(@other, @today)
|
||||
end
|
||||
|
||||
test "does not limit a missing address" do
|
||||
assert {:ok, nil} = GuestLimits.take(nil, @today)
|
||||
assert {:ok, nil} = GuestLimits.take(nil, @today)
|
||||
end
|
||||
|
||||
test "reset clears spent budgets" do
|
||||
for _ <- 1..5, do: assert({:ok, _} = GuestLimits.take(@address, @today))
|
||||
assert {:limit_reached, _} = GuestLimits.take(@address, @today)
|
||||
|
||||
GuestLimits.reset()
|
||||
|
||||
assert {:ok, 4} = GuestLimits.take(@address, @today)
|
||||
end
|
||||
end
|
||||
@@ -6,6 +6,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
||||
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.DailyPuzzles
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Themes
|
||||
@@ -51,19 +52,19 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
||||
document = LazyHTML.from_document(html)
|
||||
|
||||
assert html =~ "Learn to see the"
|
||||
assert html =~ "LUCID"
|
||||
assert html =~ Branding.wordmark()
|
||||
assert html =~ "Privacy Policy"
|
||||
assert html =~ "/#terms-conditions"
|
||||
assert html =~ "/terms-conditions"
|
||||
assert html =~ "Start training"
|
||||
assert html =~ ~s(id="nav-links")
|
||||
assert html =~ "menu-button"
|
||||
assert html =~ ~s(class="site-footer")
|
||||
assert html =~ "© #{DateTime.utc_now().year} Lucid Chess"
|
||||
assert html =~ "© #{DateTime.utc_now().year} #{Branding.name()}"
|
||||
assert html =~ ~p"/endgames"
|
||||
assert html =~ "/assets/js/marketing.js"
|
||||
refute html =~ "/assets/js/app.js"
|
||||
|
||||
assert LazyHTML.text(LazyHTML.query(document, "title")) =~ "Lucid Chess — Endgame Trainer"
|
||||
assert LazyHTML.text(LazyHTML.query(document, "title")) =~ Branding.home_title()
|
||||
refute html =~ "Phoenix Framework"
|
||||
|
||||
eyebrow = LazyHTML.query(document, ".eyebrow")
|
||||
@@ -80,18 +81,83 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
||||
|
||||
for {selector, content} <- [
|
||||
{~s(meta[property="og:type"]), "website"},
|
||||
{~s(meta[property="og:site_name"]), "Lucid Chess"},
|
||||
{~s(meta[property="og:title"]), "Lucid Chess — Endgame Trainer"},
|
||||
{~s(meta[property="og:site_name"]), Branding.name()},
|
||||
{~s(meta[property="og:title"]), Branding.home_title()},
|
||||
{~s(meta[property="og:description"]), @description},
|
||||
{~s(meta[property="og:url"]), canonical},
|
||||
{~s(meta[name="twitter:card"]), "summary"},
|
||||
{~s(meta[name="twitter:title"]), "Lucid Chess — Endgame Trainer"},
|
||||
{~s(meta[name="twitter:title"]), Branding.home_title()},
|
||||
{~s(meta[name="twitter:description"]), @description}
|
||||
] do
|
||||
assert LazyHTML.attribute(LazyHTML.query(document, selector), "content") == [content]
|
||||
end
|
||||
end
|
||||
|
||||
test "GET /privacy renders the privacy policy", %{conn: conn} do
|
||||
html = conn |> get(~p"/privacy") |> html_response(200)
|
||||
document = LazyHTML.from_document(html)
|
||||
|
||||
assert LazyHTML.text(LazyHTML.query(document, "h1")) == "Privacy Policy"
|
||||
assert html =~ "Last updated: 6 November 2026"
|
||||
assert html =~ "What we collect"
|
||||
assert html =~ "Cookies and local storage"
|
||||
assert html =~ "Guest puzzle limit"
|
||||
assert html =~ "HMAC-SHA256"
|
||||
assert html =~ "Article 6(1)(f) GDPR"
|
||||
|
||||
assert LazyHTML.text(LazyHTML.query(document, "title")) ==
|
||||
Branding.title("Privacy Policy")
|
||||
|
||||
assert [canonical] =
|
||||
LazyHTML.attribute(LazyHTML.query(document, ~s(link[rel="canonical"])), "href")
|
||||
|
||||
assert URI.parse(canonical).path == "/privacy"
|
||||
end
|
||||
|
||||
test "GET /terms-conditions renders the terms", %{conn: conn} do
|
||||
html = conn |> get(~p"/terms-conditions") |> html_response(200)
|
||||
document = LazyHTML.from_document(html)
|
||||
|
||||
assert LazyHTML.text(LazyHTML.query(document, "h1")) == "Terms & Conditions"
|
||||
assert html =~ "Last updated: 6 November 2026"
|
||||
assert html =~ "Acceptable use"
|
||||
assert html =~ "Governing law"
|
||||
assert html =~ "fixed number of puzzles per UTC day"
|
||||
assert html =~ ~p"/privacy"
|
||||
|
||||
assert LazyHTML.text(LazyHTML.query(document, "title")) ==
|
||||
Branding.title("Terms & Conditions")
|
||||
|
||||
assert [canonical] =
|
||||
LazyHTML.attribute(LazyHTML.query(document, ~s(link[rel="canonical"])), "href")
|
||||
|
||||
assert URI.parse(canonical).path == "/terms-conditions"
|
||||
end
|
||||
|
||||
test "branding is read from application config", %{conn: conn} do
|
||||
previous = Application.get_env(:chesstrainer, :branding)
|
||||
|
||||
on_exit(fn ->
|
||||
if previous,
|
||||
do: Application.put_env(:chesstrainer, :branding, previous),
|
||||
else: Application.delete_env(:chesstrainer, :branding)
|
||||
end)
|
||||
|
||||
Application.put_env(:chesstrainer, :branding,
|
||||
name: "Test Brand",
|
||||
wordmark: "TEST",
|
||||
tagline: "Trainer",
|
||||
support_email: "help@test.example"
|
||||
)
|
||||
|
||||
html = conn |> get(~p"/privacy") |> html_response(200)
|
||||
|
||||
assert html =~ "Privacy Policy — Test Brand"
|
||||
assert html =~ "Test Brand is an endgame training site"
|
||||
assert html =~ "help@test.example"
|
||||
assert html =~ ~s(content="Test Brand")
|
||||
end
|
||||
|
||||
test "hero shows the number of players with at least one attempt", %{conn: conn} do
|
||||
user = user_fixture()
|
||||
endgame = endgame_fixture()
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do
|
||||
use ChesstrainerWeb.ConnCase
|
||||
|
||||
import Phoenix.LiveViewTest
|
||||
import Chesstrainer.EndgamesFixtures
|
||||
|
||||
alias Chesstrainer.Attempts.Attempt
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
|
||||
alias Chesstrainer.FEN
|
||||
alias Chesstrainer.GuestLimits
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
@guest_address {127, 0, 0, 1}
|
||||
|
||||
setup do
|
||||
GuestLimits.reset()
|
||||
:ok
|
||||
end
|
||||
|
||||
defp seed_tablebase(fen, opts) do
|
||||
tablebase = %Tablebase{
|
||||
category: Keyword.get(opts, :category, :win),
|
||||
checkmate: Keyword.get(opts, :checkmate, false),
|
||||
moves: Keyword.get(opts, :moves, [])
|
||||
}
|
||||
|
||||
key = FEN.position_key(fen)
|
||||
TablebaseCache.put(key, tablebase)
|
||||
on_exit(fn -> TablebaseCache.delete(key) end)
|
||||
end
|
||||
|
||||
defp grading_moves do
|
||||
[%Tablebase.Move{uci: "d1d7", san: "Qd7+", category: :loss, dtz: -1}]
|
||||
end
|
||||
|
||||
# Plays the move the seeded tablebase grades as optimal and completes the
|
||||
# puzzle by checkmate on the follow-up position.
|
||||
defp solve_current(view) do
|
||||
endgame = :sys.get_state(view.pid).socket.assigns.endgame
|
||||
after_fen = "8/8/8/8/8/8/8/8 b - - 0 1"
|
||||
|
||||
seed_tablebase(after_fen, checkmate: true, moves: [])
|
||||
|
||||
render_hook(view, "endgame_move_played", %{
|
||||
"from" => "d1",
|
||||
"to" => "d7",
|
||||
"san" => "Qd7+",
|
||||
"prev_fen" => endgame.fen,
|
||||
"fen" => after_fen,
|
||||
"endgame_id" => endgame.id
|
||||
})
|
||||
end
|
||||
|
||||
defp spend_puzzles(count) do
|
||||
for _ <- 1..count do
|
||||
assert {:ok, _remaining} = GuestLimits.take(@guest_address)
|
||||
end
|
||||
end
|
||||
|
||||
describe "access" do
|
||||
test "lets an anonymous visitor play a random puzzle", %{conn: conn} do
|
||||
endgame = endgame_fixture()
|
||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
|
||||
assert has_element?(view, "#endgame-board[data-endgame-id='#{endgame.id}']")
|
||||
refute has_element?(view, "#difficulty-picker")
|
||||
refute has_element?(view, "#session-bar")
|
||||
assert render(view) =~ "A random endgame puzzle"
|
||||
assert render(view) =~ "4 of 5 free puzzles left today"
|
||||
end
|
||||
|
||||
test "redirects signed-in users to the difficulty picker", %{conn: conn} do
|
||||
%{conn: conn} = register_and_log_in_user(%{conn: conn})
|
||||
|
||||
assert {:error, {:redirect, %{to: "/train"}}} = live(conn, ~p"/guest-train")
|
||||
end
|
||||
end
|
||||
|
||||
describe "without puzzles" do
|
||||
test "shows an empty state", %{conn: conn} do
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
|
||||
assert render(view) =~ "No endgames are available yet"
|
||||
refute has_element?(view, "#endgame-board")
|
||||
end
|
||||
end
|
||||
|
||||
describe "playing" do
|
||||
test "solves a puzzle without recording an attempt", %{conn: conn} do
|
||||
endgame = endgame_fixture()
|
||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
|
||||
solve_current(view)
|
||||
|
||||
assert render(view) =~ "Solved!"
|
||||
assert has_element?(view, "#next-puzzle-button")
|
||||
assert Repo.aggregate(Attempt, :count) == 0
|
||||
end
|
||||
|
||||
test "next puzzle loads a different endgame", %{conn: conn} do
|
||||
endgames =
|
||||
for _ <- 1..2 do
|
||||
endgame = endgame_fixture()
|
||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||
endgame
|
||||
end
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
first = :sys.get_state(view.pid).socket.assigns.endgame
|
||||
|
||||
solve_current(view)
|
||||
view |> element("#next-puzzle-button") |> render_click()
|
||||
|
||||
second = :sys.get_state(view.pid).socket.assigns.endgame
|
||||
assert second.id != first.id
|
||||
assert Enum.any?(endgames, &(&1.id == second.id))
|
||||
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 3
|
||||
end
|
||||
|
||||
test "trying again does not spend another puzzle", %{conn: conn} do
|
||||
endgame = endgame_fixture()
|
||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
|
||||
solve_current(view)
|
||||
view |> element("button", "Try again") |> render_click()
|
||||
|
||||
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4
|
||||
end
|
||||
end
|
||||
|
||||
describe "daily budget" do
|
||||
test "shows the sign-up wall once the budget is spent", %{conn: conn} do
|
||||
endgame = endgame_fixture()
|
||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||
|
||||
spend_puzzles(4)
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 0
|
||||
assert render(view) =~ "Last free puzzle today"
|
||||
|
||||
solve_current(view)
|
||||
view |> element("#next-puzzle-button") |> render_click()
|
||||
|
||||
assert has_element?(view, "#guest-limit")
|
||||
assert render(view) =~ "used your 5 free puzzles today"
|
||||
assert render(view) =~ "Sign up for a free account to keep training"
|
||||
assert has_element?(view, "#guest-sign-up[href='/users/register']")
|
||||
assert render(view) =~ "reset at 00:00 UTC"
|
||||
refute has_element?(view, "#next-puzzle-button")
|
||||
end
|
||||
|
||||
test "a fresh visit after the limit shows only the wall", %{conn: conn} do
|
||||
spend_puzzles(5)
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/guest-train")
|
||||
|
||||
assert has_element?(view, "#guest-limit")
|
||||
refute has_element?(view, "#endgame-board")
|
||||
assert render(view) =~ "used your 5 free puzzles today"
|
||||
end
|
||||
|
||||
test "signed-in visitors do not spend the guest budget", %{conn: conn} do
|
||||
%{conn: conn} = register_and_log_in_user(%{conn: conn})
|
||||
|
||||
assert {:error, {:redirect, %{to: "/train"}}} = live(conn, ~p"/guest-train")
|
||||
|
||||
assert {:ok, 4} = GuestLimits.take(@guest_address)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -7,6 +7,8 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndexTest do
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
|
||||
setup :register_and_log_in_user
|
||||
|
||||
test "groups endgames by Key and shows themes on expand", %{conn: conn} do
|
||||
theme = theme_fixture(%{name: "Lucena"})
|
||||
endgame = endgame_fixture()
|
||||
|
||||
Reference in New Issue
Block a user