Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2759b34296 | ||
|
|
e6f08e0ca6 | ||
|
|
946fc38756 | ||
|
|
80cb033077 | ||
|
|
7209923de7
|
||
|
|
f4ff1e00fb
|
||
|
|
514c6ac924
|
||
|
|
e0b446bbfb | ||
|
|
fa1fef7b62 | ||
|
|
37e0ac8e56 | ||
|
|
b33c5e334a | ||
|
|
aebb2aecfb | ||
|
|
8934d191ad | ||
|
|
021e412167 | ||
|
|
0563b5aca2 | ||
|
|
0ae4c5b6fd | ||
|
|
b41c8bf1a6 | ||
|
|
69b89f68ef |
@@ -7,6 +7,12 @@ MAILING_LIST_ENABLED=false
|
||||
SES_REGION=eu-north-1
|
||||
SES_ACCESS_KEY_ID=AKIA...
|
||||
SES_SECRET_ACCESS_KEY=...
|
||||
SES_CONFIGURATION_SET=my-first-configuration-set
|
||||
# Optional: override the sender or send everything to one address while testing.
|
||||
# MAIL_FROM=no-reply@mail.innersquare.app
|
||||
# MAIL_REDIRECT_TO=you@example.com
|
||||
# Optional: directory of local Syzygy .rtbw/.rtbz files. Ignored by the test
|
||||
# suite, which always uses the committed 3-piece fixtures.
|
||||
TABLEBASE_PATH=
|
||||
|
||||
MATOMO_URL=https://analytics.owenrees.eu/
|
||||
|
||||
@@ -105,6 +105,14 @@ carries a start time and a rating baseline for the timer and rating-gain
|
||||
monitor. Ephemeral — it lives only in the running LiveView, never persisted.
|
||||
_Avoid_: Run, game, attempt
|
||||
|
||||
**Repeat window**:
|
||||
The minimum interval before the same endgame may be served to the same user
|
||||
again. Selection skips endgames attempted inside the window; only when nothing
|
||||
else is available does the least recently attempted endgame come back. It is
|
||||
independent of the rating window, which decides whether a replay may move a
|
||||
rating.
|
||||
_Avoid_: Cooldown (reserved for tablebase rate-limiting), due date
|
||||
|
||||
## Ratings
|
||||
|
||||
**Rating**:
|
||||
@@ -128,11 +136,13 @@ systems; the trainer deliberately does not track it.
|
||||
_Avoid_: Variance, inconsistency
|
||||
|
||||
**Difficulty**:
|
||||
A choice — `easy`, `medium` or `hard` — that selects which puzzles to serve
|
||||
relative to the current user's rating: `medium` is near the user's rating,
|
||||
`easy` below it, `hard` above it. The band width is a configured constant. It is
|
||||
a property of a session, not of an endgame — the same endgame is easy for one
|
||||
user and hard for another.
|
||||
A choice — `easy`, `medium` or `hard` — that biases which puzzles are served
|
||||
relative to the current user's rating: `medium` centres on the user's rating,
|
||||
`easy` below it, `hard` above it. Candidates are weighted by how close their
|
||||
rating is to that centre, so a session draws mostly from near the target but the
|
||||
whole library stays reachable. The spread is a configured constant. It is a
|
||||
property of a session, not of an endgame — the same endgame is easy for one user
|
||||
and hard for another.
|
||||
_Avoid_: Level, rank, tier
|
||||
|
||||
## Infrastructure
|
||||
|
||||
@@ -43,6 +43,10 @@
|
||||
.avatar-stack i:last-child { background: var(--color-deep); color: var(--color-on-deep); }
|
||||
.puzzle-section { width: min(1180px, calc(100% - 48px)); margin: 0 auto; padding: 110px 0 125px; }
|
||||
.puzzle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
|
||||
.puzzle-coming-soon { min-height: 285px; display: grid; place-content: center; justify-items: center; gap: 10px; padding: 46px 28px; text-align: center; border: 1px dashed var(--color-hairline); border-radius: 12px; background: var(--color-canvas-raised); }
|
||||
.puzzle-coming-soon .eyebrow { margin-bottom: 6px; }
|
||||
.puzzle-coming-soon strong { font-family: 'DM Serif Display', serif; font-size: 30px; font-weight: 400; }
|
||||
.puzzle-coming-soon p { max-width: 420px; margin: 0; color: var(--color-muted); font-size: 14px; line-height: 1.7; }
|
||||
.puzzle-card { display: block; position: relative; min-height: 285px; padding: 25px; text-align: left; text-decoration: none; color: inherit; cursor: pointer; border: 1px solid var(--color-hairline); border-radius: 12px; background: rgba(255,255,255,.28); overflow: hidden; transition: transform .25s, background .25s, box-shadow .25s; }
|
||||
.puzzle-card:hover, .puzzle-card.active { transform: translateY(-5px); background: var(--color-canvas-raised); box-shadow: 0 18px 36px rgba(23,53,45,.08); }
|
||||
.puzzle-card.active { border-color: var(--color-success-text); }
|
||||
@@ -69,6 +73,7 @@ html[data-theme="dark"] .learning-strip { box-shadow: inset 0 1px 0 var(--color-
|
||||
@media (max-width: 650px) {
|
||||
.puzzle-section { width: calc(100% - 36px); padding: 80px 0; }
|
||||
.puzzle-grid { grid-template-columns: 1fr; }
|
||||
.puzzle-coming-soon { min-height: 255px; padding: 38px 22px; }
|
||||
.puzzle-card { min-height: 255px; }
|
||||
.progress-banner { width: calc(100% - 36px); padding: 48px 28px; flex-direction: column; align-items: flex-start; gap: 34px; }
|
||||
}
|
||||
|
||||
@@ -43,6 +43,13 @@
|
||||
/* Play board */
|
||||
#endgame-board { position: relative; }
|
||||
|
||||
/* Chessground's stock stylesheet shifts the file labels 24px right of the
|
||||
board, assuming a gutter we don't have, so they land on square boundaries
|
||||
instead of under each file. Place the row on the board and right-justify
|
||||
each label within its square; the row's width already matches the board
|
||||
because the container is sized to whole squares. */
|
||||
#endgame-board coords.files { left: 0; text-align: right; }
|
||||
|
||||
/* Chessground's wrapper has no intrinsic height; let it fill the sized
|
||||
aspect-ratio container so the board scales with the viewport. */
|
||||
#endgame-board .cg-wrap { width: 100%; height: 100%; }
|
||||
@@ -1,2 +1,9 @@
|
||||
.eyebrow { display: flex; align-items: center; gap: 9px; margin-bottom: 27px; color: var(--color-coral-text); text-transform: uppercase; letter-spacing: .13em; font-size: 12px; font-weight: 700; }
|
||||
.eyebrow svg { width: 20px; height: 20px; }
|
||||
|
||||
/* Icon-only external links, e.g. the Discord invite in the navbar and footer.
|
||||
Colour is inherited so the glyph matches the surrounding link row. */
|
||||
.discord-link { display: inline-flex; align-items: center; color: inherit; transition: opacity .2s; }
|
||||
.discord-link:hover { opacity: .55; }
|
||||
.discord-link:focus-visible { outline: 2px solid var(--color-coral-control); outline-offset: 3px; border-radius: 4px; }
|
||||
.discord-link svg { width: 20px; height: 20px; }
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
display: grid; grid-template-columns: 1.5fr repeat(3, 1fr); align-items: center; background: var(--color-deep); color: var(--color-on-deep);
|
||||
}
|
||||
|
||||
.learning-strip > p { max-width: 260px; color: var(--color-on-deep-muted); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
|
||||
.learning-quote { margin: 0; max-width: 300px; }
|
||||
.learning-quote blockquote { margin: 0; color: var(--color-on-deep); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
|
||||
.learning-quote figcaption { margin-top: 10px; color: var(--color-on-deep-faint); font-size: 10px; text-transform: uppercase; letter-spacing: .09em; }
|
||||
|
||||
.stat { padding-left: 34px; border-left: 1px solid rgba(255,255,255,.17); }
|
||||
.stat strong { display: block; font-family: 'DM Serif Display', serif; font-size: 28px; font-weight: 400; }
|
||||
@@ -15,7 +17,7 @@
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.learning-strip { padding: 38px 24px; grid-template-columns: 1fr 1fr; gap: 30px 10px; }
|
||||
.learning-strip > p { grid-column: 1 / -1; }
|
||||
.learning-quote { grid-column: 1 / -1; }
|
||||
.stat { padding-left: 18px; }
|
||||
.stat:last-child { grid-column: 1 / -1; }
|
||||
}
|
||||
@@ -14,6 +14,9 @@
|
||||
.nav-links a { transition: opacity .2s; }
|
||||
.nav-links a:hover { opacity: .55; }
|
||||
.nav-links a.nav-cta:hover { opacity: 1; }
|
||||
/* Utilities (colour mode, Discord) sit in the bar on desktop and in the
|
||||
collapsible menu on small screens. */
|
||||
.nav-menu-tools { display: none; }
|
||||
.nav-user-menu { position: relative; }
|
||||
.nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; }
|
||||
.nav-user-menu summary::-webkit-details-marker { display: none; }
|
||||
@@ -42,6 +45,11 @@ html[data-theme="dark"] .nav-user-menu-panel { box-shadow: 0 18px 40px rgba(0, 0
|
||||
.nav-links.open { display: flex; }
|
||||
.nav-cta { width: 100%; }
|
||||
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
||||
.nav-menu-tools { display: flex; align-items: center; justify-content: space-between; gap: 18px; width: 100%; }
|
||||
/* The menu owns these on small screens; keep them in the bar only when no
|
||||
menu is rendered (prelaunch with no links). */
|
||||
.nav-wrap:has(#nav-links) .nav-right > [role="radiogroup"],
|
||||
.nav-wrap:has(#nav-links) .nav-right > .discord-link { display: none; }
|
||||
.nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; }
|
||||
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
||||
}
|
||||
@@ -15,7 +15,8 @@ config :chesstrainer, :branding,
|
||||
wordmark: "INNERSQUARE",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@innersquare.app",
|
||||
mail_from: "no-reply@innersquare.app"
|
||||
mail_from: "no-reply@mail.innersquare.app",
|
||||
discord_invite: "https://discord.gg/Z2NfkG7thV"
|
||||
|
||||
# Prelaunch gating. Production sets these from PRELAUNCH and
|
||||
# MAILING_LIST_ENABLED; dev and test use these defaults.
|
||||
@@ -61,11 +62,16 @@ config :chesstrainer, :ratings,
|
||||
window_days: 7,
|
||||
rd_inflation_c: 10.0
|
||||
|
||||
# Difficulty bands for puzzle sessions. An endgame is "medium" when its rating
|
||||
# falls within `band_width` of the user's rating, "easy" below that band and
|
||||
# "hard" above it. Tweak to widen or narrow the served difficulty (e.g. 150 or
|
||||
# 200).
|
||||
config :chesstrainer, :puzzles, band_width: 100
|
||||
# Puzzle selection. Difficulty is a weighted bias towards a target rating —
|
||||
# `medium` targets the user's rating, `easy` 200 below it and `hard` 200 above
|
||||
# it — and `spread` is how many rating points it takes for a puzzle's chance to
|
||||
# fall off by a factor of e. `repeat_window_days` is how long an attempted
|
||||
# puzzle stays out of the pool. Tweak `spread` to widen or narrow the served
|
||||
# difficulty (e.g. 100 or 250).
|
||||
config :chesstrainer, :puzzles,
|
||||
spread: 150,
|
||||
repeat_window_days: 30,
|
||||
targets: [easy: -200, medium: 0, hard: 200]
|
||||
|
||||
# Public codes of the endgames pinned to the landing-page puzzle grid, in
|
||||
# display order. When empty (or short) the grid is topped up with a date-seeded
|
||||
|
||||
@@ -28,11 +28,33 @@ if mailing_list_enabled = System.get_env("MAILING_LIST_ENABLED") do
|
||||
config :chesstrainer, :mailing_list_enabled, mailing_list_enabled in ~w(true 1)
|
||||
end
|
||||
|
||||
# Sender address override. The default lives in config/config.exs; this lets a
|
||||
# deploy try a different From address (for example a new sending subdomain)
|
||||
# without a rebuild.
|
||||
if mail_from = System.get_env("MAIL_FROM") do
|
||||
branding = Application.get_env(:chesstrainer, :branding, [])
|
||||
config :chesstrainer, :branding, Keyword.put(branding, :mail_from, mail_from)
|
||||
end
|
||||
|
||||
# SES configuration set stamped on every outgoing email. The set is what links
|
||||
# a message to its SNS bounce and complaint notifications.
|
||||
config :chesstrainer,
|
||||
:ses_configuration_set,
|
||||
System.get_env("SES_CONFIGURATION_SET", "my-first-configuration-set")
|
||||
|
||||
# Rewrite every recipient to one address while testing. Leave unset in normal
|
||||
# operation; see `mix mail.check`.
|
||||
config :chesstrainer, :mail_redirect_to, System.get_env("MAIL_REDIRECT_TO")
|
||||
|
||||
# Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the
|
||||
# .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups
|
||||
# fall back to Lichess.
|
||||
if tablebase_path = System.get_env("TABLEBASE_PATH") do
|
||||
config :chesstrainer, :tablebase_path, tablebase_path
|
||||
# fall back to Lichess. Tests are always pinned to the committed 3-piece
|
||||
# fixtures by config/test.exs, so an exported TABLEBASE_PATH cannot make them
|
||||
# depend on whatever tables the developer happens to have downloaded.
|
||||
if config_env() != :test do
|
||||
if tablebase_path = System.get_env("TABLEBASE_PATH") do
|
||||
config :chesstrainer, :tablebase_path, tablebase_path
|
||||
end
|
||||
end
|
||||
|
||||
# Tablebase cache: size and the UTC time of the daily backup. Environment
|
||||
|
||||
@@ -100,6 +100,10 @@ DNS:
|
||||
`/etc/chesstrainer/postgres.env` holds the Postgres container credentials,
|
||||
also `root:root` and `0600`.
|
||||
|
||||
`/etc/chesstrainer/probe.env` holds the public probe's URL and its
|
||||
healthchecks.io ping URL, also `root:root` and `0600`. See §Monitoring and
|
||||
alerting.
|
||||
|
||||
The app runs as the dedicated `chesstrainer` system user. It must own
|
||||
`/opt/chesstrainer` so it can write `priv/static/backups`.
|
||||
|
||||
@@ -137,6 +141,7 @@ MAILING_LIST_ENABLED=false
|
||||
SES_REGION=eu-north-1
|
||||
SES_ACCESS_KEY_ID=AKIA...
|
||||
SES_SECRET_ACCESS_KEY=...
|
||||
SES_CONFIGURATION_SET=my-first-configuration-set
|
||||
|
||||
MATOMO_URL=https://analytics.owenrees.eu/
|
||||
MATOMO_SITE_ID=6
|
||||
@@ -158,6 +163,47 @@ pages and the guest trainer. Signed-in account and admin pages are excluded.
|
||||
The privacy controls, Matomo server settings, retention, and opt-out behaviour
|
||||
are documented in `docs/analytics.md`.
|
||||
|
||||
## Transactional email
|
||||
|
||||
Every outgoing email goes through `Chesstrainer.Mail`, which applies the same
|
||||
house rules everywhere:
|
||||
|
||||
- **From**: `Inner Square Chess <no-reply@mail.innersquare.app>`. The address
|
||||
lives on the `mail.` subdomain; SES verifies the parent domain, and subdomains
|
||||
inherit that verification, so the subdomain does not need its own identity.
|
||||
- **Reply-To**: `support@innersquare.app`. Replies reach a monitored inbox even
|
||||
though the sender says `no-reply`.
|
||||
- **SES configuration set**: `SES_CONFIGURATION_SET`, default
|
||||
`my-first-configuration-set`. The set is what links a message to its SNS
|
||||
bounce and complaint notifications. It must exist in `SES_REGION`.
|
||||
|
||||
Optional overrides:
|
||||
|
||||
```sh
|
||||
MAIL_FROM=no-reply@mail.innersquare.app # try another sender without a rebuild
|
||||
MAIL_REDIRECT_TO=you@example.com # rewrite every recipient (staging/smoke tests)
|
||||
```
|
||||
|
||||
`MAIL_REDIRECT_TO` rewrites `to`, `cc` and `bcc` to one address, prefixes the
|
||||
subject with the original recipients and adds an `X-Original-To` header, so a
|
||||
redirected message explains itself. Leave it unset in normal operation.
|
||||
|
||||
Check delivery from the release environment:
|
||||
|
||||
```sh
|
||||
bin/chesstrainer eval 'Mix.Task.run("mail.check", ["--to", "you@example.com"])'
|
||||
```
|
||||
|
||||
or, in a checkout configured with the production SES variables,
|
||||
`mix mail.check --to you@example.com`. The task sends to the given address plus
|
||||
the SES mailbox simulators (`success@`, `bounce@`, `complaint@simulator...
|
||||
amazonses.com`) so the configuration set's bounce and complaint path can be
|
||||
exercised without touching a real inbox. Use `--no-simulators` to skip them.
|
||||
|
||||
DNS: the apex publishes DMARC (`p=quarantine`) with aggregate reports sent to
|
||||
`dmarc@innersquare.app`, and `mail.innersquare.app` carries the custom MAIL FROM
|
||||
SPF record and the SES feedback MX.
|
||||
|
||||
Generate the two secrets:
|
||||
|
||||
```sh
|
||||
@@ -562,9 +608,9 @@ receive `403 Access Denied`.
|
||||
Do not let a deploy overwrite the shared Caddyfile.
|
||||
|
||||
See `docs/security.md` for the application throttle, real-IP setup and the
|
||||
Cloudflare edge controls. Production currently has Bot Fight Mode enabled and
|
||||
the free-plan login flood rule: 10 POSTs per 10 seconds per IP, blocked for 10
|
||||
seconds.
|
||||
Cloudflare edge controls. Production currently has Bot Fight Mode off (see
|
||||
#153) and the free-plan login flood rule: 10 POSTs per 10 seconds per IP,
|
||||
blocked for 10 seconds.
|
||||
|
||||
## Building a release
|
||||
|
||||
@@ -752,7 +798,9 @@ curl -i http://127.0.0.1:4100/health
|
||||
|
||||
`/health` returns JSON with `status`, `db`, `tablebase`, and `process`.
|
||||
It returns 200 for `ok`/`degraded` and 503 for `down`. A missing local tablebase
|
||||
reports `degraded` but still 200 because Lichess fallback is available.
|
||||
reports `degraded` but still 200 because Lichess fallback is available. See
|
||||
§Monitoring and alerting for the public probe that watches it, and for what a
|
||||
green check does and does not prove.
|
||||
|
||||
### Reading production logs
|
||||
|
||||
@@ -800,6 +848,221 @@ Set `Storage=persistent` and a `SystemMaxUse=` value in
|
||||
rate-limits bursts; if a crash storm drops lines, raise `RateLimitBurst` or
|
||||
`RateLimitIntervalSec` there.
|
||||
|
||||
## Monitoring and alerting
|
||||
|
||||
Three checks watch production at three different layers:
|
||||
|
||||
| Where | What | Notices | Alerts |
|
||||
|---|---|---|---|
|
||||
| VPS | `chesstrainer-probe.timer` → `chesstrainer-probe.service` | the user-facing HTTP path: DNS, Cloudflare, Caddy, Phoenix, Postgres | healthchecks.io |
|
||||
| VPS | Beszel hub + agent | host liveness, CPU, memory, disk, container restarts and OOM kills | Beszel notifications |
|
||||
| VPS | `chesstrainer-backup.timer` heartbeat | whether the nightly dump finished | healthchecks.io (its own check) |
|
||||
|
||||
The backup heartbeat is documented in §Backups. The probe and the Beszel gap
|
||||
are below.
|
||||
|
||||
### On-box prober, off-box alerting
|
||||
|
||||
The probe runs on the VPS and curls the **public** hostname, so it crosses the
|
||||
same path a visitor does: Cloudflare's DNS and edge, the proxy back to Caddy,
|
||||
Caddy's Cloudflare allowlist, the Phoenix router, and one database query.
|
||||
|
||||
That is deliberately not `127.0.0.1:4100`. A loopback probe stays green through
|
||||
every failure that makes the site unusable: a bad `cloudflare-ranges.caddy`
|
||||
reload, a stopped Caddy (`521`), an expired origin certificate (`526`), a
|
||||
deleted proxied DNS record, a WAF rule blocking `/health`, or a Cloudflare
|
||||
incident. Beszel is green through all of those too, because the host and the
|
||||
container are fine.
|
||||
|
||||
The trade-off is that the prober shares a host with the app. It cannot report
|
||||
that its own host is down, and it cannot prove the view from another network.
|
||||
Host death is caught by **silence**: the timer stops, no ping arrives, and
|
||||
healthchecks.io — which is off-box — alerts after the grace period. That is the
|
||||
whole reason the check-in URL points at a SaaS rather than at another box here.
|
||||
Do not describe this as external uptime monitoring.
|
||||
|
||||
### The healthchecks.io check
|
||||
|
||||
Create the check at healthchecks.io:
|
||||
|
||||
- Name `innersquare.app /health`, period **2 minutes**, grace **2 minutes**
|
||||
- Integrations: email and Discord (webhook). Use each integration's test
|
||||
notification once, and keep recovery notifications enabled so a resolved
|
||||
incident is visible.
|
||||
- Copy the ping URL. It is a secret: anyone who has it can mark the check
|
||||
green. It belongs only in the root-owned env file.
|
||||
|
||||
Every check-in carries evidence:
|
||||
|
||||
- A healthy run posts the raw `/health` JSON.
|
||||
- A tablebase mismatch still posts a **success**, because a Lichess fallback is
|
||||
not an outage. The body carries the expected and actual values, so the
|
||||
mismatch is visible in the check history without alerting anyone.
|
||||
- A non-200, a malformed body, a `db` that is not `ok`, or a network/TLS
|
||||
failure posts to `<ping-url>/fail` with a JSON body containing the reason,
|
||||
the HTTP status, the curl exit code, the response body, and a loopback
|
||||
`origin_status`/`origin_body` for comparison. The origin fields are evidence
|
||||
only; the verdict comes from the public request.
|
||||
|
||||
A ping that cannot be delivered is a journal warning, not a second verdict:
|
||||
the next timer run reports the state again.
|
||||
|
||||
### Install the probe
|
||||
|
||||
Write the env file, root-owned and `0600`:
|
||||
|
||||
```sh
|
||||
sudo install -m 600 /dev/null /etc/chesstrainer/probe.env
|
||||
sudoedit /etc/chesstrainer/probe.env
|
||||
```
|
||||
|
||||
Start from `deploy/probe.env.example`. `PROBE_URL` and `HEALTHCHECK_URL` are the
|
||||
only required values. Then install the script, the units, and the timer:
|
||||
|
||||
```sh
|
||||
sudo install -m 0755 /opt/chesstrainer/src/deploy/probe \
|
||||
/usr/local/sbin/chesstrainer-probe
|
||||
sudo install -m 0644 \
|
||||
/opt/chesstrainer/src/deploy/chesstrainer-probe.service \
|
||||
/opt/chesstrainer/src/deploy/chesstrainer-probe.timer \
|
||||
/etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chesstrainer-probe.timer
|
||||
```
|
||||
|
||||
The timer runs the installed `/usr/local/sbin/chesstrainer-probe`, not the copy
|
||||
under `/opt/chesstrainer/src`, because that tree belongs to the application
|
||||
user. When `deploy/probe` changes, install it to both places so the timer and
|
||||
the repo agree.
|
||||
|
||||
Verify:
|
||||
|
||||
```sh
|
||||
systemctl list-timers chesstrainer-probe.timer
|
||||
sudo journalctl -u chesstrainer-probe -n 5 -o cat
|
||||
```
|
||||
|
||||
Expect a `probe.ok` line every two minutes and a green check within one period.
|
||||
Each run prints exactly one JSON line (`probe.ok`, `probe.degraded` or
|
||||
`probe.failed`), like the backup script, so #140's log shipping can pick it up.
|
||||
|
||||
### What `/health` does and does not mean
|
||||
|
||||
`/health` returns `status`, `db`, `tablebase` and `process`. It returns 200 for
|
||||
`ok` and `degraded`, and 503 for `down`.
|
||||
|
||||
- `db` is one `SELECT 1` through the connection pool. It proves the pool can
|
||||
reach Postgres. It does not prove migrations are current or that writes work.
|
||||
- `tablebase` reflects the local Syzygy directory. `fallback` means lookups go
|
||||
to Lichess. `degraded` is 200 because the fallback is usable.
|
||||
- `process` is always `"ok"`. It is not independent evidence of liveness.
|
||||
|
||||
A green probe therefore means: DNS resolved, Cloudflare served the request,
|
||||
Caddy routed it under the Cloudflare allowlist, Phoenix answered, and Postgres
|
||||
answered one query. It does not mean background jobs are running, SES accepts
|
||||
mail, writes succeed, tablebase lookups are fast, or the site is fast under
|
||||
load. Beszel covers resource exhaustion and container restarts; the release
|
||||
health check and the logs cover deploy mistakes.
|
||||
|
||||
### Beszel's blind spot
|
||||
|
||||
Beszel watches the host: agent connection, CPU, memory, disk, container
|
||||
restarts, OOM kills. Its hub runs on the same VPS as the agent, so a VPS
|
||||
outage or network loss silences it as well — that case is covered by the probe
|
||||
check going quiet. More importantly, Beszel never calls `/health`. A Phoenix
|
||||
release returning 500s on a healthy host, or Postgres refusing connections
|
||||
inside a running container, reads green in Beszel and red in the probe. The two
|
||||
are complementary, not redundant.
|
||||
|
||||
### Drills
|
||||
|
||||
Nothing below touches production data, and the app keeps serving throughout.
|
||||
|
||||
`--dry-run` needs no network and no env file. It evaluates the success,
|
||||
degraded, fail, non-JSON and unreachable fixtures and sends no check-ins:
|
||||
|
||||
```sh
|
||||
sudo /usr/local/sbin/chesstrainer-probe --dry-run
|
||||
```
|
||||
|
||||
A degraded check-in, recorded but never alerting. A value passed on the command
|
||||
line wins over the env file:
|
||||
|
||||
```sh
|
||||
sudo EXPECT_TABLEBASE=not_configured /usr/local/sbin/chesstrainer-probe
|
||||
```
|
||||
|
||||
Expect exit 0, a green check, and a body showing `tablebase: local` against
|
||||
`expected_tablebase: not_configured`. No email and no Discord message.
|
||||
|
||||
The one fail ping, and the full alert path. Stop the timer first so the next
|
||||
scheduled run cannot mask the result:
|
||||
|
||||
```sh
|
||||
sudo systemctl stop chesstrainer-probe.timer
|
||||
sudo PROBE_URL=https://innersquare.app/health-does-not-exist \
|
||||
/usr/local/sbin/chesstrainer-probe
|
||||
```
|
||||
|
||||
Expect exit 1, one `probe.failed` line with `http_status: 404`, one fail ping
|
||||
whose body shows `origin_status: 200`, one alert in Discord/email, and no
|
||||
second fail ping. Then send a real check-in and re-arm:
|
||||
|
||||
```sh
|
||||
sudo /usr/local/sbin/chesstrainer-probe
|
||||
sudo systemctl start chesstrainer-probe.timer
|
||||
```
|
||||
|
||||
The real run posts a success, and healthchecks.io notifies that the check is
|
||||
back up. For the unreachable branch, point the probe at a closed port instead;
|
||||
the origin evidence should still show `200`:
|
||||
|
||||
```sh
|
||||
sudo PROBE_URL=https://127.0.0.1:9/health /usr/local/sbin/chesstrainer-probe
|
||||
```
|
||||
|
||||
The outage drill: stop Phoenix, prove the alert, bring it back. Forcing each
|
||||
probe run instead of waiting for the timer keeps the outage under a minute.
|
||||
Start the probe **once** per step: every run sends its own check-in, so a
|
||||
second start during the outage is a second alert.
|
||||
|
||||
```sh
|
||||
sudo systemctl start chesstrainer-probe.service # baseline: probe.ok
|
||||
sudo systemctl stop chesstrainer
|
||||
sudo systemctl start chesstrainer-probe.service || true # probe.failed, http 502
|
||||
# confirm one Discord message and one email, then:
|
||||
sudo systemctl start chesstrainer
|
||||
curl -sS -o /dev/null -w '%{http_code}\n' https://innersquare.app/health # 200
|
||||
sudo systemctl start chesstrainer-probe.service # probe.ok, recovery
|
||||
```
|
||||
|
||||
Expect `http_status: 502` from Caddy and `origin_status: 000` with
|
||||
`origin_curl_exit: 7` in the fail body: Phoenix is down, while the host and the
|
||||
edge are fine.
|
||||
|
||||
Planned maintenance: stopping the timer is reported as a down check after
|
||||
period plus grace, so about four minutes. Pause the check in the healthchecks.io
|
||||
UI for the duration, or accept the alert.
|
||||
|
||||
The probe reaches the edge as a plain `curl`. If a bot policy or WAF rule ever
|
||||
starts rejecting it, the fail body's `origin_status` shows the app itself is
|
||||
healthy; that is an edge-policy change, not an application outage. Re-enabling
|
||||
Bot Fight Mode is tracked in #153.
|
||||
|
||||
### Drill log
|
||||
|
||||
- **2026-11-13 — install and first drills.** Script and units installed 12:34
|
||||
UTC, timer enabled, first scheduled `probe.ok` at 12:35. Forced-failure drill
|
||||
(`PROBE_URL` at a missing path): one fail ping with `http_status: 404` and
|
||||
`origin_status: 200`, one Discord message and one email, then one recovery
|
||||
notification. Degraded drill (`EXPECT_TABLEBASE=not_configured`): green
|
||||
check-in with the mismatch in the body, no notification. Outage drill: the
|
||||
app was stopped 13:32:55 and started 13:33:42 UTC; the manual probe was
|
||||
started twice while it was down, so `probe.failed` fired at 13:33:06 and
|
||||
13:33:14 (`http 502`) and two notifications arrived for one down → up
|
||||
transition. `probe.ok` at 13:34:03 and one recovery notification. No
|
||||
production data was touched. Start the probe once per drill step.
|
||||
|
||||
## Interactive shell and user management
|
||||
|
||||
Attach an IEx shell to the **running** release. This does not restart the
|
||||
@@ -1223,5 +1486,7 @@ restore over `chesstrainer_prod` while the application is running.
|
||||
globals file.
|
||||
12. Workstation age key and pull configuration installed, user timers and linger
|
||||
enabled, first pull verified, first drill passes.
|
||||
13. Remote shell attaches and exits cleanly:
|
||||
13. `/etc/chesstrainer/probe.env` written, probe script and units installed,
|
||||
timer enabled, and the healthchecks.io check green within one period.
|
||||
14. Remote shell attaches and exits cleanly:
|
||||
`sudo /opt/chesstrainer/current/bin/chesstrainer remote` (Ctrl-C twice).
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Probe the public Inner Square Chess app and report to healthchecks.io
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
ExecStart=/usr/local/sbin/chesstrainer-probe
|
||||
TimeoutStartSec=90s
|
||||
SyslogIdentifier=chesstrainer-probe
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Probe the public Inner Square Chess app every two minutes
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=2min
|
||||
AccuracySec=5s
|
||||
Unit=chesstrainer-probe.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,359 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Probe the public Inner Square Chess app and report the verdict to
|
||||
# healthchecks.io.
|
||||
#
|
||||
# Installed as /usr/local/sbin/chesstrainer-probe (root-owned 0755) and run by
|
||||
# chesstrainer-probe.timer every two minutes. The probe deliberately goes
|
||||
# through the public hostname, not loopback: DNS, Cloudflare, Caddy and the
|
||||
# origin allowlist are part of what a visitor depends on. A loopback health
|
||||
# URL is still consulted on failure, as evidence only.
|
||||
#
|
||||
# sudo /usr/local/sbin/chesstrainer-probe
|
||||
# sudo /usr/local/sbin/chesstrainer-probe --dry-run # no network, no config
|
||||
#
|
||||
# Configuration lives in /etc/chesstrainer/probe.env (root:root 0600). See
|
||||
# deploy/README.md §Monitoring and alerting. Individual settings can be passed
|
||||
# as environment variables to a manual run, which is how the drills vary the
|
||||
# URL and the expected tablebase.
|
||||
#
|
||||
# Each run prints exactly one JSON line (probe.ok, probe.degraded or
|
||||
# probe.failed) so journald, and #140's log shipping, can pick it up.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
ENV_FILE="${ENV_FILE:-/etc/chesstrainer/probe.env}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
DRY_RUN=0
|
||||
TMPDIR_PROBE=""
|
||||
HTTP_BODY_FILE=""
|
||||
HTTP_HEADER_FILE=""
|
||||
HTTP_ERROR_FILE=""
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: chesstrainer-probe [--dry-run]
|
||||
|
||||
--dry-run print the verdict for the success, degraded, fail, non-JSON and
|
||||
unreachable fixtures without reading the env file or making a
|
||||
network request
|
||||
EOF
|
||||
}
|
||||
|
||||
while (($# > 0)); do
|
||||
case "$1" in
|
||||
--dry-run) DRY_RUN=1 ;;
|
||||
-h | --help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
usage >&2
|
||||
echo "probe: unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
log_event() {
|
||||
local event="$1"
|
||||
local extra="${2:-}"
|
||||
|
||||
printf '{"timestamp":"%s","event":"%s"%s}\n' \
|
||||
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
|
||||
}
|
||||
|
||||
fail() {
|
||||
echo "probe: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
json_escape() {
|
||||
local text="$1"
|
||||
|
||||
text="${text//\\/\\\\}"
|
||||
text="${text//\"/\\\"}"
|
||||
text="${text//$'\n'/\\n}"
|
||||
text="${text//$'\r'/\\r}"
|
||||
text="${text//$'\t'/\\t}"
|
||||
text="$(printf '%s' "$text" | LC_ALL=C tr -d '[:cntrl:]')"
|
||||
|
||||
printf '%s' "$text"
|
||||
}
|
||||
|
||||
body_snippet() {
|
||||
local file="$1"
|
||||
|
||||
if [[ -s "$file" ]]; then
|
||||
head -c "$MAX_BODY_BYTES" "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
json_field() {
|
||||
local key="$1"
|
||||
local json="$2"
|
||||
|
||||
if [[ "$json" =~ \"$key\"[[:space:]]*:[[:space:]]*\"([^\"]*)\" ]]; then
|
||||
printf '%s' "${BASH_REMATCH[1]}"
|
||||
fi
|
||||
}
|
||||
|
||||
http_get() {
|
||||
local url="$1"
|
||||
local prefix="$2"
|
||||
local proto="$3"
|
||||
local status=""
|
||||
local exit_code=0
|
||||
|
||||
HTTP_BODY_FILE="$prefix.body"
|
||||
HTTP_HEADER_FILE="$prefix.headers"
|
||||
HTTP_ERROR_FILE="$prefix.error"
|
||||
: >"$HTTP_BODY_FILE"
|
||||
: >"$HTTP_HEADER_FILE"
|
||||
: >"$HTTP_ERROR_FILE"
|
||||
|
||||
if status="$(curl --silent --show-error --location \
|
||||
--proto "$proto" \
|
||||
--connect-timeout 5 \
|
||||
--max-time "$PROBE_TIMEOUT_SECONDS" \
|
||||
--output "$HTTP_BODY_FILE" \
|
||||
--dump-header "$HTTP_HEADER_FILE" \
|
||||
--write-out '%{http_code}' \
|
||||
"$url")"; then
|
||||
exit_code=0
|
||||
else
|
||||
exit_code=$?
|
||||
fi
|
||||
|
||||
HTTP_STATUS="${status:-000}"
|
||||
CURL_EXIT="$exit_code"
|
||||
}
|
||||
|
||||
# Sets VERDICT (ok, degraded, failed), REASON, DB and TABLEBASE. The database is
|
||||
# the only hard dependency; a missing local tablebase still serves users from
|
||||
# Lichess, so it is reported as a green but degraded check-in.
|
||||
evaluate() {
|
||||
local status="$1"
|
||||
local exit_code="$2"
|
||||
local body="$3"
|
||||
local trimmed=""
|
||||
|
||||
VERDICT="failed"
|
||||
REASON=""
|
||||
DB=""
|
||||
TABLEBASE=""
|
||||
|
||||
if ((exit_code != 0)); then
|
||||
REASON="unreachable: curl exit $exit_code"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$status" != "200" ]]; then
|
||||
REASON="http $status"
|
||||
return
|
||||
fi
|
||||
|
||||
trimmed="${body#"${body%%[![:space:]]*}"}"
|
||||
trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
|
||||
if [[ "${trimmed:0:1}" != "{" || "${trimmed: -1}" != "}" ]]; then
|
||||
REASON="non-JSON response"
|
||||
return
|
||||
fi
|
||||
|
||||
DB="$(json_field db "$body")"
|
||||
TABLEBASE="$(json_field tablebase "$body")"
|
||||
|
||||
if [[ -z "$DB" ]]; then
|
||||
REASON="response has no db field"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$DB" != "ok" ]]; then
|
||||
REASON="db is $DB"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$EXPECT_TABLEBASE" != "any" && "$TABLEBASE" != "$EXPECT_TABLEBASE" ]]; then
|
||||
VERDICT="degraded"
|
||||
REASON="tablebase is ${TABLEBASE:-unknown}, expected $EXPECT_TABLEBASE"
|
||||
return
|
||||
fi
|
||||
|
||||
VERDICT="ok"
|
||||
}
|
||||
|
||||
# Exactly one call site per run, and one call site per outcome, so a forced
|
||||
# failure can only ever produce one fail ping.
|
||||
ping_check() {
|
||||
local outcome="$1"
|
||||
local body="$2"
|
||||
local url=""
|
||||
local body_file=""
|
||||
|
||||
if [[ -z "$HEALTHCHECK_URL" ]]; then
|
||||
echo "probe: HEALTHCHECK_URL is not set, not reporting" >&2
|
||||
return 0
|
||||
fi
|
||||
|
||||
url="${HEALTHCHECK_URL%/}"
|
||||
if [[ "$outcome" == "fail" ]]; then
|
||||
url="$url/fail"
|
||||
fi
|
||||
|
||||
body_file="$(mktemp)"
|
||||
printf '%s' "$body" >"$body_file"
|
||||
|
||||
if ! curl --silent --show-error --fail \
|
||||
--max-time 10 --retry 2 --retry-delay 2 \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-binary "@$body_file" \
|
||||
--output /dev/null "$url"; then
|
||||
echo "probe: check-in ping failed (run result is unaffected)" >&2
|
||||
fi
|
||||
|
||||
rm -f "$body_file"
|
||||
}
|
||||
|
||||
origin_evidence() {
|
||||
local prefix="$1"
|
||||
|
||||
http_get "$ORIGIN_URL" "$prefix" '=https,http'
|
||||
ORIGIN_STATUS="$HTTP_STATUS"
|
||||
ORIGIN_EXIT="$CURL_EXIT"
|
||||
ORIGIN_BODY="$(body_snippet "$HTTP_BODY_FILE")"
|
||||
ORIGIN_ERROR="$(body_snippet "$HTTP_ERROR_FILE")"
|
||||
}
|
||||
|
||||
fail_evidence() {
|
||||
local evidence=""
|
||||
|
||||
evidence="$(printf '{"probe":"failed","reason":"%s","url":"%s","http_status":"%s","curl_exit":%s' \
|
||||
"$(json_escape "$REASON")" "$(json_escape "$PROBE_URL")" "$PUBLIC_STATUS" "$PUBLIC_EXIT")"
|
||||
|
||||
if [[ -n "$ERROR_TEXT" ]]; then
|
||||
evidence+="$(printf ',"error":"%s"' "$(json_escape "$ERROR_TEXT")")"
|
||||
fi
|
||||
|
||||
if [[ -n "$BODY" ]]; then
|
||||
evidence+="$(printf ',"body":"%s"' "$(json_escape "$BODY")")"
|
||||
fi
|
||||
|
||||
evidence+="$(printf ',"origin_url":"%s","origin_status":"%s","origin_curl_exit":%s' \
|
||||
"$(json_escape "$ORIGIN_URL")" "$ORIGIN_STATUS" "$ORIGIN_EXIT")"
|
||||
|
||||
if [[ -n "$ORIGIN_BODY" ]]; then
|
||||
evidence+="$(printf ',"origin_body":"%s"' "$(json_escape "$ORIGIN_BODY")")"
|
||||
fi
|
||||
|
||||
if [[ -n "$ORIGIN_ERROR" ]]; then
|
||||
evidence+="$(printf ',"origin_error":"%s"' "$(json_escape "$ORIGIN_ERROR")")"
|
||||
fi
|
||||
|
||||
printf '%s}' "$evidence"
|
||||
}
|
||||
|
||||
dry_run() {
|
||||
local -a scenarios=(
|
||||
'HTTP 200, healthy|200|0|{"process":"ok","status":"ok","db":"ok","tablebase":"local"}'
|
||||
'HTTP 200, tablebase fallback|200|0|{"process":"ok","status":"degraded","db":"ok","tablebase":"fallback"}'
|
||||
'HTTP 503, db down|503|0|{"process":"ok","status":"down","db":"down","tablebase":"local"}'
|
||||
'HTTP 200, non-JSON|200|0|<html><body>502 Bad Gateway</body></html>'
|
||||
'timeout, no response|000|28|'
|
||||
)
|
||||
local row name status exit_code body action
|
||||
|
||||
printf 'probe: dry run, no network calls and no configuration read\n'
|
||||
printf 'probe: every fixture is evaluated with EXPECT_TABLEBASE=local\n\n'
|
||||
printf '%-28s %-9s %-46s %s\n' "scenario" "verdict" "reason" "would ping"
|
||||
|
||||
for row in "${scenarios[@]}"; do
|
||||
IFS='|' read -r name status exit_code body <<<"$row"
|
||||
EXPECT_TABLEBASE="local"
|
||||
evaluate "$status" "$exit_code" "$body"
|
||||
|
||||
case "$VERDICT" in
|
||||
ok) action="success, raw /health JSON" ;;
|
||||
degraded) action="success, mismatch evidence" ;;
|
||||
*) action="fail, evidence JSON" ;;
|
||||
esac
|
||||
|
||||
printf '%-28s %-9s %-46s %s\n' "$name" "$VERDICT" "${REASON:--}" "$action"
|
||||
done
|
||||
|
||||
printf '\nprobe: dry run complete, no check-ins sent\n'
|
||||
}
|
||||
|
||||
if ((DRY_RUN)); then
|
||||
dry_run
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Overrides passed on the command line survive the env file, so the drills can
|
||||
# vary the URL or the expected tablebase without editing a root-only file.
|
||||
_OVERRIDE_PROBE_URL="${PROBE_URL:-}"
|
||||
_OVERRIDE_EXPECT_TABLEBASE="${EXPECT_TABLEBASE:-}"
|
||||
_OVERRIDE_PROBE_TIMEOUT_SECONDS="${PROBE_TIMEOUT_SECONDS:-}"
|
||||
|
||||
if [[ -r "$ENV_FILE" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$ENV_FILE"
|
||||
else
|
||||
fail "cannot read $ENV_FILE (set ENV_FILE to override)"
|
||||
fi
|
||||
|
||||
PROBE_URL="${_OVERRIDE_PROBE_URL:-${PROBE_URL:-}}"
|
||||
EXPECT_TABLEBASE="${_OVERRIDE_EXPECT_TABLEBASE:-${EXPECT_TABLEBASE:-local}}"
|
||||
PROBE_TIMEOUT_SECONDS="${_OVERRIDE_PROBE_TIMEOUT_SECONDS:-${PROBE_TIMEOUT_SECONDS:-10}}"
|
||||
|
||||
HEALTHCHECK_URL="${HEALTHCHECK_URL:-}"
|
||||
ORIGIN_URL="${ORIGIN_URL:-http://127.0.0.1:4100/health}"
|
||||
MAX_BODY_BYTES="${MAX_BODY_BYTES:-2000}"
|
||||
|
||||
[[ "$PROBE_URL" == https://* ]] || fail "PROBE_URL must be an https URL"
|
||||
[[ -n "$HEALTHCHECK_URL" ]] || fail "HEALTHCHECK_URL is not set"
|
||||
[[ "$EXPECT_TABLEBASE" =~ ^(local|fallback|not_configured|any)$ ]] ||
|
||||
fail "EXPECT_TABLEBASE must be local, fallback, not_configured or any"
|
||||
[[ "$PROBE_TIMEOUT_SECONDS" =~ ^[0-9]+$ ]] || fail "PROBE_TIMEOUT_SECONDS must be an integer"
|
||||
command -v curl >/dev/null 2>&1 || fail "missing command: curl"
|
||||
|
||||
TMPDIR_PROBE="$(mktemp -d)"
|
||||
|
||||
cleanup() {
|
||||
if [[ -n "$TMPDIR_PROBE" && -d "$TMPDIR_PROBE" ]]; then
|
||||
rm -rf "$TMPDIR_PROBE"
|
||||
fi
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
http_get "$PROBE_URL" "$TMPDIR_PROBE/public" '=https'
|
||||
PUBLIC_STATUS="$HTTP_STATUS"
|
||||
PUBLIC_EXIT="$CURL_EXIT"
|
||||
BODY="$(body_snippet "$HTTP_BODY_FILE")"
|
||||
ERROR_TEXT="$(body_snippet "$HTTP_ERROR_FILE")"
|
||||
|
||||
evaluate "$PUBLIC_STATUS" "$PUBLIC_EXIT" "$BODY"
|
||||
|
||||
case "$VERDICT" in
|
||||
ok)
|
||||
log_event probe.ok ",\"status\":\"$PUBLIC_STATUS\",\"tablebase\":\"$(json_escape "$TABLEBASE")\",\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
ping_check ok "$BODY"
|
||||
;;
|
||||
degraded)
|
||||
evidence="$(printf '{"expected_tablebase":"%s","health":%s}' \
|
||||
"$(json_escape "$EXPECT_TABLEBASE")" "$BODY")"
|
||||
log_event probe.degraded ",\"reason\":\"$(json_escape "$REASON")\",\"tablebase\":\"$(json_escape "$TABLEBASE")\",\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
ping_check ok "$evidence"
|
||||
;;
|
||||
*)
|
||||
origin_evidence "$TMPDIR_PROBE/origin"
|
||||
evidence="$(fail_evidence)"
|
||||
log_event probe.failed ",\"reason\":\"$(json_escape "$REASON")\",\"http_status\":\"$PUBLIC_STATUS\",\"curl_exit\":$PUBLIC_EXIT,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
ping_check fail "$evidence"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,28 @@
|
||||
# /etc/chesstrainer/probe.env -- root:root, mode 0600.
|
||||
#
|
||||
# Sourced by /usr/local/sbin/chesstrainer-probe. The check-in URL is a secret:
|
||||
# anyone who has it can mark the check green, so keep it out of the repo and
|
||||
# out of world-readable files.
|
||||
|
||||
# The public URL a visitor actually requests. Probing the edge rather than
|
||||
# loopback is deliberate: DNS, TLS, Cloudflare, Caddy and the origin allowlist
|
||||
# are part of the contract. Must be https.
|
||||
PROBE_URL=https://innersquare.app/health
|
||||
|
||||
# healthchecks.io ping URL for the two-minute probe check. A healthy run posts
|
||||
# to it; a failed run posts to <url>/fail.
|
||||
HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||
|
||||
# The tablebase value /health should report. "local" means Syzygy files are
|
||||
# loaded, "fallback" means Lichess is used, "not_configured" means
|
||||
# TABLEBASE_PATH is unset. A mismatch is reported as degraded, never as down.
|
||||
# Set to "any" to accept whatever the app reports.
|
||||
EXPECT_TABLEBASE=local
|
||||
|
||||
# Whole-request timeout. The timer runs every two minutes, so keep this well
|
||||
# under that.
|
||||
PROBE_TIMEOUT_SECONDS=10
|
||||
|
||||
# Loopback health URL. It is consulted only when the public probe fails, and
|
||||
# only as evidence: it does not change the verdict. Defaults to the value shown.
|
||||
# ORIGIN_URL=http://127.0.0.1:4100/health
|
||||
|
Before Width: | Height: | Size: 152 B After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,65 @@
|
||||
# Launch observability is the probe, honest error states, and the runbook
|
||||
|
||||
_Status: accepted._
|
||||
|
||||
At launch, observability means three things and no more: an external check that
|
||||
the public app answers, error states that are honest and recoverable, and a
|
||||
written runbook for when either fails. Everything else is deferred with a named
|
||||
trigger, so the gaps are explicit rather than ambient.
|
||||
|
||||
## The launch bar
|
||||
|
||||
- **Probe.** A healthchecks.io check with a two-minute period and grace, fed by
|
||||
an on-box prober with off-box alerting (#160, #161). It curls the public
|
||||
`/health` through Cloudflare, so DNS, TLS, Caddy, the origin allowlist,
|
||||
Phoenix and one Postgres query are covered. The loopback cross-check in a
|
||||
failure body is evidence only. The prober shares a host with the app, so host
|
||||
death is caught by silence, not by a ping.
|
||||
- **Error states.** The audit (#162) and its fixes (#163), verified by #164.
|
||||
Every failure mode has copy and a retry or a way home; exception details and
|
||||
raw error terms do not reach the page.
|
||||
- **Runbook.** `deploy/README.md` §Monitoring and alerting: the check, install,
|
||||
what `/health` proves and does not, Beszel's blind spot, the drills, and the
|
||||
dated drill log.
|
||||
|
||||
## Deferred, with triggers
|
||||
|
||||
- **Error tracking (#109, GlitchTip/Sentry).** Deferred because JSON logs
|
||||
already carry the crash reason and stacktrace per request, and there is no
|
||||
traffic to aggregate over. Revisit when the first production 500 cannot be
|
||||
diagnosed from its journal line (missing or truncated stacktrace), or a user
|
||||
reports an error without a request id, or unexplained errors exceed roughly
|
||||
50 a day and per-line grep stops being practical.
|
||||
- **Metrics and LiveDashboard (#111).** Deferred because Beszel covers host
|
||||
resources and the probe covers the HTTP contract. Revisit when a capacity
|
||||
question needs a number neither can answer (database pool saturation, p95
|
||||
latency, queue depth), or daily active users pass 100, or a performance
|
||||
incident takes more than an hour to localise.
|
||||
- **Off-box log shipping and error-rate alerts (#140).** Deferred because
|
||||
journald is persistent on the host and the probe alerts on downness. Revisit
|
||||
when an alert must fire on a log pattern (error rate, authentication
|
||||
failures), or the journal retention budget cannot cover a 30-day
|
||||
investigation, or the host is rebuilt and local logs would be lost in the same
|
||||
incident.
|
||||
|
||||
## Why journald and backups are enough at launch
|
||||
|
||||
Persistent journald (`Storage=persistent`, `SystemMaxUse`) holds one JSON object
|
||||
per line: crashes carry a reason and stacktrace, access lines carry status and
|
||||
duration, and token-shaped paths, emails and credentials are redacted. Off-box
|
||||
encrypted backups cover the data.
|
||||
|
||||
The accepted risk: losing the host loses the logs with it, and there is no
|
||||
aggregate error rate. At launch that is acceptable — one host, one operator,
|
||||
low traffic, and an incident is diagnosed from the journal on the box or from
|
||||
the probe's alert body. The triggers above are the point at which that risk
|
||||
stops being acceptable.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Investigation starts with `journalctl -u chesstrainer -o cat | jq`, not a
|
||||
dashboard.
|
||||
- Error tracking, metrics and log shipping stay explicit backlog items with
|
||||
triggers rather than ambient gaps.
|
||||
- The probe is an on-box prober with off-box alerting; it is not external
|
||||
uptime monitoring and the runbook says so.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Asset bundle sizes
|
||||
|
||||
What the browser downloads, measured rather than guessed. Numbers below are
|
||||
from the last production build (`mix assets.deploy`, minified and digested) and
|
||||
were read with `mix assets.sizes`.
|
||||
|
||||
Re-measure after any asset change:
|
||||
|
||||
```sh
|
||||
mix assets.deploy
|
||||
mix assets.sizes
|
||||
```
|
||||
|
||||
`mix assets.sizes` prints raw, gzip and brotli sizes for every built JS and CSS
|
||||
file. Brotli shows as `-` when the `brotli` CLI is not installed.
|
||||
|
||||
## Current bundles
|
||||
|
||||
| File | Raw | Gzip |
|
||||
| --- | ---: | ---: |
|
||||
| `assets/js/app.js` (LiveView entry) | 219.7 KB | 69.2 KB |
|
||||
| `assets/js/marketing.js` (controller pages) | 4.8 KB | 1.9 KB |
|
||||
| `assets/css/app.css` | 94.2 KB | 17.3 KB |
|
||||
|
||||
Cached font files, served only when used: DM Sans variable 62.5 KB, DM Serif
|
||||
Display 24.5 KB, DM Serif Display italic 24.4 KB, DM Sans italic 14.6 KB
|
||||
(woff2, already compressed).
|
||||
|
||||
## What is in each bundle
|
||||
|
||||
`app.js` is a single entry loaded by every LiveView page. It contains:
|
||||
|
||||
| Part | Raw | Gzip |
|
||||
| --- | ---: | ---: |
|
||||
| `phoenix`, `phoenix_live_view`, `phoenix_html` | — | ~30 KB |
|
||||
| `chessground` (`dist/chessground.min.js`) | 30.0 KB | 11.0 KB |
|
||||
| `chess.js` (`dist/esm/chess.js`) | 107.1 KB | 23.9 KB |
|
||||
| `topbar` | 4.3 KB | 1.5 KB |
|
||||
| `nav`, `analytics`, hooks | ~8 KB | ~3 KB |
|
||||
|
||||
The library figures are the packages' own builds; esbuild's minification and
|
||||
tree shaking mean the bundle total is smaller than the naive sum.
|
||||
|
||||
`marketing.js` is deliberately tiny: `phoenix_html`, the nav toggle and the
|
||||
cookieless analytics loader. It has no LiveView, socket, hooks or topbar.
|
||||
Controller pages (landing page, legal pages, 404) load it instead of `app.js`.
|
||||
|
||||
`app.css` is one Tailwind build for the whole site, including the three
|
||||
chessground stylesheets (`chessground.base.css` 3.3 KB, `chessground.brown.css`
|
||||
2.8 KB, `chessground.cburnett.css` 11.5 KB raw, ~4.7 KB gzipped together).
|
||||
|
||||
## Findings
|
||||
|
||||
1. **Board code is about half of `app.js` and most pages do not use it.**
|
||||
chessground and chess.js are ~35 KB of the 69 KB gzip payload. They are
|
||||
needed only by pages that render `ChessBoard`: guest training, play, review.
|
||||
Profile, settings, the endgame list and every admin screen pay for them and
|
||||
never instantiate a board.
|
||||
2. **The marketing/public split is already right.** Public pages do not load
|
||||
the LiveView runtime at all.
|
||||
3. **Board CSS is in the global stylesheet.** ~4.7 KB gzipped of chess piece
|
||||
and board styling reaches every page, including the landing page.
|
||||
4. **Stale digested bundles accumulate.** `priv/static/assets` currently holds
|
||||
three generations of `app-*.js` and `app-*.css`. They are not linked but do
|
||||
bloat the release. `mix phx.digest.clean --age 0` (or deploying from a clean
|
||||
build) removes them.
|
||||
|
||||
## Recommendation (not applied)
|
||||
|
||||
Split the board libraries out of the LiveView entry:
|
||||
|
||||
- Load `chessground` and `chess.js` with a dynamic `import()` inside
|
||||
`assets/js/hooks/chessBoard.js` and build with esbuild `--splitting
|
||||
--format=esm`. Pages without a board then never fetch the chunk; board pages
|
||||
fetch it once, in parallel with the hook mounting.
|
||||
- Expected result: `app.js` drops from ~69 KB to ~35 KB gzip on most
|
||||
authenticated pages, with a separate ~35 KB board chunk fetched only where
|
||||
needed.
|
||||
- Move the chessground stylesheets into the board chunk's CSS (or a second CSS
|
||||
entry loaded only on board pages) to take ~4.7 KB off every page.
|
||||
- Set a budget in CI once the split lands: `app.js` ≤ 40 KB gzip, board chunk
|
||||
≤ 40 KB gzip, `marketing.js` ≤ 2 KB gzip, `app.css` ≤ 20 KB gzip.
|
||||
|
||||
No build configuration was changed as part of this measurement.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Error-state verification
|
||||
|
||||
The #162 checklist, walked on 2026-11-13 against a local production-like build.
|
||||
Failures were filed as #171 and fixed in the follow-up for that issue; this page
|
||||
records the verification run, not the current state. It is linked from the
|
||||
audit.
|
||||
|
||||
## Method
|
||||
|
||||
- **Build:** `MIX_ENV=prod` `mix phx.server` on `127.0.0.1:4010`, commit
|
||||
`021e412` plus this branch's documentation.
|
||||
- **Database:** a scratch `postgres:18.6` on port 55432. Empty at first, then
|
||||
one confirmed user and one 8+ piece endgame (inserted directly, because the
|
||||
admin changeset rejects positions beyond seven pieces).
|
||||
- **Configuration:** `PRELAUNCH=false`, `MAILING_LIST_ENABLED=true`,
|
||||
`TABLEBASE_PATH` pointing at a missing directory, dummy SES credentials.
|
||||
- **Forced failures:** Postgres stopped, missing tablebase directory, empty
|
||||
puzzle pool, expired reset and confirmation tokens (backdated
|
||||
`users_tokens.inserted_at`), stale and invalid mailing-list forms, guest
|
||||
budget exhausted, unknown public play code.
|
||||
- **Observation:** `curl` for controller-rendered pages, headless Chrome over
|
||||
the DevTools Protocol for LiveView-connected pages, and `mix test` for the
|
||||
interactive states that need a click. Each row names its evidence.
|
||||
- **Not forced:** a real Lichess 429 (the cooldown and classifier paths were
|
||||
exercised by the tests), a crash after connect, and the two admin-only import
|
||||
leaks (code inspection and tests). The first run rejected the socket origin
|
||||
because `PHX_HOST` defaulted to `example.com`; setting `PHX_HOST=127.0.0.1`
|
||||
fixed it. That was local configuration, not a product finding.
|
||||
|
||||
## Results
|
||||
|
||||
| Checklist row | Result | Evidence |
|
||||
|---|---|---|
|
||||
| T1 cooldown | **pass** | LiveView test: mount with a cooldown shows "Tablebase cooling down"; Retry re-fetches and returns to play. |
|
||||
| T2 429 | **pass** | LiveView test: classifier maps 429 to "Tablebase rate-limited"; HTML carries no `429`, `too_many_requests` or upstream body. |
|
||||
| T3 not covered | **pass** | Prod run: guest page with a 12-piece endgame shows "Position not covered… can't be graded", no `not_covered` in the DOM, Next puzzle or back available. |
|
||||
| T4 generic | **pass** | LiveView test: classifier returns "Tablebase unavailable"; the reason is logged and never rendered. |
|
||||
| T5/T6 load and reply failure | **pass** | T5 covered by the cooldown-at-mount test and Retry. T6 shares the blocked panel and `reset/1` path; not separately forced. |
|
||||
| T8 invalid FEN | **fail** | Existing test: the flash still contains the client message and the raw FEN. #171. |
|
||||
| S1/S2/S3/S5 empty pools | **pass** | S1 prod: Medium picker shows the in-page empty state and Retry. S5 prod: guest shows "No endgames are available yet" and Retry. S2/S3 tests: exhausted state, Retry and Change difficulty. |
|
||||
| S4 guest limit | **pass** | Prod run: five visits exhaust the budget; the wall shows the reset time, Sign up free and Log in. |
|
||||
| A1 reset token | **pass** | Prod run: an expired token flashes "Reset password link is invalid or it has expired." on the log-in page, with Forgot your password available. |
|
||||
| A2 confirmation token | **fail** | Prod run: an expired token flashes "User not found or token is invalid." and lands on registration, not log in. #171. |
|
||||
| A3/A4 login | **pass** | Tests: invalid credentials use one message; the throttle reports the remaining minutes. |
|
||||
| M1–M5 mailing list | **pass** | Prod run: invalid confirmation link, removed address, stale form, invalid email and an SES send failure each show their specific copy with the form reachable. |
|
||||
| W1/W2 404 and 500 | **pass** | Prod run: styled 404 for an unknown path; with Postgres stopped, `/` returns the styled 500 with no exception or stacktrace. |
|
||||
| W3 crash | **fail** | The server-error banner has no reload action; a repeating crash has no manual escape. Not separately forced; same banner as W4. #171. |
|
||||
| W4 disconnect | **pass** | Observed "Something went wrong! Attempting to reconnect" while the socket was rejected, with automatic retries; the banner hides on reconnect. |
|
||||
| W5 database down | **pass** | Prod run: `/health` returns 503 `db:down`; `/` returns the 500 page. Note the loop: the home link also needs the database, so it 500s too. |
|
||||
| D1/D2 export | **fail** | Prod run: an export with the database stopped returns the 500 page (no export-specific copy); `/users/profile/export/xml` returns plain text "Unknown export format". #171. |
|
||||
| H1 empty-database home | **fail** | Prod run: the fallback board renders, but "Try today's puzzle" points at the auth-gated `/endgames`. #171. |
|
||||
| X1 unknown play code | **pass** | Prod run: `/endgames/nope/play` returns the styled 404 page. This corrects the audit's earlier claim that it 500ed. |
|
||||
| X2/X3 admin leaks | **fail** | Code inspection and tests: both importer messages still interpolate `inspect(reason)`. Not forced. #171. |
|
||||
|
||||
## Tally
|
||||
|
||||
- 14 checklist rows pass, 6 fail (8 individual regressions, because D1/D2 and
|
||||
X2/X3 share a row).
|
||||
- Every failure row is a state that was already listed as "improve" in the
|
||||
audit and was outside #163; no new regression came from the #163 changes.
|
||||
- The regressions are filed together in #171 rather than fixed silently.
|
||||
@@ -0,0 +1,152 @@
|
||||
# User-facing error states
|
||||
|
||||
What a player sees when something fails, with a verdict for every state and the
|
||||
concrete change each one needs. This is the audit required by #162; #163
|
||||
implements the tablebase and empty-pool items, and #164 walks the sign-off
|
||||
checklist on a production-like build.
|
||||
|
||||
Verdicts:
|
||||
|
||||
- **keep** — the state is honest, recoverable and leak-free as it stands
|
||||
- **improve** — a state exists but needs different copy, a recovery action, or
|
||||
both
|
||||
- **add** — there is no user-facing state today
|
||||
|
||||
"Internal detail" means an exception term, an `inspect/1` result, a raw HTTP
|
||||
status body, a stacktrace, or a raw FEN appearing in rendered HTML.
|
||||
|
||||
**Status:** #163 implements T1–T6, S1–S3 and S5. The rows below describe the
|
||||
state before that change. #164 walked this checklist on a local prod build:
|
||||
see [error-states-verification.md](error-states-verification.md).
|
||||
|
||||
## Play and tablebase
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| T1 | Cooldown | A previous 429 put Lichess in cooldown; `Tablebase.new/1` returns `{:cooldown, ms}` (`play_core.ex:386`) | Panel headed **Tablebase unavailable**, body "The tablebase is rate-limited. Try again in about Ns."; move hint "The tablebase is unavailable, so moves cannot be entered."; **Reset** | improve | Heading per failure class ("Tablebase cooling down"), keep the countdown, and relabel Reset to **Retry** while blocked. Fold into #163. |
|
||||
| T2 | Lichess 429 | Lichess returns 429; the parser records a cooldown (`tablebase/parser.ex:69`) | Same panel; "The tablebase is rate-limited. Try again in a minute." | improve | Same class as T1, with the real countdown once known. Never show `429` or the response body. Fold into #163. |
|
||||
| T3 | Position not covered | More than seven pieces, Lichess 404, or `:not_covered` (`play_core.ex:394-401`) | Panel headed **Tablebase unavailable**, body "This position is not covered by the tablebase."; **Reset** | improve | Say the puzzle cannot be graded, and offer **Try another puzzle** (session) or **Browse endgames** (single). Retry is futile here, so do not present it as the primary action. Fold into #163. |
|
||||
| T4 | Generic tablebase failure | 5xx, transport error, malformed response (`play_core.ex:403`) | **"The tablebase is unavailable (#{inspect(reason)})."** | improve | Replace with "The tablebase is unavailable right now. Try again in a moment." and log the reason. This is the leak #163 calls out. Also applies to the review panel's `review_blocked` copy. |
|
||||
| T5 | Load failure at session start | `Tablebase.new/1` fails in `PlayCore.init/2` → `load_attempt/1` | Board non-interactive; blocked panel and reason; **Reset** | improve | Class-correct copy plus **Retry**; `reset/1` already re-fetches, so this is a label and copy change. Fold into #163. |
|
||||
| T6 | Fetch failure for the opponent's reply | `start_opponent_reply/2` cannot fetch the new position (`play_core.ex:457`) | Play stops; blocked panel; the move already played is still on the board; **Reset** | improve | Explain that the puzzle is paused and **Retry** resumes from the current position. Fold into #163. |
|
||||
| T7 | Move while blocked | A move event arrives while `status == :blocked` (`play_core.ex:76`) | Flash "The tablebase is unavailable, so this move cannot be graded." | keep | Defensive guard; the board should already be non-interactive. #164 asserts that. |
|
||||
| T8 | Invalid FEN from the board hook | `chess_fen_invalid` (`play_core.ex:184`) | Flash **"Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})"** | improve | Generic copy ("The board couldn't load this position. Reset to try again."), log the details, and keep **Reset** visible. Leak: client message and raw FEN. |
|
||||
|
||||
## Sessions and puzzle pools
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| S1 | No puzzles available | `Puzzles.next_endgame/3` returns `nil` on start (`train.ex:201`) | Flash error "No puzzles are available right now."; the difficulty picker stays behind it | improve | Replace the flash with an in-page state inside the picker: what happened, **Retry**, and a way to pick another difficulty. Fold into #163. |
|
||||
| S2 | No more puzzles at this difficulty | `next_endgame` returns `nil` with `exclude_ids` (`train.ex:232`) | Flash info "No more puzzles at this difficulty."; the finished puzzle and **Next puzzle** remain | improve | In-page end-of-run panel: "You've finished every puzzle at this difficulty" with **Retry**, **Change difficulty** (stop session) and the existing Stop session. Hide or disable Next. Fold into #163. |
|
||||
| S3 | Guest: no more puzzles | Guest `next_puzzle` finds nothing (`guest_train.ex:137`) | Flash info "No more puzzles are available right now." | improve | In-page state with **Retry** and the sign-up/log-in actions, matching the guest-limit panel's tone. Fold into #163. |
|
||||
| S4 | Guest limit reached | `GuestLimits.take/1` returns `{:limit_reached, ms}` (`guest_train.ex:45-70`) | In-page panel: used N free puzzles, reset time, **Sign up free**, **Log in** | keep | This is the reference state for tone and recovery. |
|
||||
| S5 | Guest pool empty on load | Random endgame is `nil` (`guest_train.ex:98`) | In-page "No endgames are available yet. Please check back soon." | improve | Add a **Retry** action so the state is not a dead end. Fold into #163. |
|
||||
|
||||
## Accounts and email
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| A1 | Reset token invalid or expired | `get_user_by_reset_password_token/1` returns `nil` (`reset_password.ex:66`) | Flash "Reset password link is invalid or it has expired." then the log-in page, where **Forgot your password?** is available | keep | Honest and recoverable in two clicks. |
|
||||
| A2 | Confirmation token invalid or expired | `Accounts.confirm_user/1` returns `:error` (`user_confirmation_controller.ex:17`) | Flash **"User not found or token is invalid."** then the registration page | improve | Say "That confirmation link is invalid or has expired." and send the user to log in, where an unconfirmed account triggers a fresh confirmation email. No "user not found" phrasing. |
|
||||
| A3 | Invalid credentials | `get_user_by_login_and_password/2` returns `nil` | Flash "Invalid email, username or password"; email is prefilled | keep | Deliberately identical for unknown and wrong-password logins, so it does not enumerate accounts. |
|
||||
| A4 | Login throttle | 5 failures per login or 10 per address in 15 minutes (`LoginThrottle`) | Flash "Too many attempts. Try again in N minutes." | keep | Accurate countdown, no account information. |
|
||||
|
||||
## Mailing list
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| M1 | Confirmation link invalid or expired | Token fails verification (`mailing_list_controller.ex:36`) | Flash "That confirmation link is invalid or has expired." → `/#mailing-list` | keep | The signup form is on the destination page. |
|
||||
| M2 | Confirmed address no longer subscribed | `MailingList.confirm/1` returns `:not_found` (`:52`) | Flash "That address is no longer on the mailing list. Please sign up again." → `/#mailing-list` | keep | Actionable and specific. |
|
||||
| M3 | Stale signup form | `MailingListFormToken.verify/1` fails (`:126`) | Flash "Please refresh the page and try again." → `/#mailing-list` | keep | The form is on the page; refresh is the fix. |
|
||||
| M4 | Invalid email | Missing or invalid address (`:132`) | Flash "Enter a valid email address." | keep | Specific and actionable. |
|
||||
| M5 | Confirmation email send failure | `Notifier.deliver_confirmation_instructions/2` returns an error (`:111`) | Flash "We couldn't send the confirmation email. Please try again." | improve | Keep the copy, add "If it keeps happening, email …" from `Branding.support_email/0`, and log the reason — the controller currently discards it. |
|
||||
| M6 | List closed / honeypot / already subscribed | Feature flag, honeypot, or existing address | "The mailing list isn't open yet." / success copy / "You're already on the mailing list." | keep | Closed and honeypot are deliberate; the existing-address message is honest. |
|
||||
|
||||
## Site-level
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| W1 | 404 | Unknown route (`ErrorHTML`, catch-all route) | Styled page: "This page isn't on the board", **Back to home**, plus **Browse puzzles** for premium users | keep | Uses the shared `error_page/1`. |
|
||||
| W2 | 500 | Controller or render crash | Styled page: "Something went wrong", **Back to home**, **Browse puzzles**, support email | keep | Honest, no exception detail. |
|
||||
| W3 | LiveView crash | Raise in `mount` or `handle_event` | Mount crash → the 500 page. A crash after connect → the **"Something went wrong!"** banner, automatic reconnect, no manual action | improve | Add a **Reload** action (and keep home) to the server-error banner so a crash that repeats on reconnect has an escape. The banner lives in `layouts.ex:274`. |
|
||||
| W4 | Disconnect | Socket or network loss | **"We can't find the internet"** banner with a spinner; hides on reconnect | keep | Automatic recovery, no action needed. |
|
||||
| W5 | Database unavailable | Postgres stopped or pool exhausted | DB-backed pages and LiveView mounts raise → the 500 page; `/health` returns 503 | keep | The 500 page is the right state, but note the loop: the home page also needs the database, so "Back to home" fails too. The probe is the operational signal. No app change proposed here. |
|
||||
|
||||
## Data and landing
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| D1 | Export failure | `Attempts.list_attempts_for_user/1` raises in `UserDataController.export/2` | The 500 page, with no export-specific explanation | improve | Rescue, log, and redirect to `/users/profile/data` with "We couldn't build your export. Try again; if it keeps failing, email …". |
|
||||
| D2 | Unknown export format | `/users/profile/export/<anything else>` | Plain text `404 "Unknown export format"` with no chrome, links, or home | improve | Return the styled 404 page instead. |
|
||||
| D3 | Export of an empty account | No attempts | CSV with the header and an empty row; JSON with an empty list | keep | Deliberate and documented by the shape. |
|
||||
| H1 | Home page with an empty database | No endgames (`PageController.home/2`) | Fallback KRK board, "Featured position", "0 players training", and a **Try today's puzzle** button pointing at `/endgames` | improve | When `active_endgame` is `nil`, do not send the visitor to an auth-gated page with no puzzles: point the call to action at `/guest-train` (which has its own empty state) or disable it with "New puzzles are coming". |
|
||||
|
||||
## Admin surfaces (extra)
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| X1 | Unknown public play code | `/endgames/:code/play` with a code that does not exist (`play.ex:79`) | The styled 404 page: `Ecto.NoResultsError` maps to 404 through `Plug.Exception` | keep | Verified by #164; no change. |
|
||||
| X2 | Bulk import lookup crash | `handle_async` exits (`import.ex:271`) | Flash **"Could not look up the FENs: #{inspect(reason)}"** | improve | Generic copy plus a logged reason. Admin-only, but still an internal leak. |
|
||||
| X3 | Bulk import tablebase load failure | `Local.check/0` returns an unexpected error (`import.ex:287`) | **"Local tablebase failed to load: #{inspect(reason)}"** | improve | Generic copy plus a logged reason. Admin-only, but still an internal leak. |
|
||||
|
||||
## Internal-detail leaks
|
||||
|
||||
These are the only places where an exception term, a raw HTTP status or a raw
|
||||
FEN can reach rendered HTML. T4 is the one #162 calls out; the rest are smaller
|
||||
but real.
|
||||
|
||||
| Where | Leak | Fix |
|
||||
|---|---|---|
|
||||
| `play_core.ex:404` | `inspect(reason)` in the blocked panel | T4 |
|
||||
| `play_core.ex:189` | client message and raw FEN in a flash | T8 |
|
||||
| `import.ex:271` | `inspect(reason)` in a flash | X2 |
|
||||
| `import.ex:287` | `inspect(reason)` in the tablebase status | X3 |
|
||||
| `user_data_controller.ex:21` | plain-text "Unknown export format" | D2 |
|
||||
|
||||
Server logs already carry the real reasons, so none of these fixes lose
|
||||
diagnostic information.
|
||||
|
||||
## Sign-off checklist
|
||||
|
||||
For #164 to walk against a production-like build. Every row passes only if the
|
||||
state offers **retry or a way home** and rendered HTML contains no exception,
|
||||
stacktrace, raw error term, or raw FEN.
|
||||
|
||||
- [ ] **T1 cooldown** — force a cooldown: class-correct heading, countdown, Retry re-fetches.
|
||||
- [ ] **T2 429** — make Lichess return 429: rate-limit copy, no `429` or response body.
|
||||
- [ ] **T3 not covered** — play a position with more than seven pieces: explanation, another puzzle or home, no futile Retry.
|
||||
- [ ] **T4 generic** — make Lichess fail (network off or 5xx): generic copy, Retry works when it recovers, no `inspect`.
|
||||
- [ ] **T5/T6 load and reply failure** — start a puzzle and lose the tablebase mid-game: paused explanation, Retry resumes.
|
||||
- [ ] **T8 invalid FEN** — force `chess_fen_invalid`: no client message or raw FEN, Reset visible.
|
||||
- [ ] **S1/S2/S3/S5 empty pools** — empty the pool: in-page states on train and guest, Retry and change-difficulty reachable.
|
||||
- [ ] **S4 guest limit** — exhaust the guest allowance: panel, reset time, sign-up and log-in reachable.
|
||||
- [ ] **A1 reset token** — use an expired link: message, log-in page, forgot-password reachable.
|
||||
- [ ] **A2 confirmation token** — use an expired link: message, log-in page, fresh confirmation email on next login.
|
||||
- [ ] **A3/A4 login** — wrong password and throttled login: no account enumeration, countdown.
|
||||
- [ ] **M1-M5 mailing list** — expired confirmation, stale form, invalid address, send failure: specific copy and the form reachable.
|
||||
- [ ] **W1/W2 404 and 500** — unknown path and forced crash: styled page, home and browse reachable, no exception.
|
||||
- [ ] **W3 crash** — raise in a `handle_event`: reload action reachable.
|
||||
- [ ] **W4 disconnect** — drop the socket: reconnect banner and automatic recovery.
|
||||
- [ ] **W5 database down** — stop Postgres: 500 pages, `/health` 503, no stacktrace; note that home is also down.
|
||||
- [ ] **D1/D2 export** — force an export error and an unknown format: flash or 404 page, home reachable.
|
||||
- [ ] **H1 empty database** — empty the pool: home renders, call to action is not an auth-gated dead end.
|
||||
- [ ] **X1 unknown play code** — open a stale link: 404 page, not a 500.
|
||||
- [ ] **X2/X3 admin leaks** — force an import crash and a tablebase error: no `inspect` output.
|
||||
|
||||
## Fix list
|
||||
|
||||
Fold into **#163** (tablebase and empty-pool recoverability): T1, T2, T3, T4,
|
||||
T5, T6, S1, S2, S3, S5.
|
||||
|
||||
Separate changes, each independently testable:
|
||||
|
||||
- **T8** — generic invalid-FEN flash; log the details.
|
||||
- **A2** — confirmation-token copy and destination.
|
||||
- **M5** — support fallback on send failure; log the reason.
|
||||
- **W3** — reload action in the server-error banner.
|
||||
- **D1** — rescue export errors into a flash on the data tab.
|
||||
- **D2** — styled 404 for unknown export formats.
|
||||
- **H1** — empty-database call to action.
|
||||
- **X2/X3** — generic admin import copy; log the details.
|
||||
|
||||
No code changes are part of this audit.
|
||||
@@ -11,7 +11,8 @@ addresses and would ban Cloudflare edge addresses on this deployment.
|
||||
`CF-Connecting-IP` as `X-Forwarded-For`. The ranges are refreshed hourly by
|
||||
`chesstrainer-cloudflare-ranges.timer`.
|
||||
- `TRUST_FORWARDED_FOR=true`, so the app throttles by the real visitor address.
|
||||
- Cloudflare Bot Fight Mode is enabled.
|
||||
- Cloudflare Bot Fight Mode is off. The Caddy origin allowlist above stays in
|
||||
force; re-enabling is tracked in #153.
|
||||
- The free-plan login flood rule allows 10 login POSTs per 10 seconds per IP and
|
||||
blocks for 10 seconds.
|
||||
|
||||
@@ -155,10 +156,13 @@ address after ten failures within fifteen minutes. A slow attacker staying under
|
||||
10 requests per 10 seconds never gets to make useful guesses because of the app
|
||||
throttle.
|
||||
|
||||
Bot Fight Mode is enabled as the plan-level bot control. If the plan later gains
|
||||
longer rate-limit windows or managed WAF rules, raise the block duration and
|
||||
consider a broader site-wide rule, such as 100 requests per 10 seconds per IP
|
||||
with a managed challenge. Use Under Attack Mode during an active incident.
|
||||
Bot Fight Mode is off. On the free plan it cannot be skipped for CI or for the
|
||||
on-box health probe, so a datacenter `curl` gets a 403 while the site itself is
|
||||
healthy; #153 covers the gate and probe changes needed before it goes back on.
|
||||
If the plan later gains longer rate-limit windows or managed WAF rules, raise
|
||||
the block duration and consider a broader site-wide rule, such as 100 requests
|
||||
per 10 seconds per IP with a managed challenge. Use Under Attack Mode during an
|
||||
active incident.
|
||||
|
||||
### Registration cannot be limited this way
|
||||
|
||||
|
||||
@@ -168,6 +168,18 @@ defmodule Chesstrainer.Accounts do
|
||||
|> Repo.update()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a user's subscription plan.
|
||||
|
||||
Plans are programmatic values; registration never casts `plan`, so a user
|
||||
cannot upgrade themselves.
|
||||
"""
|
||||
def update_user_plan(%User{} = user, plan) do
|
||||
user
|
||||
|> User.plan_changeset(%{plan: plan})
|
||||
|> Repo.update()
|
||||
end
|
||||
|
||||
## Admin user management
|
||||
|
||||
@doc """
|
||||
|
||||
@@ -55,6 +55,17 @@ defmodule Chesstrainer.Accounts.User do
|
||||
|> validate_required([:role])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the plan.
|
||||
|
||||
The plan is programmatic and must never be cast from user-supplied params.
|
||||
"""
|
||||
def plan_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:plan])
|
||||
|> validate_required([:plan])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for an admin-created invitation.
|
||||
|
||||
|
||||
@@ -2,20 +2,15 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
# Delivers the email using the application mailer.
|
||||
defp deliver(recipient, subject, body) do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({Branding.name(), Branding.mail_from()})
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|> Mail.deliver()
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
@@ -106,8 +106,8 @@ defmodule Chesstrainer.Attempts do
|
||||
@doc """
|
||||
The distinct endgame ids `user_id` has attempted in the last `days` days.
|
||||
|
||||
Used by puzzle selection to prefer fresh puzzles; a retry still counts as an
|
||||
attempt, even though the rating window leaves it unrated.
|
||||
Used by puzzle selection to skip puzzles inside the repeat window; a retry
|
||||
still counts as an attempt, even though the rating window leaves it unrated.
|
||||
"""
|
||||
def recent_endgame_ids(user_id, days \\ 30) do
|
||||
cutoff = DateTime.add(DateTime.utc_now(), -days, :day)
|
||||
|
||||
@@ -12,7 +12,8 @@ defmodule Chesstrainer.Branding do
|
||||
wordmark: "INNERSQUARE",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@innersquare.app",
|
||||
mail_from: "no-reply@innersquare.app"
|
||||
mail_from: "no-reply@mail.innersquare.app",
|
||||
discord_invite: "https://discord.gg/Z2NfkG7thV"
|
||||
]
|
||||
|
||||
@doc "The display name, e.g. `\"Lucid Chess\"`."
|
||||
@@ -30,6 +31,26 @@ defmodule Chesstrainer.Branding do
|
||||
@doc "The From address used for outgoing mail."
|
||||
def mail_from, do: get(:mail_from)
|
||||
|
||||
@doc """
|
||||
The Discord invite URL, or `nil` when no invite is configured.
|
||||
|
||||
Accepts either a bare invite code (`"abc123"`) or a full URL; a bare code is
|
||||
expanded to `https://discord.gg/<code>`.
|
||||
"""
|
||||
def discord_invite_url do
|
||||
case get(:discord_invite) do
|
||||
value when is_binary(value) ->
|
||||
case String.trim(value) do
|
||||
"" -> nil
|
||||
"http" <> _ = url -> url
|
||||
code -> "https://discord.gg/#{code}"
|
||||
end
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`."
|
||||
def home_title, do: "#{name()} — #{tagline()}"
|
||||
|
||||
|
||||
@@ -111,8 +111,13 @@ defmodule Chesstrainer.Endgames do
|
||||
@doc """
|
||||
Returns `{key, count}` groups for endgames matching the filters, sorted by key.
|
||||
|
||||
Filters is a map with optional `:themes` (a list of theme ids; an endgame must
|
||||
carry any one of them) and `:key` (an exact Key).
|
||||
Filters is a map with optional:
|
||||
|
||||
* `:themes` - a list of theme ids; an endgame must carry any one of them
|
||||
* `:key` - an exact Key
|
||||
* `:with_theme` - `{theme_id, source}`; only endgames linked to the theme
|
||||
with that source
|
||||
* `:without_theme` - a theme id; only endgames not linked to the theme at all
|
||||
"""
|
||||
def list_key_groups(filters \\ %{}) do
|
||||
Endgame
|
||||
@@ -125,20 +130,31 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns the endgames for one Key, matching the filters, with themes preloaded.
|
||||
|
||||
Accepts `:limit` and `:offset` options for paginating large Key groups.
|
||||
"""
|
||||
def list_endgames_for_key(key, filters \\ %{}) do
|
||||
def list_endgames_for_key(key, filters \\ %{}, opts \\ []) do
|
||||
skip = Keyword.get(opts, :offset, 0)
|
||||
|
||||
Endgame
|
||||
|> apply_filters(filters)
|
||||
|> where([e], e.key == ^key)
|
||||
|> preload(:themes)
|
||||
|> order_by([e], asc: e.fen)
|
||||
|> order_by([e], asc: e.fen, asc: e.id)
|
||||
|> limit_query(Keyword.get(opts, :limit))
|
||||
|> offset(^skip)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
defp limit_query(query, nil), do: query
|
||||
defp limit_query(query, limit), do: limit(query, ^limit)
|
||||
|
||||
defp apply_filters(query, filters) do
|
||||
query
|
||||
|> filter_themes(Map.get(filters, :themes, []))
|
||||
|> filter_key(Map.get(filters, :key))
|
||||
|> filter_with_theme(Map.get(filters, :with_theme))
|
||||
|> filter_without_theme(Map.get(filters, :without_theme))
|
||||
end
|
||||
|
||||
defp filter_themes(query, []), do: query
|
||||
@@ -156,6 +172,30 @@ defmodule Chesstrainer.Endgames do
|
||||
defp filter_key(query, key) when key in [nil, ""], do: query
|
||||
defp filter_key(query, key), do: where(query, [e], e.key == ^key)
|
||||
|
||||
defp filter_with_theme(query, nil), do: query
|
||||
|
||||
defp filter_with_theme(query, {theme_id, source}) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id and t.source == ^to_string(source),
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
defp filter_without_theme(query, nil), do: query
|
||||
|
||||
defp filter_without_theme(query, theme_id) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id,
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id not in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single endgame.
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
defmodule Chesstrainer.Endgames.MaterialThemes do
|
||||
@moduledoc """
|
||||
Derives each endgame's material family from its canonical Key.
|
||||
|
||||
Every endgame belongs to exactly one family, so the themes behave as a
|
||||
partition: selecting several in a filter produces their union, never an
|
||||
ambiguous intersection. A lone king against heavy or pawn material is split
|
||||
out because those positions teach a specific technique — basic mate or
|
||||
promotion — rather than a general material class.
|
||||
|
||||
Families are derived, never judged. They are stored with source `derived`, so
|
||||
a refresh replaces them without touching curated or community themes.
|
||||
Positions with no legal content (`K v K`) and rows without a Key are skipped.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@families [
|
||||
basic_mate: %{
|
||||
name: "basic mate",
|
||||
description:
|
||||
"A lone king against the queen or a rook, with no pawns: the puzzle is about delivering mate."
|
||||
},
|
||||
king_and_pawn: %{
|
||||
name: "king and pawn",
|
||||
description:
|
||||
"A lone king against king and pawns: the puzzle is about promotion, or holding the draw."
|
||||
},
|
||||
bare_king_other: %{
|
||||
name: "bare king other",
|
||||
description:
|
||||
"A lone king against minor pieces, or against pawns and pieces: usually a technique exercise with little counterplay."
|
||||
},
|
||||
queen_and_pawn: %{
|
||||
name: "queen and pawn",
|
||||
description: "Queens and pawns on the board."
|
||||
},
|
||||
queen_endgame: %{
|
||||
name: "queen endgame",
|
||||
description: "Queens on the board, with no pawns."
|
||||
},
|
||||
rook_and_pawn: %{
|
||||
name: "rook and pawn",
|
||||
description: "Rooks and pawns, with no queens."
|
||||
},
|
||||
rook_endgame: %{
|
||||
name: "rook endgame",
|
||||
description: "Rooks, with no queens and no pawns."
|
||||
},
|
||||
minor_piece_and_pawn: %{
|
||||
name: "minor piece and pawn",
|
||||
description: "Bishops and knights with pawns, with no queens or rooks."
|
||||
},
|
||||
minor_piece_endgame: %{
|
||||
name: "minor piece endgame",
|
||||
description: "Bishops and knights, with no queens, rooks or pawns."
|
||||
},
|
||||
pawn_endgame: %{
|
||||
name: "pawn endgame",
|
||||
description: "Kings and pawns only."
|
||||
}
|
||||
]
|
||||
|
||||
@type family ::
|
||||
:basic_mate
|
||||
| :king_and_pawn
|
||||
| :bare_king_other
|
||||
| :queen_and_pawn
|
||||
| :queen_endgame
|
||||
| :rook_and_pawn
|
||||
| :rook_endgame
|
||||
| :minor_piece_and_pawn
|
||||
| :minor_piece_endgame
|
||||
| :pawn_endgame
|
||||
|
||||
@doc "The material families, in a stable order."
|
||||
def families, do: @families
|
||||
|
||||
@doc """
|
||||
Returns the material family for a Key.
|
||||
|
||||
Returns `:kings_only` for `"K v K"` and `:unknown` when the Key is missing or
|
||||
not shaped like `"<side> v <side>"`.
|
||||
"""
|
||||
@spec family(String.t() | nil) :: family() | :kings_only | :unknown
|
||||
def family(key) when is_binary(key) do
|
||||
case String.split(key, " v ") do
|
||||
[a, b] ->
|
||||
cond do
|
||||
bare?(a) and bare?(b) -> :kings_only
|
||||
bare?(a) -> bare_king_family(counts(b))
|
||||
bare?(b) -> bare_king_family(counts(a))
|
||||
true -> material_family(merge(counts(a), counts(b)))
|
||||
end
|
||||
|
||||
_ ->
|
||||
:unknown
|
||||
end
|
||||
end
|
||||
|
||||
def family(_key), do: :unknown
|
||||
|
||||
@doc """
|
||||
Creates or corrects the material themes, keyed by family.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a material theme
|
||||
without losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{family() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@families, fn {family, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :material)
|
||||
{family, ensure_material_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived material theme.
|
||||
|
||||
Returns the number of endgames tagged, the number skipped (kings only or no
|
||||
Key) and the number of material themes. Re-running is idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
tagged: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
material_ids = Enum.map(themes, fn {_family, theme} -> theme.id end)
|
||||
|
||||
{links, skipped} =
|
||||
Endgame
|
||||
|> select([e], {e.id, e.key})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0}, fn {id, key}, {links, skipped} ->
|
||||
case family(key) do
|
||||
family when family in [:kings_only, :unknown] ->
|
||||
{links, skipped + 1}
|
||||
|
||||
family ->
|
||||
{[{id, Map.fetch!(themes, family).id} | links], skipped}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(material_ids, links)
|
||||
|
||||
%{tagged: length(links), skipped: skipped, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_material_theme(theme, attrs) do
|
||||
if theme.kind == :material and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :material, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp bare?(side), do: side == "K"
|
||||
|
||||
defp bare_king_family(counts) do
|
||||
cond do
|
||||
count(counts, "P") == 0 and (count(counts, "Q") > 0 or count(counts, "R") > 0) ->
|
||||
:basic_mate
|
||||
|
||||
count(counts, "P") > 0 and count(counts, "Q") == 0 and count(counts, "R") == 0 ->
|
||||
:king_and_pawn
|
||||
|
||||
true ->
|
||||
:bare_king_other
|
||||
end
|
||||
end
|
||||
|
||||
defp material_family(counts) do
|
||||
cond do
|
||||
count(counts, "Q") > 0 and count(counts, "P") > 0 ->
|
||||
:queen_and_pawn
|
||||
|
||||
count(counts, "Q") > 0 ->
|
||||
:queen_endgame
|
||||
|
||||
count(counts, "R") > 0 and count(counts, "P") > 0 ->
|
||||
:rook_and_pawn
|
||||
|
||||
count(counts, "R") > 0 ->
|
||||
:rook_endgame
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 and count(counts, "P") > 0 ->
|
||||
:minor_piece_and_pawn
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 ->
|
||||
:minor_piece_endgame
|
||||
|
||||
count(counts, "P") > 0 ->
|
||||
:pawn_endgame
|
||||
|
||||
true ->
|
||||
:kings_only
|
||||
end
|
||||
end
|
||||
|
||||
defp counts(side), do: Enum.frequencies(String.graphemes(side))
|
||||
|
||||
defp merge(left, right), do: Map.merge(left, right, fn _piece, a, b -> a + b end)
|
||||
|
||||
defp count(counts, piece), do: Map.get(counts, piece, 0)
|
||||
end
|
||||
@@ -0,0 +1,198 @@
|
||||
defmodule Chesstrainer.Endgames.MotifThemes do
|
||||
@moduledoc """
|
||||
Derives objective motif themes by probing each endgame's position.
|
||||
|
||||
Motifs describe the kind of problem, independent of the material family: an
|
||||
endgame can be a rook endgame and an only-move puzzle at the same time. Every
|
||||
motif is proved from the local Syzygy tables — one probe returns the root WDL,
|
||||
the DTZ and every legal move with its own WDL — so nothing here is a guess and
|
||||
nothing calls the remote backend.
|
||||
|
||||
Motif links are recorded as `derived` and refreshed as a whole. Material
|
||||
families, curated links and community links are untouched because the refresh
|
||||
is scoped to the motif themes.
|
||||
|
||||
Loss endgames are skipped: only-move is undefined when every move loses, and
|
||||
the library no longer contains them.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Backend.Fathom, as: FathomBackend
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@motifs [
|
||||
only_move: %{
|
||||
name: "only move",
|
||||
description:
|
||||
"Exactly one legal move keeps the result, so the puzzle is about finding the single accurate move."
|
||||
},
|
||||
underpromotion: %{
|
||||
name: "underpromotion",
|
||||
description:
|
||||
"The result can only be preserved by promoting to a rook, bishop or knight; promoting to a queen does not work."
|
||||
},
|
||||
fifty_move_draw: %{
|
||||
name: "50-move draw",
|
||||
description:
|
||||
"The result turns on the fifty-move rule: the win needs more moves than the halfmove clock allows, so the defender can claim a draw."
|
||||
}
|
||||
]
|
||||
|
||||
@type motif :: :only_move | :underpromotion | :fifty_move_draw
|
||||
|
||||
@doc "The motif themes, in a stable order."
|
||||
def motifs, do: @motifs
|
||||
|
||||
@doc """
|
||||
Returns the motifs for one probed position.
|
||||
|
||||
`moves` are Fathom move tuples `{wdl, from, to, promotes, ep, dtz}` and carry
|
||||
the mover's perspective, so they are compared with the root WDL directly.
|
||||
`halfmove_clock` comes from the FEN; the probe itself runs with `rule50 = 0`.
|
||||
"""
|
||||
@spec motifs_for(atom(), integer() | nil, [tuple()], non_neg_integer()) :: [motif()]
|
||||
def motifs_for(wdl, dtz, moves, halfmove_clock) do
|
||||
outcome = Tablebase.normalize_wdl(wdl)
|
||||
|
||||
preserving =
|
||||
Enum.filter(moves, fn {move_wdl, _from, _to, _promotes, _ep, _dtz} ->
|
||||
Tablebase.normalize_wdl(move_wdl) == outcome
|
||||
end)
|
||||
|
||||
[]
|
||||
|> maybe_only_move(outcome, moves, preserving)
|
||||
|> maybe_underpromotion(preserving)
|
||||
|> maybe_fifty_move(wdl, dtz, halfmove_clock)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates or corrects the motif themes, keyed by motif.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a motif without
|
||||
losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{motif() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@motifs, fn {motif, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :motif)
|
||||
{motif, ensure_motif_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived motif links.
|
||||
|
||||
Returns the number of links written, the number of endgames skipped because
|
||||
the local tables could not answer them, and a count per motif. Re-running is
|
||||
idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
links: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
by_motif: %{motif() => non_neg_integer()},
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
motif_ids = Enum.map(themes, fn {_motif, theme} -> theme.id end)
|
||||
|
||||
initial_counts = Map.new(@motifs, fn {motif, _attrs} -> {motif, 0} end)
|
||||
|
||||
{links, skipped, by_motif} =
|
||||
Endgame
|
||||
|> where([e], e.result in [:win, :draw])
|
||||
|> select([e], {e.id, e.fen})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0, initial_counts}, fn {id, fen}, {links, skipped, counts} ->
|
||||
case probe(fen) do
|
||||
{:ok, %{wdl: wdl, dtz: dtz, moves: moves}} ->
|
||||
motifs = motifs_for(wdl, dtz, moves, halfmove_clock(fen))
|
||||
|
||||
links =
|
||||
Enum.reduce(motifs, links, fn motif, acc ->
|
||||
[{id, Map.fetch!(themes, motif).id} | acc]
|
||||
end)
|
||||
|
||||
counts =
|
||||
Enum.reduce(motifs, counts, fn motif, acc ->
|
||||
Map.update!(acc, motif, &(&1 + 1))
|
||||
end)
|
||||
|
||||
{links, skipped, counts}
|
||||
|
||||
{:error, _reason} ->
|
||||
{links, skipped + 1, counts}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(motif_ids, links)
|
||||
|
||||
%{links: length(links), skipped: skipped, by_motif: by_motif, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_motif_theme(theme, attrs) do
|
||||
if theme.kind == :motif and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :motif, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp probe(fen), do: probe_module().probe_local_detail(fen)
|
||||
|
||||
defp probe_module do
|
||||
Application.get_env(:chesstrainer, :motif_probe, FathomBackend)
|
||||
end
|
||||
|
||||
defp maybe_only_move(acc, outcome, moves, preserving) do
|
||||
if outcome in [:win, :draw] and length(moves) > 1 and length(preserving) == 1 do
|
||||
[:only_move | acc]
|
||||
else
|
||||
acc
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_underpromotion(acc, preserving) do
|
||||
underpromotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes in [2, 3, 4]
|
||||
end)
|
||||
|
||||
queen_promotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes == 1
|
||||
end)
|
||||
|
||||
if underpromotes? and not queen_promotes?, do: [:underpromotion | acc], else: acc
|
||||
end
|
||||
|
||||
defp maybe_fifty_move(acc, wdl, dtz, halfmove_clock) do
|
||||
table_draw? = wdl in [:cursed_win, :blessed_loss]
|
||||
|
||||
clock_exhausted? =
|
||||
wdl == :win and is_integer(dtz) and dtz > 100 - halfmove_clock
|
||||
|
||||
if table_draw? or clock_exhausted?, do: [:fifty_move_draw | acc], else: acc
|
||||
end
|
||||
|
||||
defp halfmove_clock(fen) do
|
||||
case String.split(fen, " ") do
|
||||
[_board, _active, _castling, _ep, clock, _fullmove] ->
|
||||
case Integer.parse(clock) do
|
||||
{value, _rest} -> value
|
||||
:error -> 0
|
||||
end
|
||||
|
||||
_ ->
|
||||
0
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -80,6 +80,38 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.Fathom do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Probes the local tablebase and returns the raw root outcome and move list.
|
||||
|
||||
Unlike `probe_result_local/1`, this keeps the per-move tuples and the raw WDL
|
||||
atom, including `:cursed_win` and `:blessed_loss`, which the motif derivation
|
||||
needs. It never falls back to the remote backend or consults the cache.
|
||||
|
||||
Returns `{:error, :unsupported}` when the local files cannot answer the
|
||||
position, including a partial tablebase set where Fathom reports `:failed`.
|
||||
"""
|
||||
@spec probe_local_detail(String.t()) ::
|
||||
{:ok, %{wdl: atom(), dtz: integer(), moves: [tuple()]}}
|
||||
| {:error, :not_configured | :terminal | :unsupported}
|
||||
def probe_local_detail(fen) do
|
||||
with {:ok, largest} <- Local.check(),
|
||||
pieces when is_integer(pieces) <- FEN.piece_count(fen),
|
||||
true <- pieces <= largest || {:error, :unsupported},
|
||||
{:ok, {root, moves}} <- Nif.probe(fen) do
|
||||
case root do
|
||||
:failed -> {:error, :unsupported}
|
||||
:checkmate -> {:error, :terminal}
|
||||
:stalemate -> {:error, :terminal}
|
||||
{wdl, _from, _to, _promotes, _ep, dtz} -> {:ok, %{wdl: wdl, dtz: dtz, moves: moves}}
|
||||
end
|
||||
else
|
||||
{:error, :not_configured} = error -> error
|
||||
{:error, :unsupported} = error -> error
|
||||
{:error, _reason} -> {:error, :unsupported}
|
||||
nil -> {:error, :unsupported}
|
||||
end
|
||||
end
|
||||
|
||||
defp fallback(fen) do
|
||||
(Application.get_env(:chesstrainer, :tablebase_fallback) || Lichess).probe(fen)
|
||||
end
|
||||
|
||||
@@ -40,6 +40,18 @@ defmodule Chesstrainer.GuestLimits do
|
||||
@doc "Clears every budget. Intended for tests."
|
||||
def reset, do: GenServer.call(__MODULE__, :reset)
|
||||
|
||||
@doc """
|
||||
Returns the puzzles left today without consuming one.
|
||||
|
||||
Mirrors `take/2`'s result shape so a caller can show the wall before doing
|
||||
work that would otherwise spend a puzzle.
|
||||
"""
|
||||
@spec remaining(address, Date.t()) ::
|
||||
{:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer}
|
||||
def remaining(address, today \\ Date.utc_today()) do
|
||||
GenServer.call(__MODULE__, {:remaining, address, today})
|
||||
end
|
||||
|
||||
@doc "The daily puzzle allowance for a guest."
|
||||
def limit, do: config() |> Keyword.get(:limit, @default_limit)
|
||||
|
||||
@@ -67,6 +79,21 @@ defmodule Chesstrainer.GuestLimits do
|
||||
@impl true
|
||||
def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
|
||||
|
||||
def handle_call({:remaining, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
|
||||
|
||||
def handle_call({:remaining, 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 ->
|
||||
{:reply, {:ok, state.limit - used}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call({:take, address, today}, _from, state) do
|
||||
day = Date.to_gregorian_days(today)
|
||||
key = key(state.secret, day, address)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
defmodule Chesstrainer.Mail do
|
||||
@moduledoc """
|
||||
House rules for every outgoing email.
|
||||
|
||||
Notifiers build the message body and hand it here, so the sender identity,
|
||||
reply-to address, SES configuration set and the test redirect are applied in
|
||||
exactly one place and no sender can forget them.
|
||||
|
||||
The From address lives on the `mail.` subdomain so transactional mail is
|
||||
distinct from the addresses that receive mail on the apex domain. SES
|
||||
verification of the parent domain covers the subdomain, so no separate
|
||||
identity is required for the From header to be accepted.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
|
||||
@default_configuration_set "my-first-configuration-set"
|
||||
|
||||
@doc """
|
||||
Applies the house rules and delivers the email.
|
||||
|
||||
Returns `{:ok, email}` so notifiers can report the message they sent.
|
||||
"""
|
||||
def deliver(%Swoosh.Email{} = email) do
|
||||
email = prepare(email)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Applies the house rules without delivering.
|
||||
|
||||
Exposed so tooling (such as `mix mail.check`) can inspect or send the exact
|
||||
message the application would send.
|
||||
"""
|
||||
def prepare(%Swoosh.Email{} = email) do
|
||||
email
|
||||
|> Swoosh.Email.from({Branding.name(), Branding.mail_from()})
|
||||
|> Swoosh.Email.reply_to(Branding.support_email())
|
||||
|> Swoosh.Email.put_provider_option(:configuration_set_name, configuration_set())
|
||||
|> redirect()
|
||||
end
|
||||
|
||||
defp configuration_set do
|
||||
Application.get_env(:chesstrainer, :ses_configuration_set, @default_configuration_set)
|
||||
end
|
||||
|
||||
# Rewrites every recipient to one address so a staging or production smoke
|
||||
# test can send through real SES without reaching users. The original
|
||||
# recipients stay in the subject and in an `X-Original-To` header so the
|
||||
# redirected message explains itself.
|
||||
defp redirect(email) do
|
||||
case Application.get_env(:chesstrainer, :mail_redirect_to) do
|
||||
address when is_binary(address) and address != "" ->
|
||||
originals = recipients(email)
|
||||
|
||||
require Logger
|
||||
|
||||
Logger.warning("mail redirect: #{Enum.join(originals, ", ")} -> #{address}")
|
||||
|
||||
%{email | to: [{"", address}], cc: [], bcc: []}
|
||||
|> Swoosh.Email.header("X-Original-To", Enum.join(originals, ", "))
|
||||
|> Swoosh.Email.subject("[→ #{Enum.join(originals, ", ")}] #{email.subject}")
|
||||
|
||||
_unset ->
|
||||
email
|
||||
end
|
||||
end
|
||||
|
||||
defp recipients(email) do
|
||||
[email.to, email.cc, email.bcc]
|
||||
|> List.flatten()
|
||||
|> Enum.reject(&is_nil/1)
|
||||
|> Enum.map(fn
|
||||
{_name, address} -> address
|
||||
address when is_binary(address) -> address
|
||||
end)
|
||||
end
|
||||
end
|
||||
@@ -6,7 +6,7 @@ defmodule Chesstrainer.MailingList.Notifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
@doc """
|
||||
Delivers the confirmation email for a mailing-list subscription.
|
||||
@@ -30,16 +30,10 @@ defmodule Chesstrainer.MailingList.Notifier do
|
||||
end
|
||||
|
||||
defp deliver(recipient, subject, body) do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({Branding.name(), Branding.mail_from()})
|
||||
|> reply_to(Branding.support_email())
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|> Mail.deliver()
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,14 +2,21 @@ defmodule Chesstrainer.Puzzles do
|
||||
@moduledoc """
|
||||
Selects endgames to serve as puzzles.
|
||||
|
||||
A puzzle is played at one of three difficulties — `:easy`, `:medium` or
|
||||
`:hard` — defined relative to the current user's rating: `:medium` is within
|
||||
a configurable band of the user's rating, `:easy` below it and `:hard` above
|
||||
it. The same endgame is therefore easy for one player and hard for another.
|
||||
Difficulty is a bias, not a filter. Every endgame is weighted by how close its
|
||||
rating is to a target derived from the user's rating — the user's own rating
|
||||
for `:medium`, below it for `:easy` and above it for `:hard` — and one
|
||||
candidate is drawn from that weighted distribution. Nearby endgames are much
|
||||
more likely, but the whole library stays reachable, so a thin region around
|
||||
the user's rating can never leave the pool empty.
|
||||
|
||||
Selection prefers endgames the user has not attempted in the last 30 days.
|
||||
When that pool is empty it falls back to any endgame in the band; the rating
|
||||
window keeps a recent replay unrated until it expires.
|
||||
Endgames the user has attempted inside the repeat window are skipped, as is
|
||||
anything passed in `:exclude_ids` (the puzzles already served in a session).
|
||||
Only when every candidate is excluded does selection fall back to the least
|
||||
recently attempted endgame, so the repeat is the most overdue one rather than
|
||||
an arbitrary one.
|
||||
|
||||
The same endgame is therefore easy for one player and hard for another: a
|
||||
rating is what makes the two comparable.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
@@ -17,95 +24,115 @@ defmodule Chesstrainer.Puzzles do
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Accounts.User
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.Attempts.Attempt
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
|
||||
@default_band_width 100
|
||||
@default_spread 150
|
||||
@default_repeat_window_days 30
|
||||
@default_targets [easy: -200, medium: 0, hard: 200]
|
||||
@difficulties [:easy, :medium, :hard]
|
||||
|
||||
@doc "The difficulties a session can be played at."
|
||||
def difficulties, do: @difficulties
|
||||
|
||||
@doc """
|
||||
The half-width of the medium band, in rating points.
|
||||
How far, in rating points, a puzzle's likelihood falls off from the target.
|
||||
|
||||
Configured under `:chesstrainer, :puzzles, :band_width`.
|
||||
A larger spread draws more widely around the target. Configured under
|
||||
`:chesstrainer, :puzzles, :spread`.
|
||||
"""
|
||||
def band_width do
|
||||
:chesstrainer
|
||||
|> Application.get_env(:puzzles, [])
|
||||
|> Keyword.get(:band_width, @default_band_width)
|
||||
end
|
||||
def spread, do: setting(:spread, @default_spread)
|
||||
|
||||
@doc """
|
||||
The `{min, max}` rating range for `difficulty` relative to `rating`.
|
||||
The minimum gap, in days, before the same endgame may be served again.
|
||||
|
||||
A `nil` bound is open-ended.
|
||||
Configured under `:chesstrainer, :puzzles, :repeat_window_days`.
|
||||
"""
|
||||
def difficulty_range(rating, difficulty) when difficulty in @difficulties do
|
||||
width = band_width()
|
||||
def repeat_window_days, do: setting(:repeat_window_days, @default_repeat_window_days)
|
||||
|
||||
case difficulty do
|
||||
:easy -> {nil, rating - width}
|
||||
:medium -> {rating - width, rating + width}
|
||||
:hard -> {rating + width, nil}
|
||||
end
|
||||
@doc """
|
||||
The rating `difficulty` aims at, given the player's `rating`.
|
||||
|
||||
The offsets are configured under `:chesstrainer, :puzzles, :targets`.
|
||||
"""
|
||||
def difficulty_target(rating, difficulty) when difficulty in @difficulties do
|
||||
rating + Keyword.fetch!(setting(:targets, @default_targets), difficulty)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Picks the next puzzle for `user` at `difficulty`, using `user.rating` as the
|
||||
baseline.
|
||||
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating
|
||||
the puzzle just played. Returns `nil` when no endgame exists at all.
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used for the puzzles
|
||||
already served in this session. Returns `nil` when no endgame exists at all.
|
||||
"""
|
||||
def next_endgame(%User{} = user, difficulty, opts \\ [])
|
||||
when difficulty in @difficulties do
|
||||
exclude_ids = Keyword.get(opts, :exclude_ids, [])
|
||||
band = difficulty_range(user.rating, difficulty)
|
||||
recent_ids = Attempts.recent_endgame_ids(user.id)
|
||||
recent_ids = Attempts.recent_endgame_ids(user.id, repeat_window_days())
|
||||
target = difficulty_target(user.rating, difficulty)
|
||||
|
||||
fresh =
|
||||
Endgame
|
||||
|> in_band(band)
|
||||
|> skip_ids(exclude_ids)
|
||||
|> skip_ids(recent_ids)
|
||||
|> random_one()
|
||||
|
||||
fresh || fallback(user.rating, band, exclude_ids)
|
||||
end
|
||||
|
||||
defp fallback(rating, band, exclude_ids) do
|
||||
Endgame
|
||||
|> in_band(band)
|
||||
|> skip_ids(exclude_ids)
|
||||
|> random_one()
|
||||
|> on_side_of(user.rating, difficulty)
|
||||
|> skip_ids(exclude_ids ++ recent_ids)
|
||||
|> weighted_one(target)
|
||||
|> case do
|
||||
nil -> nearest(rating, exclude_ids)
|
||||
nil -> least_recently_attempted(user.id, exclude_ids)
|
||||
endgame -> endgame
|
||||
end
|
||||
end
|
||||
|
||||
defp nearest(rating, exclude_ids) do
|
||||
# Keep the labels honest: "easy" never serves above the user's rating plus the
|
||||
# spread, and "hard" never below it minus the spread. "medium" is open, which
|
||||
# is what lets it reach the rest of the library.
|
||||
defp on_side_of(query, _rating, :medium), do: query
|
||||
|
||||
defp on_side_of(query, rating, :easy),
|
||||
do: where(query, [e], e.rating <= ^(rating + spread()))
|
||||
|
||||
defp on_side_of(query, rating, :hard),
|
||||
do: where(query, [e], e.rating >= ^(rating - spread()))
|
||||
|
||||
# Draw one row with probability proportional to
|
||||
# `exp(-|rating - target| / spread)`: an exponential race, where the row with
|
||||
# the smallest `-ln(U) / weight` wins.
|
||||
defp weighted_one(query, target) do
|
||||
spread = spread() * 1.0
|
||||
target = target * 1.0
|
||||
|
||||
query
|
||||
|> order_by(
|
||||
[e],
|
||||
fragment("-ln(1 - random()) * exp(abs(? - ?) / ?)", e.rating, ^target, ^spread)
|
||||
)
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
# Every candidate is excluded, so the repeat window is overruled: serve
|
||||
# whatever the user has waited longest to see again.
|
||||
defp least_recently_attempted(user_id, exclude_ids) do
|
||||
attempted =
|
||||
Attempt
|
||||
|> where([a], a.user_id == ^user_id)
|
||||
|> group_by([a], a.endgame_id)
|
||||
|> select([a], %{endgame_id: a.endgame_id, last_at: max(a.inserted_at)})
|
||||
|
||||
Endgame
|
||||
|> skip_ids(exclude_ids)
|
||||
|> order_by([e], asc: fragment("ABS(? - ?)", e.rating, ^rating))
|
||||
|> join(:left, [e], a in subquery(attempted), on: a.endgame_id == e.id)
|
||||
|> order_by([_e, a], asc_nulls_first: a.last_at)
|
||||
|> order_by([e], fragment("random()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp random_one(query) do
|
||||
query
|
||||
|> order_by([e], fragment("RANDOM()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp in_band(query, {nil, max}), do: where(query, [e], e.rating <= ^max)
|
||||
defp in_band(query, {min, nil}), do: where(query, [e], e.rating >= ^min)
|
||||
|
||||
defp in_band(query, {min, max}),
|
||||
do: where(query, [e], e.rating >= ^min and e.rating <= ^max)
|
||||
|
||||
defp skip_ids(query, []), do: query
|
||||
defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids)
|
||||
|
||||
defp setting(key, default) do
|
||||
:chesstrainer
|
||||
|> Application.get_env(:puzzles, [])
|
||||
|> Keyword.get(key, default)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -18,6 +18,28 @@ defmodule Chesstrainer.Release do
|
||||
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Derives material family themes for the whole library.
|
||||
|
||||
Runs in the release without starting the web application: `with_repo/2`
|
||||
starts just the repository, which is all the derivation needs.
|
||||
"""
|
||||
def derive_material, do: with_repo(&Chesstrainer.Endgames.MaterialThemes.derive/0)
|
||||
|
||||
@doc """
|
||||
Derives motif themes from the local tablebase for the whole library.
|
||||
"""
|
||||
def derive_motifs, do: with_repo(&Chesstrainer.Endgames.MotifThemes.derive/0)
|
||||
|
||||
defp with_repo(fun) do
|
||||
load_app()
|
||||
|
||||
for repo <- repos() do
|
||||
{:ok, result, _} = Ecto.Migrator.with_repo(repo, fn _repo -> fun.() end)
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
defp repos do
|
||||
Application.fetch_env!(@app, :ecto_repos)
|
||||
end
|
||||
|
||||
@@ -4,6 +4,8 @@ defmodule Chesstrainer.Themes do
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
alias Chesstrainer.Themes.Theme
|
||||
@@ -74,9 +76,26 @@ defmodule Chesstrainer.Themes do
|
||||
"""
|
||||
def get_theme!(id), do: Repo.get!(Theme, id)
|
||||
|
||||
@doc """
|
||||
Gets a single endgame theme by its slug.
|
||||
|
||||
Returns `nil` when no endgame theme has that slug.
|
||||
"""
|
||||
def get_theme_by_slug(slug) when is_binary(slug) do
|
||||
Repo.one(
|
||||
from t in Theme,
|
||||
where: t.slug == ^slug and t.category == :endgame,
|
||||
limit: 1
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme.
|
||||
|
||||
This is the unscoped path used by internal callers such as seeds, fixtures and
|
||||
the admin picker, which are already behind an authorization check. Prefer
|
||||
`create_theme/2` wherever a scope is available.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> create_theme(%{field: value})
|
||||
@@ -92,6 +111,21 @@ defmodule Chesstrainer.Themes do
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme on behalf of an administrator.
|
||||
|
||||
Members cannot introduce new theme names; their contribution path is a
|
||||
suggestion, which a moderator reviews. Returns `{:error, :unauthorized}`
|
||||
for a scope that cannot manage themes.
|
||||
"""
|
||||
def create_theme(%Scope{} = scope, attrs) do
|
||||
if Policy.can?(scope, :manage_themes) do
|
||||
create_theme(attrs)
|
||||
else
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a theme.
|
||||
|
||||
@@ -160,20 +194,167 @@ defmodule Chesstrainer.Themes do
|
||||
@doc """
|
||||
Finds a theme by name (trimmed and case-insensitive) for a category, creating it
|
||||
if it does not exist.
|
||||
|
||||
Options:
|
||||
|
||||
* `:kind` - the kind for a newly created theme; defaults to `:technique`
|
||||
|
||||
This is the picker's helper and is expected to run behind an admin check.
|
||||
"""
|
||||
def get_or_create(name, category) when is_binary(name) do
|
||||
def get_or_create(name, category, opts \\ []) when is_binary(name) do
|
||||
name = String.trim(name)
|
||||
|
||||
if name == "" do
|
||||
{:error, :blank_name}
|
||||
else
|
||||
case find_by_name(name, category) do
|
||||
nil -> create_theme(%{name: name, category: category})
|
||||
theme -> {:ok, theme}
|
||||
nil ->
|
||||
create_theme(%{
|
||||
name: name,
|
||||
category: category,
|
||||
kind: Keyword.get(opts, :kind, :technique)
|
||||
})
|
||||
|
||||
theme ->
|
||||
{:ok, theme}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Replaces every link to `scoped_theme_ids` with the derived links in `links`.
|
||||
|
||||
This is for themes that are objectively derived: the pass owns its themes
|
||||
entirely, so a link's previous source is irrelevant and every link is
|
||||
rewritten as `derived`. Links to themes outside `scoped_theme_ids` — curated
|
||||
or community — are untouched.
|
||||
|
||||
The operation is a full refresh for the given themes, so it can move an
|
||||
endgame between families when a rule changes. `links` is a list of
|
||||
`{endgame_id, theme_id}` pairs.
|
||||
"""
|
||||
@spec replace_theme_links([term()], [{Ecto.UUID.t(), term()}]) :: :ok
|
||||
def replace_theme_links(scoped_theme_ids, links) when is_list(links) do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
Repo.transaction(fn ->
|
||||
if scoped_theme_ids != [] do
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where: l.theme_id in ^scoped_theme_ids
|
||||
)
|
||||
end
|
||||
|
||||
links
|
||||
|> Enum.map(fn {endgame_id, theme_id} ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: "derived",
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|> Enum.chunk_every(5_000)
|
||||
|> Enum.each(fn rows ->
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end)
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
@link_sources [:curated, :community]
|
||||
|
||||
@doc """
|
||||
Links `theme` to many endgames at once with the given source.
|
||||
|
||||
Defaults to `:curated`, which is what the admin tagging workspace writes.
|
||||
Existing links are left alone, so re-applying is safe. Returns the number of
|
||||
endgames the link was attempted for.
|
||||
"""
|
||||
@spec tag_endgames(Theme.t(), [Ecto.UUID.t()], :curated | :community) ::
|
||||
{:ok, non_neg_integer()}
|
||||
def tag_endgames(%Theme{id: theme_id}, endgame_ids, source \\ :curated)
|
||||
when is_list(endgame_ids) and source in @link_sources do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
endgame_ids
|
||||
|> Enum.uniq()
|
||||
|> Enum.map(fn endgame_id ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: to_string(source),
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|> Enum.chunk_every(5_000)
|
||||
|> Enum.each(fn rows ->
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end)
|
||||
|
||||
{:ok, length(Enum.uniq(endgame_ids))}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Removes a link from `theme` to one endgame, but only if it has the given
|
||||
source.
|
||||
|
||||
The tagging workspace removes `:curated` links only, so a derived or
|
||||
community link can never be deleted by hand. Returns the number removed.
|
||||
"""
|
||||
@spec untag_endgame(Theme.t(), Ecto.UUID.t(), :curated | :community) ::
|
||||
{:ok, non_neg_integer()}
|
||||
def untag_endgame(%Theme{id: theme_id}, endgame_id, source \\ :curated)
|
||||
when source in @link_sources do
|
||||
{count, _} =
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where:
|
||||
l.theme_id == ^theme_id and l.endgame_id == type(^endgame_id, :binary_id) and
|
||||
l.source == ^to_string(source)
|
||||
)
|
||||
|
||||
{:ok, count}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Replaces the derived theme links for one endgame.
|
||||
|
||||
Only links whose source is `derived` are removed, so curated and
|
||||
community-approved links survive every derivation pass. Links that are
|
||||
already present are left alone, which makes the operation idempotent.
|
||||
"""
|
||||
@spec sync_derived_themes(Ecto.UUID.t(), [term()]) :: :ok
|
||||
def sync_derived_themes(endgame_id, theme_ids) do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
Repo.transaction(fn ->
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id) and l.source == "derived"
|
||||
)
|
||||
|
||||
rows =
|
||||
theme_ids
|
||||
|> Enum.uniq()
|
||||
|> Enum.map(fn theme_id ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: "derived",
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|
||||
if rows != [] do
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp find_by_name(name, category) do
|
||||
downcased = String.downcase(name)
|
||||
|
||||
|
||||
@@ -1,29 +1,106 @@
|
||||
defmodule Chesstrainer.Themes.Theme do
|
||||
@moduledoc """
|
||||
A label describing an endgame's technique or goal.
|
||||
|
||||
A theme has a stable `slug` for URLs, a `kind` saying where the label comes
|
||||
from — `material`, `motif` or `technique` — and an optional description. The
|
||||
slug is generated from the name when the theme is first created and is then
|
||||
left alone, so renaming a theme never breaks a link to it.
|
||||
"""
|
||||
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@kinds [material: "material", motif: "motif", technique: "technique"]
|
||||
|
||||
schema "themes" do
|
||||
field :name, :string
|
||||
field :slug, :string
|
||||
field :description, :string
|
||||
field :kind, Ecto.Enum, values: @kinds, default: :technique
|
||||
field :category, Ecto.Enum, values: [endgame: "endgame", opening: "opening", tactic: "tactic"]
|
||||
|
||||
timestamps(type: :utc_datetime)
|
||||
end
|
||||
|
||||
@doc "The kinds a theme can have."
|
||||
def kinds, do: Keyword.keys(@kinds)
|
||||
|
||||
@doc """
|
||||
Turns a theme name into a URL-safe slug.
|
||||
|
||||
Lowercase letters, digits and single hyphens; accents are folded, runs of
|
||||
other characters collapse to one hyphen, and a blank result becomes
|
||||
`"theme"`.
|
||||
"""
|
||||
@spec slugify(String.t() | nil) :: String.t()
|
||||
def slugify(name) do
|
||||
slug =
|
||||
name
|
||||
|> to_string()
|
||||
|> :unicode.characters_to_nfd_binary()
|
||||
|> String.replace(~r/[\x{0300}-\x{036F}]/u, "")
|
||||
|> String.downcase()
|
||||
|> String.replace(~r/[^a-z0-9]+/u, "-")
|
||||
|> String.trim("-")
|
||||
|
||||
if slug == "", do: "theme", else: slug
|
||||
end
|
||||
|
||||
@doc false
|
||||
def changeset(theme, attrs) do
|
||||
theme
|
||||
|> cast(attrs, [:name, :category])
|
||||
|> update_change(:name, fn
|
||||
name when is_binary(name) -> String.trim(name)
|
||||
name -> name
|
||||
end)
|
||||
|> validate_required([:name, :category])
|
||||
|> cast(attrs, [:name, :slug, :description, :kind, :category])
|
||||
|> update_change(:name, &trim/1)
|
||||
|> update_change(:description, &trim/1)
|
||||
|> put_slug()
|
||||
|> validate_required([:name, :slug, :kind, :category])
|
||||
|> validate_length(:name, min: 1, max: 60)
|
||||
|> validate_length(:slug, min: 1, max: 80)
|
||||
|> validate_length(:description, max: 500)
|
||||
|> validate_format(:slug, ~r/\A[a-z0-9]+(?:-[a-z0-9]+)*\z/,
|
||||
message: "must be lowercase letters, numbers and single hyphens"
|
||||
)
|
||||
|> unique_constraint(:name,
|
||||
name: :themes_name_category_lower_index,
|
||||
message: "already exists"
|
||||
)
|
||||
|> unique_constraint(:slug, message: "is already taken")
|
||||
|> check_constraint(:kind, name: :themes_kind_in_allowed)
|
||||
end
|
||||
|
||||
defp put_slug(changeset) do
|
||||
case get_field(changeset, :slug) do
|
||||
slug when is_binary(slug) ->
|
||||
if String.trim(slug) == "" do
|
||||
generate_slug(changeset)
|
||||
else
|
||||
put_change(changeset, :slug, slugify(slug))
|
||||
end
|
||||
|
||||
nil ->
|
||||
generate_slug(changeset)
|
||||
end
|
||||
end
|
||||
|
||||
# A new theme starts without a name, so generating a slug from it would only
|
||||
# produce the fallback. Wait until there is a name to derive from.
|
||||
defp generate_slug(changeset) do
|
||||
case get_field(changeset, :name) do
|
||||
name when is_binary(name) ->
|
||||
if String.trim(name) == "" do
|
||||
changeset
|
||||
else
|
||||
put_change(changeset, :slug, slugify(name))
|
||||
end
|
||||
|
||||
_ ->
|
||||
changeset
|
||||
end
|
||||
end
|
||||
|
||||
defp trim(value) when is_binary(value), do: String.trim(value)
|
||||
defp trim(value), do: value
|
||||
end
|
||||
|
||||
@@ -17,7 +17,11 @@ defmodule ChesstrainerWeb do
|
||||
those modules here.
|
||||
"""
|
||||
|
||||
def static_paths, do: ~w(assets fonts images favicon.ico)
|
||||
def static_paths do
|
||||
~w(assets fonts images favicon.ico favicon.svg favicon-16x16.png favicon-32x32.png
|
||||
apple-touch-icon.png android-chrome-192x192.png android-chrome-512x512.png
|
||||
site.webmanifest)
|
||||
end
|
||||
|
||||
@doc "Whether the app is gated behind the prelaunch page."
|
||||
def prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false)
|
||||
@@ -103,6 +107,7 @@ defmodule ChesstrainerWeb do
|
||||
alias Phoenix.LiveView.JS
|
||||
alias Chesstrainer.Branding
|
||||
alias ChesstrainerWeb.Layouts
|
||||
alias ChesstrainerWeb.SEO
|
||||
|
||||
# Routes generation with the ~p sigil
|
||||
unquote(verified_routes())
|
||||
|
||||
@@ -126,8 +126,15 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
Start training <.icon_arrow />
|
||||
</.pill_button>
|
||||
<% end %>
|
||||
|
||||
<div class="nav-menu-tools">
|
||||
<.colour_mode_toggle />
|
||||
<.discord_link />
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<.discord_link />
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
@@ -225,6 +232,7 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
<a href="/terms-conditions">Terms & Conditions</a>
|
||||
<a href="/mentions-legales">Mentions légales</a>
|
||||
<a href="/sitemap.xml">Sitemap</a>
|
||||
<.discord_link />
|
||||
</nav>
|
||||
|
||||
<small>© {@year} {Branding.name()}</small>
|
||||
@@ -232,6 +240,35 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Renders the Discord invite as an icon-only link.
|
||||
|
||||
The glyph is decorative; the `aria-label` carries the link's purpose for
|
||||
screen readers. Renders nothing when no invite is configured, so environments
|
||||
without one never show a dead link.
|
||||
"""
|
||||
def discord_link(assigns) do
|
||||
assigns = assign(assigns, :href, Branding.discord_invite_url())
|
||||
|
||||
~H"""
|
||||
<a
|
||||
:if={@href}
|
||||
class="discord-link"
|
||||
href={@href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={"Join the #{Branding.name()} Discord"}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M20.317 4.3698a19.7913 19.7913 0 0 0-4.8851-1.5152.0741.0741 0 0 0-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 0 0-.0785-.037 19.7363 19.7363 0 0 0-4.8852 1.515.0699.0699 0 0 0-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 0 0 .0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 0 0 .0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 0 0-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 0 1-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 0 1 .0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 0 1 .0785.0105c.1202.0991.246.1971.3728.2914a.077.077 0 0 1-.0066.1277c-.5986.3428-1.2201.6447-1.8739.8923a.0766.0766 0 0 0-.0407.1057c.36.699.7715 1.3647 1.225 1.9942a.076.076 0 0 0 .0843.0276c1.9608-.6066 3.9493-1.5218 6.0021-3.0294a.077.077 0 0 0 .0322-.0561c.5008-5.1763-.8398-9.6746-3.5543-13.6607a.061.061 0 0 0-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Shows the flash group with standard titles and content.
|
||||
|
||||
@@ -282,6 +319,17 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
{gettext("Attempting to reconnect")}
|
||||
<.icon name="hero-arrow-path" class="ml-1 size-3 motion-safe:animate-spin" />
|
||||
</.flash>
|
||||
|
||||
<div
|
||||
id="connection-actions"
|
||||
hidden
|
||||
phx-disconnected={show("#connection-actions")}
|
||||
phx-connected={hide("#connection-actions")}
|
||||
class="pointer-events-auto flex items-center gap-3 rounded-lg border border-base-300 bg-base-100 px-4 py-2 text-sm shadow-lg"
|
||||
>
|
||||
<a href="" class="font-semibold text-primary-text hover:underline">Reload</a>
|
||||
<.link href={~p"/"} class="text-muted hover:underline">Home</.link>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
@@ -357,7 +405,8 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
matomo_url: url,
|
||||
matomo_site_id: site_id && to_string(site_id),
|
||||
analytics_enabled:
|
||||
is_binary(url) and url != "" and site_id not in [nil, ""] and is_nil(user)
|
||||
is_binary(url) and byte_size(url) > 0 and is_binary(site_id) and byte_size(site_id) > 0 and
|
||||
is_nil(user)
|
||||
)
|
||||
|
||||
~H"""
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<html lang={assigns[:lang] || "en"}>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta :if={assigns[:noindex]} name="robots" content="noindex" />
|
||||
<meta :if={assigns[:noindex]} name="robots" content="noindex, nofollow" />
|
||||
|
||||
<meta name="csrf-token" content={get_csrf_token()} />
|
||||
<.live_title
|
||||
@@ -30,7 +30,24 @@
|
||||
content={assigns[:meta_description]}
|
||||
/>
|
||||
<meta :if={assigns[:canonical_url]} property="og:url" content={assigns[:canonical_url]} />
|
||||
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary" />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
property="og:image"
|
||||
content={assigns[:og_image_url] || SEO.og_image_url()}
|
||||
/>
|
||||
<meta :if={assigns[:meta_description]} property="og:image:width" content="1200" />
|
||||
<meta :if={assigns[:meta_description]} property="og:image:height" content="630" />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
property="og:image:alt"
|
||||
content={"#{Branding.name()} — #{Branding.tagline()}"}
|
||||
/>
|
||||
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary_large_image" />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
name="twitter:image"
|
||||
content={assigns[:og_image_url] || SEO.og_image_url()}
|
||||
/>
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
name="twitter:title"
|
||||
@@ -41,6 +58,14 @@
|
||||
name="twitter:description"
|
||||
content={assigns[:meta_description]}
|
||||
/>
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32" />
|
||||
<link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<meta name="theme-color" content="#17352d" />
|
||||
|
||||
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
|
||||
<link
|
||||
rel="preload"
|
||||
@@ -65,6 +90,9 @@
|
||||
>
|
||||
</script>
|
||||
<Layouts.theme_script />
|
||||
<script :if={assigns[:json_ld]} type="application/ld+json">
|
||||
<%= raw(assigns[:json_ld]) %>
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<a
|
||||
|
||||
@@ -65,7 +65,10 @@
|
||||
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
|
||||
|
||||
event.preventDefault();
|
||||
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]"));
|
||||
// Each breakpoint renders its own copy of the switch, so only the visible
|
||||
// group takes part in arrow-key navigation.
|
||||
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]"))
|
||||
.filter((button) => button.offsetParent !== null);
|
||||
const offset = event.key === "ArrowRight" ? 1 : -1;
|
||||
const index = (buttons.indexOf(button) + offset + buttons.length) % buttons.length;
|
||||
const next = buttons[index];
|
||||
|
||||
@@ -14,14 +14,14 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
attr :endgame, :any, required: true
|
||||
attr :fen, :string, default: nil
|
||||
attr :status, :atom, required: true
|
||||
attr :blocked_reason, :string, default: nil
|
||||
attr :blocked, :map, default: nil
|
||||
attr :best_move, :string, default: nil
|
||||
attr :plies, :list, required: true
|
||||
attr :line, :list, required: true
|
||||
attr :reviewing, :boolean, required: true
|
||||
attr :review_index, :integer, required: true
|
||||
attr :review_tablebase, :any, default: nil
|
||||
attr :review_blocked, :string, default: nil
|
||||
attr :review_blocked, :map, default: nil
|
||||
attr :awaiting_reply, :boolean, required: true
|
||||
attr :last_grade, :atom, default: nil
|
||||
attr :awaiting_best_line, :boolean, default: false
|
||||
@@ -169,7 +169,23 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
>
|
||||
<.icon name="hero-eye" /> Review
|
||||
</.button>
|
||||
<.button phx-click="reset" variant="primary">
|
||||
<.button
|
||||
:if={@status == :blocked && @blocked && @blocked.retry}
|
||||
id="retry-blocked"
|
||||
phx-click="reset"
|
||||
variant="primary"
|
||||
>
|
||||
<.icon name="hero-arrow-path" /> Retry
|
||||
</.button>
|
||||
<.button
|
||||
:if={@status == :blocked && @blocked && !@blocked.retry && @session}
|
||||
id="next-after-blocked"
|
||||
phx-click="next_puzzle"
|
||||
variant="primary"
|
||||
>
|
||||
Next puzzle
|
||||
</.button>
|
||||
<.button :if={@status != :blocked} phx-click="reset" variant="primary">
|
||||
<.icon name="hero-arrow-path" />
|
||||
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
|
||||
</.button>
|
||||
@@ -194,7 +210,7 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
<%= cond do %>
|
||||
<% @review_blocked -> %>
|
||||
<p class="text-muted">Best move unavailable here</p>
|
||||
<p class="text-muted">{@review_blocked}</p>
|
||||
<p class="text-muted">{@review_blocked.message}</p>
|
||||
<% @review_tablebase -> %>
|
||||
<p class="text-muted font-semibold mb-1">Best move:</p>
|
||||
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
|
||||
@@ -211,9 +227,9 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
<%= cond do %>
|
||||
<% @status == :loading -> %>
|
||||
<p class="text-muted">Loading tablebase…</p>
|
||||
<% @status == :blocked -> %>
|
||||
<p class="font-semibold text-error-text">Tablebase unavailable</p>
|
||||
<p class="text-error-text">{@blocked_reason}</p>
|
||||
<% @status == :blocked && @blocked -> %>
|
||||
<p class="font-semibold text-error-text">{@blocked.title}</p>
|
||||
<p class="text-error-text">{@blocked.message}</p>
|
||||
<% @status == :solved -> %>
|
||||
<p class="font-semibold text-success-text">
|
||||
{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"}
|
||||
@@ -421,8 +437,7 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
|> Enum.with_index(1)
|
||||
end
|
||||
|
||||
defp display_plies(true, line, _plies), do: line
|
||||
defp display_plies(false, _line, plies), do: plies
|
||||
defp display_plies(reviewing, line, plies), do: if(reviewing, do: line, else: plies)
|
||||
|
||||
defp colour_name(:white), do: "White"
|
||||
defp colour_name(:black), do: "Black"
|
||||
@@ -460,8 +475,7 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
|
||||
defp move_hint(:loading, _awaiting), do: "Loading the tablebase…"
|
||||
|
||||
defp move_hint(:blocked, _awaiting),
|
||||
do: "The tablebase is unavailable, so moves cannot be entered."
|
||||
defp move_hint(:blocked, _awaiting), do: "Moves are paused."
|
||||
|
||||
defp move_hint(status, _awaiting) when status in [:solved, :failed],
|
||||
do: "This puzzle is finished. Reset or try again."
|
||||
@@ -488,7 +502,10 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
"Loading the tablebase."
|
||||
|
||||
assigns.status == :blocked ->
|
||||
"Tablebase unavailable. #{assigns.blocked_reason || "Moves cannot be graded."}"
|
||||
case assigns.blocked do
|
||||
%{title: title, message: message} -> "#{title}. #{message}"
|
||||
_ -> "Tablebase unavailable."
|
||||
end
|
||||
|
||||
assigns.reviewing ->
|
||||
review_announcement(assigns)
|
||||
|
||||
@@ -3,8 +3,12 @@ defmodule ChesstrainerWeb.ThemePicker do
|
||||
Search-and-select control shared by the endgame form and bulk importer.
|
||||
|
||||
The parent LiveView owns the assignments and handles the events:
|
||||
`search_themes`, `add_theme`, `create_theme`, `create_theme_from_search` and
|
||||
`remove_theme`.
|
||||
`search_themes`, `add_theme`, `create_theme` and `remove_theme`.
|
||||
|
||||
The control renders no `<form>` of its own. It is embedded in the endgame
|
||||
form, where a nested form would be dropped by the HTML parser and take its
|
||||
bindings with it, and it is used standalone on the bulk importer. Binding
|
||||
`phx-change` on the search input keeps both call sites working.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :html
|
||||
@@ -35,10 +39,11 @@ defmodule ChesstrainerWeb.ThemePicker do
|
||||
</.badge>
|
||||
</div>
|
||||
|
||||
<form id="theme-form" phx-change="search_themes" phx-submit="create_theme_from_search">
|
||||
<div id="theme-picker">
|
||||
<.input
|
||||
name="theme_search"
|
||||
value={@theme_query}
|
||||
phx-change="search_themes"
|
||||
phx-debounce="200"
|
||||
autocomplete="off"
|
||||
placeholder="Search or create a theme…"
|
||||
@@ -67,7 +72,7 @@ defmodule ChesstrainerWeb.ThemePicker do
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@@ -6,6 +6,14 @@
|
||||
<meta name="robots" content="noindex" />
|
||||
<title>{Branding.title("Page not found")}</title>
|
||||
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32" />
|
||||
<link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<meta name="theme-color" content="#17352d" />
|
||||
|
||||
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
|
||||
<link
|
||||
rel="preload"
|
||||
|
||||
@@ -6,6 +6,14 @@
|
||||
<meta name="robots" content="noindex" />
|
||||
<title>{Branding.title("Something went wrong")}</title>
|
||||
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32" />
|
||||
<link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<meta name="theme-color" content="#17352d" />
|
||||
|
||||
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
|
||||
<link
|
||||
rel="preload"
|
||||
|
||||
@@ -10,7 +10,7 @@ defmodule ChesstrainerWeb.HealthController do
|
||||
status = if health.status == "down", do: :service_unavailable, else: :ok
|
||||
|
||||
conn
|
||||
|> put_resp_header("x-robots-tag", "noindex")
|
||||
|> put_resp_header("x-robots-tag", "noindex, nofollow")
|
||||
|> put_status(status)
|
||||
|> json(health)
|
||||
end
|
||||
|
||||
@@ -6,6 +6,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.DailyPuzzles
|
||||
alias Chesstrainer.Endgames
|
||||
alias ChesstrainerWeb.SEO
|
||||
|
||||
@description "Short, focused endgame puzzles against tablebase-perfect defence. " <>
|
||||
"Learn to see the winning move and make the endgame your strongest phase."
|
||||
@@ -15,13 +16,15 @@ defmodule ChesstrainerWeb.PageController do
|
||||
render_coming_soon(conn)
|
||||
else
|
||||
endgames = Endgames.curated_endgames()
|
||||
canonical_url = SEO.canonical_url(conn)
|
||||
|
||||
conn
|
||||
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|
||||
|> assign(:page_title, Branding.home_title())
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, @description)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, canonical_url)
|
||||
|> assign(:json_ld, SEO.json_ld(canonical_url))
|
||||
|> assign(:mailing_list_enabled, mailing_list_enabled?())
|
||||
|> render(:home,
|
||||
endgames: endgames,
|
||||
@@ -43,7 +46,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
:meta_description,
|
||||
"How #{Branding.name()} collects, uses, and protects your personal data."
|
||||
)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> render(:privacy)
|
||||
end
|
||||
|
||||
@@ -53,7 +56,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
|> 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))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> render(:terms_conditions)
|
||||
end
|
||||
|
||||
@@ -66,7 +69,8 @@ defmodule ChesstrainerWeb.PageController do
|
||||
:meta_description,
|
||||
"Éditeur, hébergeur et informations légales de #{Branding.name()}."
|
||||
)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> assign(:lang, "fr")
|
||||
|> render(:mentions_legales)
|
||||
end
|
||||
|
||||
@@ -86,7 +90,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
|> assign(:page_title, Branding.home_title())
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, @description)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> assign(:noindex, true)
|
||||
|> assign(:mailing_list_enabled, mailing_list_enabled?())
|
||||
|> render(:coming_soon)
|
||||
|
||||
@@ -8,6 +8,6 @@ defmodule ChesstrainerWeb.PageHTML do
|
||||
|
||||
embed_templates "page_html/*"
|
||||
|
||||
defp play_path(nil), do: ~p"/endgames"
|
||||
defp play_path(nil), do: ~p"/guest-train"
|
||||
defp play_path(%{public_code: public_code}), do: ~p"/endgames/#{public_code}/play"
|
||||
end
|
||||
|
||||
@@ -12,9 +12,15 @@
|
||||
Train your intuition to find the winning moves under pressure. Puzzle sessions focused purely on technical execution.
|
||||
</p>
|
||||
<div class="hero-actions">
|
||||
<.pill_button variant={:primary} navigate={play_path(@active_endgame)}>
|
||||
Try today's puzzle <.icon_arrow />
|
||||
</.pill_button>
|
||||
<%= if @active_endgame do %>
|
||||
<.pill_button variant={:primary} navigate={play_path(@active_endgame)}>
|
||||
Try today's puzzle <.icon_arrow />
|
||||
</.pill_button>
|
||||
<% else %>
|
||||
<.pill_button variant={:primary} navigate={play_path(nil)}>
|
||||
Start training <.icon_arrow />
|
||||
</.pill_button>
|
||||
<% end %>
|
||||
<div class="rating-note">
|
||||
<span class="avatar-stack">
|
||||
<i>♟</i>
|
||||
@@ -34,8 +40,11 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<%!-- <section class="learning-strip" id="method">
|
||||
<p>Built for the part of chess that decides everything.</p>
|
||||
<section class="learning-strip" id="method">
|
||||
<figure class="learning-quote">
|
||||
<blockquote>“The hardest game to win is a won game.”</blockquote>
|
||||
<figcaption>— Emmanuel Lasker</figcaption>
|
||||
</figure>
|
||||
<div class="stat">
|
||||
<strong>{count_label(@puzzle_count)}</strong>
|
||||
<span>puzzles</span>
|
||||
@@ -44,9 +53,9 @@
|
||||
<strong>{@user_count}</strong>
|
||||
<span>Players improving their endgame</span>
|
||||
</div>
|
||||
</section> --%>
|
||||
</section>
|
||||
|
||||
<%!-- <section class="puzzle-section" id="puzzles">
|
||||
<section class="puzzle-section" id="puzzles">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<span class="section-kicker">Choose your lesson</span>
|
||||
@@ -59,16 +68,16 @@
|
||||
that you’ll recognise over the board.
|
||||
</p>
|
||||
</div>
|
||||
<div class="puzzle-grid">
|
||||
<%= for {endgame, index} <- Enum.with_index(@endgames) do %>
|
||||
<.puzzle_card
|
||||
endgame={endgame}
|
||||
index={index}
|
||||
active={@active_endgame && endgame.id == @active_endgame.id}
|
||||
/>
|
||||
<% end %>
|
||||
<div class="puzzle-coming-soon">
|
||||
<div class="eyebrow">
|
||||
<.icon_spark /> Coming soon
|
||||
</div>
|
||||
<strong>The lesson library is on its way.</strong>
|
||||
<p>
|
||||
A growing set of positions, each teaching one idea. Today’s puzzle is already live.
|
||||
</p>
|
||||
</div>
|
||||
</section> --%>
|
||||
</section>
|
||||
|
||||
<.mailing_list_signup :if={@mailing_list_enabled} />
|
||||
|
||||
|
||||
@@ -6,12 +6,16 @@ defmodule ChesstrainerWeb.SitemapController do
|
||||
them and they render the same interactive surface with only the position
|
||||
differing, so listing them all would be index bloat. Revisit that if public
|
||||
browse pages (by Key or theme) exist and are worth ranking.
|
||||
|
||||
No `<lastmod>` is emitted: none of these pages has a stored modification time,
|
||||
and an invented date (such as "today" on every request) teaches crawlers to
|
||||
distrust the sitemap.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
def index(conn, _params) do
|
||||
urls = [
|
||||
entries = [
|
||||
url(conn, ~p"/"),
|
||||
url(conn, ~p"/privacy"),
|
||||
url(conn, ~p"/terms-conditions"),
|
||||
@@ -20,16 +24,19 @@ defmodule ChesstrainerWeb.SitemapController do
|
||||
|
||||
conn
|
||||
|> put_resp_content_type("application/xml")
|
||||
|> send_resp(200, render_sitemap(urls))
|
||||
|> send_resp(200, render_sitemap(entries))
|
||||
end
|
||||
|
||||
defp render_sitemap(urls) do
|
||||
entries = Enum.map_join(urls, &" <url><loc>#{escape(&1)}</loc></url>\n")
|
||||
defp render_sitemap(entries) do
|
||||
urls =
|
||||
Enum.map_join(entries, fn loc ->
|
||||
" <url><loc>#{escape(loc)}</loc></url>\n"
|
||||
end)
|
||||
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
#{entries}</urlset>
|
||||
#{urls}</urlset>
|
||||
"""
|
||||
end
|
||||
|
||||
|
||||
@@ -15,8 +15,11 @@ defmodule ChesstrainerWeb.UserConfirmationController do
|
||||
|
||||
:error ->
|
||||
conn
|
||||
|> put_flash(:error, "User not found or token is invalid.")
|
||||
|> redirect(to: ~p"/users/register")
|
||||
|> put_flash(
|
||||
:error,
|
||||
"That confirmation link is invalid or has expired. Log in to request a new one."
|
||||
)
|
||||
|> redirect(to: ~p"/users/log-in")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
defmodule ChesstrainerWeb.UserDataController do
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
require Logger
|
||||
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.Branding
|
||||
|
||||
@user_columns ~w(user_username user_email user_rating user_rating_deviation user_plan user_joined_at)
|
||||
@attempt_columns ~w(played_at puzzle public_code color result outcome rated_at)
|
||||
@@ -9,16 +12,41 @@ defmodule ChesstrainerWeb.UserDataController do
|
||||
|
||||
def export(conn, %{"format" => format}) when format in ["csv", "json"] do
|
||||
user = conn.assigns.current_scope.user
|
||||
attempts = Attempts.list_attempts_for_user(user.id)
|
||||
filename = "lucid-chess-data-#{Date.utc_today()}.#{format}"
|
||||
|
||||
conn
|
||||
|> put_resp_content_type(content_type(format))
|
||||
|> put_resp_header("content-disposition", ~s(attachment; filename="#{filename}"))
|
||||
|> send_resp(200, body(format, user, attempts))
|
||||
try do
|
||||
attempts = Attempts.list_attempts_for_user(user.id)
|
||||
filename = "lucid-chess-data-#{Date.utc_today()}.#{format}"
|
||||
|
||||
conn
|
||||
|> put_resp_content_type(content_type(format))
|
||||
|> put_resp_header("content-disposition", ~s(attachment; filename="#{filename}"))
|
||||
|> send_resp(200, body(format, user, attempts))
|
||||
rescue
|
||||
exception ->
|
||||
export_failed(conn, Exception.message(exception))
|
||||
catch
|
||||
:exit, reason ->
|
||||
export_failed(conn, inspect(reason))
|
||||
end
|
||||
end
|
||||
|
||||
def export(conn, _params), do: send_resp(conn, 404, "Unknown export format")
|
||||
def export(conn, _params) do
|
||||
conn
|
||||
|> put_status(:not_found)
|
||||
|> put_view(ChesstrainerWeb.ErrorHTML)
|
||||
|> render("404.html")
|
||||
end
|
||||
|
||||
defp export_failed(conn, reason) do
|
||||
Logger.error("profile.export_failed", reason: reason)
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:error,
|
||||
"We couldn't build your export. Try again; if it keeps failing, email #{Branding.support_email()}."
|
||||
)
|
||||
|> redirect(to: ~p"/users/profile/data")
|
||||
end
|
||||
|
||||
defp body("csv", user, attempts), do: to_csv(user, attempts)
|
||||
|
||||
|
||||
@@ -12,14 +12,6 @@ defmodule ChesstrainerWeb.UserSessionController do
|
||||
authenticate(conn, user_params, ~p"/users/log-in", nil)
|
||||
end
|
||||
|
||||
def create_admin(conn, %{"user" => user_params}) do
|
||||
if ChesstrainerWeb.prelaunch?() do
|
||||
authenticate(conn, user_params, ~p"/admin/log-in", ~p"/admin/endgames")
|
||||
else
|
||||
authenticate(conn, user_params, ~p"/users/log-in", nil)
|
||||
end
|
||||
end
|
||||
|
||||
defp authenticate(conn, user_params, failure_path, success_path) do
|
||||
%{"email" => login} = user_params
|
||||
address = ClientAddress.from_conn(conn)
|
||||
|
||||
@@ -19,12 +19,18 @@ defmodule ChesstrainerWeb.Endpoint do
|
||||
#
|
||||
# When code reloading is disabled (e.g., in production),
|
||||
# the `gzip` option is enabled to serve compressed
|
||||
# static files generated by running `phx.digest`.
|
||||
# static files generated by running `phx.digest`, and the cache headers promise
|
||||
# a year. Build output is digested, and the stable-name assets (fonts, piece
|
||||
# art, icons) only change when the file is renamed, so a long max-age is safe
|
||||
# and keeps browsers and the CDN off the origin. Dev keeps plain `public` so
|
||||
# edits show up immediately.
|
||||
plug Plug.Static,
|
||||
at: "/",
|
||||
from: :chesstrainer,
|
||||
gzip: not code_reloading?,
|
||||
only: ChesstrainerWeb.static_paths(),
|
||||
cache_control_for_etags:
|
||||
if(code_reloading?, do: "public", else: "public, max-age=31536000, immutable"),
|
||||
raise_on_missing_only: code_reloading?
|
||||
|
||||
# Code reloading can be explicitly enabled under the
|
||||
|
||||
@@ -11,6 +11,12 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||
{"Tactic", "tactic"}
|
||||
]
|
||||
|
||||
@kind_options [
|
||||
{"Technique", "technique"},
|
||||
{"Motif", "motif"},
|
||||
{"Material", "material"}
|
||||
]
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
@@ -21,18 +27,31 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||
{@page_title}
|
||||
<:subtitle>
|
||||
Themes group endgames for filtering. Names must be unique within a category,
|
||||
ignoring case.
|
||||
ignoring case. The slug is generated from the name and stays fixed afterwards,
|
||||
so links to a theme keep working when it is renamed.
|
||||
</:subtitle>
|
||||
</.header>
|
||||
|
||||
<.form for={@form} id="theme-form" phx-change="validate" phx-submit="save">
|
||||
<.input field={@form[:name]} type="text" label="Name" autocomplete="off" required />
|
||||
<.input
|
||||
field={@form[:kind]}
|
||||
type="select"
|
||||
label="Kind"
|
||||
options={@kind_options}
|
||||
/>
|
||||
<.input
|
||||
field={@form[:category]}
|
||||
type="select"
|
||||
label="Category"
|
||||
options={@category_options}
|
||||
/>
|
||||
<.input
|
||||
field={@form[:description]}
|
||||
type="textarea"
|
||||
label="Description"
|
||||
rows="3"
|
||||
/>
|
||||
|
||||
<footer>
|
||||
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
|
||||
@@ -54,6 +73,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||
socket
|
||||
|> assign(:page_title, "New theme")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:kind_options, @kind_options)
|
||||
|> assign(:category_options, @category_options)
|
||||
|> assign(:form, to_form(Themes.change_theme(theme)))
|
||||
end
|
||||
@@ -64,6 +84,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||
socket
|
||||
|> assign(:page_title, "Edit theme")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:kind_options, @kind_options)
|
||||
|> assign(:category_options, @category_options)
|
||||
|> assign(:form, to_form(Themes.change_theme(theme)))
|
||||
end
|
||||
@@ -87,13 +108,16 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||
end
|
||||
|
||||
defp save_theme(socket, :new, theme_params) do
|
||||
case Themes.create_theme(theme_params) do
|
||||
case Themes.create_theme(socket.assigns.current_scope, theme_params) do
|
||||
{:ok, _theme} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Theme created successfully.")
|
||||
|> push_navigate(to: ~p"/admin/themes")}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||
end
|
||||
|
||||
@@ -2,6 +2,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@category_options [
|
||||
@@ -20,7 +21,8 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
|
||||
<.header>
|
||||
Themes
|
||||
<:subtitle>
|
||||
Themes group endgames for filtering and puzzle selection. Deleting a theme detaches
|
||||
Themes group endgames for filtering and puzzle selection. Coverage shows how
|
||||
many endgames carry a theme out of the whole library. Deleting a theme detaches
|
||||
it from every endgame and leaves the endgames intact.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
@@ -69,26 +71,36 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kind</th>
|
||||
<th>Category</th>
|
||||
<th>Used by</th>
|
||||
<th>Coverage</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="themes">
|
||||
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
|
||||
<td>{theme.name}</td>
|
||||
<td>{theme.kind}</td>
|
||||
<td>{theme.category}</td>
|
||||
<td>
|
||||
<span id={"theme-usage-#{theme.id}"}>{usage_label(usage_count)}</span>
|
||||
<span id={"theme-usage-#{theme.id}"}>
|
||||
{coverage_label(usage_count, @total_endgames)}
|
||||
</span>
|
||||
</td>
|
||||
<td class="w-0 font-semibold">
|
||||
<div class="flex gap-4">
|
||||
<.link
|
||||
:if={theme.category == :endgame and theme.kind == :technique}
|
||||
navigate={~p"/admin/themes/#{theme.id}/tag"}
|
||||
>
|
||||
Tag
|
||||
</.link>
|
||||
<.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit</.link>
|
||||
<.link
|
||||
phx-click="delete"
|
||||
phx-value-id={theme.id}
|
||||
data-confirm={
|
||||
"Delete #{theme.name}? Used by #{usage_label(usage_count)}. " <>
|
||||
"Delete #{theme.name}? Used by #{coverage_label(usage_count, @total_endgames)}. " <>
|
||||
"The endgames will be kept and simply detached."
|
||||
}
|
||||
>
|
||||
@@ -152,9 +164,10 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
|
||||
category: socket.assigns.category
|
||||
)
|
||||
|
||||
assign(socket, :themes, themes)
|
||||
assign(socket, themes: themes, total_endgames: Endgames.count_endgames())
|
||||
end
|
||||
|
||||
defp usage_label(1), do: "1 endgame"
|
||||
defp usage_label(count), do: "#{count} endgames"
|
||||
defp coverage_label(count, total) do
|
||||
"#{count} of #{total} #{if total == 1, do: "endgame", else: "endgames"}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
defmodule ChesstrainerWeb.Admin.ThemeLive.Tag do
|
||||
@moduledoc """
|
||||
Workspace for applying a technique theme to endgames by family.
|
||||
|
||||
Candidates are grouped by Key so an admin tags a whole family rather than
|
||||
individual rows. Boards are previews only; nothing here starts a puzzle.
|
||||
Only technique themes can be tagged, because material themes are derived and
|
||||
a hand-made link would be erased by the next refresh.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Game
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
import ChesstrainerWeb.Board.BoardComponent
|
||||
|
||||
@page_size 24
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Tag “{@theme.name}”
|
||||
<:subtitle>
|
||||
Pick a family, preview the positions and apply the theme in bulk. The links are
|
||||
recorded as curated, so derivation never overwrites them.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button navigate={~p"/admin/themes"}>
|
||||
<.icon name="hero-arrow-left" /> All themes
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<.form
|
||||
for={@theme_form}
|
||||
id="theme-workspace-form"
|
||||
phx-change="select_theme"
|
||||
class="mb-6 max-w-md"
|
||||
>
|
||||
<.input
|
||||
field={@theme_form[:theme_id]}
|
||||
type="select"
|
||||
label="Technique theme"
|
||||
options={@theme_options}
|
||||
/>
|
||||
</.form>
|
||||
|
||||
<div class="mb-6 flex flex-wrap gap-6 text-sm">
|
||||
<span>
|
||||
<span class="font-semibold" id="tagged-count">{@tagged_count}</span> tagged
|
||||
</span>
|
||||
<span>
|
||||
<span class="font-semibold" id="candidate-count">{@candidate_count}</span> candidates
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
:if={MapSet.size(@selected) > 0}
|
||||
id="selection-bar"
|
||||
class="sticky top-0 z-10 mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-primary/30 bg-base-100 p-3 text-sm"
|
||||
>
|
||||
<span class="font-semibold">{MapSet.size(@selected)} selected</span>
|
||||
<button
|
||||
type="button"
|
||||
id="apply-theme"
|
||||
phx-click="apply"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
Apply “{@theme.name}”
|
||||
</button>
|
||||
<button type="button" phx-click="clear_selection" class="text-base-content/70">
|
||||
Clear selection
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section class="mb-12">
|
||||
<h2 class="mb-3 text-lg font-semibold">Candidates</h2>
|
||||
<p :if={@candidate_groups == []} class="text-base-content/70">
|
||||
Every endgame already carries this theme.
|
||||
</p>
|
||||
|
||||
<table :if={@candidate_groups != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Endgames</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={{key, count} <- @candidate_groups} id={"candidates-#{group_id(key)}"}>
|
||||
<td class="font-mono">{key}</td>
|
||||
<td>{count}</td>
|
||||
<td class="w-0">
|
||||
<button
|
||||
type="button"
|
||||
id={"toggle-candidates-#{group_id(key)}"}
|
||||
phx-click="toggle_group"
|
||||
phx-value-key={key}
|
||||
phx-value-view="candidates"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
{open_label(@open, key, "candidates")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<.group_panel
|
||||
:if={@open && @open.view == "candidates"}
|
||||
view="candidates"
|
||||
group={@open.key}
|
||||
items={@items}
|
||||
selected={@selected}
|
||||
page={@page}
|
||||
pages={@pages}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="mb-3 text-lg font-semibold">Curated links</h2>
|
||||
<p :if={@tagged_groups == []} class="text-base-content/70">
|
||||
No endgame carries this theme yet.
|
||||
</p>
|
||||
|
||||
<table :if={@tagged_groups != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Endgames</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={{key, count} <- @tagged_groups} id={"tagged-#{group_id(key)}"}>
|
||||
<td class="font-mono">{key}</td>
|
||||
<td>{count}</td>
|
||||
<td class="w-0">
|
||||
<button
|
||||
type="button"
|
||||
id={"toggle-tagged-#{group_id(key)}"}
|
||||
phx-click="toggle_group"
|
||||
phx-value-key={key}
|
||||
phx-value-view="tagged"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
{open_label(@open, key, "tagged")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<.group_panel
|
||||
:if={@open && @open.view == "tagged"}
|
||||
view="tagged"
|
||||
group={@open.key}
|
||||
items={@items}
|
||||
selected={@selected}
|
||||
page={@page}
|
||||
pages={@pages}
|
||||
/>
|
||||
</section>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
attr :view, :string, required: true
|
||||
attr :group, :string, required: true
|
||||
attr :items, :list, required: true
|
||||
attr :selected, :any, required: true
|
||||
attr :page, :integer, required: true
|
||||
attr :pages, :integer, required: true
|
||||
|
||||
defp group_panel(assigns) do
|
||||
~H"""
|
||||
<div id="group-panel" class="mt-4">
|
||||
<div :if={@view == "candidates"} class="mb-3 flex gap-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
id="select-page"
|
||||
phx-click="select_page"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
Select this page
|
||||
</button>
|
||||
<span class="text-base-content/60">{@group}</span>
|
||||
</div>
|
||||
|
||||
<p :if={@items == []} class="text-base-content/70">No endgames on this page.</p>
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<div
|
||||
:for={endgame <- @items}
|
||||
id={"endgame-#{endgame.id}"}
|
||||
class="rounded-lg border border-base-300 p-3"
|
||||
>
|
||||
<.board
|
||||
game={endgame.game}
|
||||
myself={nil}
|
||||
interactive={false}
|
||||
class="mb-2 w-full max-w-[240px]"
|
||||
/>
|
||||
<p class="break-all font-mono text-xs text-base-content/60">{endgame.fen}</p>
|
||||
|
||||
<label :if={@view == "candidates"} class="mt-2 flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={"select-#{endgame.id}"}
|
||||
checked={MapSet.member?(@selected, endgame.id)}
|
||||
phx-click="toggle_select"
|
||||
phx-value-id={endgame.id}
|
||||
/> Select
|
||||
</label>
|
||||
|
||||
<button
|
||||
:if={@view == "tagged"}
|
||||
type="button"
|
||||
id={"remove-#{endgame.id}"}
|
||||
phx-click="remove"
|
||||
phx-value-id={endgame.id}
|
||||
class="mt-2 text-sm font-semibold text-error"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div :if={@pages > 1} class="mt-4 flex items-center gap-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
phx-click="page"
|
||||
phx-value-page={@page - 1}
|
||||
disabled={@page <= 1}
|
||||
class="font-semibold disabled:opacity-40"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<span>Page {@page} of {@pages}</span>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="page"
|
||||
phx-value-page={@page + 1}
|
||||
disabled={@page >= @pages}
|
||||
class="font-semibold disabled:opacity-40"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(%{"id" => id}, _session, socket) do
|
||||
theme = Themes.get_theme!(id)
|
||||
|
||||
if theme.category == :endgame and theme.kind == :technique do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Tag #{theme.name}")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:selected, MapSet.new())
|
||||
|> assign(:open, nil)
|
||||
|> assign(:items, [])
|
||||
|> assign(:page, 1)
|
||||
|> assign(:pages, 1)
|
||||
|> assign_theme_options()
|
||||
|> load_counts()}
|
||||
else
|
||||
{:ok,
|
||||
socket
|
||||
|> put_flash(
|
||||
:error,
|
||||
"Only technique themes can be tagged by hand; material themes are derived."
|
||||
)
|
||||
|> push_navigate(to: ~p"/admin/themes")}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("select_theme", %{"theme_id" => id}, socket) do
|
||||
if to_string(socket.assigns.theme.id) == id do
|
||||
{:noreply, socket}
|
||||
else
|
||||
{:noreply, push_navigate(socket, to: ~p"/admin/themes/#{id}/tag")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_group", %{"key" => key, "view" => view}, socket) do
|
||||
case socket.assigns.open do
|
||||
%{key: ^key, view: ^view} ->
|
||||
{:noreply, assign(socket, open: nil, items: [], page: 1, pages: 1)}
|
||||
|
||||
_ ->
|
||||
{:noreply, open_group(socket, key, view, 1)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("page", %{"page" => page}, socket) do
|
||||
case socket.assigns.open do
|
||||
nil ->
|
||||
{:noreply, socket}
|
||||
|
||||
%{key: key, view: view} ->
|
||||
{:noreply, open_group(socket, key, view, parse_page(page))}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_select", %{"id" => id}, socket) do
|
||||
selected =
|
||||
if MapSet.member?(socket.assigns.selected, id) do
|
||||
MapSet.delete(socket.assigns.selected, id)
|
||||
else
|
||||
MapSet.put(socket.assigns.selected, id)
|
||||
end
|
||||
|
||||
{:noreply, assign(socket, :selected, selected)}
|
||||
end
|
||||
|
||||
def handle_event("select_page", _params, socket) do
|
||||
page_ids = Enum.map(socket.assigns.items, & &1.id)
|
||||
selected = Enum.reduce(page_ids, socket.assigns.selected, &MapSet.put(&2, &1))
|
||||
{:noreply, assign(socket, :selected, selected)}
|
||||
end
|
||||
|
||||
def handle_event("clear_selection", _params, socket) do
|
||||
{:noreply, assign(socket, :selected, MapSet.new())}
|
||||
end
|
||||
|
||||
def handle_event("apply", _params, socket) do
|
||||
selected = MapSet.to_list(socket.assigns.selected)
|
||||
|
||||
if selected == [] do
|
||||
{:noreply, put_flash(socket, :error, "Select at least one endgame.")}
|
||||
else
|
||||
{:ok, count} = Themes.tag_endgames(socket.assigns.theme, selected, :curated)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Tagged #{count} endgame(s) with “#{socket.assigns.theme.name}”.")
|
||||
|> assign(:selected, MapSet.new())
|
||||
|> assign(open: nil, items: [], page: 1, pages: 1)
|
||||
|> load_counts()}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("remove", %{"id" => id}, socket) do
|
||||
{:ok, removed} = Themes.untag_endgame(socket.assigns.theme, id, :curated)
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> put_flash(:info, removal_message(removed, socket.assigns.theme))
|
||||
|> load_counts()
|
||||
|> refresh_open()
|
||||
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
defp removal_message(0, theme), do: "That endgame had no curated “#{theme.name}” link."
|
||||
defp removal_message(_, theme), do: "Removed “#{theme.name}” from the endgame."
|
||||
|
||||
defp refresh_open(%{assigns: %{open: nil}} = socket), do: socket
|
||||
|
||||
defp refresh_open(%{assigns: %{open: %{key: key, view: view}, page: page}} = socket) do
|
||||
open_group(socket, key, view, page)
|
||||
end
|
||||
|
||||
defp open_group(socket, key, view, page) do
|
||||
count = group_count(socket, key, view)
|
||||
pages = max(ceil_div(count, @page_size), 1)
|
||||
page = page |> max(1) |> min(pages)
|
||||
|
||||
endgames =
|
||||
Endgames.list_endgames_for_key(key, filters_for(socket.assigns.theme, view),
|
||||
limit: @page_size,
|
||||
offset: (page - 1) * @page_size
|
||||
)
|
||||
|> Enum.map(&Map.put(&1, :game, board_game(&1.fen)))
|
||||
|
||||
assign(socket,
|
||||
open: %{key: key, view: view},
|
||||
items: endgames,
|
||||
page: page,
|
||||
pages: pages
|
||||
)
|
||||
end
|
||||
|
||||
defp filters_for(%{id: theme_id}, "tagged"), do: %{with_theme: {theme_id, :curated}}
|
||||
defp filters_for(%{id: theme_id}, "candidates"), do: %{without_theme: theme_id}
|
||||
|
||||
defp group_count(socket, key, view) do
|
||||
groups =
|
||||
if view == "tagged", do: socket.assigns.tagged_groups, else: socket.assigns.candidate_groups
|
||||
|
||||
Enum.find_value(groups, 0, fn
|
||||
{^key, count} -> count
|
||||
_ -> nil
|
||||
end)
|
||||
end
|
||||
|
||||
defp parse_page(page) when is_integer(page), do: page
|
||||
|
||||
defp parse_page(page) when is_binary(page) do
|
||||
case Integer.parse(page) do
|
||||
{value, _} -> value
|
||||
:error -> 1
|
||||
end
|
||||
end
|
||||
|
||||
defp ceil_div(0, _), do: 0
|
||||
defp ceil_div(count, size), do: div(count + size - 1, size)
|
||||
|
||||
defp load_counts(socket) do
|
||||
theme = socket.assigns.theme
|
||||
tagged = Endgames.list_key_groups(%{with_theme: {theme.id, :curated}})
|
||||
candidates = Endgames.list_key_groups(%{without_theme: theme.id})
|
||||
|
||||
assign(socket,
|
||||
tagged_groups: tagged,
|
||||
candidate_groups: candidates,
|
||||
tagged_count: total(tagged),
|
||||
candidate_count: total(candidates)
|
||||
)
|
||||
end
|
||||
|
||||
defp total(groups), do: Enum.reduce(groups, 0, fn {_key, count}, acc -> acc + count end)
|
||||
|
||||
defp assign_theme_options(socket) do
|
||||
options =
|
||||
Themes.list_themes()
|
||||
|> Enum.filter(&(&1.category == :endgame and &1.kind == :technique))
|
||||
|> Enum.sort_by(& &1.name)
|
||||
|> Enum.map(&{&1.name, &1.id})
|
||||
|
||||
assign(socket,
|
||||
theme_options: options,
|
||||
theme_form: to_form(%{"theme_id" => to_string(socket.assigns.theme.id)})
|
||||
)
|
||||
end
|
||||
|
||||
defp board_game(fen) do
|
||||
case Game.game_from_fen(fen, :endgame) do
|
||||
{:ok, game} -> game
|
||||
{:error, :invalid_fen, game} -> game
|
||||
end
|
||||
end
|
||||
|
||||
defp open_label(%{key: key, view: view}, key, view), do: "Hide"
|
||||
defp open_label(_open, _key, _view), do: "Show"
|
||||
|
||||
defp group_id(key), do: String.replace(key, ~r/[^A-Za-z0-9]+/, "-")
|
||||
end
|
||||
@@ -21,13 +21,6 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
<:subtitle>Use this form to manage endgame records in your database.</:subtitle>
|
||||
</.header>
|
||||
|
||||
<.theme_picker
|
||||
selected_themes={@selected_themes}
|
||||
theme_query={@theme_query}
|
||||
theme_results={@theme_results}
|
||||
can_create={@can_create}
|
||||
/>
|
||||
|
||||
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
|
||||
<div class="flex flex-col gap-6 sm:flex-row sm:items-start">
|
||||
<div class="min-w-0 flex-1">
|
||||
@@ -40,6 +33,13 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
label="Rating"
|
||||
/>
|
||||
|
||||
<.theme_picker
|
||||
selected_themes={@selected_themes}
|
||||
theme_query={@theme_query}
|
||||
theme_results={@theme_results}
|
||||
can_create={@can_create}
|
||||
/>
|
||||
|
||||
<.input field={@form[:message]} type="textarea" label="Message" />
|
||||
<.input field={@form[:notes]} type="textarea" label="Notes" />
|
||||
<.input
|
||||
@@ -122,10 +122,6 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
{:noreply, create_theme(socket, name)}
|
||||
end
|
||||
|
||||
def handle_event("create_theme_from_search", %{"theme_search" => name}, socket) do
|
||||
{:noreply, create_theme(socket, name)}
|
||||
end
|
||||
|
||||
def handle_event("remove_theme", %{"id" => id}, socket) do
|
||||
selected = Enum.reject(socket.assigns.selected_themes, &(Integer.to_string(&1.id) == id))
|
||||
{:noreply, assign(socket, :selected_themes, selected)}
|
||||
|
||||
@@ -70,12 +70,12 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
</section>
|
||||
|
||||
<PlayComponents.play_surface
|
||||
:if={@endgame}
|
||||
:if={@endgame && @empty != :exhausted}
|
||||
session={is_nil(@limit_reached)}
|
||||
endgame={@endgame}
|
||||
fen={@fen}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
blocked={@blocked}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
@@ -94,19 +94,51 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
|
||||
<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"
|
||||
<section
|
||||
:if={@empty == :exhausted}
|
||||
id="guest-pool-exhausted"
|
||||
class="rounded-xl border border-hairline bg-canvas-raised p-6"
|
||||
>
|
||||
No endgames are available yet. Please check back soon.
|
||||
</p>
|
||||
<h2 class="text-lg font-semibold">No more puzzles are available right now</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Try again in a moment, or create a free account to train at your level.
|
||||
</p>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
|
||||
<.icon name="hero-arrow-path" /> Retry
|
||||
</.button>
|
||||
<.button navigate={~p"/users/register"}>Sign up free</.button>
|
||||
<.button navigate={~p"/users/log-in"}>Log in</.button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
|
||||
id="guest-pool-empty"
|
||||
class="rounded-xl border border-hairline bg-canvas-raised p-6"
|
||||
>
|
||||
<h2 class="text-lg font-semibold">No endgames are available yet</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Please check back soon, or create a free account to be ready when they land.
|
||||
</p>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
|
||||
<.icon name="hero-arrow-path" /> Retry
|
||||
</.button>
|
||||
<.button navigate={~p"/users/register"}>Sign up free</.button>
|
||||
<.button navigate={~p"/users/log-in"}>Log in</.button>
|
||||
</div>
|
||||
</section>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
socket = assign(socket, :limit, GuestLimits.limit())
|
||||
socket =
|
||||
socket
|
||||
|> assign(:limit, GuestLimits.limit())
|
||||
|> assign(:served_ids, [])
|
||||
|
||||
cond do
|
||||
signed_in?(socket) ->
|
||||
@@ -120,6 +152,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
socket
|
||||
|> assign(:loading, true)
|
||||
|> assign(:endgame, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, nil)
|
||||
|> assign(:guest_address, nil)}
|
||||
@@ -127,29 +160,14 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
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()
|
||||
def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
|
||||
|
||||
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)}
|
||||
def handle_event("retry_pool", _params, socket) do
|
||||
if socket.assigns.empty == :exhausted do
|
||||
{:noreply, next_puzzle(socket)}
|
||||
else
|
||||
{:ok, socket} = take_puzzle(socket, socket.assigns.guest_address)
|
||||
{:noreply, socket}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -193,36 +211,80 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
|
||||
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)}
|
||||
|
||||
defp next_puzzle(socket) do
|
||||
case GuestLimits.remaining(socket.assigns.guest_address) do
|
||||
{: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)}
|
||||
socket
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:limit_reached, retry_ms)
|
||||
|
||||
{:ok, _remaining} ->
|
||||
case random_unserved(socket) do
|
||||
nil -> assign(socket, :empty, :exhausted)
|
||||
endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame)
|
||||
end
|
||||
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")
|
||||
defp take_puzzle(socket, address) do
|
||||
case GuestLimits.remaining(address) do
|
||||
{:limit_reached, retry_ms} ->
|
||||
{:ok, limit_wall(socket, address, retry_ms)}
|
||||
|
||||
{:ok, _remaining} ->
|
||||
case random_unserved(socket) do
|
||||
nil -> {:ok, empty_pool(socket, address)}
|
||||
endgame -> {:ok, start_guest_puzzle(socket, address, endgame)}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Prefer an endgame this visitor has not seen in this session. Once the whole
|
||||
# pool is served — only possible on a very long guest session — start over
|
||||
# rather than dead-end.
|
||||
defp random_unserved(socket) do
|
||||
Endgames.random_endgame(exclude_ids: socket.assigns.served_ids) ||
|
||||
Endgames.random_endgame()
|
||||
end
|
||||
|
||||
defp start_guest_puzzle(socket, address, endgame) do
|
||||
case GuestLimits.take(address) do
|
||||
{:ok, remaining} ->
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, remaining)
|
||||
|> assign(:limit_reached, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:served_ids, [endgame.id | socket.assigns.served_ids])
|
||||
|> PlayCore.init(endgame, page_title: "Train")
|
||||
|
||||
{:limit_reached, retry_ms} ->
|
||||
limit_wall(socket, address, retry_ms)
|
||||
end
|
||||
end
|
||||
|
||||
defp empty_pool(socket, address) do
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:endgame, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, nil)
|
||||
end
|
||||
|
||||
defp limit_wall(socket, address, retry_ms) do
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, retry_ms)
|
||||
|> assign(:endgame, nil)
|
||||
|> assign(:empty, nil)
|
||||
end
|
||||
|
||||
defp signed_in?(socket) do
|
||||
case socket.assigns.current_scope do
|
||||
%{user: %{}} -> true
|
||||
|
||||
@@ -8,6 +8,8 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
require Logger
|
||||
|
||||
alias Chesstrainer.Endgames.BulkImport
|
||||
alias Chesstrainer.Endgames.Tablebase.Local
|
||||
|
||||
@@ -194,10 +196,6 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
|
||||
{:noreply, create_theme(socket, name)}
|
||||
end
|
||||
|
||||
def handle_event("create_theme_from_search", %{"theme_search" => name}, socket) do
|
||||
{:noreply, create_theme(socket, name)}
|
||||
end
|
||||
|
||||
def handle_event("remove_theme", %{"id" => id}, socket) do
|
||||
selected = Enum.reject(socket.assigns.selected_themes, &(Integer.to_string(&1.id) == id))
|
||||
{:noreply, assign(socket, :selected_themes, selected)}
|
||||
@@ -272,7 +270,14 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
|
||||
end
|
||||
|
||||
def handle_async(:lookup, {:exit, reason}, socket) do
|
||||
{:noreply, put_flash(socket, :error, "Could not look up the FENs: #{inspect(reason)}")}
|
||||
Logger.error("bulk_import.lookup_failed", reason: inspect(reason))
|
||||
|
||||
{:noreply,
|
||||
put_flash(
|
||||
socket,
|
||||
:error,
|
||||
"The lookup failed. Try again; if it keeps happening, check the server log."
|
||||
)}
|
||||
end
|
||||
|
||||
defp tablebase_status do
|
||||
@@ -288,7 +293,8 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
|
||||
{:error, "Local tablebase is not configured. Set TABLEBASE_PATH to enable imports."}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, "Local tablebase failed to load: #{inspect(reason)}"}
|
||||
Logger.warning("bulk_import.tablebase_unavailable", reason: inspect(reason))
|
||||
{:error, "The local tablebase failed to load. Check TABLEBASE_PATH and the server log."}
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
||||
endgame={@endgame}
|
||||
fen={@fen}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
blocked={@blocked}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
|
||||
@@ -21,8 +21,23 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
alias Chesstrainer.Ratings
|
||||
alias ChesstrainerWeb.RatingComponents
|
||||
|
||||
require Logger
|
||||
|
||||
@uci_pattern ~r/^[a-h][1-8][a-h][1-8][qrbn]?$/
|
||||
|
||||
@typedoc """
|
||||
A blocked puzzle's user-facing state.
|
||||
|
||||
`kind` names the failure class, `title` and `message` are the only copy shown
|
||||
to the player, and `retry` says whether fetching again can plausibly help.
|
||||
"""
|
||||
@type blocked :: %{
|
||||
kind: :cooldown | :rate_limited | :not_covered | :unavailable,
|
||||
title: String.t(),
|
||||
message: String.t(),
|
||||
retry: boolean()
|
||||
}
|
||||
|
||||
@doc """
|
||||
Loads `endgame` and starts an attempt on it.
|
||||
|
||||
@@ -39,7 +54,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
|> assign(:fen, endgame.fen)
|
||||
|> assign(:tablebase, nil)
|
||||
|> assign(:status, :loading)
|
||||
|> assign(:blocked_reason, nil)
|
||||
|> assign(:blocked, nil)
|
||||
|> assign(:best_move, nil)
|
||||
|> assign(:plies, [])
|
||||
|> assign(:reviewing, false)
|
||||
@@ -164,7 +179,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
|> snapshot(fen, tablebase)
|
||||
|> assign(:awaiting_reply, false)
|
||||
|> assign(:status, :playing)
|
||||
|> assign(:blocked_reason, nil)
|
||||
|> assign(:blocked, nil)
|
||||
|> assign(:move_input_error, nil)
|
||||
|> push_event("resume_board", %{})}
|
||||
|
||||
@@ -173,7 +188,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
socket
|
||||
|> assign(:awaiting_reply, false)
|
||||
|> assign(:status, :blocked)
|
||||
|> assign(:blocked_reason, blocked_reason(other))}
|
||||
|> assign(:blocked, blocked(other))}
|
||||
end
|
||||
end
|
||||
else
|
||||
@@ -182,12 +197,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
end
|
||||
|
||||
def fen_invalid(socket, %{"fen" => fen, "message" => message}) do
|
||||
Logger.warning("board.fen_invalid", fen: fen, message: message)
|
||||
|
||||
{:noreply,
|
||||
put_flash(
|
||||
socket,
|
||||
:error,
|
||||
"Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})"
|
||||
)}
|
||||
put_flash(socket, :error, "The board couldn't load this position. Reset to try again.")}
|
||||
end
|
||||
|
||||
def reset(socket) do
|
||||
@@ -359,14 +372,14 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
|> assign(:tablebase, tablebase)
|
||||
|> snapshot(fen, tablebase)
|
||||
|> assign(:status, :playing)
|
||||
|> assign(:blocked_reason, nil)
|
||||
|> assign(:blocked, nil)
|
||||
|> push_init_board(fen)
|
||||
|
||||
other ->
|
||||
socket
|
||||
|> assign(:tablebase, nil)
|
||||
|> assign(:status, :blocked)
|
||||
|> assign(:blocked_reason, blocked_reason(other))
|
||||
|> assign(:blocked, blocked(other))
|
||||
|> push_init_board(fen)
|
||||
end
|
||||
else
|
||||
@@ -383,25 +396,54 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
})
|
||||
end
|
||||
|
||||
defp blocked_reason({:cooldown, remaining_ms}) do
|
||||
@doc """
|
||||
Classifies a failed tablebase fetch into the copy the player sees.
|
||||
|
||||
One message per failure class; the underlying reason never reaches the page.
|
||||
"""
|
||||
@spec blocked(term()) :: blocked()
|
||||
def blocked({:cooldown, remaining_ms}) do
|
||||
seconds = max(div(remaining_ms + 999, 1000), 1)
|
||||
"The tablebase is rate-limited. Try again in about #{seconds}s."
|
||||
|
||||
%{
|
||||
kind: :cooldown,
|
||||
title: "Tablebase cooling down",
|
||||
message: "The tablebase is rate-limited. Try again in about #{seconds}s.",
|
||||
retry: true
|
||||
}
|
||||
end
|
||||
|
||||
defp blocked_reason({:error, {:too_many_requests, _, _}}) do
|
||||
"The tablebase is rate-limited. Try again in a minute."
|
||||
def blocked({:error, {:too_many_requests, _, _}}) do
|
||||
%{
|
||||
kind: :rate_limited,
|
||||
title: "Tablebase rate-limited",
|
||||
message: "The tablebase is rate-limited. Try again in a minute.",
|
||||
retry: true
|
||||
}
|
||||
end
|
||||
|
||||
defp blocked_reason({:error, {:client_error, 404, _}}) do
|
||||
"This position is not covered by the tablebase."
|
||||
def blocked({:error, {:client_error, 404, _}}), do: not_covered()
|
||||
def blocked({:error, :not_covered}), do: not_covered()
|
||||
def blocked({:error, :invalid_endgame}), do: not_covered()
|
||||
|
||||
def blocked({:error, reason}) do
|
||||
Logger.warning("tablebase.unavailable", reason: inspect(reason))
|
||||
|
||||
%{
|
||||
kind: :unavailable,
|
||||
title: "Tablebase unavailable",
|
||||
message: "The tablebase is unavailable right now. Try again in a moment.",
|
||||
retry: true
|
||||
}
|
||||
end
|
||||
|
||||
defp blocked_reason({:error, :not_covered}) do
|
||||
"This position is not covered by the tablebase."
|
||||
end
|
||||
|
||||
defp blocked_reason({:error, reason}) do
|
||||
"The tablebase is unavailable (#{inspect(reason)})."
|
||||
defp not_covered do
|
||||
%{
|
||||
kind: :not_covered,
|
||||
title: "Position not covered",
|
||||
message: "This position isn't in the tablebase, so it can't be graded.",
|
||||
retry: false
|
||||
}
|
||||
end
|
||||
|
||||
defp grade_and_record(socket, from, to, promotion, san, fen_after, draw, check, checkmate) do
|
||||
@@ -464,7 +506,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:status, :blocked)
|
||||
|> assign(:blocked_reason, blocked_reason(other))}
|
||||
|> assign(:blocked, blocked(other))}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -727,7 +769,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
:error ->
|
||||
case Tablebase.new(fen) do
|
||||
{:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)}
|
||||
other -> {:unavailable, blocked_reason(other), socket}
|
||||
other -> {:unavailable, blocked(other), socket}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -77,11 +77,12 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
</div>
|
||||
|
||||
<PlayComponents.play_surface
|
||||
:if={is_nil(@pool)}
|
||||
session={true}
|
||||
endgame={@endgame}
|
||||
fen={@fen}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
blocked={@blocked}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
@@ -99,6 +100,26 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
rating={@user_rating}
|
||||
rating_delta={@last_rating_delta}
|
||||
/>
|
||||
|
||||
<section
|
||||
:if={@pool}
|
||||
id="pool-exhausted"
|
||||
class="rounded-xl border border-hairline bg-canvas-raised p-6"
|
||||
>
|
||||
<h2 class="text-lg font-semibold">You've played every puzzle available right now</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
There are no more {difficulty_label(@session.difficulty)} puzzles right now.
|
||||
Try again, or pick another difficulty.
|
||||
</p>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
|
||||
<.icon name="hero-arrow-path" /> Retry
|
||||
</.button>
|
||||
<.button id="change-difficulty" phx-click="stop_session">
|
||||
Change difficulty
|
||||
</.button>
|
||||
</div>
|
||||
</section>
|
||||
<% else %>
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div id="difficulty-picker" class="w-full max-w-md rounded-xl bg-base-100 p-6 shadow-xl">
|
||||
@@ -140,7 +161,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Choose a difficulty</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Difficulty bands are ±{Puzzles.band_width()} around your rating.
|
||||
Easy draws easier endgames, hard draws harder ones — your rating sets the centre.
|
||||
</p>
|
||||
</div>
|
||||
<.link
|
||||
@@ -155,8 +176,21 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
<div class="mt-4">
|
||||
<.rating_guide rating={@user_rating} deviation={@user_deviation} />
|
||||
</div>
|
||||
<div
|
||||
:if={@pool}
|
||||
id="pool-empty"
|
||||
class="mt-4 rounded-lg border border-warning/30 bg-warning/10 p-3 text-sm"
|
||||
>
|
||||
<p class="font-semibold">No puzzles available right now</p>
|
||||
<p class="mt-1 text-muted">
|
||||
There are no {difficulty_label(@pool.difficulty)} puzzles yet. Try again, or choose another difficulty.
|
||||
</p>
|
||||
<.button id="retry-pool" phx-click="retry_pool" class="mt-3">
|
||||
<.icon name="hero-arrow-path" /> Retry
|
||||
</.button>
|
||||
</div>
|
||||
<div class="mt-4 grid gap-2">
|
||||
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %>
|
||||
<%= for {difficulty, label, description} <- difficulty_options() do %>
|
||||
<.button
|
||||
id={"difficulty-#{difficulty}"}
|
||||
phx-click="start_session"
|
||||
@@ -188,62 +222,32 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
|> assign(:last_session, nil)
|
||||
|> assign(:puzzle_started_mono, nil)
|
||||
|> assign(:puzzle_counted, false)
|
||||
|> assign(:pool, nil)
|
||||
|> assign(:user_rating, socket.assigns.current_scope.user.rating)
|
||||
|> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("start_session", %{"difficulty" => difficulty}, socket) do
|
||||
difficulty = parse_difficulty(difficulty)
|
||||
|
||||
case Puzzles.next_endgame(selection_user(socket), difficulty) do
|
||||
nil ->
|
||||
{:noreply, put_flash(socket, :error, "No puzzles are available right now.")}
|
||||
|
||||
endgame ->
|
||||
session = %{
|
||||
difficulty: difficulty,
|
||||
started_at_ms: System.system_time(:millisecond),
|
||||
baseline: socket.assigns.user_rating,
|
||||
count: 0,
|
||||
sum_ms: 0
|
||||
}
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> assign(:session, session)
|
||||
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|
||||
|> assign(:puzzle_counted, false)
|
||||
|> assign(:last_rating_delta, nil)
|
||||
|> PlayCore.init(endgame, page_title: "Train")
|
||||
|
||||
{:noreply, socket}
|
||||
end
|
||||
{:noreply, start_session(socket, parse_difficulty(difficulty))}
|
||||
end
|
||||
|
||||
def handle_event("next_puzzle", _params, socket) do
|
||||
session = socket.assigns.session
|
||||
def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
|
||||
|
||||
if session do
|
||||
case Puzzles.next_endgame(selection_user(socket), session.difficulty,
|
||||
exclude_ids: [socket.assigns.endgame.id]
|
||||
) do
|
||||
def handle_event("retry_pool", _params, socket) do
|
||||
socket =
|
||||
case socket.assigns.session do
|
||||
nil ->
|
||||
{:noreply, put_flash(socket, :info, "No more puzzles at this difficulty.")}
|
||||
case socket.assigns.pool do
|
||||
%{difficulty: difficulty} -> start_session(socket, difficulty)
|
||||
_ -> socket
|
||||
end
|
||||
|
||||
endgame ->
|
||||
socket =
|
||||
socket
|
||||
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|
||||
|> assign(:puzzle_counted, false)
|
||||
|> assign(:last_rating_delta, nil)
|
||||
|> PlayCore.init(endgame, page_title: "Train")
|
||||
|
||||
{:noreply, socket}
|
||||
_session ->
|
||||
next_puzzle(socket)
|
||||
end
|
||||
else
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
def handle_event("stop_session", _params, socket) do
|
||||
@@ -253,7 +257,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
session -> assign(socket, :last_session, summarise(session, socket.assigns.user_rating))
|
||||
end
|
||||
|
||||
{:noreply, assign(socket, :session, nil)}
|
||||
{:noreply, socket |> assign(:session, nil) |> assign(:pool, nil)}
|
||||
end
|
||||
|
||||
def handle_event("endgame_move_played", params, socket) do
|
||||
@@ -300,6 +304,57 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
|
||||
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
|
||||
|
||||
defp start_session(socket, difficulty) do
|
||||
case Puzzles.next_endgame(selection_user(socket), difficulty) do
|
||||
nil ->
|
||||
assign(socket, :pool, %{difficulty: difficulty})
|
||||
|
||||
endgame ->
|
||||
session = %{
|
||||
difficulty: difficulty,
|
||||
started_at_ms: System.system_time(:millisecond),
|
||||
baseline: socket.assigns.user_rating,
|
||||
count: 0,
|
||||
sum_ms: 0,
|
||||
served_ids: [endgame.id]
|
||||
}
|
||||
|
||||
socket
|
||||
|> assign(:session, session)
|
||||
|> assign(:pool, nil)
|
||||
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|
||||
|> assign(:puzzle_counted, false)
|
||||
|> assign(:last_rating_delta, nil)
|
||||
|> PlayCore.init(endgame, page_title: "Train")
|
||||
end
|
||||
end
|
||||
|
||||
defp next_puzzle(socket) do
|
||||
session = socket.assigns.session
|
||||
|
||||
if session do
|
||||
case Puzzles.next_endgame(selection_user(socket), session.difficulty,
|
||||
exclude_ids: session.served_ids
|
||||
) do
|
||||
nil ->
|
||||
assign(socket, :pool, %{difficulty: session.difficulty})
|
||||
|
||||
endgame ->
|
||||
session = %{session | served_ids: [endgame.id | session.served_ids]}
|
||||
|
||||
socket
|
||||
|> assign(:session, session)
|
||||
|> assign(:pool, nil)
|
||||
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|
||||
|> assign(:puzzle_counted, false)
|
||||
|> assign(:last_rating_delta, nil)
|
||||
|> PlayCore.init(endgame, page_title: "Train")
|
||||
end
|
||||
else
|
||||
socket
|
||||
end
|
||||
end
|
||||
|
||||
# A completed puzzle contributes one first-attempt time to the average. A
|
||||
# retry happens after this point and is deliberately ignored.
|
||||
defp account_completion(socket) do
|
||||
@@ -344,13 +399,11 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
|
||||
defp parse_difficulty(_value), do: :medium
|
||||
|
||||
defp difficulty_options(rating) do
|
||||
width = Puzzles.band_width()
|
||||
|
||||
defp difficulty_options do
|
||||
[
|
||||
{:easy, "Easy", "below #{round(rating - width)}"},
|
||||
{:medium, "Medium", "#{round(rating - width)}–#{round(rating + width)}"},
|
||||
{:hard, "Hard", "above #{round(rating + width)}"}
|
||||
{:easy, "Easy", "easier than your rating"},
|
||||
{:medium, "Medium", "around your rating"},
|
||||
{:hard, "Hard", "harder than your rating"}
|
||||
]
|
||||
end
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
|
||||
:let={f}
|
||||
for={@form}
|
||||
id="login_form_password"
|
||||
action={@login_action}
|
||||
action={~p"/users/log-in"}
|
||||
phx-submit="submit_password"
|
||||
phx-trigger-action={@trigger_submit}
|
||||
>
|
||||
@@ -75,17 +75,12 @@ defmodule ChesstrainerWeb.UserLive.Login do
|
||||
get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
|
||||
|
||||
form = to_form(%{"email" => email}, as: "user")
|
||||
prelaunch = ChesstrainerWeb.prelaunch?()
|
||||
|
||||
login_action =
|
||||
if prelaunch, do: ~p"/admin/log-in", else: ~p"/users/log-in"
|
||||
|
||||
{:ok,
|
||||
assign(socket,
|
||||
form: form,
|
||||
trigger_submit: false,
|
||||
prelaunch: prelaunch,
|
||||
login_action: login_action
|
||||
prelaunch: ChesstrainerWeb.prelaunch?()
|
||||
)}
|
||||
end
|
||||
|
||||
|
||||
@@ -19,7 +19,15 @@ defmodule ChesstrainerWeb.Plugs.Prelaunch do
|
||||
/health
|
||||
/robots.txt
|
||||
/sitemap.xml
|
||||
/users/log-in
|
||||
/favicon.ico
|
||||
/favicon.svg
|
||||
/favicon-16x16.png
|
||||
/favicon-32x32.png
|
||||
/apple-touch-icon.png
|
||||
/android-chrome-192x192.png
|
||||
/android-chrome-512x512.png
|
||||
/site.webmanifest
|
||||
)
|
||||
|
||||
@allowed_prefixes ~w(
|
||||
@@ -33,7 +41,6 @@ defmodule ChesstrainerWeb.Plugs.Prelaunch do
|
||||
/assets
|
||||
/fonts
|
||||
/images
|
||||
/dev
|
||||
)
|
||||
|
||||
def init(opts), do: opts
|
||||
|
||||
@@ -36,8 +36,6 @@ defmodule ChesstrainerWeb.Router do
|
||||
get "/terms-conditions", PageController, :terms_conditions
|
||||
get "/mentions-legales", PageController, :mentions_legales
|
||||
post "/mailing-list", MailingListController, :create
|
||||
get "/mailing-list/confirm/:token", MailingListController, :confirm
|
||||
post "/admin/log-in", UserSessionController, :create_admin
|
||||
end
|
||||
|
||||
scope "/admin", ChesstrainerWeb do
|
||||
@@ -57,6 +55,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
live "/themes", Admin.ThemeLive.Index, :index
|
||||
live "/themes/new", Admin.ThemeLive.Form, :new
|
||||
live "/themes/:id/edit", Admin.ThemeLive.Form, :edit
|
||||
live "/themes/:id/tag", Admin.ThemeLive.Tag, :tag
|
||||
|
||||
live "/users", Admin.UserLive.Index, :index
|
||||
live "/users/new", Admin.UserLive.New, :new
|
||||
@@ -89,7 +88,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
## Authentication routes
|
||||
|
||||
scope "/", ChesstrainerWeb do
|
||||
pipe_through [:browser, :require_authenticated_user]
|
||||
pipe_through [:browser, :noindex, :require_authenticated_user]
|
||||
|
||||
live_session :require_authenticated_user,
|
||||
on_mount: [
|
||||
@@ -111,7 +110,9 @@ defmodule ChesstrainerWeb.Router do
|
||||
end
|
||||
|
||||
scope "/", ChesstrainerWeb do
|
||||
pipe_through [:browser]
|
||||
# App surface: play pages, auth forms and guest training are reachable
|
||||
# without a session but must never appear in search results.
|
||||
pipe_through [:browser, :noindex]
|
||||
|
||||
live_session :current_user,
|
||||
on_mount: [
|
||||
@@ -122,12 +123,12 @@ defmodule ChesstrainerWeb.Router do
|
||||
live "/endgames/:public_code/play", EndgameLive.Play, :play
|
||||
live "/users/register", UserLive.Registration, :new
|
||||
live "/users/log-in", UserLive.Login, :new
|
||||
live "/admin/log-in", UserLive.Login, :new
|
||||
live "/users/reset-password", UserLive.ResetPassword, :new
|
||||
live "/users/reset-password/:token", UserLive.ResetPassword, :edit
|
||||
end
|
||||
|
||||
get "/users/confirm/:token", UserConfirmationController, :edit
|
||||
get "/mailing-list/confirm/:token", MailingListController, :confirm
|
||||
|
||||
post "/users/log-in", UserSessionController, :create
|
||||
delete "/users/log-out", UserSessionController, :delete
|
||||
@@ -146,7 +147,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
# Keep this last: routes match in definition order. It gives unmatched paths a
|
||||
# branded 404 page with the site chrome instead of Phoenix's bare status page.
|
||||
scope "/", ChesstrainerWeb do
|
||||
pipe_through :browser
|
||||
pipe_through [:browser, :noindex]
|
||||
|
||||
match :*, "/*path", PageController, :not_found
|
||||
end
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
defmodule ChesstrainerWeb.SEO do
|
||||
@moduledoc """
|
||||
Absolute URLs and crawler metadata for controller-rendered pages.
|
||||
|
||||
Search engines need absolute URLs, so these helpers read the endpoint's
|
||||
configured host rather than the request host (which is a proxy address).
|
||||
|
||||
Canonical URLs deliberately drop the query string: campaign parameters such
|
||||
as `?utm_source=...` must not become canonical pages of their own.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias ChesstrainerWeb.Endpoint
|
||||
|
||||
@og_image "/images/og.png"
|
||||
@logo "/apple-touch-icon.png"
|
||||
|
||||
@doc "The request path as an absolute canonical URL, without any query string."
|
||||
def canonical_url(conn) do
|
||||
Phoenix.VerifiedRoutes.unverified_url(conn, conn.request_path)
|
||||
end
|
||||
|
||||
@doc "Absolute URL of the social share image."
|
||||
def og_image_url, do: Endpoint.url() <> @og_image
|
||||
|
||||
@doc """
|
||||
JSON-LD for the site, encoded as a string ready for a
|
||||
`<script type="application/ld+json">` block.
|
||||
"""
|
||||
def json_ld(url) do
|
||||
%{
|
||||
"@context" => "https://schema.org",
|
||||
"@graph" => [
|
||||
%{
|
||||
"@type" => "WebSite",
|
||||
"name" => Branding.name(),
|
||||
"url" => url
|
||||
},
|
||||
%{
|
||||
"@type" => "Organization",
|
||||
"name" => Branding.name(),
|
||||
"url" => url,
|
||||
"logo" => Endpoint.url() <> @logo
|
||||
}
|
||||
]
|
||||
}
|
||||
|> Jason.encode!()
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,101 @@
|
||||
defmodule Mix.Tasks.Assets.Sizes do
|
||||
use Mix.Task
|
||||
|
||||
@shortdoc "Report raw, gzip and brotli sizes of built assets"
|
||||
|
||||
@moduledoc """
|
||||
Prints the size of every built JavaScript and CSS file under
|
||||
`priv/static/assets`, uncompressed and compressed, so bundle changes can be
|
||||
measured rather than guessed.
|
||||
|
||||
mix assets.sizes
|
||||
|
||||
Run it after `mix assets.build` (development, unminified) or
|
||||
`mix assets.deploy` (production, minified and digested). Production numbers
|
||||
are the ones that matter: they are what the browser downloads.
|
||||
|
||||
Brotli sizes are shown as a dash when the `brotli` CLI is not installed.
|
||||
"""
|
||||
|
||||
@assets_globs ["priv/static/assets/js/**/*.js", "priv/static/assets/css/**/*.css"]
|
||||
|
||||
@impl true
|
||||
def run(_argv) do
|
||||
files = @assets_globs |> Enum.flat_map(&Path.wildcard/1) |> Enum.sort()
|
||||
|
||||
if files == [] do
|
||||
Mix.raise("no built assets found under priv/static/assets; run mix assets.build")
|
||||
end
|
||||
|
||||
rows = Enum.map(files, &measure/1)
|
||||
print(rows)
|
||||
end
|
||||
|
||||
defp measure(path) do
|
||||
contents = File.read!(path)
|
||||
|
||||
%{
|
||||
path: Path.relative_to_cwd(path),
|
||||
raw: byte_size(contents),
|
||||
gzip: byte_size(:zlib.gzip(contents)),
|
||||
brotli: brotli_size(path)
|
||||
}
|
||||
end
|
||||
|
||||
defp brotli_size(path) do
|
||||
with executable when is_binary(executable) <- System.find_executable("brotli"),
|
||||
{output, 0} <- System.cmd(executable, ["-q", "11", "-c", path], into: "") do
|
||||
byte_size(output)
|
||||
else
|
||||
_unavailable -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp print(rows) do
|
||||
widths = column_widths(rows)
|
||||
|
||||
header = [
|
||||
pad("file", widths.path),
|
||||
pad("raw", widths.raw, :right),
|
||||
pad("gzip", widths.gzip, :right),
|
||||
pad("brotli", widths.brotli, :right)
|
||||
]
|
||||
|
||||
Mix.shell().info(Enum.join(header, " "))
|
||||
Mix.shell().info(String.duplicate("-", Enum.sum(Map.values(widths)) + 6))
|
||||
Enum.each(rows, &print_row(&1, widths))
|
||||
end
|
||||
|
||||
defp print_row(row, widths) do
|
||||
values = [
|
||||
pad(row.path, widths.path),
|
||||
pad(human(row.raw), widths.raw, :right),
|
||||
pad(human(row.gzip), widths.gzip, :right),
|
||||
pad(human(row.brotli), widths.brotli, :right)
|
||||
]
|
||||
|
||||
Mix.shell().info(Enum.join(values, " "))
|
||||
end
|
||||
|
||||
defp column_widths(rows) do
|
||||
%{
|
||||
path: rows |> Enum.map(&String.length(&1.path)) |> Enum.max(),
|
||||
raw: rows |> Enum.map(&String.length(human(&1.raw))) |> Enum.max(),
|
||||
gzip: rows |> Enum.map(&String.length(human(&1.gzip))) |> Enum.max(),
|
||||
brotli: rows |> Enum.map(&String.length(human(&1.brotli))) |> Enum.max()
|
||||
}
|
||||
end
|
||||
|
||||
defp pad(value, width, align \\ :left) do
|
||||
value = to_string(value)
|
||||
|
||||
case align do
|
||||
:right -> String.pad_leading(value, width)
|
||||
:left -> String.pad_trailing(value, width)
|
||||
end
|
||||
end
|
||||
|
||||
defp human(nil), do: "-"
|
||||
defp human(bytes) when bytes < 1024, do: "#{bytes} B"
|
||||
defp human(bytes), do: "#{Float.round(bytes / 1024, 1)} KB"
|
||||
end
|
||||
@@ -0,0 +1,84 @@
|
||||
defmodule Mix.Tasks.Mail.Check do
|
||||
use Mix.Task
|
||||
|
||||
@shortdoc "Send test email through the configured mailer and SES simulators"
|
||||
|
||||
@moduledoc """
|
||||
Sends a test message through the application mailer, applying the same house
|
||||
rules as real mail: From identity, Reply-To, and the SES configuration set.
|
||||
|
||||
mix mail.check --to you@example.com
|
||||
|
||||
By default it also sends to the SES mailbox simulator addresses so bounce and
|
||||
complaint wiring can be exercised without touching a real inbox:
|
||||
|
||||
* `success@simulator.amazonses.com`
|
||||
* `bounce@simulator.amazonses.com`
|
||||
* `complaint@simulator.amazonses.com`
|
||||
|
||||
The simulators only do something when the mailer is the SES adapter. Pass
|
||||
`--no-simulators` to send only to the given address.
|
||||
|
||||
If `MAIL_REDIRECT_TO` is set, every recipient is rewritten to that address
|
||||
first (including the simulators), so this task cannot reach users even in
|
||||
production.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
@simulators [
|
||||
"success@simulator.amazonses.com",
|
||||
"bounce@simulator.amazonses.com",
|
||||
"complaint@simulator.amazonses.com"
|
||||
]
|
||||
|
||||
@impl true
|
||||
def run(argv) do
|
||||
{opts, _args} = OptionParser.parse!(argv, strict: [to: :string, simulators: :boolean])
|
||||
|
||||
recipient =
|
||||
opts[:to] ||
|
||||
Mix.raise("pass the address to check: mix mail.check --to you@example.com")
|
||||
|
||||
Mix.Task.run("app.start")
|
||||
|
||||
targets = if opts[:simulators] == false, do: [recipient], else: [recipient | @simulators]
|
||||
|
||||
Mix.shell().info("adapter: #{inspect(adapter())}")
|
||||
|
||||
if redirect(), do: Mix.shell().info("redirect: every message goes to #{redirect()}")
|
||||
|
||||
Enum.each(targets, &send_message/1)
|
||||
end
|
||||
|
||||
defp send_message(recipient) do
|
||||
email =
|
||||
Swoosh.Email.new()
|
||||
|> Swoosh.Email.to(recipient)
|
||||
|> Swoosh.Email.subject("Mail check #{DateTime.utc_now() |> DateTime.to_iso8601()}")
|
||||
|> Swoosh.Email.text_body(
|
||||
"This is a delivery check from the chess trainer. " <>
|
||||
"If you can read it, the mailer, sender identity and configuration set are wired up."
|
||||
)
|
||||
|> Mail.prepare()
|
||||
|
||||
case Chesstrainer.Mailer.deliver(email) do
|
||||
{:ok, metadata} ->
|
||||
Mix.shell().info("sent #{recipient} #{format_metadata(metadata)}")
|
||||
|
||||
{:error, reason} ->
|
||||
Mix.shell().error("failed #{recipient} #{inspect(reason)}")
|
||||
end
|
||||
end
|
||||
|
||||
defp format_metadata(%{id: id}) when is_binary(id), do: "(message id #{id})"
|
||||
defp format_metadata(_metadata), do: ""
|
||||
|
||||
defp adapter do
|
||||
:chesstrainer
|
||||
|> Application.get_env(Chesstrainer.Mailer, [])
|
||||
|> Keyword.get(:adapter)
|
||||
end
|
||||
|
||||
defp redirect, do: Application.get_env(:chesstrainer, :mail_redirect_to)
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
defmodule Mix.Tasks.Themes.DeriveMaterial do
|
||||
use Mix.Task
|
||||
|
||||
@shortdoc "Tags every endgame with its material family theme"
|
||||
|
||||
@moduledoc """
|
||||
Derives each endgame's material family from its Key and stores the result as
|
||||
a derived theme.
|
||||
|
||||
mix themes.derive_material
|
||||
|
||||
Every endgame belongs to exactly one family, so the themes partition the
|
||||
library. Re-running is idempotent: only derived links are replaced, and
|
||||
curated or community links are untouched.
|
||||
|
||||
Positions that are kings only, or that have no Key, are reported as skipped.
|
||||
"""
|
||||
|
||||
@impl Mix.Task
|
||||
def run(_args) do
|
||||
Mix.Task.run("app.start")
|
||||
|
||||
%{tagged: tagged, skipped: skipped, themes: themes} =
|
||||
Chesstrainer.Endgames.MaterialThemes.derive()
|
||||
|
||||
Mix.shell().info(
|
||||
"Material themes: #{themes} themes, #{tagged} endgames tagged, " <>
|
||||
"#{skipped} skipped (kings only or no Key)."
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
defmodule Mix.Tasks.Themes.DeriveMotifs do
|
||||
use Mix.Task
|
||||
|
||||
@shortdoc "Tags every endgame with its tablebase-proved motifs"
|
||||
|
||||
@moduledoc """
|
||||
Derives only-move, underpromotion and 50-move-draw motifs from the local
|
||||
Syzygy tablebase.
|
||||
|
||||
mix themes.derive_motifs
|
||||
|
||||
The pass never calls the remote tablebase. Positions the local files cannot
|
||||
answer are skipped and reported. Re-running is idempotent: only links to the
|
||||
motif themes are replaced, so material, curated and community links survive.
|
||||
"""
|
||||
|
||||
@impl Mix.Task
|
||||
def run(_args) do
|
||||
Mix.Task.run("app.start")
|
||||
|
||||
%{links: links, skipped: skipped, by_motif: by_motif, themes: themes} =
|
||||
Chesstrainer.Endgames.MotifThemes.derive()
|
||||
|
||||
Mix.shell().info(
|
||||
"Motif themes: #{themes} themes, #{links} link(s) written, #{skipped} endgame(s) skipped."
|
||||
)
|
||||
|
||||
for {motif, count} <- Enum.sort(by_motif) do
|
||||
Mix.shell().info(" #{motif}: #{count}")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,5 +1,5 @@
|
||||
[tools]
|
||||
erlang = "28.5"
|
||||
elixir = "1.19.5-otp-28"
|
||||
rust = "1.98.1"
|
||||
erlang = "29.1.2"
|
||||
elixir = "1.20.5-otp-29"
|
||||
rust = "1.100.0"
|
||||
node = "24"
|
||||
|
||||
@@ -5,7 +5,7 @@ defmodule Chesstrainer.MixProject do
|
||||
[
|
||||
app: :chesstrainer,
|
||||
version: "0.1.0",
|
||||
elixir: "~> 1.15",
|
||||
elixir: "~> 1.20",
|
||||
elixirc_paths: elixirc_paths(Mix.env()),
|
||||
start_permanent: Mix.env() == :prod,
|
||||
aliases: aliases(),
|
||||
@@ -41,18 +41,18 @@ defmodule Chesstrainer.MixProject do
|
||||
# Type `mix help deps` for examples and options.
|
||||
defp deps do
|
||||
[
|
||||
{:bcrypt_elixir, "~> 3.0"},
|
||||
{:phoenix, "~> 1.8.8"},
|
||||
{:phoenix_ecto, "~> 4.5"},
|
||||
{:ecto_sql, "~> 3.13"},
|
||||
{:postgrex, ">= 0.0.0"},
|
||||
{:phoenix_html, "~> 4.1"},
|
||||
{:phoenix_live_reload, "~> 1.2", only: :dev},
|
||||
{:bcrypt_elixir, "~> 3.3.2"},
|
||||
{:phoenix, "~> 1.8.16"},
|
||||
{:phoenix_ecto, "~> 4.7"},
|
||||
{:ecto_sql, "~> 3.14"},
|
||||
{:postgrex, ">= 0.22.4"},
|
||||
{:phoenix_html, "~> 4.4"},
|
||||
{:phoenix_live_reload, "~> 1.7", only: :dev},
|
||||
{:phoenix_live_view, "~> 1.2.0"},
|
||||
{:lazy_html, ">= 0.1.0", only: :test},
|
||||
{:phoenix_live_dashboard, "~> 0.8.3"},
|
||||
{:lazy_html, ">= 0.1.14", only: :test},
|
||||
{:phoenix_live_dashboard, "~> 0.9.1"},
|
||||
{:esbuild, "~> 0.10", runtime: Mix.env() == :dev},
|
||||
{:tailwind, "~> 0.3", runtime: Mix.env() == :dev},
|
||||
{:tailwind, "~> 0.5", runtime: Mix.env() == :dev},
|
||||
{:heroicons,
|
||||
github: "tailwindlabs/heroicons",
|
||||
tag: "v2.2.0",
|
||||
@@ -60,15 +60,15 @@ defmodule Chesstrainer.MixProject do
|
||||
app: false,
|
||||
compile: false,
|
||||
depth: 1},
|
||||
{:swoosh, "~> 1.16"},
|
||||
{:req, "~> 0.5"},
|
||||
{:gen_smtp, "~> 1.2"},
|
||||
{:telemetry_metrics, "~> 1.0"},
|
||||
{:telemetry_poller, "~> 1.0"},
|
||||
{:swoosh, "~> 1.29"},
|
||||
{:req, "~> 0.7"},
|
||||
{:gen_smtp, "~> 1.3"},
|
||||
{:telemetry_metrics, "~> 1.2"},
|
||||
{:telemetry_poller, "~> 1.3"},
|
||||
{:gettext, "~> 1.0"},
|
||||
{:jason, "~> 1.2"},
|
||||
{:dns_cluster, "~> 0.2.0"},
|
||||
{:bandit, "~> 1.5"},
|
||||
{:jason, "~> 1.4"},
|
||||
{:dns_cluster, "~> 0.3.1"},
|
||||
{:bandit, "~> 1.13"},
|
||||
{:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"},
|
||||
{:rustler, "~> 0.38", runtime: false},
|
||||
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false},
|
||||
|
||||
@@ -1,55 +1,55 @@
|
||||
%{
|
||||
"bandit": {:hex, :bandit, "1.12.0", "6c5214daa2469644ac4ab0113b98abc24f75e348378e6a974c6343b3e5da22ef", [:mix], [{:hpax, "~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.5", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "45dac82dc86f45cf4a196dee9cc5a8b791d9c9469d996055f055e6ee36c66e20"},
|
||||
"bandit": {:hex, :bandit, "1.14.1", "5fb450e2360faf03d9b9fb45cfe52e14197f62d376c34781219bec0f9bc7ca06", [:mix], [{:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.6", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "87c7ee5e08fb5f22d4e072e681e1101266a21432889b08ef8d0cb0c1450f8bba"},
|
||||
"bcrypt_elixir": {:hex, :bcrypt_elixir, "3.3.2", "d50091e3c9492d73e17fc1e1619a9b09d6a5ef99160eb4d736926fd475a16ca3", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "471be5151874ae7931911057d1467d908955f93554f7a6cd1b7d804cac8cef53"},
|
||||
"cc_precompiler": {:hex, :cc_precompiler, "0.1.11", "8c844d0b9fb98a3edea067f94f616b3f6b29b959b6b3bf25fee94ffe34364768", [:mix], [{:elixir_make, "~> 0.7", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "3427232caf0835f94680e5bcf082408a70b48ad68a5f5c0b02a3bea9f3a075b9"},
|
||||
"chex": {:git, "https://github.com/therealowenrees/chex.git", "655b5c3df6c5297689d7872bbce1e86c6c629d26", [tag: "v0.2.0-alpha.2"]},
|
||||
"comeonin": {:hex, :comeonin, "5.5.1", "5113e5f3800799787de08a6e0db307133850e635d34e9fab23c70b6501669510", [:mix], [], "hexpm", "65aac8f19938145377cee73973f192c5645873dcf550a8a6b18187d17c13ccdb"},
|
||||
"db_connection": {:hex, :db_connection, "2.10.1", "d5465f6bcc125c1b8981c1dbf23c193ca16f446ec0b25832dc174f74f18be510", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "18ed94c6e627b4bf452dbd4df61b69a35a1e768525140bc1917b7a685026a6a3"},
|
||||
"decimal": {:hex, :decimal, "3.1.1", "430d87b04011ce6cbd4fd205be758311a81f87d552d40904abd00f015935b1d0", [:mix], [], "hexpm", "c5f25f2ced74a0587d03e6023f595db8e924c9d3922c8c8ffd9edfc4498cf1f6"},
|
||||
"dialyxir": {:hex, :dialyxir, "1.4.8", "7ef671a8aff9948b091d8c30f09467fbb16e77305cda451bce48109a0f5e021c", [:mix], [{:erlex, ">= 0.2.8", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "cbd5a851571e5dfeb32aaf2e840bfa98b7864cb3071bf2ef5d95d1276b12e072"},
|
||||
"dns_cluster": {:hex, :dns_cluster, "0.2.0", "aa8eb46e3bd0326bd67b84790c561733b25c5ba2fe3c7e36f28e88f384ebcb33", [:mix], [], "hexpm", "ba6f1893411c69c01b9e8e8f772062535a4cf70f3f35bcc964a324078d8c8240"},
|
||||
"ecto": {:hex, :ecto, "3.14.0", "2fa64521eebfcb2670d907a86e4ad947290e9933706bb315e6fb5c21b172cb26", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "130d69ffb4285f9ce4792b65dfbb994fd13ea4cbc3cbea2524b199aa3de84af3"},
|
||||
"db_connection": {:hex, :db_connection, "2.10.2", "ae391e803a5adff104da913c2fc1c0c14a37f8b10001dcef568796e1fb7bf95c", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "510b14482330f1af6490a2fa0efd8d4f1435d1529b165647df22ac0f2df0fa93"},
|
||||
"decimal": {:hex, :decimal, "3.2.0", "f1235f05d841a211fda78a08fdb9777f2ff51a71f18455233fae186ff76187c6", [:mix], [], "hexpm", "190bca80580ce61aa69bb0eacadd7677710205c770225c2c2c07e32a5c31b234"},
|
||||
"dialyxir": {:hex, :dialyxir, "1.4.9", "ba347da6eac1f22e5f80764e9a35febd96865fa99f4a243bb23f130eba437f3d", [:mix], [{:erlex, ">= 0.2.8", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "1c049c22b47680f4fff78ed0b0fe377073a762e96af153fdfe28bf00131de76d"},
|
||||
"dns_cluster": {:hex, :dns_cluster, "0.3.1", "b4e707e4ddaf0d3f13580ee7dc4ab0e685f7f7f5bbe90e84535524bc12d1cf3e", [:mix], [], "hexpm", "afa60bbbd84463e977eeeecc0c564d8c5ddea260beccdb8d5f45cbb860846627"},
|
||||
"ecto": {:hex, :ecto, "3.14.3", "4e7f7728c1432b18d8a48e4aeef879e8b908ecefd66afde17adb8cca0a46eff4", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "da2548bd3ced0f56c27d54255389bbbb8f110150ce15cffc95ec0cafa364465c"},
|
||||
"ecto_sql": {:hex, :ecto_sql, "3.14.0", "06446ab8410d2f85bfbb80857ee224ab3b693700cbb38f6535d507449a627b2e", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:ecto, "~> 3.14.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.8", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f4d8d36faf294c9417b5a37ec7ac8217ee2abdef5fcf197ba690f361548d3949"},
|
||||
"elixir_make": {:hex, :elixir_make, "0.9.0", "6484b3cd8c0cee58f09f05ecaf1a140a8c97670671a6a0e7ab4dc326c3109726", [:mix], [], "hexpm", "db23d4fd8b757462ad02f8aa73431a426fe6671c80b200d9710caf3d1dd0ffdb"},
|
||||
"elixir_make": {:hex, :elixir_make, "0.10.1", "f5a44ab6b48421de1c4fd33c147e22cd2f82fd86e8a9a4d24809d466cad63c5e", [:mix], [], "hexpm", "ce1eaa234bc87f0279718e793fd6f8ad35b4e8ee8d412329e3879eee8d40adba"},
|
||||
"erlex": {:hex, :erlex, "0.2.9", "7debbbaa9f4f368b8cd648983e0f1d7963028508e9c59e9d4ed504e94ef52a55", [:mix], [], "hexpm", "8cfffc0ec7159e6d73de2ab28a588064de80f88b2798d5cbe4482cbbc200178b"},
|
||||
"esbuild": {:hex, :esbuild, "0.10.0", "b0aa3388a1c23e727c5a3e7427c932d89ee791746b0081bbe56103e9ef3d291f", [:mix], [{:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "468489cda427b974a7cc9f03ace55368a83e1a7be12fba7e30969af78e5f8c70"},
|
||||
"esbuild": {:hex, :esbuild, "0.10.1", "32b44b468d2c6386b6bf9229617cbf51be025ce4380eacd383a8979cbb8327ef", [:mix], [{:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "890f251330052dcacafa40c409769e7c42e3876fb0ae450707bde831be7b34ea"},
|
||||
"expo": {:hex, :expo, "1.1.1", "4202e1d2ca6e2b3b63e02f69cfe0a404f77702b041d02b58597c00992b601db5", [:mix], [], "hexpm", "5fb308b9cb359ae200b7e23d37c76978673aa1b06e2b3075d814ce12c5811640"},
|
||||
"file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"},
|
||||
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
|
||||
"fine": {:hex, :fine, "0.1.6", "4bf7151493443c454aac9f2fa2f34f5fefd0346a83fb5586a016c4a135c63247", [:mix], [], "hexpm", "5638eb4495488e885ebec167fa57973e5c35e1a50c344eb7666c90ec1c4e3b12"},
|
||||
"finch": {:hex, :finch, "0.24.0", "4022b6194e907b6d9b597c168001cac38e488a35fe36cef9d8297e3159782510", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "33ba40069c3587c2f99f9125b766e19dad87d6d54be3c6961db2304df04cef00"},
|
||||
"fine": {:hex, :fine, "0.2.0", "71d9ff9fa69a4167cff1f6e9fd3350ab8e45d26b52f484c6d6514194b594df02", [:mix], [], "hexpm", "6f69a9e8dadbfd017b27f611b000362870683ae65f28aec904f36ec4c5058db5"},
|
||||
"gen_smtp": {:hex, :gen_smtp, "1.3.0", "62c3d91f0dcf6ce9db71bcb6881d7ad0d1d834c7f38c13fa8e952f4104a8442e", [:rebar3], [{:ranch, ">= 1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "0b73fbf069864ecbce02fe653b16d3f35fd889d0fdd4e14527675565c39d84e6"},
|
||||
"gettext": {:hex, :gettext, "1.0.2", "5457e1fd3f4abe47b0e13ff85086aabae760497a3497909b8473e0acee57673b", [:mix], [{:expo, "~> 0.5.1 or ~> 1.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "eab805501886802071ad290714515c8c4a17196ea76e5afc9d06ca85fb1bfeb3"},
|
||||
"glicko": {:hex, :glicko, "0.8.1", "3f038a9b1022116d19e33f03b95641d8a199882d718592f9b03bbdc63d55215c", [:mix], [], "hexpm", "86dc0c86f3ef442d8c0b977d377a8aed50bc732ebf4582eb1bf19b87d7bd5b1c"},
|
||||
"heroicons": {:git, "https://github.com/tailwindlabs/heroicons.git", "0435d4ca364a608cc75e2f8683d374e55abbae26", [tag: "v2.2.0", sparse: "optimized", depth: 1]},
|
||||
"hpax": {:hex, :hpax, "1.0.3", "ed67ef51ad4df91e75cc6a1494f851850c0bd98ebc0be6e81b026e765ee535aa", [:mix], [], "hexpm", "8eab6e1cfa8d5918c2ce4ba43588e894af35dbd8e91e6e55c817bca5847df34a"},
|
||||
"hpax": {:hex, :hpax, "1.1.0", "782931867cc23217c68fb5f68fe1a11f5e7544c7fda82c8a7019a5df5a4a1cdf", [:mix], [], "hexpm", "0b8d0f05832f55571d65ac720f79bf8994138ffbb133209dc4685eae0ad456a8"},
|
||||
"idna": {:hex, :idna, "7.1.0", "1067a13043538129602d2f2ce6899d8713125c7d19734aa557ce2e3ea55bd4f1", [:rebar3], [], "hexpm", "6ae959a025bf36df61a8cab8508d9654891b5426a84c44d82deaffd6ddf8c71f"},
|
||||
"jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
|
||||
"lazy_html": {:hex, :lazy_html, "0.1.11", "136c8e9cd616b4f4e9c1562daa683880891120b759606dc4c3b6b18058ba5d79", [:make, :mix], [{:cc_precompiler, "~> 0.1", [hex: :cc_precompiler, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.9.0", [hex: :elixir_make, repo: "hexpm", optional: false]}, {:fine, "~> 0.1.0", [hex: :fine, repo: "hexpm", optional: false]}], "hexpm", "3b1be592929c31eca1a21673d25696e5c14cddfe922d9d1a3e3b48be4163883b"},
|
||||
"lazy_html": {:hex, :lazy_html, "0.1.14", "d733120403d0e6cce25eae8cf03800b5be47f28c40d1fe44a2a0850d33f9f0a2", [:make, :mix], [{:cc_precompiler, "~> 0.1", [hex: :cc_precompiler, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.9", [hex: :elixir_make, repo: "hexpm", optional: false]}, {:fine, "~> 0.2.0", [hex: :fine, repo: "hexpm", optional: false]}], "hexpm", "99210889b0cc591398d006def761f2faef438d1ac77d045a527791733571dc0c"},
|
||||
"mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
|
||||
"mint": {:hex, :mint, "1.9.0", "d6f534c2a3e98b2a8cc749b4796eb77e9e3af79a76f96e4c74035a827de0d318", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "007154c7d8c43916aed3c93afd1f11aebbaa9c5ff4b7ba55ebe0d17ee0296042"},
|
||||
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
|
||||
"mint": {:hex, :mint, "1.11.0", "a713551624815c0435237b93d90ea8b9b14254690c66f732d0ef8930f76ff1d9", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "c6279ba2d6aa3a383a1d4cfbe7b59f42e6efd400f58d8e2acfeac48a438693ab"},
|
||||
"nimble_options": {:hex, :nimble_options, "1.2.0", "73e5c5fecb08e59f390e0f59c2320b585d72470dbdd9230a469e06881b9dd4a8", [:mix], [], "hexpm", "3a784a75ef9e407619c8c9e98239b1acd29216deb737044a8c1063e2671ce6d9"},
|
||||
"nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"},
|
||||
"nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"},
|
||||
"phoenix": {:hex, :phoenix, "1.8.8", "ada3d761359274178180c0e992ef0c2b536bd7c3bd75ebba94acbf39ab4347fe", [:mix], [{:bandit, "~> 1.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.1", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.7", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:websock_adapter, "~> 0.5.3", [hex: :websock_adapter, repo: "hexpm", optional: false]}], "hexpm", "f0c843037bd2e7012fc1d1ec9574dfa6972b7e3d09e9b77fd23aa283af0aa994"},
|
||||
"phoenix": {:hex, :phoenix, "1.8.16", "6a4742054740496bfabefc95253f978d8f595f07bb601039b7a18b384a873916", [:mix], [{:bandit, "~> 1.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.4", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.7", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 2.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:websock_adapter, "~> 0.5", [hex: :websock_adapter, repo: "hexpm", optional: false]}], "hexpm", "e7355c35889305bc539eb09dae2393abcbaf0f65f6874a3f0dcb5f0ec53737fe"},
|
||||
"phoenix_ecto": {:hex, :phoenix_ecto, "4.7.0", "75c4b9dfb3efdc42aec2bd5f8bccd978aca0651dbcbc7a3f362ea5d9d43153c6", [:mix], [{:ecto, "~> 3.5", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.16 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}], "hexpm", "1d75011e4254cb4ddf823e81823a9629559a1be93b4321a6a5f11a5306fbf4cc"},
|
||||
"phoenix_html": {:hex, :phoenix_html, "4.3.0", "d3577a5df4b6954cd7890c84d955c470b5310bb49647f0a114a6eeecc850f7ad", [:mix], [], "hexpm", "3eaa290a78bab0f075f791a46a981bbe769d94bc776869f4f3063a14f30497ad"},
|
||||
"phoenix_live_dashboard": {:hex, :phoenix_live_dashboard, "0.8.7", "405880012cb4b706f26dd1c6349125bfc903fb9e44d1ea668adaf4e04d4884b7", [:mix], [{:ecto, "~> 3.6.2 or ~> 3.7", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_mysql_extras, "~> 0.5", [hex: :ecto_mysql_extras, repo: "hexpm", optional: true]}, {:ecto_psql_extras, "~> 0.7", [hex: :ecto_psql_extras, repo: "hexpm", optional: true]}, {:ecto_sqlite3_extras, "~> 1.1.7 or ~> 1.2.0", [hex: :ecto_sqlite3_extras, repo: "hexpm", optional: true]}, {:mime, "~> 1.6 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.19 or ~> 1.0", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6 or ~> 1.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "3a8625cab39ec261d48a13b7468dc619c0ede099601b084e343968309bd4d7d7"},
|
||||
"phoenix_live_reload": {:hex, :phoenix_live_reload, "1.6.2", "b18b0773a1ba77f28c52decbb0f10fd1ac4d3ae5b8632399bbf6986e3b665f62", [:mix], [{:file_system, "~> 0.2.10 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "d1f89c18114c50d394721365ffb428cce24f1c13de0467ffa773e2ff4a30d5b9"},
|
||||
"phoenix_live_view": {:hex, :phoenix_live_view, "1.2.3", "e8abe7f2acb96d98695e9290b35cb5a01a696cc2086d4ff2e0b3aa8b9c74675f", [:mix], [{:igniter, ">= 0.6.16 and < 1.0.0-0", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:lazy_html, "~> 0.1.0", [hex: :lazy_html, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.15 or ~> 1.7.0 or ~> 1.8.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.3 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "449affd6aea24daaa2f6b43748fc1e2c6a87610df996cc1f54e7b19a7a18e638"},
|
||||
"phoenix_pubsub": {:hex, :phoenix_pubsub, "2.2.0", "ff3a5616e1bed6804de7773b92cbccfc0b0f473faf1f63d7daf1206c7aeaaa6f", [:mix], [], "hexpm", "adc313a5bf7136039f63cfd9668fde73bba0765e0614cba80c06ac9460ff3e96"},
|
||||
"phoenix_template": {:hex, :phoenix_template, "1.0.4", "e2092c132f3b5e5b2d49c96695342eb36d0ed514c5b252a77048d5969330d639", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "2c0c81f0e5c6753faf5cca2f229c9709919aba34fab866d3bc05060c9c444206"},
|
||||
"plug": {:hex, :plug, "1.19.2", "e4950525b22c6789dfb38a3f95d47171ba159da3fc5a33be9643b43d5e8adb98", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b6fce20a56af5e60fa5dfecf3f907bb98ec981be43c79a3809a499bc3d133de0"},
|
||||
"plug_crypto": {:hex, :plug_crypto, "2.1.1", "19bda8184399cb24afa10be734f84a16ea0a2bc65054e23a62bb10f06bc89491", [:mix], [], "hexpm", "6470bce6ffe41c8bd497612ffde1a7e4af67f36a15eea5f921af71cf3e11247c"},
|
||||
"postgrex": {:hex, :postgrex, "0.22.2", "4aec14df2a72722aee92492566edbeeb44e233ecb86b1915d03136297ef1385d", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "8946382ddb06294f56026ac4278b3cc212bac8a2c82ed68b4087819ed1abc53b"},
|
||||
"ranch": {:hex, :ranch, "2.3.0", "7de7b041a9a6a5091a3aa5898d66c0564be671d87db4f9d63b1b5ee775b097df", [:make, :rebar3], [], "hexpm", "6168ec49409d982f7cfbd83dd083144f6cbe67caa4036551d2f0a3ad67c9d023"},
|
||||
"req": {:hex, :req, "0.6.2", "b9b2024f35bcf60a92cc8cad2eaaf9d4e7aace463ff74be1afe5986830184413", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "cc9cd30a2ddd04989929b887178e1610c940456d962c6c3a52df6146d2eef9bf"},
|
||||
"phoenix_html": {:hex, :phoenix_html, "4.4.0", "d4007bc52fee85af48c30a0d541a5b0590e4f1f12f2f9c227bb004620090c0e3", [:mix], [], "hexpm", "94832038da7ab8f86d4c0d36f7797a269fd06fe611f25c69f55108c075505228"},
|
||||
"phoenix_live_dashboard": {:hex, :phoenix_live_dashboard, "0.9.1", "d4786b24bbe1eacc431049dbbb8d377f5359fce57b9d7cdd773bba4ac0af2ef6", [:mix], [{:ecto, "~> 3.6.2 or ~> 3.7", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_mysql_extras, "~> 0.5", [hex: :ecto_mysql_extras, repo: "hexpm", optional: true]}, {:ecto_psql_extras, "~> 0.7", [hex: :ecto_psql_extras, repo: "hexpm", optional: true]}, {:ecto_sqlite3_extras, "~> 1.1.7 or ~> 1.2.0", [hex: :ecto_sqlite3_extras, repo: "hexpm", optional: true]}, {:mime, "~> 1.6 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 1.0", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6 or ~> 1.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "de25e1a28cfb64413d8bdaf3ba5b64da1a19e0ed44a02320119523cc45da051d"},
|
||||
"phoenix_live_reload": {:hex, :phoenix_live_reload, "1.7.0", "fb1e429f6d8778ce3a6962debdc5e555428a05a6e7b058d6dbad13d281a2c31f", [:mix], [{:file_system, "~> 0.2.10 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "dc9f44271aa6fc4ab7797f2aa374ba096ef2c87520586280eb095626b7387a68"},
|
||||
"phoenix_live_view": {:hex, :phoenix_live_view, "1.2.13", "850284c529f013e82d9596325bd92cb5859c0872176616b6e2ec4294e2ef616e", [:mix], [{:igniter, ">= 0.6.16 and < 1.0.0-0", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:lazy_html, "~> 0.1.0", [hex: :lazy_html, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.15 or ~> 1.7.0 or ~> 1.8.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.3 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a5cd2a3df10552bce6b7e68e5d376ff3b46cca3ca62d6c43bd4398d80c197fbe"},
|
||||
"phoenix_pubsub": {:hex, :phoenix_pubsub, "2.4.1", "2ff3e7ba8b432120989870997b9adaefb76e1f63805554ab0b9e948987981f4b", [:mix], [], "hexpm", "352fba7a87bf61395b6e97da66944ad9b1bfe5459e5981039f60d68270bd9700"},
|
||||
"phoenix_template": {:hex, :phoenix_template, "1.1.0", "b329582281b1e00e4dc664afd60ef5b489cbb356923caa3b1e00abe8651b9a18", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "eba70070de79b2c3501ef205a74a69f98ab352f3785aa15da9ed161f9fe0fd5d"},
|
||||
"plug": {:hex, :plug, "1.20.3", "56c480c633ec2ce10140e236e15233bf576e1d323887d7c96711bd02ab5160db", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "be266aee1b8536ef6409d58cf39a3121319f0ec47cfa1b24024485aa0e76ad76"},
|
||||
"plug_crypto": {:hex, :plug_crypto, "2.2.1", "bd1d0358a2e2f5ffb818217e64c394f9d24ed191d862b7fa1bcce264ace2b8ea", [:mix], [], "hexpm", "4417ccbd8f85e627321cd07d2ab9c4b621f1fd883b9905af241f9b4b780b94b6"},
|
||||
"postgrex": {:hex, :postgrex, "0.22.4", "d271f595dfd25230b6398354e19d17bb5e2d20130fd2d9bdca7e15f125d43552", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "4aae45a2d60e35b04eea2602440be152fae332901f1fc7a60fc7cb7f0f9a9c5a"},
|
||||
"ranch": {:hex, :ranch, "2.4.0", "1552c523119cfb8dda7f171f02f664805ab08d89d2a18adfa8992676184d767a", [:make, :rebar3], [], "hexpm", "64d98b8c61d39b7b9a2e2cf92ae659b8623a69766f415ae13dc726864ec04ab9"},
|
||||
"req": {:hex, :req, "0.7.5", "0c3293cbf7717aba20b1b1b3ea13fe8d3fdf6f1557490f390c3f1ef6dd9db955", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "576853c4bf403faa3c1fa5d093e0759227083b78f8a6864c67d62c0a9c45514d"},
|
||||
"rustler": {:hex, :rustler, "0.38.0", "7a8906998ff0d28e3021c0a73264abcda719bda344b2e58307c6805b0f87c9b4", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "704c03c1bf66be12b031c5a389347b91c81c5cb819a24b068b0de36fe4a5652a"},
|
||||
"swoosh": {:hex, :swoosh, "1.26.1", "2989f1089e3cf1a938bbd3908c11d7dba8c8a4fe78801a7762d26f01bdbb32b4", [:mix], [{:bandit, ">= 1.0.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, ">= 1.9.0 and < 5.0.0", [hex: :hackney, repo: "hexpm", optional: true]}, {:idna, ">= 6.0.0 and < 8.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mua, "~> 0.2.3", [hex: :mua, repo: "hexpm", optional: true]}, {:multipart, "~> 0.4", [hex: :multipart, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:req, "~> 0.5.10 or ~> 0.6 or ~> 1.0", [hex: :req, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "8ad197c025102bbcbaffcd67c10ff7b390746c32f534ff5158891b149460118e"},
|
||||
"tailwind": {:hex, :tailwind, "0.5.1", "35435b13158c90d37da11e1cfc808755fca1d7b6c5ab87b1b19c5de87e2f0a10", [:mix], [], "hexpm", "c4e26302a59fec72abc5610ecb6ad2116d9aa31f31aab2d4b8eb6e95d25a689c"},
|
||||
"swoosh": {:hex, :swoosh, "1.29.3", "17a7177e9d4f590f9354ea5950e75122e07a93b3f10535ca4c1a130850865916", [:mix], [{:bandit, ">= 1.0.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, ">= 1.9.0 and < 5.0.0", [hex: :hackney, repo: "hexpm", optional: true]}, {:idna, ">= 6.0.0 and < 8.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mua, "~> 0.2.3", [hex: :mua, repo: "hexpm", optional: true]}, {:multipart, "~> 0.4", [hex: :multipart, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:req, "~> 0.5.10 or ~> 0.6 or ~> 1.0", [hex: :req, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "844719cc70ba28b1c042461ddafbbd5088c485ccd89aa84ef5bfc65b84345d20"},
|
||||
"tailwind": {:hex, :tailwind, "0.5.2", "d8bc230361fd3e14b495043c364aefddfac2ad4bf2eada380f458e9a15cb2e20", [:mix], [], "hexpm", "e0e5fd9799fb9231b97e52ce074d9ff509043d1946713a71fbc608e81eff7e66"},
|
||||
"telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
|
||||
"telemetry_metrics": {:hex, :telemetry_metrics, "1.1.0", "5bd5f3b5637e0abea0426b947e3ce5dd304f8b3bc6617039e2b5a008adc02f8f", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e7b79e8ddfde70adb6db8a6623d1778ec66401f366e9a8f5dd0955c56bc8ce67"},
|
||||
"telemetry_metrics": {:hex, :telemetry_metrics, "1.2.0", "7632c19c01d88d8aaca5da1a0e8912f5af39b79e7c08a2c253aeb3c14c2c957e", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "71dde12fc29b58b9c77ec17ec319109e5ca848d010fc1965ed4463bba1837c07"},
|
||||
"telemetry_poller": {:hex, :telemetry_poller, "1.3.0", "d5c46420126b5ac2d72bc6580fb4f537d35e851cc0f8dbd571acf6d6e10f5ec7", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "51f18bed7128544a50f75897db9974436ea9bfba560420b646af27a9a9b35211"},
|
||||
"thousand_island": {:hex, :thousand_island, "1.5.0", "f50a213cac97262b6d5ebb85745aa2c00fec1413191e6e66834788d45425cecb", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "708923d40523e43cf99041ab37a0d4b0ec426ac6438fa3716ab23d919eaeb412"},
|
||||
"thousand_island": {:hex, :thousand_island, "1.6.0", "d6ad7c2220c96a270cc8ca1586ec4d8bde648a4a3a53f003ce093f41beec0288", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4d4720470f091fc21a1311777c2ac66916c43621bffc068590c9f9bb3cd057a3"},
|
||||
"websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"},
|
||||
"websock_adapter": {:hex, :websock_adapter, "0.5.9", "43dc3ba6d89ef5dec5b1d0a39698436a1e856d000d84bf31a3149862b01a287f", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "5534d5c9adad3c18a0f58a9371220d75a803bf0b9a3d87e6fe072faaeed76a08"},
|
||||
"websock_adapter": {:hex, :websock_adapter, "0.7.2", "2a70852d206daa9e75669030e9be9622f8919ff1e558665b9844413f4f9b4d84", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:roadrunner_plug, ">= 0.1.0", [hex: :roadrunner_plug, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "f9e80710008783864177c81e9d8418d05769ce10a26e9e538f5ed72e283f7358"},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
defmodule Chesstrainer.Repo.Migrations.ThemeProvenanceKindsAndCoverage do
|
||||
use Ecto.Migration
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
def up do
|
||||
alter table(:themes) do
|
||||
add :slug, :string
|
||||
add :description, :string
|
||||
add :kind, :string, null: false, default: "technique"
|
||||
end
|
||||
|
||||
alter table(:endgames_themes) do
|
||||
add :source, :string, null: false, default: "curated"
|
||||
add :inserted_at, :utc_datetime, null: false, default: fragment("now()")
|
||||
end
|
||||
|
||||
flush()
|
||||
|
||||
backfill_slugs()
|
||||
|
||||
alter table(:themes) do
|
||||
modify :slug, :string, null: false
|
||||
end
|
||||
|
||||
create unique_index(:themes, [:slug])
|
||||
|
||||
create constraint(:themes, :kind_in_allowed,
|
||||
check: "kind in ('material', 'motif', 'technique')"
|
||||
)
|
||||
|
||||
create constraint(:endgames_themes, :source_in_allowed,
|
||||
check: "source in ('derived', 'curated', 'community')"
|
||||
)
|
||||
end
|
||||
|
||||
def down do
|
||||
drop constraint(:endgames_themes, :source_in_allowed)
|
||||
drop constraint(:themes, :kind_in_allowed)
|
||||
drop unique_index(:themes, [:slug])
|
||||
|
||||
alter table(:endgames_themes) do
|
||||
remove :inserted_at
|
||||
remove :source
|
||||
end
|
||||
|
||||
alter table(:themes) do
|
||||
remove :kind
|
||||
remove :description
|
||||
remove :slug
|
||||
end
|
||||
end
|
||||
|
||||
# Themes were created without a slug, so every existing row needs one before
|
||||
# the column can become mandatory. Names are unique per category but not
|
||||
# globally, so collisions get a numeric suffix.
|
||||
defp backfill_slugs do
|
||||
themes = repo().all(from(t in "themes", select: {t.id, t.name}))
|
||||
|
||||
Enum.reduce(themes, MapSet.new(), fn {id, name}, used ->
|
||||
slug = unique_slug(slugify(name), used)
|
||||
repo().update_all(from(t in "themes", where: t.id == ^id), set: [slug: slug])
|
||||
MapSet.put(used, slug)
|
||||
end)
|
||||
end
|
||||
|
||||
defp unique_slug(base, used) do
|
||||
if MapSet.member?(used, base) do
|
||||
Enum.find_value(2..1_000, base, fn suffix ->
|
||||
candidate = "#{base}-#{suffix}"
|
||||
if MapSet.member?(used, candidate), do: nil, else: candidate
|
||||
end)
|
||||
else
|
||||
base
|
||||
end
|
||||
end
|
||||
|
||||
defp slugify(name) do
|
||||
slug =
|
||||
name
|
||||
|> to_string()
|
||||
|> :unicode.characters_to_nfd_binary()
|
||||
|> String.replace(~r/[\x{0300}-\x{036F}]/u, "")
|
||||
|> String.downcase()
|
||||
|> String.replace(~r/[^a-z0-9]+/u, "-")
|
||||
|> String.trim("-")
|
||||
|
||||
if slug == "", do: "theme", else: slug
|
||||
end
|
||||
end
|
||||
@@ -59,7 +59,14 @@ theme_names =
|
||||
Repo.insert_all(
|
||||
Theme,
|
||||
Enum.map(theme_names, fn name ->
|
||||
%{name: name, category: :endgame, inserted_at: now, updated_at: now}
|
||||
%{
|
||||
name: name,
|
||||
slug: Theme.slugify(name),
|
||||
kind: :technique,
|
||||
category: :endgame,
|
||||
inserted_at: now,
|
||||
updated_at: now
|
||||
}
|
||||
end),
|
||||
on_conflict: :nothing
|
||||
)
|
||||
|
||||
@@ -6,8 +6,7 @@ defmodule Chesstrainer.Repo.Seeds.Endgames.Win do
|
||||
color: :white,
|
||||
message: "Rook vs king endgame",
|
||||
notes: "Basic rook endgame",
|
||||
result: :win,
|
||||
themes: ["rook endgame"]
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
||||
|
||||
@@ -8,6 +8,10 @@ defmodule Chesstrainer.Repo.Seeds.Themes do
|
||||
"Lucena",
|
||||
"Philidor",
|
||||
"opposition",
|
||||
"key squares",
|
||||
"triangulation",
|
||||
"shouldering",
|
||||
"king activity",
|
||||
"promotion",
|
||||
"stalemate"
|
||||
]
|
||||
|
||||
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 781 B |
|
After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 152 B After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<circle cx="32" cy="32" r="32" fill="#17352d"/>
|
||||
<path fill="#f4f0e6" d="M28.75 19.15Q29.69 18.56 29.69 17.57Q29.69 16.94 29.31 16.21Q28.93 15.49 28.93 14.93Q28.93 13.76 30.4 13Q32.56 15.06 32.75 16.19Q32.94 17.32 32.94 17.65Q32.94 18.84 32.08 19.15H32.18Q32.18 19.17 32.13 19.17Q45.74 27.81 46.89 51H22.25Q21.92 49.58 21.92 48.1Q21.92 44.04 27.06 40.45Q32.2 36.85 32.2 33.98Q32.2 33.78 32.18 33.6Q30.5 37.84 27.53 37.84H27.28Q24.99 41.55 22.37 41.55Q22.27 41.55 22.2 41.55L23.41 38.91L20.7 40.94Q17.8 40.23 17.11 38.12Q19.35 32.3 19.35 27.48Q19.35 26.79 19.3 26.13Q20.52 23.36 23.03 20.72Q23.11 20.47 23.11 20.24Q23.11 19.53 22.54 19.2Q21.97 18.87 21.97 17.98Q21.97 17.04 22.47 15.36Q25.12 16.05 26.54 19.15ZM22.22 25.62V26.03Q22.32 26.79 22.53 26.79H23.06Q24.81 26.79 24.81 25.55Q24.81 24.68 25.9 23.47H25.75Q23.31 23.47 22.37 25.09ZM19.45 37.05V37.66Q19.45 38.4 20.16 38.4H20.42Q22.25 38.02 22.25 36.67L22.07 35.81Q20.49 35.81 19.45 37.05ZM32.1 21.18 33.42 23.44Q42.95 30.27 43.1 49.68H45.06Q43.91 28.09 32.1 21.18Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -1,6 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 71 48" fill="currentColor" aria-hidden="true">
|
||||
<path
|
||||
d="m26.371 33.477-.552-.1c-3.92-.729-6.397-3.1-7.57-6.829-.733-2.324.597-4.035 3.035-4.148 1.995-.092 3.362 1.055 4.57 2.39 1.557 1.72 2.984 3.558 4.514 5.305 2.202 2.515 4.797 4.134 8.347 3.634 3.183-.448 5.958-1.725 8.371-3.828.363-.316.761-.592 1.144-.886l-.241-.284c-2.027.63-4.093.841-6.205.735-3.195-.16-6.24-.828-8.964-2.582-2.486-1.601-4.319-3.746-5.19-6.611-.704-2.315.736-3.934 3.135-3.6.948.133 1.746.56 2.463 1.165.583.493 1.143 1.015 1.738 1.493 2.8 2.25 6.712 2.375 10.265-.068-5.842-.026-9.817-3.24-13.308-7.313-1.366-1.594-2.7-3.216-4.095-4.785-2.698-3.036-5.692-5.71-9.79-6.623C12.8-.623 7.745.14 2.893 2.361 1.926 2.804.997 3.319 0 4.149c.494 0 .763.006 1.032 0 2.446-.064 4.28 1.023 5.602 3.024.962 1.457 1.415 3.104 1.761 4.798.513 2.515.247 5.078.544 7.605.761 6.494 4.08 11.026 10.26 13.346 2.267.852 4.591 1.135 7.172.555ZM10.751 3.852c-.976.246-1.756-.148-2.56-.962 1.377-.343 2.592-.476 3.897-.528-.107.848-.607 1.306-1.336 1.49Zm32.002 37.924c-.085-.626-.62-.901-1.04-1.228-1.857-1.446-4.03-1.958-6.333-2-1.375-.026-2.735-.128-4.031-.61-.595-.22-1.26-.505-1.244-1.272.015-.78.693-1 1.31-1.184.505-.15 1.026-.247 1.6-.382-1.46-.936-2.886-1.065-4.787-.3-2.993 1.202-5.943 1.06-8.926-.017-1.684-.608-3.179-1.563-4.735-2.408l-.077.057c1.29 2.115 3.034 3.817 5.004 5.271 3.793 2.8 7.936 4.471 12.784 3.73A66.714 66.714 0 0 1 37 40.877c1.98-.16 3.866.398 5.753.899Zm-9.14-30.345c-.105-.076-.206-.266-.42-.069 1.745 2.36 3.985 4.098 6.683 5.193 4.354 1.767 8.773 2.07 13.293.51 3.51-1.21 6.033-.028 7.343 3.38.19-3.955-2.137-6.837-5.843-7.401-2.084-.318-4.01.373-5.962.94-5.434 1.575-10.485.798-15.094-2.553Zm27.085 15.425c.708.059 1.416.123 2.124.185-1.6-1.405-3.55-1.517-5.523-1.404-3.003.17-5.167 1.903-7.14 3.972-1.739 1.824-3.31 3.87-5.903 4.604.043.078.054.117.066.117.35.005.699.021 1.047.005 3.768-.17 7.317-.965 10.14-3.7.89-.86 1.685-1.817 2.544-2.71.716-.746 1.584-1.159 2.645-1.07Zm-8.753-4.67c-2.812.246-5.254 1.409-7.548 2.943-1.766 1.18-3.654 1.738-5.776 1.37-.374-.066-.75-.114-1.124-.17l-.013.156c.135.07.265.151.405.207.354.14.702.308 1.07.395 4.083.971 7.992.474 11.516-1.803 2.221-1.435 4.521-1.707 7.013-1.336.252.038.503.083.756.107.234.022.479.255.795.003-2.179-1.574-4.526-2.096-7.094-1.872Zm-10.049-9.544c1.475.051 2.943-.142 4.486-1.059-.452.04-.643.04-.827.076-2.126.424-4.033-.04-5.733-1.383-.623-.493-1.257-.974-1.889-1.457-2.503-1.914-5.374-2.555-8.514-2.5.05.154.054.26.108.315 3.417 3.455 7.371 5.836 12.369 6.008Zm24.727 17.731c-2.114-2.097-4.952-2.367-7.578-.537 1.738.078 3.043.632 4.101 1.728a13 13 0 0 0 1.182 1.106c1.6 1.29 4.311 1.352 5.896.155-1.861-.726-1.861-.726-3.601-2.452Zm-21.058 16.06c-1.858-3.46-4.981-4.24-8.59-4.008a9.667 9.667 0 0 1 2.977 1.39c.84.586 1.547 1.311 2.243 2.055 1.38 1.473 3.534 2.376 4.962 2.07-.656-.412-1.238-.848-1.592-1.507Zl-.006.006-.036-.004.021.018.012.053Za.127.127 0 0 0 .015.043c.005.008.038 0 .058-.002Zl-.008.01.005.026.024.014Z"
|
||||
fill="#FD4F00"
|
||||
/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Inner Square Chess",
|
||||
"short_name": "Inner Square",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#f4f0e6",
|
||||
"theme_color": "#17352d",
|
||||
"icons": [
|
||||
{ "src": "/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
|
||||
{ "src": "/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
defmodule Chesstrainer.AccountsAdminTest do
|
||||
use Chesstrainer.DataCase, async: false
|
||||
|
||||
require Logger
|
||||
|
||||
import Chesstrainer.AccountsFixtures
|
||||
import ExUnit.CaptureLog
|
||||
import Swoosh.TestAssertions
|
||||
|
||||
@@ -276,6 +276,21 @@ defmodule Chesstrainer.AccountsTest do
|
||||
end
|
||||
end
|
||||
|
||||
describe "update_user_plan/2" do
|
||||
test "changes the user's plan" do
|
||||
user = user_fixture()
|
||||
|
||||
assert {:ok, %User{plan: :premium}} = Accounts.update_user_plan(user, :premium)
|
||||
end
|
||||
|
||||
test "rejects a plan that is not in the enum" do
|
||||
user = user_fixture()
|
||||
|
||||
assert {:error, changeset} = Accounts.update_user_plan(user, :platinum)
|
||||
assert %{plan: ["is invalid"]} = errors_on(changeset)
|
||||
end
|
||||
end
|
||||
|
||||
describe "sudo_mode?/2" do
|
||||
test "validates the authenticated_at time" do
|
||||
now = DateTime.utc_now()
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
defmodule Chesstrainer.BrandingTest do
|
||||
use ExUnit.Case, async: false
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
|
||||
describe "discord_invite_url/0" do
|
||||
setup do
|
||||
previous = Application.get_env(:chesstrainer, :branding)
|
||||
on_exit(fn -> restore(:branding, previous) end)
|
||||
:ok
|
||||
end
|
||||
|
||||
test "passes a full URL through" do
|
||||
put_branding(discord_invite: "https://discord.gg/abc123")
|
||||
|
||||
assert Branding.discord_invite_url() == "https://discord.gg/abc123"
|
||||
end
|
||||
|
||||
test "expands a bare invite code" do
|
||||
put_branding(discord_invite: " abc123 ")
|
||||
|
||||
assert Branding.discord_invite_url() == "https://discord.gg/abc123"
|
||||
end
|
||||
|
||||
test "returns nil when the invite is blank" do
|
||||
put_branding(discord_invite: "")
|
||||
|
||||
assert Branding.discord_invite_url() == nil
|
||||
end
|
||||
end
|
||||
|
||||
defp put_branding(overrides) do
|
||||
config = Application.get_env(:chesstrainer, :branding, [])
|
||||
Application.put_env(:chesstrainer, :branding, Keyword.merge(config, overrides))
|
||||
end
|
||||
|
||||
defp restore(key, nil), do: Application.delete_env(:chesstrainer, key)
|
||||
defp restore(key, value), do: Application.put_env(:chesstrainer, key, value)
|
||||
end
|
||||
@@ -0,0 +1,173 @@
|
||||
defmodule Chesstrainer.Endgames.MaterialThemesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.MaterialThemes
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@kr_v_k "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||
@kp_v_k "8/8/3k4/8/8/3KP3/8/8 w - - 0 1"
|
||||
@kbn_v_k "8/8/3k4/8/8/3KBN2/8/8 w - - 0 1"
|
||||
@krp_v_k "8/8/3k4/8/8/3KR2P/8/8 w - - 0 1"
|
||||
@kp_v_kp "4k3/8/8/8/8/4p3/4P3/4K3 w - - 0 1"
|
||||
@kq_v_kp "8/8/3k4/8/8/3K1Q1p/8/8 w - - 0 1"
|
||||
@kq_v_kq "3q4/8/3k4/8/8/3K1Q2/8/8 w - - 0 1"
|
||||
@kn_v_kp "8/8/3k4/8/8/3KN2p/8/8 w - - 0 1"
|
||||
@kb_v_kb "8/8/3k1b2/8/8/3K1B2/8/8 w - - 0 1"
|
||||
@krp_v_kr "8/8/3k4/8/8/3KR2P/8/5r2 w - - 0 1"
|
||||
@kr_v_kr "8/8/3k4/8/8/3K1R2/8/5r2 b - - 0 1"
|
||||
@k_v_k "8/8/3k4/8/8/3K4/8/8 w - - 0 1"
|
||||
|
||||
describe "family/1" do
|
||||
test "classifies a lone king against heavy or pawn material" do
|
||||
assert MaterialThemes.family("KQ v K") == :basic_mate
|
||||
assert MaterialThemes.family("KR v K") == :basic_mate
|
||||
assert MaterialThemes.family("KP v K") == :king_and_pawn
|
||||
assert MaterialThemes.family("KPP v K") == :king_and_pawn
|
||||
assert MaterialThemes.family("KBN v K") == :bare_king_other
|
||||
assert MaterialThemes.family("KRP v K") == :bare_king_other
|
||||
end
|
||||
|
||||
test "classifies material presence into one family" do
|
||||
assert MaterialThemes.family("KP v KP") == :pawn_endgame
|
||||
assert MaterialThemes.family("KQ v KP") == :queen_and_pawn
|
||||
assert MaterialThemes.family("KQ v KQ") == :queen_endgame
|
||||
assert MaterialThemes.family("KRP v KR") == :rook_and_pawn
|
||||
assert MaterialThemes.family("KR v KR") == :rook_endgame
|
||||
assert MaterialThemes.family("KN v KP") == :minor_piece_and_pawn
|
||||
assert MaterialThemes.family("KB v KB") == :minor_piece_endgame
|
||||
end
|
||||
|
||||
test "flags content-free and malformed keys" do
|
||||
assert MaterialThemes.family("K v K") == :kings_only
|
||||
assert MaterialThemes.family(nil) == :unknown
|
||||
assert MaterialThemes.family("not a key") == :unknown
|
||||
end
|
||||
end
|
||||
|
||||
describe "derive/0" do
|
||||
test "creates every material family as a material theme" do
|
||||
MaterialThemes.derive()
|
||||
|
||||
themes = Themes.list_themes()
|
||||
|
||||
assert length(themes) == length(MaterialThemes.families())
|
||||
assert Enum.all?(themes, &(&1.kind == :material))
|
||||
assert Enum.all?(themes, &(&1.description not in [nil, ""]))
|
||||
end
|
||||
|
||||
test "tags every endgame with exactly one family" do
|
||||
pawn = create_endgame!(@kp_v_kp)
|
||||
rook = create_endgame!(@kr_v_kr)
|
||||
rook_and_pawn = create_endgame!(@krp_v_kr)
|
||||
queen_and_pawn = create_endgame!(@kq_v_kp)
|
||||
queen = create_endgame!(@kq_v_kq)
|
||||
minor_and_pawn = create_endgame!(@kn_v_kp)
|
||||
minor = create_endgame!(@kb_v_kb)
|
||||
mate = create_endgame!(@kr_v_k)
|
||||
promotion = create_endgame!(@kp_v_k)
|
||||
bare_minor = create_endgame!(@kbn_v_k)
|
||||
bare_other = create_endgame!(@krp_v_k)
|
||||
kings_only = create_endgame!(@k_v_k)
|
||||
|
||||
assert %{tagged: 11, skipped: 1} = MaterialThemes.derive()
|
||||
|
||||
assert ["pawn endgame"] = theme_names(pawn)
|
||||
assert ["rook endgame"] = theme_names(rook)
|
||||
assert ["rook and pawn"] = theme_names(rook_and_pawn)
|
||||
assert ["queen and pawn"] = theme_names(queen_and_pawn)
|
||||
assert ["queen endgame"] = theme_names(queen)
|
||||
assert ["minor piece and pawn"] = theme_names(minor_and_pawn)
|
||||
assert ["minor piece endgame"] = theme_names(minor)
|
||||
assert ["basic mate"] = theme_names(mate)
|
||||
assert ["king and pawn"] = theme_names(promotion)
|
||||
assert ["bare king other"] = theme_names(bare_minor)
|
||||
assert ["bare king other"] = theme_names(bare_other)
|
||||
assert [] = theme_names(kings_only)
|
||||
end
|
||||
|
||||
test "corrects an existing technique theme and claims its links as derived" do
|
||||
{:ok, existing} = Themes.create_theme(%{name: "rook endgame", category: :endgame})
|
||||
endgame = create_endgame!(@kr_v_kr, [existing])
|
||||
|
||||
MaterialThemes.derive()
|
||||
|
||||
theme = Themes.get_theme!(existing.id)
|
||||
assert theme.kind == :material
|
||||
assert theme.description =~ "Rooks"
|
||||
|
||||
assert [{theme_id, "derived"}] = link_rows(endgame.id)
|
||||
assert theme_id == existing.id
|
||||
end
|
||||
|
||||
test "removes a curated link to a material theme that contradicts the family" do
|
||||
{:ok, rook} = Themes.create_theme(%{name: "rook endgame", category: :endgame})
|
||||
mate = create_endgame!(@kr_v_k, [rook])
|
||||
|
||||
MaterialThemes.derive()
|
||||
|
||||
assert ["basic mate"] = theme_names(mate)
|
||||
end
|
||||
|
||||
test "is idempotent" do
|
||||
endgame = create_endgame!(@kq_v_kp)
|
||||
|
||||
MaterialThemes.derive()
|
||||
first = link_rows(endgame.id)
|
||||
MaterialThemes.derive()
|
||||
|
||||
assert link_rows(endgame.id) == first
|
||||
assert length(first) == 1
|
||||
end
|
||||
|
||||
test "leaves curated and community links to other themes alone" do
|
||||
{:ok, lucena} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
endgame = create_endgame!(@kr_v_kr)
|
||||
insert_link(endgame.id, lucena.id, "community")
|
||||
|
||||
MaterialThemes.derive()
|
||||
|
||||
rows = link_rows(endgame.id)
|
||||
assert {lucena.id, "community"} in rows
|
||||
assert length(rows) == 2
|
||||
end
|
||||
end
|
||||
|
||||
defp create_endgame!(fen, themes \\ []) do
|
||||
{:ok, endgame} =
|
||||
Endgames.create_endgame(%{fen: fen, color: :white, result: :win, rating: 1500}, themes)
|
||||
|
||||
endgame
|
||||
end
|
||||
|
||||
defp theme_names(endgame) do
|
||||
endgame
|
||||
|> Map.fetch!(:id)
|
||||
|> link_rows()
|
||||
|> Enum.map(fn {theme_id, _source} -> Themes.get_theme!(theme_id).name end)
|
||||
|> Enum.sort()
|
||||
end
|
||||
|
||||
defp link_rows(endgame_id) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id),
|
||||
select: {l.theme_id, l.source},
|
||||
order_by: l.theme_id
|
||||
)
|
||||
end
|
||||
|
||||
defp insert_link(endgame_id, theme_id, source) do
|
||||
Repo.insert_all("endgames_themes", [
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: source,
|
||||
inserted_at: DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
}
|
||||
])
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,170 @@
|
||||
defmodule Chesstrainer.Endgames.MotifThemesTest.Stub do
|
||||
@moduledoc false
|
||||
|
||||
def probe_local_detail(fen), do: Map.fetch!(Process.get(:motif_stub), fen)
|
||||
end
|
||||
|
||||
defmodule Chesstrainer.Endgames.MotifThemesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.MotifThemes
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
setup do
|
||||
previous = Application.get_env(:chesstrainer, :motif_probe)
|
||||
Application.put_env(:chesstrainer, :motif_probe, __MODULE__.Stub)
|
||||
|
||||
on_exit(fn ->
|
||||
if previous,
|
||||
do: Application.put_env(:chesstrainer, :motif_probe, previous),
|
||||
else: Application.delete_env(:chesstrainer, :motif_probe)
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
describe "motifs_for/4" do
|
||||
test "detects an only move for wins and draws" do
|
||||
assert [:only_move] = MotifThemes.motifs_for(:win, 5, [move(:win), move(:draw)], 0)
|
||||
|
||||
assert [:only_move] =
|
||||
MotifThemes.motifs_for(:draw, 5, [move(:draw), move(:loss), move(:loss)], 0)
|
||||
end
|
||||
|
||||
test "does not report an only move when several moves preserve the result" do
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:win), move(:win)], 0)
|
||||
end
|
||||
|
||||
test "does not report an only move for a forced single move or a lost position" do
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:win)], 0)
|
||||
assert [] = MotifThemes.motifs_for(:loss, 5, [move(:loss), move(:loss)], 0)
|
||||
end
|
||||
|
||||
test "requires an underpromotion while no queen promotion preserves the result" do
|
||||
assert [:underpromotion] =
|
||||
MotifThemes.motifs_for(:win, 5, [move(:win, 4), move(:win), move(:draw, 1)], 0)
|
||||
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:win, 4), move(:win, 1)], 0)
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:draw, 4), move(:win), move(:win)], 0)
|
||||
end
|
||||
|
||||
test "detects the 50-move rule from the raw WDL" do
|
||||
assert [:fifty_move_draw] =
|
||||
MotifThemes.motifs_for(:cursed_win, 120, [move(:cursed_win)], 0)
|
||||
|
||||
assert [:fifty_move_draw] =
|
||||
MotifThemes.motifs_for(:blessed_loss, 120, [move(:blessed_loss)], 0)
|
||||
end
|
||||
|
||||
test "detects the 50-move rule when the clock runs out before the next zeroing move" do
|
||||
assert [:fifty_move_draw] = MotifThemes.motifs_for(:win, 60, [move(:win)], 50)
|
||||
assert [] = MotifThemes.motifs_for(:win, 40, [move(:win)], 50)
|
||||
assert [] = MotifThemes.motifs_for(:win, 100, [move(:win)], 0)
|
||||
end
|
||||
|
||||
test "a position can carry several motifs" do
|
||||
assert [:underpromotion, :only_move] =
|
||||
MotifThemes.motifs_for(:win, 5, [move(:win, 4), move(:draw)], 0)
|
||||
end
|
||||
end
|
||||
|
||||
describe "derive/0" do
|
||||
@win_fen "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||
@draw_fen "4k3/8/8/8/8/4p3/4P3/4K3 w - - 0 1"
|
||||
@loss_fen "8/8/3k4/8/8/3K4/8/6q1 w - - 0 1"
|
||||
|
||||
test "links the motifs reported for each endgame and skips losses" do
|
||||
win = create_endgame!(@win_fen, :win)
|
||||
draw = create_endgame!(@draw_fen, :draw)
|
||||
loss = create_endgame!(@loss_fen, :loss)
|
||||
|
||||
stub(%{
|
||||
win.fen => {:ok, %{wdl: :win, dtz: 5, moves: [move(:win), move(:draw)]}},
|
||||
draw.fen => {:ok, %{wdl: :cursed_win, dtz: 120, moves: [move(:cursed_win)]}}
|
||||
})
|
||||
|
||||
assert %{links: 2, skipped: 0, themes: 3} = MotifThemes.derive()
|
||||
|
||||
assert theme_names(win) == ["only move"]
|
||||
assert theme_names(draw) == ["50-move draw"]
|
||||
assert theme_names(loss) == []
|
||||
|
||||
assert Enum.all?(Themes.list_themes(), &(&1.kind == :motif))
|
||||
assert Enum.all?(Themes.list_themes(), &(&1.description not in [nil, ""]))
|
||||
end
|
||||
|
||||
test "reports endgames the local tables cannot answer" do
|
||||
endgame = create_endgame!(@win_fen, :win)
|
||||
stub(%{endgame.fen => {:error, :unsupported}})
|
||||
|
||||
assert %{links: 0, skipped: 1} = MotifThemes.derive()
|
||||
assert theme_names(endgame) == []
|
||||
end
|
||||
|
||||
test "is idempotent and leaves material, curated and community links alone" do
|
||||
win = create_endgame!(@win_fen, :win)
|
||||
stub(%{win.fen => {:ok, %{wdl: :win, dtz: 5, moves: [move(:win), move(:draw)]}}})
|
||||
|
||||
{:ok, lucena} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
|
||||
{:ok, rook_endgame} =
|
||||
Themes.create_theme(%{name: "rook endgame", kind: :material, category: :endgame})
|
||||
|
||||
{:ok, _} = Themes.tag_endgames(lucena, [win.id], :curated)
|
||||
:ok = Themes.sync_derived_themes(win.id, [rook_endgame.id])
|
||||
|
||||
MotifThemes.derive()
|
||||
first = link_rows(win.id)
|
||||
MotifThemes.derive()
|
||||
|
||||
assert link_rows(win.id) == first
|
||||
assert {lucena.id, "curated"} in first
|
||||
assert {rook_endgame.id, "derived"} in first
|
||||
assert length(first) == 3
|
||||
end
|
||||
|
||||
test "corrects an existing technique theme into a motif theme" do
|
||||
{:ok, existing} = Themes.create_theme(%{name: "only move", category: :endgame})
|
||||
endgame = create_endgame!(@win_fen, :win)
|
||||
stub(%{endgame.fen => {:ok, %{wdl: :win, dtz: 5, moves: [move(:win), move(:draw)]}}})
|
||||
|
||||
MotifThemes.derive()
|
||||
|
||||
theme = Themes.get_theme!(existing.id)
|
||||
assert theme.kind == :motif
|
||||
assert theme.description =~ "Exactly one legal move"
|
||||
end
|
||||
end
|
||||
|
||||
defp stub(responses), do: Process.put(:motif_stub, responses)
|
||||
|
||||
defp move(wdl, promotes \\ 0, dtz \\ 0), do: {wdl, 0, 0, promotes, 0, dtz}
|
||||
|
||||
defp create_endgame!(fen, result) do
|
||||
{:ok, endgame} =
|
||||
Endgames.create_endgame(%{fen: fen, color: :white, result: result, rating: 1500})
|
||||
|
||||
endgame
|
||||
end
|
||||
|
||||
defp theme_names(endgame) do
|
||||
endgame
|
||||
|> Map.fetch!(:id)
|
||||
|> link_rows()
|
||||
|> Enum.map(fn {theme_id, _source} -> Themes.get_theme!(theme_id).name end)
|
||||
|> Enum.sort()
|
||||
end
|
||||
|
||||
defp link_rows(endgame_id) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id),
|
||||
select: {l.theme_id, l.source},
|
||||
order_by: l.theme_id
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -6,6 +6,11 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest.Stub do
|
||||
def probe(_fen), do: {:ok, %Tablebase{category: :draw, checkmate: false, moves: []}}
|
||||
end
|
||||
|
||||
defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest.ExplodingFallback do
|
||||
@moduledoc false
|
||||
def probe(_fen), do: raise("the remote tablebase must not be called")
|
||||
end
|
||||
|
||||
defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest do
|
||||
# Not async: the local backend reads app config and Fathom keeps global state.
|
||||
use ExUnit.Case, async: false
|
||||
@@ -18,6 +23,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest do
|
||||
|
||||
@krk "4k3/8/8/8/8/8/8/R3K3 w - - 0 1"
|
||||
@mate "7k/6Q1/5K2/8/8/8/8/8 b - - 0 1"
|
||||
@kpk "8/8/3k4/8/8/3KP3/8/8 w - - 0 1"
|
||||
|
||||
test "probes a KRvK position locally" do
|
||||
assert {:ok, %Tablebase{} = tablebase} = FathomBackend.probe(@krk)
|
||||
@@ -82,4 +88,37 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest do
|
||||
assert {:ok, %Tablebase{category: :draw}} = FathomBackend.probe(@krk)
|
||||
end
|
||||
end
|
||||
|
||||
describe "probe_local_detail/1" do
|
||||
test "returns the raw root WDL, DTZ and every legal move" do
|
||||
assert {:ok, %{wdl: :win, dtz: dtz, moves: moves}} =
|
||||
FathomBackend.probe_local_detail(@krk)
|
||||
|
||||
assert is_integer(dtz)
|
||||
assert length(moves) == 15
|
||||
assert Enum.all?(moves, &(elem(&1, 0) in [:win, :cursed_win, :draw, :blessed_loss, :loss]))
|
||||
end
|
||||
|
||||
test "returns terminal for a finished position" do
|
||||
assert {:error, :terminal} = FathomBackend.probe_local_detail(@mate)
|
||||
end
|
||||
|
||||
test "returns unsupported when the local files cannot answer the position" do
|
||||
assert {:error, :unsupported} = FathomBackend.probe_local_detail(@kpk)
|
||||
end
|
||||
|
||||
test "never calls the remote backend" do
|
||||
previous = Application.get_env(:chesstrainer, :tablebase_fallback)
|
||||
|
||||
on_exit(fn ->
|
||||
if previous,
|
||||
do: Application.put_env(:chesstrainer, :tablebase_fallback, previous),
|
||||
else: Application.delete_env(:chesstrainer, :tablebase_fallback)
|
||||
end)
|
||||
|
||||
Application.put_env(:chesstrainer, :tablebase_fallback, __MODULE__.ExplodingFallback)
|
||||
|
||||
assert {:error, :unsupported} = FathomBackend.probe_local_detail(@kpk)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
defmodule Chesstrainer.EndgamesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Chesstrainer.EndgamesFixtures
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Themes
|
||||
@@ -387,4 +389,30 @@ defmodule Chesstrainer.EndgamesTest do
|
||||
assert Endgames.curated_endgames() == []
|
||||
end
|
||||
end
|
||||
|
||||
describe "theme filters and pagination" do
|
||||
test "groups endgames by whether they carry a theme" do
|
||||
{:ok, theme} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
tagged = create_endgame!(@kr)
|
||||
create_endgame!(@kq)
|
||||
{:ok, _} = Endgames.update_endgame(tagged, %{}, [theme])
|
||||
|
||||
assert Endgames.list_key_groups(%{with_theme: {theme.id, :curated}}) == [{"KR v K", 1}]
|
||||
assert Endgames.list_key_groups(%{without_theme: theme.id}) == [{"KQ v K", 1}]
|
||||
end
|
||||
|
||||
test "paginates the endgames in one key group" do
|
||||
endgames = for _ <- 1..3, do: endgame_fixture()
|
||||
|
||||
first = Endgames.list_endgames_for_key("K v K", %{}, limit: 2, offset: 0)
|
||||
second = Endgames.list_endgames_for_key("K v K", %{}, limit: 2, offset: 2)
|
||||
|
||||
assert length(first) == 2
|
||||
assert length(second) == 1
|
||||
|
||||
ids = Enum.map(first ++ second, & &1.id)
|
||||
assert Enum.sort(ids) == Enum.sort(Enum.map(endgames, & &1.id))
|
||||
assert length(Enum.uniq(ids)) == 3
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -37,9 +37,21 @@ defmodule Chesstrainer.GuestLimitsTest do
|
||||
assert {:ok, 4} = GuestLimits.take(@other, @today)
|
||||
end
|
||||
|
||||
test "remaining reports the budget without consuming it" do
|
||||
assert {:ok, 5} = GuestLimits.remaining(@address, @today)
|
||||
assert {:ok, 5} = GuestLimits.remaining(@address, @today)
|
||||
|
||||
assert {:ok, 4} = GuestLimits.take(@address, @today)
|
||||
assert {:ok, 4} = GuestLimits.remaining(@address, @today)
|
||||
|
||||
for _ <- 1..4, do: assert({:ok, _} = GuestLimits.take(@address, @today))
|
||||
assert {:limit_reached, _} = GuestLimits.remaining(@address, @today)
|
||||
end
|
||||
|
||||
test "does not limit a missing address" do
|
||||
assert {:ok, nil} = GuestLimits.take(nil, @today)
|
||||
assert {:ok, nil} = GuestLimits.take(nil, @today)
|
||||
assert {:ok, nil} = GuestLimits.remaining(nil, @today)
|
||||
end
|
||||
|
||||
test "reset clears spent budgets" do
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
defmodule Chesstrainer.MailTest do
|
||||
use ExUnit.Case, async: false
|
||||
|
||||
import Swoosh.TestAssertions
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
setup do
|
||||
previous_redirect = Application.get_env(:chesstrainer, :mail_redirect_to)
|
||||
previous_set = Application.get_env(:chesstrainer, :ses_configuration_set)
|
||||
|
||||
on_exit(fn ->
|
||||
restore_env(:mail_redirect_to, previous_redirect)
|
||||
restore_env(:ses_configuration_set, previous_set)
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp simple_email(recipient \\ "player@example.com") do
|
||||
Swoosh.Email.new()
|
||||
|> Swoosh.Email.to(recipient)
|
||||
|> Swoosh.Email.subject("Confirmation instructions")
|
||||
|> Swoosh.Email.text_body("Hello")
|
||||
end
|
||||
|
||||
test "sends from the no-reply address on the mail subdomain" do
|
||||
{:ok, email} = Mail.deliver(simple_email())
|
||||
|
||||
assert email.from == {Branding.name(), "no-reply@mail.innersquare.app"}
|
||||
assert email.reply_to == {"", "support@innersquare.app"}
|
||||
end
|
||||
|
||||
test "stamps the SES configuration set on the provider options" do
|
||||
{:ok, email} = Mail.deliver(simple_email())
|
||||
|
||||
assert email.provider_options[:configuration_set_name] == "my-first-configuration-set"
|
||||
end
|
||||
|
||||
test "the configuration set can be overridden by config" do
|
||||
Application.put_env(:chesstrainer, :ses_configuration_set, "staging-set")
|
||||
|
||||
{:ok, email} = Mail.deliver(simple_email())
|
||||
|
||||
assert email.provider_options[:configuration_set_name] == "staging-set"
|
||||
end
|
||||
|
||||
test "redirects every recipient when a test address is configured" do
|
||||
Application.put_env(:chesstrainer, :mail_redirect_to, "ops@example.com")
|
||||
|
||||
email = simple_email("player@example.com")
|
||||
|
||||
{:ok, sent} = Mail.deliver(email)
|
||||
|
||||
assert sent.to == [{"", "ops@example.com"}]
|
||||
assert sent.bcc == []
|
||||
assert sent.cc == []
|
||||
assert sent.subject == "[→ player@example.com] Confirmation instructions"
|
||||
assert {"X-Original-To", "player@example.com"} in sent.headers
|
||||
end
|
||||
|
||||
test "delivers the message it returns" do
|
||||
{:ok, email} = Mail.deliver(simple_email())
|
||||
|
||||
assert_email_sent(to: "player@example.com", subject: "Confirmation instructions")
|
||||
assert email.to == [{"", "player@example.com"}]
|
||||
end
|
||||
|
||||
defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key)
|
||||
defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value)
|
||||
end
|
||||
@@ -7,6 +7,7 @@ defmodule Chesstrainer.PuzzlesTest do
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.Puzzles
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
# The shared `endgame_fixture/1` picks one of six FENs at random-ish, which
|
||||
# can collide when one test creates several endgames under async load. Pin
|
||||
@@ -22,71 +23,103 @@ defmodule Chesstrainer.PuzzlesTest do
|
||||
endgame_fixture(fen: Enum.fetch!(@fens, index), rating: rating)
|
||||
end
|
||||
|
||||
describe "difficulty_range/2" do
|
||||
test "is centred on the rating and open-ended at the extremes" do
|
||||
assert Puzzles.difficulty_range(1500, :medium) == {1400, 1600}
|
||||
assert Puzzles.difficulty_range(1500, :easy) == {nil, 1400}
|
||||
assert Puzzles.difficulty_range(1500, :hard) == {1600, nil}
|
||||
defp attempt_days_ago(user, endgame, days) do
|
||||
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||
|
||||
attempt
|
||||
|> Ecto.Changeset.change(
|
||||
inserted_at: DateTime.utc_now() |> DateTime.add(-days, :day) |> DateTime.truncate(:second)
|
||||
)
|
||||
|> Repo.update!()
|
||||
end
|
||||
|
||||
describe "difficulty_target/2" do
|
||||
test "centres on the rating and offsets easy and hard" do
|
||||
assert Puzzles.difficulty_target(1500, :medium) == 1500
|
||||
assert Puzzles.difficulty_target(1500, :easy) == 1300
|
||||
assert Puzzles.difficulty_target(1500, :hard) == 1700
|
||||
end
|
||||
end
|
||||
|
||||
describe "selection settings" do
|
||||
test "uses the configured spread and repeat window" do
|
||||
assert Puzzles.spread() == 150
|
||||
assert Puzzles.repeat_window_days() == 30
|
||||
end
|
||||
end
|
||||
|
||||
describe "next_endgame/3" do
|
||||
test "medium picks an endgame within the band" do
|
||||
test "draws far more often from near the user's rating" do
|
||||
user = user_fixture()
|
||||
in_band = endgame_at(1550, 0)
|
||||
_out_of_band = endgame_at(1900, 1)
|
||||
near = endgame_at(1500, 0)
|
||||
_far = endgame_at(4000, 1)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium).id == in_band.id
|
||||
for _ <- 1..50 do
|
||||
assert Puzzles.next_endgame(user, :medium).id == near.id
|
||||
end
|
||||
end
|
||||
|
||||
test "easy picks an endgame below the user's rating" do
|
||||
test "easy never serves above the user's rating plus the spread" do
|
||||
user = user_fixture()
|
||||
easy = endgame_at(1300, 0)
|
||||
_medium = endgame_at(1500, 1)
|
||||
_too_hard = endgame_at(3000, 1)
|
||||
|
||||
assert Puzzles.next_endgame(user, :easy).id == easy.id
|
||||
end
|
||||
|
||||
test "hard picks an endgame above the user's rating" do
|
||||
test "hard never serves below the user's rating minus the spread" do
|
||||
user = user_fixture()
|
||||
hard = endgame_at(1700, 0)
|
||||
_medium = endgame_at(1500, 1)
|
||||
_too_easy = endgame_at(100, 1)
|
||||
|
||||
assert Puzzles.next_endgame(user, :hard).id == hard.id
|
||||
end
|
||||
|
||||
test "falls back to the nearest endgame when the band is empty" do
|
||||
user = user_fixture()
|
||||
only = endgame_at(2200, 0)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium).id == only.id
|
||||
end
|
||||
|
||||
test "prefers endgames not attempted in the last 30 days" do
|
||||
test "prefers endgames not attempted inside the repeat window" do
|
||||
user = user_fixture()
|
||||
attempted = endgame_at(1500, 0)
|
||||
fresh = endgame_at(1500, 1)
|
||||
|
||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), attempted, :solved)
|
||||
attempt_days_ago(user, attempted, 1)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium).id == fresh.id
|
||||
end
|
||||
|
||||
test "falls back to a recent endgame once the fresh pool is empty" do
|
||||
test "serves an endgame again once its attempt is outside the repeat window" do
|
||||
user = user_fixture()
|
||||
only = endgame_at(1500, 0)
|
||||
|
||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), only, :solved)
|
||||
attempt_days_ago(user, only, 31)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium).id == only.id
|
||||
end
|
||||
|
||||
test "skips excluded ids" do
|
||||
test "falls back to the least recently attempted endgame when all are excluded" do
|
||||
user = user_fixture()
|
||||
excluded = endgame_at(1500, 0)
|
||||
older = endgame_at(1500, 0)
|
||||
newer = endgame_at(1500, 1)
|
||||
|
||||
attempt_days_ago(user, older, 20)
|
||||
attempt_days_ago(user, newer, 10)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium).id == older.id
|
||||
end
|
||||
|
||||
test "skips endgames already served in the session" do
|
||||
user = user_fixture()
|
||||
served = endgame_at(1500, 0)
|
||||
other = endgame_at(1500, 1)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium, exclude_ids: [excluded.id]).id == other.id
|
||||
assert Puzzles.next_endgame(user, :medium, exclude_ids: [served.id]).id == other.id
|
||||
end
|
||||
|
||||
test "returns nil when every endgame has been served and attempted" do
|
||||
user = user_fixture()
|
||||
only = endgame_at(1500, 0)
|
||||
|
||||
attempt_days_ago(user, only, 1)
|
||||
|
||||
assert Puzzles.next_endgame(user, :medium, exclude_ids: [only.id]) == nil
|
||||
end
|
||||
|
||||
test "returns nil when no endgames exist" do
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
defmodule Chesstrainer.ThemesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
import Chesstrainer.AccountsFixtures
|
||||
import Chesstrainer.EndgamesFixtures
|
||||
import Chesstrainer.ThemesFixtures
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
describe "themes" do
|
||||
alias Chesstrainer.Themes.Theme
|
||||
|
||||
import Chesstrainer.ThemesFixtures
|
||||
|
||||
@invalid_attrs %{name: nil, category: nil}
|
||||
|
||||
test "list_themes/0 returns all themes" do
|
||||
@@ -76,4 +84,200 @@ defmodule Chesstrainer.ThemesTest do
|
||||
assert changeset.errors[:name]
|
||||
end
|
||||
end
|
||||
|
||||
describe "theme identity" do
|
||||
test "generates a slug from the name" do
|
||||
assert {:ok, theme} = Themes.create_theme(%{name: " Mate in 2! ", category: :endgame})
|
||||
assert theme.slug == "mate-in-2"
|
||||
end
|
||||
|
||||
test "normalises an explicit slug" do
|
||||
assert {:ok, theme} =
|
||||
Themes.create_theme(%{
|
||||
name: "Lucena",
|
||||
slug: " Lucena-Position ",
|
||||
category: :endgame
|
||||
})
|
||||
|
||||
assert theme.slug == "lucena-position"
|
||||
end
|
||||
|
||||
test "keeps the slug stable when the name changes" do
|
||||
theme = theme_fixture(%{name: "Lucena"})
|
||||
|
||||
assert {:ok, updated} = Themes.update_theme(theme, %{name: "Lucena position"})
|
||||
assert updated.slug == "lucena"
|
||||
end
|
||||
|
||||
test "rejects a slug that is already taken, even in another category" do
|
||||
assert {:ok, _theme} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
|
||||
assert {:error, changeset} = Themes.create_theme(%{name: "Lucena", category: :tactic})
|
||||
assert changeset.errors[:slug]
|
||||
end
|
||||
|
||||
test "defaults the kind to technique" do
|
||||
assert {:ok, theme} = Themes.create_theme(%{name: "Opposition", category: :endgame})
|
||||
assert theme.kind == :technique
|
||||
end
|
||||
|
||||
test "accepts a material kind" do
|
||||
assert {:ok, theme} =
|
||||
Themes.create_theme(%{
|
||||
name: "Rook endgame",
|
||||
kind: :material,
|
||||
category: :endgame
|
||||
})
|
||||
|
||||
assert theme.kind == :material
|
||||
end
|
||||
|
||||
test "rejects an unknown kind" do
|
||||
assert {:error, changeset} =
|
||||
Themes.create_theme(%{
|
||||
name: "Zugzwang",
|
||||
kind: :bogus,
|
||||
category: :endgame
|
||||
})
|
||||
|
||||
assert changeset.errors[:kind]
|
||||
end
|
||||
|
||||
test "get_theme_by_slug/1 finds an endgame theme and ignores other categories" do
|
||||
theme = theme_fixture(%{name: "Philidor"})
|
||||
tactic = theme_fixture(%{name: "Philidor's pin", category: :tactic})
|
||||
|
||||
assert Themes.get_theme_by_slug("philidor").id == theme.id
|
||||
assert Themes.get_theme_by_slug(tactic.slug) == nil
|
||||
assert Themes.get_theme_by_slug("unknown") == nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "create_theme/2 authorization" do
|
||||
test "an admin scope may create a theme" do
|
||||
{:ok, admin} = Accounts.update_user_role(user_fixture(), :admin)
|
||||
scope = Scope.for_user(admin)
|
||||
|
||||
assert {:ok, %Themes.Theme{}} =
|
||||
Themes.create_theme(scope, %{name: "Opposition", category: :endgame})
|
||||
end
|
||||
|
||||
test "a member scope cannot create a theme" do
|
||||
scope = user_scope_fixture()
|
||||
|
||||
assert {:error, :unauthorized} =
|
||||
Themes.create_theme(scope, %{name: "Opposition", category: :endgame})
|
||||
|
||||
assert Themes.list_themes() == []
|
||||
end
|
||||
end
|
||||
|
||||
describe "theme link provenance" do
|
||||
test "links created from the endgame context default to curated" do
|
||||
theme = theme_fixture()
|
||||
endgame = endgame_fixture()
|
||||
|
||||
assert {:ok, _endgame} = Endgames.update_endgame(endgame, %{}, [theme])
|
||||
|
||||
assert [%{theme_id: theme_id, source: "curated"}] = link_rows(endgame.id)
|
||||
assert theme_id == theme.id
|
||||
end
|
||||
|
||||
test "sync_derived_themes/2 adds derived links and leaves curated and community links alone" do
|
||||
curated = theme_fixture(%{name: "Lucena"})
|
||||
community = theme_fixture(%{name: "Philidor"})
|
||||
derived = theme_fixture(%{name: "Rook endgame"})
|
||||
endgame = endgame_fixture()
|
||||
|
||||
{:ok, _} = Endgames.update_endgame(endgame, %{}, [curated])
|
||||
insert_link(endgame.id, community.id, "community")
|
||||
|
||||
assert :ok = Themes.sync_derived_themes(endgame.id, [derived.id, curated.id])
|
||||
|
||||
sources = link_sources(endgame.id)
|
||||
assert sources[curated.id] == "curated"
|
||||
assert sources[community.id] == "community"
|
||||
assert sources[derived.id] == "derived"
|
||||
end
|
||||
|
||||
test "sync_derived_themes/2 replaces only its own derived links" do
|
||||
curated = theme_fixture(%{name: "Lucena"})
|
||||
old_derived = theme_fixture(%{name: "Rook endgame"})
|
||||
new_derived = theme_fixture(%{name: "Two pawns"})
|
||||
endgame = endgame_fixture()
|
||||
|
||||
{:ok, _} = Endgames.update_endgame(endgame, %{}, [curated])
|
||||
Themes.sync_derived_themes(endgame.id, [old_derived.id])
|
||||
|
||||
assert :ok = Themes.sync_derived_themes(endgame.id, [new_derived.id])
|
||||
|
||||
sources = link_sources(endgame.id)
|
||||
assert sources[curated.id] == "curated"
|
||||
refute Map.has_key?(sources, old_derived.id)
|
||||
assert sources[new_derived.id] == "derived"
|
||||
end
|
||||
end
|
||||
|
||||
describe "tag_endgames/3 and untag_endgame/3" do
|
||||
test "adds curated links without duplicating them" do
|
||||
theme = theme_fixture()
|
||||
first = endgame_fixture()
|
||||
second = endgame_fixture()
|
||||
|
||||
assert {:ok, 2} = Themes.tag_endgames(theme, [first.id, second.id])
|
||||
assert {:ok, 2} = Themes.tag_endgames(theme, [first.id, second.id])
|
||||
|
||||
assert link_sources(first.id) == %{theme.id => "curated"}
|
||||
assert link_sources(second.id) == %{theme.id => "curated"}
|
||||
end
|
||||
|
||||
test "never overwrites a derived link" do
|
||||
theme = theme_fixture()
|
||||
endgame = endgame_fixture()
|
||||
|
||||
:ok = Themes.sync_derived_themes(endgame.id, [theme.id])
|
||||
|
||||
assert {:ok, 1} = Themes.tag_endgames(theme, [endgame.id])
|
||||
assert link_sources(endgame.id) == %{theme.id => "derived"}
|
||||
end
|
||||
|
||||
test "removes only the requested source" do
|
||||
theme = theme_fixture()
|
||||
curated = endgame_fixture()
|
||||
community = endgame_fixture()
|
||||
|
||||
{:ok, _} = Themes.tag_endgames(theme, [curated.id], :curated)
|
||||
{:ok, _} = Themes.tag_endgames(theme, [community.id], :community)
|
||||
|
||||
assert {:ok, 1} = Themes.untag_endgame(theme, curated.id, :curated)
|
||||
assert link_sources(curated.id) == %{}
|
||||
assert link_sources(community.id) == %{theme.id => "community"}
|
||||
end
|
||||
end
|
||||
|
||||
defp link_rows(endgame_id) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id),
|
||||
select: %{theme_id: l.theme_id, source: l.source},
|
||||
order_by: l.theme_id
|
||||
)
|
||||
end
|
||||
|
||||
defp link_sources(endgame_id) do
|
||||
endgame_id
|
||||
|> link_rows()
|
||||
|> Map.new(&{&1.theme_id, &1.source})
|
||||
end
|
||||
|
||||
defp insert_link(endgame_id, theme_id, source) do
|
||||
Repo.insert_all("endgames_themes", [
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: source,
|
||||
inserted_at: DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
}
|
||||
])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -5,6 +5,7 @@ defmodule ChesstrainerWeb.LayoutsTest do
|
||||
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Accounts.User
|
||||
alias Chesstrainer.Branding
|
||||
alias ChesstrainerWeb.Layouts
|
||||
|
||||
describe "navbar/1" do
|
||||
@@ -28,6 +29,53 @@ defmodule ChesstrainerWeb.LayoutsTest do
|
||||
assert html =~ ~p"/users/register"
|
||||
refute html =~ ~s(class="nav-user-menu")
|
||||
end
|
||||
|
||||
test "renders the utility controls in both the bar and the mobile menu" do
|
||||
html = render_component(&Layouts.navbar/1, %{current_scope: nil})
|
||||
|
||||
assert html =~ ~s(class="nav-menu-tools")
|
||||
# One copy for the bar, one for the collapsible menu; CSS shows one.
|
||||
assert length(String.split(html, ~s(role="radiogroup"))) == 3
|
||||
assert length(String.split(html, ~s(class="discord-link"))) == 3
|
||||
end
|
||||
end
|
||||
|
||||
describe "discord_link/1" do
|
||||
setup do
|
||||
previous = Application.get_env(:chesstrainer, :branding)
|
||||
on_exit(fn -> restore_env(:branding, previous) end)
|
||||
:ok
|
||||
end
|
||||
|
||||
test "renders an icon-only link to the configured invite" do
|
||||
html = render_component(&Layouts.discord_link/1, %{})
|
||||
|
||||
assert html =~ ~s(href="#{Branding.discord_invite_url()}")
|
||||
assert html =~ ~s(aria-label="Join the #{Branding.name()} Discord")
|
||||
assert html =~ ~s(target="_blank")
|
||||
assert html =~ "noopener noreferrer"
|
||||
assert html =~ ~r/<a[^>]*class="discord-link"[^>]*>\s*<svg/
|
||||
end
|
||||
|
||||
test "is rendered by the navbar and the footer" do
|
||||
navbar = render_component(&Layouts.navbar/1, %{current_scope: nil})
|
||||
assert navbar =~ ~s(class="discord-link")
|
||||
|
||||
footer = render_component(&Layouts.footer/1, %{})
|
||||
assert footer =~ ~s(class="discord-link")
|
||||
end
|
||||
|
||||
test "renders nothing when no invite is configured" do
|
||||
Application.put_env(
|
||||
:chesstrainer,
|
||||
:branding,
|
||||
Keyword.put(Application.get_env(:chesstrainer, :branding, []), :discord_invite, "")
|
||||
)
|
||||
|
||||
html = render_component(&Layouts.discord_link/1, %{})
|
||||
|
||||
refute html =~ "discord-link"
|
||||
end
|
||||
end
|
||||
|
||||
describe "colour_mode_toggle/1" do
|
||||
|
||||
@@ -10,7 +10,7 @@ defmodule ChesstrainerWeb.HealthControllerTest do
|
||||
assert body["db"] == "ok"
|
||||
assert body["tablebase"] == "local"
|
||||
assert body["process"] == "ok"
|
||||
assert get_resp_header(conn, "x-robots-tag") == ["noindex"]
|
||||
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
|
||||
end
|
||||
|
||||
test "returns degraded when local tablebases are not configured", %{conn: conn} do
|
||||
@@ -53,7 +53,7 @@ defmodule ChesstrainerWeb.HealthControllerTest do
|
||||
assert body["db"] == "down"
|
||||
assert body["tablebase"] == "local"
|
||||
assert body["process"] == "ok"
|
||||
assert get_resp_header(conn, "x-robots-tag") == ["noindex"]
|
||||
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
|
||||
end
|
||||
end
|
||||
|
||||
|
||||