Initial commit: TSS Bot Web Frontend (React/Vite + production server)
This commit is contained in:
+16
@@ -0,0 +1,16 @@
|
||||
node_modules
|
||||
dist
|
||||
dist-next
|
||||
dist-previous
|
||||
.env
|
||||
.env.local
|
||||
.env.backup-*
|
||||
.DS_Store
|
||||
npm-debug.log*
|
||||
vite-dev*.log
|
||||
server-local*.log
|
||||
.local-storage/
|
||||
.claude/
|
||||
frontend/public/data/*
|
||||
!frontend/public/data/
|
||||
!frontend/public/data/README.md
|
||||
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,50 @@
|
||||
# tssbot.web-frontend
|
||||
|
||||
React/Vite frontend and production Node.js server for the TSS Bot web platform.
|
||||
|
||||
## Structure
|
||||
|
||||
- `frontend/` - React SPA (Vite + Tailwind v4)
|
||||
- `server.cjs` - Production Node.js server (serves SPA, proxies API, analytics, uptime)
|
||||
- `webhook.cjs` - GitHub deploy webhook listener
|
||||
- `systemd/` - systemd unit files for all services
|
||||
- `scripts/` - Deployment and test scripts
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp example.env .env # edit with your values
|
||||
npm run dev # Vite dev server on :3001
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
npm run build # Outputs to dist/
|
||||
```
|
||||
|
||||
## Production
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
node server.cjs # Serves on PORT (default 3010)
|
||||
```
|
||||
|
||||
## Deploy Webhook
|
||||
|
||||
```bash
|
||||
node webhook.cjs # Listens on WEBHOOK_PORT (default 3011)
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
See `example.env` for all available variables. Key ones:
|
||||
|
||||
| Variable | Description |
|
||||
|---|---|
|
||||
| `PORT` | Server port (default: 3010) |
|
||||
| `API_UPSTREAM` | Backend API URL (default: http://127.0.0.1:6000) |
|
||||
| `PUBLIC_ORIGIN` | Public-facing URL |
|
||||
| `VITE_TURNSTILE_SITE_KEY` | Cloudflare Turnstile public key |
|
||||
| `TURNSTILE_SECRET_KEY` | Cloudflare Turnstile secret key |
|
||||
@@ -0,0 +1,153 @@
|
||||
# 3D Replay View — Design
|
||||
|
||||
**Date:** 2026-06-21
|
||||
**App:** `tssbot.web` (React frontend + Node `server.cjs` + Rust/Python upstream)
|
||||
|
||||
## Goal
|
||||
|
||||
Add a **2D/3D toggle** to the game-detail Replay panel. The existing 2D
|
||||
minimap replayer stays the default; a new 3D view (ported from the standalone
|
||||
`REPLAY_VIEWER` three.js app) renders the same replay in an orbitable 3D scene.
|
||||
Both views share one clock, the ticket bar, the battle log, and the team side
|
||||
panels, so switching between them is seamless in real time.
|
||||
|
||||
## Requirements
|
||||
|
||||
1. Toggle labelled **2D / 3D** next to the "Replay" heading, **2D by default**,
|
||||
sitting alongside the existing Ground/Air toggle.
|
||||
2. The 3D renderer is **pure**: only its `<canvas>`. No name labels, no axis
|
||||
lines, no map guide lines, no on-canvas controls/legend.
|
||||
3. Keep the existing **team side panels** (winners/losers legends).
|
||||
4. **Clicking a side-panel row focuses that unit in 3D** (camera flies to it and
|
||||
it glows). In 2D, click behaves the same as hover (no new behavior).
|
||||
5. Keep the **ticket bar on top** and **battle log below**, both synced to the
|
||||
shared clock regardless of active view.
|
||||
6. The **Ground/Air** toggle controls both views.
|
||||
7. 3D uses **real height (Y)** from the replay data.
|
||||
|
||||
## Data flow
|
||||
|
||||
Pipeline today:
|
||||
`replay_data.json[.gz]` (raw, path rows `[t, x, y, z]`)
|
||||
→ `python -m BOT.render_replay <replay> <out.json>` (in `GitHub/BOTS/TSSBOT`)
|
||||
→ `replay_canvas.json` (2D: path points `{t, x, z}`, plus `levelCoords`,
|
||||
`tankMapCoords`, `mapCoords`, `fullMapLevel`, players, kills, captureAreas,
|
||||
captureState, tickets, teamNames, winnerSlot)
|
||||
→ cached + served at `GET /api/tss/games/:id/replay-canvas`
|
||||
→ `ReplayCanvasEngine` (in `frontend/src/ReplayCanvas.jsx`).
|
||||
|
||||
**Update (verified during implementation):** `render_replay.py` *already* emits
|
||||
`y` per canvas path point (`render_replay.py:4237` → `{t, x, z, y}`), and
|
||||
`replay_canvas.json` already includes `captureAreas` (with `x/z/radius/center`),
|
||||
`captureState` (cap timelines keyed `A/B/…`), `kills` (with `killerPos`/
|
||||
`victimPos` in world coords), and all map coords. **No backend change is
|
||||
needed.** 3D still falls back to `y = 0` if a point is missing.
|
||||
|
||||
### Runtime flow
|
||||
|
||||
- `ReplayCanvasPanel.jsx` fetches `/api/tss/games/:id/replay-canvas` once and
|
||||
builds `ReplayCanvasEngine` with the data object.
|
||||
- The engine **eagerly** constructs both the 2D canvas and a hidden
|
||||
`ReplayCanvas3D` view from the same `data`.
|
||||
- `engine._tick` advances `currentTime` and calls `activeView.setTime(currentTime)`.
|
||||
Scrubber `input` does the same. Ticket bar + battle log update from
|
||||
`currentTime` independent of the active view.
|
||||
- `engine.setViewMode('2d'|'3d')` toggles visibility of the 2D canvas vs the 3D
|
||||
container, sets `activeView`, calls the new view's `setTime`/`setMode`/
|
||||
`resize`, and preserves play state + time → seamless swap.
|
||||
- `engine.setMode('ground'|'air')` updates 2D coords (unchanged) **and** calls
|
||||
`view3d.setMode(mode)`.
|
||||
- `rc-row` click → `engine.focus(playerId)` → routed to `activeView.focus`. 3D
|
||||
flies the camera to the unit and glows it; 2D `focus` is a no-op.
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Backend / `render_replay.py`
|
||||
No change — `y`, capture data, and kill positions are already emitted.
|
||||
|
||||
### 2. `frontend/src/ReplayCanvas3D.js` (new)
|
||||
The ported three.js renderer as a UI-less class.
|
||||
|
||||
- **Constructor** `(container, data)`: builds renderer, scene, camera,
|
||||
OrbitControls into `container`; resolves map info from `data`
|
||||
(levelCoords/tankMapCoords/mapCoords/fullMapLevel) the same way the standalone
|
||||
viewer's `resolveMapInfo` does; builds map plane, tank/marker entities, path
|
||||
lines, kill lines, capture zones; starts its own `requestAnimationFrame` loop
|
||||
for camera damping + rendering (it renders continuously but only changes unit
|
||||
positions when `setTime` is called).
|
||||
- **Methods:**
|
||||
- `setTime(t)` — place all entities/markers/kill-lines/zones at game time `t`
|
||||
(same interpolation/death-freeze logic as the standalone viewer).
|
||||
- `setMode('ground'|'air')` — swap coords/map image + rebuild scene extents.
|
||||
- `focus(playerId)` — move camera target to that player's current entity and
|
||||
apply the path glow / dim-others effect.
|
||||
- `setHighlight(playerId|null)` — optional, mirror hover highlight (best
|
||||
effort; may reuse `focus` glow without camera move). *MVP: `focus` only.*
|
||||
- `resize()` — match container size.
|
||||
- `dispose()` — stop loop, dispose geometries/materials/renderer, remove
|
||||
canvas.
|
||||
- **Stripped vs standalone viewer:** remove name-label sprites, axis lines, map
|
||||
guide lines/annotations, the on-canvas play/speed/scrub controls, the active
|
||||
list / hover panel / meta panel DOM, and the replay-select. Keep: map plane +
|
||||
texture, tank model + sphere fallback, path lines, kill lines, capture zones,
|
||||
death-freeze, path glow + camera focus, Shift-to-boost camera movement, the
|
||||
`Plane*`-mesh removal fix, and the capture/heading/freeze fixes already made.
|
||||
- **Entity identity:** each 3D entity carries its `playerId` (from `data`) so
|
||||
`focus(playerId)` can find the currently-live entity for that player.
|
||||
- **Model asset:** the tank `.obj` and map images. 3D loads the tank model from
|
||||
a static path served by the app (copy `REPLAY_VIEWER/public/models/t34/` into
|
||||
`tssbot.web/frontend/public/models/t34/` or equivalent served dir). Map images
|
||||
come from the existing minimap endpoint (`/api/match/minimap/<level>` and
|
||||
`?type=full`), the same URLs the 2D engine uses.
|
||||
|
||||
### 3. `frontend/src/ReplayCanvas.jsx` — `ReplayCanvasEngine`
|
||||
- Add a center child container for the 3D canvas next to the 2D `<canvas>`.
|
||||
- New state: `this._viewMode = '2d'`, `this.view3d = null`, `this.activeView`.
|
||||
- In `init()` (after map data is ready), eagerly construct `ReplayCanvas3D`.
|
||||
- `setViewMode(mode)`: show/hide canvases, set `activeView`, push current
|
||||
`currentTime` + ground/air mode to the newly active view, `resize()` it.
|
||||
- In `_tick` and scrubber handler: when `_viewMode === '3d'`, call
|
||||
`view3d.setTime(currentTime)` instead of (or in addition to) the 2D `render()`.
|
||||
2D `render()` is skipped while 3D is active for perf.
|
||||
- `setMode(mode)`: keep existing 2D behavior, also `view3d?.setMode(mode)`.
|
||||
- `focus(playerId)`: call `activeView.focus?.(playerId)`.
|
||||
- `rc-row` click listener → `this.focus(pid)`.
|
||||
- `destroy()`: also `view3d?.dispose()`.
|
||||
|
||||
### 4. `frontend/src/ReplayCanvas.jsx` — `ReplayCanvasPanel`
|
||||
- State adds `viewMode: '2d'`.
|
||||
- Render a 2D/3D toggle (mirroring `rc-mode-toggle` styling) next to the
|
||||
"Replay" `<h2>`, always visible once `status === 'ready'`.
|
||||
- `switchView(mode)` → `engine.setViewMode(mode)` + `setState`.
|
||||
- If WebGL is unavailable, disable the 3D button (dimmed, tooltip) and stay 2D.
|
||||
|
||||
### 5. Styles
|
||||
- `.rc-view-toggle` / `.rc-view-btn` (reuse `.rc-mode-toggle` look).
|
||||
- Center stacking so the 2D `<canvas>` and 3D container occupy the same slot
|
||||
(one hidden via class).
|
||||
|
||||
## Error handling
|
||||
|
||||
- **Missing `y`** (stale cache): 3D uses `y = 0` → flat scene, no crash.
|
||||
- **No WebGL**: 3D button disabled; panel stays 2D.
|
||||
- **Model/texture load failure**: 3D falls back to sphere markers / untextured
|
||||
map (already handled in the standalone viewer's loaders).
|
||||
|
||||
## Testing / verification
|
||||
|
||||
Manual, since this is interactive visual UI:
|
||||
- 2D view byte-for-byte unchanged when 3D is never opened.
|
||||
- Toggle 2D⇄3D mid-playback: time, play/pause, and ticket/battle-log stay in
|
||||
sync; no jump.
|
||||
- Ground/Air toggle affects both views (use a game with aircraft).
|
||||
- Clicking a side row in 3D flies the camera + glows that unit; in 2D it matches
|
||||
hover.
|
||||
- `vite build` compiles.
|
||||
- One game regenerated through `render_replay` includes `y`.
|
||||
|
||||
## Out of scope (YAGNI)
|
||||
|
||||
- Persistent 2D click-focus / 2D recenter (explicitly declined).
|
||||
- Name labels / legend inside the 3D canvas.
|
||||
- Lazy-loading three.js (eager chosen).
|
||||
- Backfilling height into all cached `replay_canvas.json` (regenerate on demand).
|
||||
@@ -0,0 +1,39 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
|
||||
export default [
|
||||
{ ignores: ['dist', 'dist-next', 'dist-previous', 'node_modules'] },
|
||||
{
|
||||
files: ['**/*.{js,jsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
ecmaFeatures: { jsx: true },
|
||||
sourceType: 'module',
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...js.configs.recommended.rules,
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['vite.config.js', 'server.cjs', 'webhook.cjs', 'backend/**/*.cjs'],
|
||||
languageOptions: {
|
||||
globals: globals.node,
|
||||
},
|
||||
},
|
||||
]
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
NODE_ENV=production
|
||||
|
||||
PORT=3010
|
||||
API_UPSTREAM=http://127.0.0.1:6000
|
||||
PUBLIC_ORIGIN=https://example.com
|
||||
|
||||
BACKEND_PORT=6000
|
||||
BACKEND_HOST=127.0.0.1
|
||||
BACKEND_ALLOWED_ORIGINS=https://example.com
|
||||
TSS_BATTLES_DB=./tss_battles.db
|
||||
TSS_TEAMS_DB=./tss_teams.db
|
||||
TSS_TOURNAMENTS_DB=./tss_tournaments.db
|
||||
|
||||
VEHICLE_TRANSLATIONS_JSON=/mnt/HC_Volume_105581488/STORAGE/CACHE/vehicle_translations.json
|
||||
VEHICLE_DATA_CACHE_JSON=/mnt/HC_Volume_105581488/STORAGE/CACHE/vehicle_data_cache.json
|
||||
VEHICLE_ICONS_DIR=./dist/vehicle-icons
|
||||
VEHICLE_ICONS_SRC=/home/deploy/BOTS/SHARED/ICONS/VEHICLES
|
||||
|
||||
UPTIME_STORAGE_DIR=~/tsswebstorage
|
||||
UPTIME_DATABASE_FILE=uptime.sqlite
|
||||
UPTIME_SAMPLE_INTERVAL_MS=1800000
|
||||
UPTIME_HISTORY_LIMIT=336
|
||||
|
||||
ANALYTICS_DATABASE_FILE=viewers.sqlite
|
||||
ANALYTICS_RETENTION_DAYS=30
|
||||
ANALYTICS_ACTIVE_WINDOW_SECONDS=75
|
||||
|
||||
API_CACHE_TTL_MS=15000
|
||||
PUBLIC_DATA_CACHE_DIR=~/tsswebstorage/public-data
|
||||
PUBLIC_DATA_CACHE_FRESH_MS=300000
|
||||
PUBLIC_DATA_CACHE_STALE_MS=86400000
|
||||
PUBLIC_DATA_PREWARM_INTERVAL_MS=300000
|
||||
PUBLIC_DATA_COLD_TIMEOUT_MS=8000
|
||||
API_RATE_LIMIT_WINDOW_MS=60000
|
||||
API_RATE_LIMIT_MAX=120
|
||||
SITE_SESSION_SECRET=change-me-to-a-long-random-secret
|
||||
SITE_SESSION_TTL_SECONDS=43200
|
||||
|
||||
TRUST_PROXY=cloudflare
|
||||
TRUSTED_UPSTREAM_IPS=127.0.0.1,::1,::ffff:127.0.0.1
|
||||
|
||||
WEBHOOK_PORT=3011
|
||||
GITHUB_WEBHOOK_SECRET=change-me
|
||||
GITHUB_WEBHOOK_REFS=refs/heads/main
|
||||
GITHUB_WEBHOOK_REPOSITORY=
|
||||
RESTART_TARGETS=tssbot-web,tssbot-backend
|
||||
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
|
||||
DISCORD_INCLUDE_PATCH=true
|
||||
|
||||
VITE_TURNSTILE_SITE_KEY=
|
||||
TURNSTILE_SECRET_KEY=
|
||||
VITE_SITE_GATE=true
|
||||
VITE_STATIC_DATA=false
|
||||
@@ -0,0 +1,143 @@
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { TRUNK_TOP_CSS } from "./Tree";
|
||||
|
||||
interface Leaf {
|
||||
x: number;
|
||||
y: number;
|
||||
size: number;
|
||||
speed: number;
|
||||
drift: number;
|
||||
rotation: number;
|
||||
rotationSpeed: number;
|
||||
opacity: number;
|
||||
sway: number;
|
||||
swaySpeed: number;
|
||||
phase: number;
|
||||
}
|
||||
|
||||
export default function FallingLeaves({ treeRef }: { treeRef: React.RefObject<HTMLCanvasElement | null> }) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
let animId: number;
|
||||
const leaves: Leaf[] = [];
|
||||
const MAX_LEAVES = 36;
|
||||
const frameInterval = 1000 / 30;
|
||||
let lastFrame = 0;
|
||||
let isVisible = true;
|
||||
let isRunning = false;
|
||||
let treeBounds = { left: 0, top: 0, width: 0 };
|
||||
let canvasBounds = { left: 0, top: 0 };
|
||||
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
function measure() {
|
||||
const parent = canvas.parentElement;
|
||||
const rect = parent?.getBoundingClientRect();
|
||||
canvas.width = Math.max(1, Math.round(rect?.width || window.innerWidth));
|
||||
canvas.height = Math.max(1, Math.round(rect?.height || window.innerHeight));
|
||||
const treeRect = treeRef.current?.getBoundingClientRect();
|
||||
const canvasRect = canvas.getBoundingClientRect();
|
||||
treeBounds = treeRect
|
||||
? { left: treeRect.left, top: treeRect.top, width: treeRect.width }
|
||||
: { left: canvasRect.left + canvas.width * 0.2, top: canvasRect.top + canvas.height * 0.4, width: canvas.width * 0.6 };
|
||||
canvasBounds = { left: canvasRect.left, top: canvasRect.top };
|
||||
}
|
||||
measure();
|
||||
const resizeObserver = new ResizeObserver(measure);
|
||||
if (canvas.parentElement) resizeObserver.observe(canvas.parentElement);
|
||||
if (treeRef.current) resizeObserver.observe(treeRef.current);
|
||||
|
||||
function spawnLeaf(): Leaf {
|
||||
const spawnY = treeBounds.top - canvasBounds.top + TRUNK_TOP_CSS;
|
||||
const spawnX = treeBounds.left - canvasBounds.left + Math.random() * treeBounds.width * 0.8 + treeBounds.width * 0.1;
|
||||
return {
|
||||
x: spawnX,
|
||||
y: spawnY,
|
||||
size: Math.random() * 4 + 2,
|
||||
speed: Math.random() * 0.3 + 0.15,
|
||||
drift: Math.random() * 0.5 - 0.25,
|
||||
rotation: Math.random() * Math.PI * 2,
|
||||
rotationSpeed: (Math.random() - 0.5) * 0.02,
|
||||
opacity: Math.random() * 0.25 + 0.08,
|
||||
sway: Math.random() * 30 + 15,
|
||||
swaySpeed: Math.random() * 0.008 + 0.003,
|
||||
phase: Math.random() * Math.PI * 2,
|
||||
};
|
||||
}
|
||||
|
||||
let spawnTimer = 0;
|
||||
|
||||
function draw(timestamp: number) {
|
||||
if (!isRunning) return;
|
||||
animId = requestAnimationFrame(draw);
|
||||
if (timestamp - lastFrame < frameInterval) return;
|
||||
lastFrame = timestamp;
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
spawnTimer++;
|
||||
if (spawnTimer > 30 && leaves.length < MAX_LEAVES) {
|
||||
leaves.push(spawnLeaf());
|
||||
spawnTimer = 0;
|
||||
}
|
||||
|
||||
for (let i = leaves.length - 1; i >= 0; i--) {
|
||||
const l = leaves[i];
|
||||
l.y += l.speed;
|
||||
l.x += l.drift + Math.sin(l.phase) * l.swaySpeed * l.sway * 0.05;
|
||||
l.phase += l.swaySpeed;
|
||||
l.rotation += l.rotationSpeed;
|
||||
|
||||
ctx.save();
|
||||
ctx.translate(l.x, l.y);
|
||||
ctx.rotate(l.rotation);
|
||||
ctx.globalAlpha = l.opacity;
|
||||
ctx.fillStyle = "#fdb068";
|
||||
|
||||
const s = Math.round(l.size);
|
||||
ctx.fillRect(-s / 2, -s / 2, s, s);
|
||||
|
||||
ctx.restore();
|
||||
|
||||
if (l.y > canvas.height + 10) {
|
||||
leaves.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (reducedMotion || isRunning || !isVisible || document.hidden) return;
|
||||
isRunning = true;
|
||||
animId = requestAnimationFrame(draw);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
isRunning = false;
|
||||
if (animId) cancelAnimationFrame(animId);
|
||||
}
|
||||
|
||||
const intersectionObserver = new IntersectionObserver(([entry]) => {
|
||||
isVisible = entry.isIntersecting;
|
||||
if (isVisible) start();
|
||||
else stop();
|
||||
});
|
||||
const onVisibilityChange = () => {
|
||||
if (document.hidden) stop();
|
||||
else start();
|
||||
};
|
||||
intersectionObserver.observe(canvas);
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
start();
|
||||
|
||||
return () => {
|
||||
stop();
|
||||
intersectionObserver.disconnect();
|
||||
resizeObserver.disconnect();
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <canvas ref={canvasRef} className="falling-leaves" />;
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import React, { forwardRef, useEffect, useRef } from "react";
|
||||
|
||||
const PX = 2;
|
||||
const W = 500;
|
||||
const H = 420;
|
||||
const LEAF_FLOOR = H - 60;
|
||||
|
||||
|
||||
function buildTree(seed: number) {
|
||||
const woodGrid = new Uint8Array(W * H);
|
||||
const leafGrid = new Uint8Array(W * H);
|
||||
|
||||
let s = seed;
|
||||
function rand() {
|
||||
s = (s * 16807 + 0) % 2147483647;
|
||||
return (s & 0x7fffffff) / 0x7fffffff;
|
||||
}
|
||||
|
||||
function setWood(x: number, y: number, shade: number) {
|
||||
const px = Math.round(x), py = Math.round(y);
|
||||
if (px >= 0 && px < W && py >= 0 && py < H) {
|
||||
const idx = py * W + px;
|
||||
if (woodGrid[idx] === 0) woodGrid[idx] = shade;
|
||||
}
|
||||
}
|
||||
|
||||
function setLeaf(x: number, y: number, shade: number) {
|
||||
const px = Math.round(x), py = Math.round(y);
|
||||
if (px >= 0 && px < W && py >= 0 && py < LEAF_FLOOR) {
|
||||
const idx = py * W + px;
|
||||
if (shade > leafGrid[idx]) leafGrid[idx] = shade;
|
||||
}
|
||||
}
|
||||
|
||||
function drawLeaf(x: number, y: number, shade: number) {
|
||||
const px = Math.round(x), py = Math.round(y);
|
||||
setLeaf(px, py, shade);
|
||||
const r = rand();
|
||||
if (r < 0.60) setLeaf(px + (rand() > 0.5 ? 1 : -1), py, shade);
|
||||
if (r < 0.32) setLeaf(px, py + (rand() > 0.45 ? -1 : 1), shade);
|
||||
}
|
||||
|
||||
function leafScatter(cx: number, cy: number, radius: number, count: number) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
const a = rand() * Math.PI * 2;
|
||||
const r = Math.sqrt(rand()) * radius;
|
||||
const lx = cx + Math.cos(a) * r * 0.5;
|
||||
const vertStretch = 1.0 + (cy / H) * 3.0;
|
||||
const ly = cy + Math.abs(Math.sin(a)) * r * vertStretch;
|
||||
const yFr = (ly - cy) / radius;
|
||||
const shade = yFr < 0.5 ? 3 : yFr < 1.2 ? 2 : 1;
|
||||
drawLeaf(lx, ly, shade);
|
||||
}
|
||||
}
|
||||
|
||||
function drawLine(
|
||||
x0: number, y0: number, x1: number, y1: number,
|
||||
thickness: number, shade: number,
|
||||
) {
|
||||
const dx = x1 - x0, dy = y1 - y0;
|
||||
const dist = Math.sqrt(dx * dx + dy * dy);
|
||||
const steps = Math.max(Math.ceil(dist * 2), 1);
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const t = i / steps;
|
||||
const bx = x0 + dx * t, by = y0 + dy * t;
|
||||
const r = (thickness / 2) * (1 - t * 0.4);
|
||||
for (let oy = -Math.ceil(r); oy <= Math.ceil(r); oy++)
|
||||
for (let ox = -Math.ceil(r); ox <= Math.ceil(r); ox++)
|
||||
if (ox * ox + oy * oy <= r * r) setWood(bx + ox, by + oy, shade);
|
||||
}
|
||||
}
|
||||
|
||||
function branch(
|
||||
x: number, y: number,
|
||||
angle: number, length: number,
|
||||
thickness: number, depth: number,
|
||||
) {
|
||||
const endX = x + Math.cos(angle) * length;
|
||||
const endY = y + Math.sin(angle) * length;
|
||||
|
||||
const woodShade = thickness > 5 ? 1 : thickness > 2.5 ? 2 : 3;
|
||||
drawLine(x, y, endX, endY, thickness, woodShade);
|
||||
|
||||
if (depth <= 0 || length < 1.5) {
|
||||
const r = 4 + rand() * 6;
|
||||
|
||||
const normalised = ((angle % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2);
|
||||
const deg = normalised * (180 / Math.PI);
|
||||
const isNearHorizontal = deg < 30 || deg > 150;
|
||||
|
||||
if (isNearHorizontal) {
|
||||
for (let i = 0; i < Math.round(r * r * 0.8); i++) {
|
||||
const ox = (rand() - 0.5) * r * 2;
|
||||
const oy = -rand() * r * 2.5;
|
||||
const shade = oy < -r ? 3 : 2;
|
||||
drawLeaf(endX + ox, endY + oy, shade);
|
||||
}
|
||||
} else {
|
||||
leafScatter(endX, endY, r, Math.round(r * r * 0.6));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (depth === 1) {
|
||||
const steps = Math.ceil(length / 5);
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const t = i / steps;
|
||||
const mx = x + Math.cos(angle) * length * t;
|
||||
const my = y + Math.sin(angle) * length * t;
|
||||
leafScatter(mx, my, 3 + rand() * 2, 8 + Math.round(rand() * 6));
|
||||
}
|
||||
}
|
||||
|
||||
const numChildren = depth > 4 ? 2 : 3 + (rand() > 0.6 ? 1 : 0);
|
||||
for (let i = 0; i < numChildren; i++) {
|
||||
const spread = 0.30 + rand() * 0.20;
|
||||
const angleOffset = (i - (numChildren - 1) / 2) * spread;
|
||||
const droopBias = 0;
|
||||
const childAngle = angle + angleOffset + (rand() - 0.5) * 0.1 + droopBias;
|
||||
const lenFactor = 0.60 + rand() * 0.12;
|
||||
const thickFactor = 0.50 + rand() * 0.10;
|
||||
branch(endX, endY, childAngle, length * lenFactor,
|
||||
Math.max(1, thickness * thickFactor), depth - 1);
|
||||
}
|
||||
|
||||
if (depth > 1 && rand() > 0.25) {
|
||||
const t = 0.25 + rand() * 0.35;
|
||||
const sx = x + Math.cos(angle) * length * t;
|
||||
const sy = y + Math.sin(angle) * length * t;
|
||||
const side = rand() > 0.5 ? 1 : -1;
|
||||
branch(sx, sy,
|
||||
angle + side * (0.30 + rand() * 0.35), length * 0.5,
|
||||
Math.max(1, thickness * 0.45), depth - 2);
|
||||
}
|
||||
}
|
||||
|
||||
const cx = W / 2;
|
||||
const trunkTop = H - 150;
|
||||
const base = H - 50;
|
||||
|
||||
|
||||
for (let ty = trunkTop; ty <= base; ty++) {
|
||||
const t = (ty - trunkTop) / (base - trunkTop);
|
||||
const width = 10 + t * t * 16;
|
||||
const hw = Math.ceil(width);
|
||||
for (let ox = -hw; ox <= hw; ox++) {
|
||||
const px = Math.round(cx + ox), py = ty;
|
||||
if (px < 0 || px >= W || py < 0 || py >= H) continue;
|
||||
woodGrid[py * W + px] = 2;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
branch(cx - 30, trunkTop + 8, -Math.PI * 0.95, 70, 11, 7);
|
||||
branch(cx - 22, trunkTop + 4, -Math.PI * 0.87, 68, 10, 7);
|
||||
branch(cx - 14, trunkTop, -Math.PI * 0.78, 66, 10, 7);
|
||||
branch(cx - 8, trunkTop - 4, -Math.PI * 0.68, 64, 9, 7);
|
||||
branch(cx - 8, trunkTop + 4, -Math.PI * 0.70, 71, 10, 7);
|
||||
branch(cx - 4, trunkTop - 7, -Math.PI * 0.60, 62, 9, 7);
|
||||
branch(cx, trunkTop - 6, -Math.PI * 0.55, 70, 9, 7);
|
||||
branch(cx, trunkTop - 7, -Math.PI * 0.50, 73, 9, 7);
|
||||
branch(cx, trunkTop - 7, -Math.PI * 0.55, 77, 9, 7);
|
||||
branch(cx, trunkTop - 6, -Math.PI * 0.45, 70, 9, 7);
|
||||
branch(cx, trunkTop - 6, -Math.PI * 0.60, 70, 9, 7);
|
||||
branch(cx, trunkTop - 6, -Math.PI * 0.40, 70, 9, 7);
|
||||
branch(cx + 30, trunkTop + 8, -Math.PI * 0.1, 65, 11, 7);
|
||||
branch(cx + 22, trunkTop + 4, -Math.PI * 0.18, 65, 10, 7);
|
||||
branch(cx + 14, trunkTop, -Math.PI * 0.22, 63, 10, 7);
|
||||
branch(cx + 14, trunkTop, -Math.PI * 0.25, 65, 10, 7);
|
||||
branch(cx + 8, trunkTop - 4, -Math.PI * 0.32, 61, 9, 7);
|
||||
branch(cx + 4, trunkTop - 7, -Math.PI * 0.40, 62, 9, 7);
|
||||
branch(cx + 2, trunkTop + 4, -Math.PI * 0.45, 67, 10, 7);
|
||||
branch(cx + 2, trunkTop + 5, -Math.PI * 0.17, 67, 10, 7);
|
||||
branch(cx - 10, trunkTop + 20, -Math.PI * 0.75, 45, 7, 6);
|
||||
branch(cx - 5, trunkTop + 20, -Math.PI * 0.62, 42, 6, 6);
|
||||
branch(cx, trunkTop + 18, -Math.PI * 0.50, 44, 7, 6);
|
||||
branch(cx + 10, trunkTop + 20, -Math.PI * 0.25, 45, 7, 6);
|
||||
branch(cx + 5, trunkTop + 20, -Math.PI * 0.38, 42, 6, 6);
|
||||
branch(cx + 3, trunkTop - 6, -Math.PI * 0.68, 10, 9, 7);
|
||||
branch(cx - 3, trunkTop - 7, -Math.PI * 0.32, 10, 9, 7);
|
||||
branch(cx + 3, trunkTop - 6, -Math.PI * 0.7, 5, 9, 7);
|
||||
branch(cx - 3, trunkTop - 7, -Math.PI * 0.3, 5, 9, 7);
|
||||
branch(cx + 3, trunkTop - 6, -Math.PI * 0.73, 20, 9, 7);
|
||||
branch(cx, trunkTop - 3, -Math.PI * 0.15, 90, 5, 3);
|
||||
|
||||
|
||||
|
||||
return { woodGrid, leafGrid };
|
||||
}
|
||||
const WOOD_COLORS = ['', '#c96303', '#c96303', '#c96303', '#321901'];
|
||||
const LEAF_COLORS = ['', '#ed5145', '#fdb068', '#fee5cd'];
|
||||
const GROUND_COLORS = ['#fee5cd', '#fdca9b', '#fdb068'];
|
||||
const GRASS_COLORS = ['#ed5145', '#fb7b04', '#c96303', '#f17c74'];
|
||||
|
||||
function hexToRgba(hex: string) {
|
||||
return [
|
||||
parseInt(hex.slice(1, 3), 16),
|
||||
parseInt(hex.slice(3, 5), 16),
|
||||
parseInt(hex.slice(5, 7), 16),
|
||||
255,
|
||||
];
|
||||
}
|
||||
|
||||
const COLOR_RGBA = new Map(
|
||||
[...WOOD_COLORS, ...LEAF_COLORS, ...GROUND_COLORS, ...GRASS_COLORS]
|
||||
.filter(Boolean)
|
||||
.map((color) => [color, hexToRgba(color)]),
|
||||
);
|
||||
|
||||
export const TRUNK_TOP_CSS = (H - 150) + 10;
|
||||
|
||||
let cachedTreeCanvas: HTMLCanvasElement | null = null;
|
||||
|
||||
function renderTreeCanvas() {
|
||||
if (cachedTreeCanvas) return cachedTreeCanvas;
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
canvas.width = W * PX;
|
||||
canvas.height = H * PX;
|
||||
ctx.imageSmoothingEnabled = false;
|
||||
|
||||
const { woodGrid, leafGrid } = buildTree(55);
|
||||
const pixelCanvas = document.createElement("canvas");
|
||||
const pixelCtx = pixelCanvas.getContext("2d")!;
|
||||
pixelCanvas.width = W;
|
||||
pixelCanvas.height = H;
|
||||
const image = pixelCtx.createImageData(W, H);
|
||||
|
||||
function setPixel(x: number, y: number, color: string) {
|
||||
const rgba = COLOR_RGBA.get(color)!;
|
||||
const index = (y * W + x) * 4;
|
||||
image.data[index] = rgba[0];
|
||||
image.data[index + 1] = rgba[1];
|
||||
image.data[index + 2] = rgba[2];
|
||||
image.data[index + 3] = rgba[3];
|
||||
}
|
||||
|
||||
for (let y = 0; y < H; y++)
|
||||
for (let x = 0; x < W; x++) {
|
||||
const v = woodGrid[y * W + x];
|
||||
if (v) setPixel(x, y, WOOD_COLORS[v] ?? '#321901');
|
||||
}
|
||||
|
||||
for (let y = 0; y < H; y++)
|
||||
for (let x = 0; x < W; x++) {
|
||||
const v = leafGrid[y * W + x];
|
||||
if (v) setPixel(x, y, LEAF_COLORS[v]);
|
||||
}
|
||||
|
||||
const GROUND_Y = H - 50;
|
||||
|
||||
let gs = 12345;
|
||||
function grassRand() {
|
||||
gs = (gs * 16807 + 0) % 2147483647;
|
||||
return (gs & 0x7fffffff) / 0x7fffffff;
|
||||
}
|
||||
|
||||
for (let x = 0; x < W; x++) {
|
||||
const wave = Math.sin(x * 0.05) * 3 + Math.sin(x * 0.12) * 2;
|
||||
const groundTop = Math.round(GROUND_Y + wave);
|
||||
for (let y = groundTop; y < H; y++) {
|
||||
const depth = (y - groundTop) / (H - groundTop);
|
||||
const ci = depth < 0.3 ? 0 : depth < 0.7 ? 1 : 2;
|
||||
setPixel(x, y, GROUND_COLORS[ci]);
|
||||
}
|
||||
}
|
||||
|
||||
for (let x = 0; x < W; x++) {
|
||||
if (grassRand() > 0.35) continue;
|
||||
const wave = Math.sin(x * 0.05) * 3 + Math.sin(x * 0.12) * 2;
|
||||
const surfaceY = Math.round(GROUND_Y + wave);
|
||||
const bladeH = Math.floor(grassRand() * 4) + 2;
|
||||
const color = GRASS_COLORS[Math.floor(grassRand() * GRASS_COLORS.length)];
|
||||
for (let b = 0; b < bladeH; b++) {
|
||||
setPixel(x, surfaceY - b - 1, color);
|
||||
}
|
||||
if (grassRand() > 0.6 && x + 1 < W) {
|
||||
setPixel(x + 1, surfaceY - 1, color);
|
||||
}
|
||||
}
|
||||
|
||||
pixelCtx.putImageData(image, 0, 0);
|
||||
ctx.drawImage(pixelCanvas, 0, 0, canvas.width, canvas.height);
|
||||
cachedTreeCanvas = canvas;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
export function prewarmTreeCanvas() {
|
||||
renderTreeCanvas();
|
||||
}
|
||||
|
||||
const Tree = forwardRef<HTMLCanvasElement>(function Tree(_, ref) {
|
||||
const internalRef = useRef<HTMLCanvasElement>(null);
|
||||
const canvasRef = (ref as React.RefObject<HTMLCanvasElement>) ?? internalRef;
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return undefined;
|
||||
|
||||
const draw = () => {
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
canvas.width = W * PX;
|
||||
canvas.height = H * PX;
|
||||
ctx.drawImage(renderTreeCanvas(), 0, 0);
|
||||
};
|
||||
const requestIdle = window.requestIdleCallback ?? ((callback) => window.setTimeout(callback, 100));
|
||||
const cancelIdle = window.cancelIdleCallback ?? window.clearTimeout;
|
||||
const idleId = requestIdle(draw, { timeout: 700 });
|
||||
|
||||
return () => cancelIdle(idleId);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="tree"
|
||||
style={{ imageRendering: "pixelated" }}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
export default Tree;
|
||||
@@ -0,0 +1,150 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>__SEO_TITLE__</title>
|
||||
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#e82517" />
|
||||
<meta name="application-name" content="Toothless' TSS Bot" />
|
||||
<style>
|
||||
html { background: #130d08; }
|
||||
html[data-theme="dark"] { background: #130d08; color-scheme: dark; }
|
||||
html[data-theme="dark"] body,
|
||||
html[data-theme="dark"] #root { background: #130d08; }
|
||||
html[data-theme="light"] { background: #fefde7; color-scheme: light; }
|
||||
html[data-theme="light"] body,
|
||||
html[data-theme="light"] #root { background: #fefde7; }
|
||||
</style>
|
||||
<script>
|
||||
(() => {
|
||||
const cookies = Object.fromEntries(
|
||||
document.cookie.split('; ').filter(Boolean).map((item) => {
|
||||
const separator = item.indexOf('=')
|
||||
const key = separator === -1 ? item : item.slice(0, separator)
|
||||
const value = separator === -1 ? '' : item.slice(separator + 1)
|
||||
try {
|
||||
return [decodeURIComponent(key), decodeURIComponent(value)]
|
||||
} catch {
|
||||
return [key, value]
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
let theme = cookies['tssbot_theme']
|
||||
if (!theme) {
|
||||
try {
|
||||
theme = localStorage.getItem('tssbot.theme')
|
||||
} catch {}
|
||||
}
|
||||
theme = theme === 'light' ? 'light' : 'dark'
|
||||
const bg = theme === 'dark' ? '#130d08' : '#fefde7'
|
||||
|
||||
document.documentElement.dataset.theme = theme
|
||||
document.documentElement.style.backgroundColor = bg
|
||||
document.documentElement.style.colorScheme = theme
|
||||
|
||||
const customColor = cookies['tssbot_custom_color'] || localStorage.getItem('tssbot.customColor')
|
||||
if (customColor && /^#[0-9a-fA-F]{6}$/.test(customColor)) {
|
||||
document.documentElement.style.setProperty('--color-fury-cyan', customColor)
|
||||
document.documentElement.style.setProperty('--color-ring', customColor)
|
||||
|
||||
const bigint = parseInt(customColor.replace('#', ''), 16)
|
||||
const r = (bigint >> 16) & 255
|
||||
const g = (bigint >> 8) & 255
|
||||
const b = bigint & 255
|
||||
document.documentElement.style.setProperty('--color-shadow', 'rgba(' + r + ', ' + g + ', ' + b + ', ' + (theme === 'dark' ? '0.18' : '0.12') + ')')
|
||||
|
||||
const adjust = (val, percent) => percent > 0
|
||||
? Math.max(0, Math.min(255, Math.round(val + (255 - val) * percent)))
|
||||
: Math.max(0, Math.min(255, Math.round(val * (1 + percent))))
|
||||
const formatHex = (nr, ng, nb) => '#' + ((1 << 24) + (nr << 16) + (ng << 8) + nb).toString(16).slice(1)
|
||||
|
||||
const aquaColor = formatHex(adjust(r, 0.2), adjust(g, 0.2), adjust(b, 0.2))
|
||||
const violetColor = formatHex(adjust(r, -0.2), adjust(g, -0.2), adjust(b, -0.2))
|
||||
|
||||
document.documentElement.style.setProperty('--color-fury-aqua', aquaColor)
|
||||
document.documentElement.style.setProperty('--color-fury-violet', violetColor)
|
||||
}
|
||||
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute(
|
||||
'content',
|
||||
customColor && /^#[0-9a-fA-F]{6}$/.test(customColor)
|
||||
? customColor
|
||||
: (theme === 'dark' ? '#101211' : '#e82517')
|
||||
)
|
||||
|
||||
try {
|
||||
const rawColors = cookies['tssbot_custom_colors'] || localStorage.getItem('tssbot.customColors')
|
||||
if (rawColors) {
|
||||
const colors = JSON.parse(rawColors)
|
||||
const cssVarMap = { bg: '--color-bg', surface: '--color-surface', text: '--color-text', border: '--color-border', textSoft: '--color-text-soft', textMuted: '--color-text-muted' }
|
||||
for (const [field, cssVar] of Object.entries(cssVarMap)) {
|
||||
if (colors[field] && /^#[0-9a-fA-F]{6}$/.test(colors[field])) {
|
||||
document.documentElement.style.setProperty(cssVar, colors[field])
|
||||
if (field === 'bg') document.documentElement.style.backgroundColor = colors[field]
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
let analyticsPreferences = null
|
||||
const serializedPreferences = cookies['tssbot_analytics_preferences']
|
||||
try {
|
||||
analyticsPreferences = JSON.parse(
|
||||
serializedPreferences || localStorage.getItem('tssbot.analyticsPreferences') || 'null',
|
||||
)
|
||||
} catch {}
|
||||
|
||||
window.__TSS_BOOT_PREFERENCES__ = { analyticsPreferences, theme }
|
||||
})()
|
||||
</script>
|
||||
<meta name="tss-turnstile-session" content="__TURNSTILE_SESSION__" />
|
||||
<meta
|
||||
name="description"
|
||||
content="__SEO_DESCRIPTION__"
|
||||
/>
|
||||
<meta
|
||||
name="keywords"
|
||||
content="War Thunder TSS, Tournament Service, TSS leaderboard, TSS teams, TSS battle logs, War Thunder tournaments, Toothless TSS Bot"
|
||||
/>
|
||||
<meta name="author" content="Toothless' TSS Bot" />
|
||||
<meta name="robots" content="__SEO_ROBOTS__" />
|
||||
<link rel="canonical" href="__SEO_CANONICAL__" />
|
||||
|
||||
<meta property="og:site_name" content="Toothless' TSS Bot" />
|
||||
<meta property="og:locale" content="en_GB" />
|
||||
<meta property="og:type" content="__SEO_OG_TYPE__" />
|
||||
<meta property="og:url" content="__SEO_CANONICAL__" />
|
||||
<meta property="og:title" content="__SEO_TITLE__" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="__SEO_DESCRIPTION__"
|
||||
/>
|
||||
<meta property="og:image" content="__SEO_IMAGE__" />
|
||||
<meta property="og:image:secure_url" content="__SEO_IMAGE__" />
|
||||
<meta property="og:image:type" content="image/png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta property="og:image:alt" content="Toothless' TSS Bot War Thunder TSS dashboard" />
|
||||
<meta property="article:author" content="__SEO_AUTHOR__" />
|
||||
<meta property="article:published_time" content="__SEO_PUBLISHED_TIME__" />
|
||||
<meta property="article:modified_time" content="__SEO_MODIFIED_TIME__" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="__SEO_TITLE__" />
|
||||
<meta
|
||||
name="twitter:description"
|
||||
content="__SEO_DESCRIPTION__"
|
||||
/>
|
||||
<meta name="twitter:image" content="__SEO_IMAGE__" />
|
||||
<link rel="icon" type="image/svg+xml" href="/embed-icon.svg" />
|
||||
<link rel="apple-touch-icon" href="/embed-icon.svg" />
|
||||
<script type="application/ld+json" id="site-structured-data">
|
||||
__SEO_JSON_LD__
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
# Static Public Data
|
||||
|
||||
The web server serves `/data/*` from the same public data cache used by
|
||||
`/api/tss/*`, and fills missing snapshots from the matching API route with a
|
||||
short timeout. The frontend uses `/api/tss/*` by default; set
|
||||
`VITE_STATIC_DATA=true` only for static-first experiments.
|
||||
|
||||
- `/data/leaderboard-teams.json`
|
||||
- `/data/leaderboard-players.json`
|
||||
- `/data/home-teams.json`
|
||||
- `/data/recent-games.json`
|
||||
- `/data/teams/{key}.json`
|
||||
- `/data/teams/{key}.games.json`
|
||||
- `/data/players/{key}.json`
|
||||
- `/data/games/{key}.json`
|
||||
- `/data/games/{key}.logs.json`
|
||||
|
||||
`{key}` is `encodeURIComponent(value).replace(/%/g, '~')`.
|
||||
|
||||
Snapshot files should keep the same response shape as the matching `/api/tss/*`
|
||||
endpoint. Missing files are fine: the app remembers the miss for the current
|
||||
browser session and uses the existing API route instead.
|
||||
|
||||
Do not generate every possible entity forever. Keep `/data` bounded:
|
||||
|
||||
- Always generate the small global snapshots: leaderboards, home teams, recent
|
||||
games.
|
||||
- Generate team/player/game detail snapshots only for hot items, such as current
|
||||
leaderboard entries, recent games, recently viewed pages, or pinned items.
|
||||
- Prune detail snapshots by age and access. For example: keep recent games for
|
||||
7-30 days, keep leaderboard teams/players while they remain ranked, and delete
|
||||
cold files that have not been refreshed recently.
|
||||
- Write snapshots atomically (`file.tmp` then rename) so readers never see a
|
||||
partial JSON file.
|
||||
- Serve compressed responses from the web server/CDN when possible. Keep source
|
||||
JSON minified unless humans need to inspect a fixture.
|
||||
@@ -0,0 +1,22 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96" role="img" aria-labelledby="title">
|
||||
<title id="title">Toothless' TSS Bot tree icon</title>
|
||||
<rect width="96" height="96" rx="18" fill="#fefde7"/>
|
||||
<rect x="7" y="7" width="82" height="82" rx="14" fill="#fff2e6" stroke="#fdca9b" stroke-width="4"/>
|
||||
<g shape-rendering="crispEdges">
|
||||
<rect x="43" y="48" width="10" height="26" fill="#c96303"/>
|
||||
<rect x="39" y="62" width="18" height="10" fill="#c96303"/>
|
||||
<rect x="34" y="70" width="28" height="5" fill="#c96303"/>
|
||||
<rect x="18" y="28" width="28" height="14" fill="#ed5145"/>
|
||||
<rect x="28" y="18" width="28" height="15" fill="#ed5145"/>
|
||||
<rect x="48" y="24" width="30" height="16" fill="#ed5145"/>
|
||||
<rect x="28" y="40" width="40" height="16" fill="#ed5145"/>
|
||||
<rect x="24" y="32" width="18" height="6" fill="#fdb068"/>
|
||||
<rect x="34" y="22" width="18" height="6" fill="#fdb068"/>
|
||||
<rect x="54" y="28" width="18" height="6" fill="#fdb068"/>
|
||||
<rect x="38" y="44" width="20" height="6" fill="#fdb068"/>
|
||||
<rect x="40" y="25" width="8" height="4" fill="#fee5cd"/>
|
||||
<rect x="56" y="31" width="8" height="4" fill="#fee5cd"/>
|
||||
<rect x="46" y="47" width="8" height="4" fill="#fee5cd"/>
|
||||
<rect x="14" y="76" width="68" height="6" fill="#fdca9b"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -0,0 +1,80 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-labelledby="title description">
|
||||
<title id="title">Toothless' TSS Bot</title>
|
||||
<desc id="description">A share card for Toothless' TSS Bot using the pixel tree from the home page.</desc>
|
||||
<rect width="1200" height="630" fill="#fefde7"/>
|
||||
<path d="M0 452 120 384l118 42 152-126 168 112 132-76 124 84 174-154 212 176v188H0Z" fill="#fcfbcf"/>
|
||||
<path d="M0 498 130 430l110 42 142-92 170 102 120-54 132 66 180-112 216 128v120H0Z" fill="#f9f69f"/>
|
||||
<rect x="72" y="72" width="1056" height="486" rx="28" fill="#fefde7" stroke="#fdca9b" stroke-width="6"/>
|
||||
<rect x="96" y="96" width="1008" height="438" rx="18" fill="#fff2e6" opacity=".54"/>
|
||||
|
||||
<g transform="translate(780 144) scale(.58)" shape-rendering="crispEdges">
|
||||
<rect x="0" y="0" width="500" height="420" fill="#fefde7" stroke="#fdca9b" stroke-width="6"/>
|
||||
<path d="M0 372c55-16 116-12 173 3 46 12 101 20 157 4 58-17 112-10 170 5v36H0Z" fill="#fee5cd"/>
|
||||
<path d="M0 394c54-10 110-8 172 6 54 12 108 10 160-4 58-15 112-10 168 4v20H0Z" fill="#fdca9b"/>
|
||||
|
||||
<g fill="#c96303">
|
||||
<rect x="232" y="248" width="38" height="118"/>
|
||||
<rect x="224" y="300" width="54" height="72"/>
|
||||
<rect x="214" y="346" width="76" height="34"/>
|
||||
<rect x="198" y="366" width="112" height="18"/>
|
||||
<rect x="196" y="232" width="62" height="16" transform="rotate(-28 196 232)"/>
|
||||
<rect x="248" y="222" width="64" height="14" transform="rotate(25 248 222)"/>
|
||||
<rect x="176" y="198" width="88" height="14" transform="rotate(-46 176 198)"/>
|
||||
<rect x="242" y="188" width="88" height="14" transform="rotate(42 242 188)"/>
|
||||
<rect x="150" y="164" width="92" height="12" transform="rotate(-20 150 164)"/>
|
||||
<rect x="270" y="154" width="98" height="12" transform="rotate(18 270 154)"/>
|
||||
<rect x="212" y="120" width="82" height="12" transform="rotate(-72 212 120)"/>
|
||||
<rect x="246" y="118" width="78" height="12" transform="rotate(68 246 118)"/>
|
||||
</g>
|
||||
|
||||
<g fill="#ed5145">
|
||||
<rect x="76" y="110" width="112" height="52"/>
|
||||
<rect x="114" y="70" width="128" height="62"/>
|
||||
<rect x="198" y="48" width="116" height="68"/>
|
||||
<rect x="278" y="76" width="132" height="60"/>
|
||||
<rect x="334" y="126" width="92" height="54"/>
|
||||
<rect x="102" y="160" width="116" height="58"/>
|
||||
<rect x="190" y="134" width="148" height="66"/>
|
||||
<rect x="278" y="172" width="116" height="58"/>
|
||||
</g>
|
||||
<g fill="#fdb068">
|
||||
<rect x="98" y="124" width="84" height="26"/>
|
||||
<rect x="138" y="84" width="92" height="30"/>
|
||||
<rect x="216" y="66" width="82" height="28"/>
|
||||
<rect x="292" y="92" width="96" height="30"/>
|
||||
<rect x="354" y="142" width="58" height="24"/>
|
||||
<rect x="126" y="178" width="78" height="24"/>
|
||||
<rect x="210" y="150" width="104" height="28"/>
|
||||
<rect x="300" y="190" width="76" height="24"/>
|
||||
</g>
|
||||
<g fill="#fee5cd">
|
||||
<rect x="150" y="98" width="44" height="16"/>
|
||||
<rect x="238" y="76" width="38" height="16"/>
|
||||
<rect x="314" y="104" width="48" height="16"/>
|
||||
<rect x="230" y="160" width="48" height="16"/>
|
||||
<rect x="322" y="202" width="36" height="14"/>
|
||||
</g>
|
||||
<g fill="#fb7b04">
|
||||
<rect x="74" y="360" width="6" height="18"/>
|
||||
<rect x="116" y="366" width="6" height="16"/>
|
||||
<rect x="342" y="362" width="6" height="20"/>
|
||||
<rect x="402" y="370" width="6" height="14"/>
|
||||
<rect x="444" y="364" width="6" height="18"/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(122 128)">
|
||||
<text x="0" y="36" fill="#e82517" font-family="Inter, Segoe UI, Arial, sans-serif" font-size="26" font-weight="800" letter-spacing="2">LIVE TSS INTEL</text>
|
||||
<text x="0" y="132" fill="#000" font-family="Inter, Segoe UI, Arial, sans-serif" font-size="76" font-weight="900">Toothless'</text>
|
||||
<text x="0" y="216" fill="#000" font-family="Inter, Segoe UI, Arial, sans-serif" font-size="76" font-weight="900">TSS Bot</text>
|
||||
<text x="0" y="282" fill="#555" font-family="Inter, Segoe UI, Arial, sans-serif" font-size="30" font-weight="600">Leaderboards, battle logs, uptime, and viewer analytics.</text>
|
||||
</g>
|
||||
<g transform="translate(122 458)" fill="#000" font-family="Inter, Segoe UI, Arial, sans-serif" font-size="24" font-weight="800">
|
||||
<rect x="0" y="-34" width="184" height="54" rx="8" fill="#fcfbcf" stroke="#fdca9b"/>
|
||||
<text x="24" y="2">Teams</text>
|
||||
<rect x="208" y="-34" width="214" height="54" rx="8" fill="#fcfbcf" stroke="#fdca9b"/>
|
||||
<text x="232" y="2">Battle Logs</text>
|
||||
<rect x="446" y="-34" width="154" height="54" rx="8" fill="#fcfbcf" stroke="#fdca9b"/>
|
||||
<text x="470" y="2">Uptime</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.6 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 83 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,12 @@
|
||||
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
|
||||
# File Created: 27.04.2017 18:23:39
|
||||
|
||||
newmtl wire_022022022
|
||||
Ns 32
|
||||
d 1
|
||||
Tr 0
|
||||
Tf 1 1 1
|
||||
illum 2
|
||||
Ka 0.0863 0.0863 0.0863
|
||||
Kd 0.0863 0.0863 0.0863
|
||||
Ks 0.3500 0.3500 0.3500
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 1.5 MiB |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,695 @@
|
||||
// Pure 3D replay view. No DOM beyond its own <canvas>; driven entirely by an
|
||||
// external clock (setTime) so it stays in sync with the 2D ReplayCanvasEngine.
|
||||
// Ported from the standalone REPLAY_VIEWER three.js viewer, stripped of all of
|
||||
// its own UI (labels, axes, guide lines, controls, hover/active-list panels).
|
||||
|
||||
import * as THREE from 'three'
|
||||
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
|
||||
import { OBJLoader } from 'three/addons/loaders/OBJLoader.js'
|
||||
|
||||
const MODEL_PATH = '/models/t34/'
|
||||
const MINIMAP_URL = (level) => `/api/match/minimap/${level}`
|
||||
const MINIMAP_FULL_URL = (level) => `/api/match/minimap/${level}?type=full`
|
||||
|
||||
const WIN_COLOR = '#00c800'
|
||||
const LOSE_COLOR = '#dc1e1e'
|
||||
const DRONE_COLOR = '#cbd5e1'
|
||||
|
||||
const DIRECTION_SAMPLE_MS = 700
|
||||
const DIRECTION_BLEND = 0.22
|
||||
const KILL_LINE_WINDOW_MS = 3000
|
||||
const FLIP_MAP_TEXTURE_Z = true
|
||||
|
||||
function coordsAreValid(c) {
|
||||
return c &&
|
||||
Number.isFinite(Number(c.x0)) && Number.isFinite(Number(c.z0)) &&
|
||||
Number.isFinite(Number(c.x1)) && Number.isFinite(Number(c.z1)) &&
|
||||
Number(c.x0) !== Number(c.x1) && Number(c.z0) !== Number(c.z1)
|
||||
}
|
||||
|
||||
function normalizeCoords(c) {
|
||||
if (!coordsAreValid(c)) return null
|
||||
return { x0: Number(c.x0), z0: Number(c.z0), x1: Number(c.x1), z1: Number(c.z1) }
|
||||
}
|
||||
|
||||
function mapSourceRect(baseCoords, renderCoords) {
|
||||
const base = normalizeCoords(baseCoords)
|
||||
const render = normalizeCoords(renderCoords)
|
||||
if (!base || !render) return { u: 0, v: 0, w: 1, h: 1 }
|
||||
const dx = base.x1 - base.x0
|
||||
const dz = base.z1 - base.z0
|
||||
const xLo = Math.min(render.x0, render.x1)
|
||||
const xHi = Math.max(render.x0, render.x1)
|
||||
const zLo = Math.min(render.z0, render.z1)
|
||||
const zHi = Math.max(render.z0, render.z1)
|
||||
const u0 = (xLo - base.x0) / dx
|
||||
const u1 = (xHi - base.x0) / dx
|
||||
const v0 = (zLo - base.z0) / dz
|
||||
const v1 = (zHi - base.z0) / dz
|
||||
const uMin = Math.max(0, Math.min(1, Math.min(u0, u1)))
|
||||
const uMax = Math.max(0, Math.min(1, Math.max(u0, u1)))
|
||||
const vMin = Math.max(0, Math.min(1, Math.min(v0, v1)))
|
||||
const vMax = Math.max(0, Math.min(1, Math.max(v0, v1)))
|
||||
const w = uMax - uMin
|
||||
const h = vMax - vMin
|
||||
if (!(w > 0 && h > 0)) return { u: 0, v: 0, w: 1, h: 1 }
|
||||
return { u: uMin, v: 1 - vMax, w, h }
|
||||
}
|
||||
|
||||
function fallbackBoundsCoords(bounds) {
|
||||
const pad = Math.max(bounds.planarSpan * 0.15, 250)
|
||||
return { x0: bounds.minX - pad, z0: bounds.minZ - pad, x1: bounds.maxX + pad, z1: bounds.maxZ + pad }
|
||||
}
|
||||
|
||||
function catmullRom(a, b, c, d, t) {
|
||||
const t2 = t * t
|
||||
const t3 = t2 * t
|
||||
return 0.5 * ((2 * b) + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t2 + (-a + 3 * b - 3 * c + d) * t3)
|
||||
}
|
||||
|
||||
export default class ReplayCanvas3D {
|
||||
constructor(container, data) {
|
||||
this.container = container
|
||||
this.data = data
|
||||
this.disposed = false
|
||||
this.currentT = 0
|
||||
this.selectedPlayerId = null
|
||||
this.smoothByEntity = new Map()
|
||||
|
||||
this.players = {}
|
||||
for (const p of data.players || []) this.players[p.id] = p
|
||||
this.teamWon = data.teamWon
|
||||
this.winnerSlot = Number(data.winnerSlot) || 0
|
||||
|
||||
this._buildEntities()
|
||||
this._buildCaptureModel()
|
||||
this.kills = (data.kills || []).filter((k) => k.killerPos && k.victimPos)
|
||||
|
||||
this.bounds = this._computeBounds()
|
||||
this.scale = 1200 / this.bounds.planarSpan
|
||||
|
||||
this._initThree()
|
||||
|
||||
this._mode = 'ground'
|
||||
this.mapInfo = this._resolveMapInfo('ground')
|
||||
|
||||
this._buildScene()
|
||||
this._loadTankTemplate()
|
||||
this._loadMapTexture()
|
||||
|
||||
this._animate = this._animate.bind(this)
|
||||
this._raf = requestAnimationFrame(this._animate)
|
||||
this.setTime(0)
|
||||
}
|
||||
|
||||
// ---- data adaptation -----------------------------------------------------
|
||||
|
||||
_isWinner(entity) {
|
||||
if (entity.playerId > 0) return this.players[entity.playerId]?.team === this.teamWon
|
||||
return entity.droneTeam === this.teamWon
|
||||
}
|
||||
|
||||
_colorFor(entity) {
|
||||
if (entity.playerId === 0 && entity.type === 'drone') return DRONE_COLOR
|
||||
return this._isWinner(entity) ? WIN_COLOR : LOSE_COLOR
|
||||
}
|
||||
|
||||
_buildEntities() {
|
||||
this.entities = []
|
||||
for (const e of this.data.entities || []) {
|
||||
if (!Array.isArray(e.path) || !e.path.length) continue
|
||||
const path = e.path.map((p) => ({ t: Number(p.t), x: Number(p.x), y: Number(p.y || 0), z: Number(p.z) }))
|
||||
this.entities.push({
|
||||
playerId: e.playerId,
|
||||
entityIndex: e.entityIndex,
|
||||
type: e.type,
|
||||
droneTeam: e.droneTeam,
|
||||
path,
|
||||
startT: path[0].t,
|
||||
endT: path[path.length - 1].t,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
_buildCaptureModel() {
|
||||
const areas = Array.isArray(this.data.captureAreas) ? this.data.captureAreas : []
|
||||
const state = this.data.captureState || {}
|
||||
this.captureZones = areas.map((area, index) => {
|
||||
const letter = String.fromCharCode(65 + index)
|
||||
const cap = Array.isArray(state[letter])
|
||||
? state[letter].map(([t, v]) => [Number(t), Number(v)]).filter(([t, v]) => Number.isFinite(t) && Number.isFinite(v))
|
||||
: []
|
||||
const center = area.tm?.center || [area.x, 0, area.z]
|
||||
return {
|
||||
key: letter,
|
||||
center: { x: Number(area.x ?? center[0]), y: Number(center[1] || 0), z: Number(area.z ?? center[2]) },
|
||||
radius: Math.max(1, Number(area.radius) || 1),
|
||||
cap,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
_computeBounds() {
|
||||
const b = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity, minZ: Infinity, maxZ: -Infinity }
|
||||
for (const e of this.entities) {
|
||||
for (const p of e.path) {
|
||||
b.minX = Math.min(b.minX, p.x); b.maxX = Math.max(b.maxX, p.x)
|
||||
b.minY = Math.min(b.minY, p.y); b.maxY = Math.max(b.maxY, p.y)
|
||||
b.minZ = Math.min(b.minZ, p.z); b.maxZ = Math.max(b.maxZ, p.z)
|
||||
}
|
||||
}
|
||||
if (!Number.isFinite(b.minX)) { b.minX = 0; b.maxX = 1; b.minY = 0; b.maxY = 1; b.minZ = 0; b.maxZ = 1 }
|
||||
b.centerX = (b.minX + b.maxX) / 2
|
||||
b.centerZ = (b.minZ + b.maxZ) / 2
|
||||
b.spanX = Math.max(1, b.maxX - b.minX)
|
||||
b.spanZ = Math.max(1, b.maxZ - b.minZ)
|
||||
b.planarSpan = Math.max(b.spanX, b.spanZ)
|
||||
return b
|
||||
}
|
||||
|
||||
_resolveMapInfo(mode) {
|
||||
const level = this.data.mission?.level
|
||||
const full = this.data.fullMapLevel
|
||||
if (mode === 'air' && full && normalizeCoords(this.data.mapCoords)) {
|
||||
const coords = normalizeCoords(this.data.mapCoords)
|
||||
return { image: MINIMAP_FULL_URL(full), coords, baseCoords: coords, sourceRect: { u: 0, v: 0, w: 1, h: 1 } }
|
||||
}
|
||||
const coords = normalizeCoords(this.data.levelCoords) || fallbackBoundsCoords(this.bounds)
|
||||
const baseCoords = normalizeCoords(this.data.tankMapCoords) || coords
|
||||
return {
|
||||
image: level ? MINIMAP_URL(level) : null,
|
||||
coords,
|
||||
baseCoords,
|
||||
sourceRect: mapSourceRect(baseCoords, coords),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- coordinate transforms ----------------------------------------------
|
||||
|
||||
_toWorld(p) {
|
||||
const b = this.bounds
|
||||
return new THREE.Vector3(
|
||||
(p.x - b.centerX) * this.scale,
|
||||
(p.y - b.minY) * this.scale,
|
||||
(p.z - b.centerZ) * this.scale,
|
||||
)
|
||||
}
|
||||
|
||||
_renderPoint(p) {
|
||||
if (!FLIP_MAP_TEXTURE_Z) return p
|
||||
const coords = normalizeCoords(this.mapInfo?.coords)
|
||||
if (!coords) return p
|
||||
return { ...p, z: coords.z0 + coords.z1 - p.z }
|
||||
}
|
||||
|
||||
// ---- three.js setup ------------------------------------------------------
|
||||
|
||||
_initThree() {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.className = 'rc3d-canvas'
|
||||
this.canvasEl = canvas
|
||||
this.container.appendChild(canvas)
|
||||
|
||||
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true })
|
||||
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2))
|
||||
this.renderer.setClearColor(0x0b0d10, 1)
|
||||
|
||||
this.scene = new THREE.Scene()
|
||||
this.camera = new THREE.PerspectiveCamera(55, 1, 0.1, 20000)
|
||||
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
|
||||
this.controls.enableDamping = true
|
||||
this.controls.dampingFactor = 0.08
|
||||
this.controls.screenSpacePanning = false
|
||||
this.controls.maxPolarAngle = Math.PI * 0.49
|
||||
this.controls.mouseButtons.LEFT = THREE.MOUSE.ROTATE
|
||||
this.controls.mouseButtons.MIDDLE = THREE.MOUSE.DOLLY
|
||||
this.controls.mouseButtons.RIGHT = THREE.MOUSE.PAN
|
||||
|
||||
this.root = new THREE.Group()
|
||||
this.mapGroup = new THREE.Group()
|
||||
this.pathGroup = new THREE.Group()
|
||||
this.zoneGroup = new THREE.Group()
|
||||
this.killLineGroup = new THREE.Group()
|
||||
this.markerGroup = new THREE.Group()
|
||||
this.root.add(this.mapGroup, this.pathGroup, this.zoneGroup, this.killLineGroup, this.markerGroup)
|
||||
this.scene.add(this.root)
|
||||
|
||||
this.scene.add(new THREE.AmbientLight(0xffffff, 0.72))
|
||||
const sun = new THREE.DirectionalLight(0xffffff, 1.1)
|
||||
sun.position.set(240, 500, 180)
|
||||
this.scene.add(sun)
|
||||
|
||||
this.resize()
|
||||
}
|
||||
|
||||
_worldMapExtents(coords = this.mapInfo?.coords) {
|
||||
const c = normalizeCoords(coords)
|
||||
if (!c) return null
|
||||
const a = this._toWorld({ x: c.x0, y: this.bounds.minY, z: c.z0 })
|
||||
const b = this._toWorld({ x: c.x1, y: this.bounds.minY, z: c.z1 })
|
||||
return {
|
||||
minX: Math.min(a.x, b.x), maxX: Math.max(a.x, b.x),
|
||||
minZ: Math.min(a.z, b.z), maxZ: Math.max(a.z, b.z),
|
||||
width: Math.abs(b.x - a.x), depth: Math.abs(b.z - a.z),
|
||||
}
|
||||
}
|
||||
|
||||
_resetCamera() {
|
||||
const ext = this._worldMapExtents()
|
||||
const span = Math.max(ext?.width || 1400, ext?.depth || 1400, 100)
|
||||
this.camera.position.set(span * 0.45, span * 0.55, span * 0.72)
|
||||
this.controls.target.set(0, 0, 0)
|
||||
this.controls.minDistance = Math.max(18, span * 0.025)
|
||||
this.controls.maxDistance = Math.max(320, span * 1.8)
|
||||
this.camera.far = Math.max(9000, span * 8)
|
||||
this.camera.updateProjectionMatrix()
|
||||
this.controls.update()
|
||||
}
|
||||
|
||||
// ---- scene construction --------------------------------------------------
|
||||
|
||||
_buildScene() {
|
||||
this._clearGroup(this.mapGroup)
|
||||
this._clearGroup(this.pathGroup)
|
||||
this._clearGroup(this.markerGroup)
|
||||
this._clearGroup(this.zoneGroup)
|
||||
this._clearGroup(this.killLineGroup)
|
||||
this._buildMapPlane()
|
||||
this._buildCaptureZones()
|
||||
this._buildKillLines()
|
||||
this.visualEntities = this.entities.map((e) => this._makeVisualEntity(e))
|
||||
this._applyHighlight()
|
||||
this._resetCamera()
|
||||
}
|
||||
|
||||
_clearGroup(group) {
|
||||
for (const child of [...group.children]) {
|
||||
group.remove(child)
|
||||
child.traverse?.((c) => {
|
||||
if (c.geometry) c.geometry.dispose()
|
||||
if (c.material) (Array.isArray(c.material) ? c.material : [c.material]).forEach((m) => m.dispose())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
_buildMapPlane() {
|
||||
const info = this.mapInfo
|
||||
if (!info || !coordsAreValid(info.coords)) return
|
||||
const x0 = Math.min(info.coords.x0, info.coords.x1)
|
||||
const x1 = Math.max(info.coords.x0, info.coords.x1)
|
||||
const z0 = Math.min(info.coords.z0, info.coords.z1)
|
||||
const z1 = Math.max(info.coords.z0, info.coords.z1)
|
||||
const width = Math.max(1, (x1 - x0) * this.scale)
|
||||
const depth = Math.max(1, (z1 - z0) * this.scale)
|
||||
const center = this._toWorld({ x: (x0 + x1) / 2, y: this.bounds.minY, z: (z0 + z1) / 2 })
|
||||
|
||||
const geometry = new THREE.PlaneGeometry(width, depth, 1, 1)
|
||||
this._applyPlaneUvs(geometry, info.sourceRect || { u: 0, v: 0, w: 1, h: 1 })
|
||||
geometry.rotateX(-Math.PI / 2)
|
||||
|
||||
const material = new THREE.MeshBasicMaterial({
|
||||
color: 0x18202a, transparent: true, opacity: 0.92, depthWrite: false, side: THREE.DoubleSide,
|
||||
})
|
||||
const plane = new THREE.Mesh(geometry, material)
|
||||
plane.position.set(center.x, -0.12, center.z)
|
||||
plane.renderOrder = -10
|
||||
this.mapGroup.add(plane)
|
||||
this._mapMaterial = material
|
||||
}
|
||||
|
||||
_applyPlaneUvs(geometry, rect) {
|
||||
const u0 = rect.u
|
||||
const u1 = rect.u + rect.w
|
||||
const vTop = rect.v
|
||||
const vBottom = rect.v + rect.h
|
||||
const uv = geometry.attributes.uv
|
||||
if (FLIP_MAP_TEXTURE_Z) {
|
||||
uv.setXY(0, u0, 1 - vTop); uv.setXY(1, u1, 1 - vTop)
|
||||
uv.setXY(2, u0, 1 - vBottom); uv.setXY(3, u1, 1 - vBottom)
|
||||
} else {
|
||||
uv.setXY(0, u0, 1 - vBottom); uv.setXY(1, u1, 1 - vBottom)
|
||||
uv.setXY(2, u0, 1 - vTop); uv.setXY(3, u1, 1 - vTop)
|
||||
}
|
||||
uv.needsUpdate = true
|
||||
}
|
||||
|
||||
_loadMapTexture() {
|
||||
if (!this.mapInfo.image || !this._mapMaterial) return
|
||||
const material = this._mapMaterial
|
||||
new THREE.TextureLoader().load(
|
||||
this.mapInfo.image,
|
||||
(texture) => {
|
||||
if (this.disposed) { texture.dispose(); return }
|
||||
texture.colorSpace = THREE.SRGBColorSpace
|
||||
texture.anisotropy = this.renderer.capabilities.getMaxAnisotropy()
|
||||
material.map = texture
|
||||
material.color.setHex(0xffffff)
|
||||
material.needsUpdate = true
|
||||
},
|
||||
undefined,
|
||||
() => { material.color.setHex(0x1f2933); material.opacity = 0.6 },
|
||||
)
|
||||
}
|
||||
|
||||
_makeVisualEntity(entity) {
|
||||
const color = this._colorFor(entity)
|
||||
const points = entity.path.map((p) => this._toWorld(this._renderPoint(p)))
|
||||
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points)
|
||||
const lineMaterial = new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.42 })
|
||||
const line = new THREE.Line(lineGeometry, lineMaterial)
|
||||
this.pathGroup.add(line)
|
||||
|
||||
const radius = 4.4
|
||||
let model
|
||||
if (this.unitTemplate && entity.type === 'ground') {
|
||||
model = this.unitTemplate.clone(true)
|
||||
model.traverse((child) => {
|
||||
if (!child.isMesh) return
|
||||
child.material = new THREE.MeshStandardMaterial({
|
||||
color, roughness: 0.72, metalness: 0.06, flatShading: true,
|
||||
emissive: new THREE.Color(color).multiplyScalar(0.22),
|
||||
})
|
||||
})
|
||||
} else {
|
||||
const geo = new THREE.SphereGeometry(radius, 18, 12)
|
||||
const mat = new THREE.MeshStandardMaterial({
|
||||
color, emissive: new THREE.Color(color).multiplyScalar(0.24), roughness: 0.45, metalness: 0.08,
|
||||
})
|
||||
model = new THREE.Mesh(geo, mat)
|
||||
}
|
||||
|
||||
const arrow = new THREE.ArrowHelper(
|
||||
new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0),
|
||||
radius * 4.6, new THREE.Color(color), radius * 1.55, radius * 0.9,
|
||||
)
|
||||
arrow.line.material.transparent = true
|
||||
arrow.line.material.opacity = 0.78
|
||||
arrow.cone.material.transparent = true
|
||||
arrow.cone.material.opacity = 0.95
|
||||
|
||||
const group = new THREE.Group()
|
||||
group.add(model, arrow)
|
||||
this.markerGroup.add(group)
|
||||
|
||||
return { entity, line, group, model, arrow, radius, smoothedDirection: null, lastDirectionT: null }
|
||||
}
|
||||
|
||||
async _loadTankTemplate() {
|
||||
try {
|
||||
const object = await new Promise((resolve, reject) => {
|
||||
const loader = new OBJLoader()
|
||||
loader.setPath(MODEL_PATH)
|
||||
loader.load('t_34_obj.obj', resolve, undefined, reject)
|
||||
})
|
||||
if (this.disposed) return
|
||||
|
||||
const planes = []
|
||||
object.traverse((child) => {
|
||||
if (!child.isMesh) return
|
||||
child.castShadow = false
|
||||
child.receiveShadow = false
|
||||
if (/^Plane/i.test(child.name || '')) { planes.push(child); return }
|
||||
})
|
||||
for (const plane of planes) plane.removeFromParent()
|
||||
|
||||
const box = new THREE.Box3()
|
||||
object.traverse((child) => { if (child.isMesh) box.expandByObject(child) })
|
||||
if (box.isEmpty()) box.setFromObject(object)
|
||||
const size = box.getSize(new THREE.Vector3())
|
||||
const maxDim = Math.max(size.x, size.y, size.z, 1)
|
||||
const scale = 70 / maxDim
|
||||
const center = box.getCenter(new THREE.Vector3())
|
||||
|
||||
const pivot = new THREE.Group()
|
||||
object.position.x -= center.x
|
||||
object.position.z -= center.z
|
||||
object.position.y -= box.min.y
|
||||
pivot.add(object)
|
||||
pivot.scale.setScalar(scale)
|
||||
this.unitTemplate = pivot
|
||||
|
||||
// Rebuild ground entities now that the model is available.
|
||||
this._buildScene()
|
||||
this.setTime(this.currentT)
|
||||
} catch {
|
||||
// No model -> spheres are used; nothing else to do.
|
||||
}
|
||||
}
|
||||
|
||||
// ---- capture zones -------------------------------------------------------
|
||||
|
||||
_buildCaptureZones() {
|
||||
for (const zone of this.captureZones) {
|
||||
const center = this._toWorld(this._renderPoint(zone.center))
|
||||
const radius = Math.max(8, zone.radius * this.scale)
|
||||
const group = new THREE.Group()
|
||||
group.position.set(center.x, 1.05, center.z)
|
||||
|
||||
const ringGeo = new THREE.RingGeometry(radius * 0.92, radius, 96)
|
||||
ringGeo.rotateX(-Math.PI / 2)
|
||||
const ring = new THREE.Mesh(ringGeo, new THREE.MeshBasicMaterial({
|
||||
color: 0xdde6ee, transparent: true, opacity: 0.7, depthWrite: false, side: THREE.DoubleSide,
|
||||
}))
|
||||
ring.renderOrder = 8
|
||||
|
||||
const fillGeo = new THREE.CircleGeometry(radius * 0.82, 96)
|
||||
fillGeo.rotateX(-Math.PI / 2)
|
||||
const fill = new THREE.Mesh(fillGeo, new THREE.MeshBasicMaterial({
|
||||
color: 0xd8dee9, transparent: true, opacity: 0, depthWrite: false, side: THREE.DoubleSide,
|
||||
}))
|
||||
fill.position.y = 0.02
|
||||
fill.renderOrder = 7
|
||||
|
||||
group.add(fill, ring)
|
||||
group.userData = { zone, fill }
|
||||
this.zoneGroup.add(group)
|
||||
}
|
||||
}
|
||||
|
||||
// Step interpolation, matching the 2D engine's _interpSeries(series, t, true).
|
||||
_captureValueAt(zone, t) {
|
||||
const cap = zone.cap
|
||||
if (!cap.length) return 0
|
||||
if (t <= cap[0][0]) return cap[0][1]
|
||||
const last = cap[cap.length - 1]
|
||||
if (t >= last[0]) return last[1]
|
||||
for (let i = 1; i < cap.length; i++) {
|
||||
if (cap[i][0] >= t) return cap[i - 1][1]
|
||||
}
|
||||
return last[1]
|
||||
}
|
||||
|
||||
_updateCaptureZones() {
|
||||
for (const group of this.zoneGroup.children) {
|
||||
const { zone, fill } = group.userData
|
||||
if (!zone || !fill) continue
|
||||
// Same logic as the 2D engine: owner is slot 2 if value>0 else slot 1,
|
||||
// coloured green when it matches the winning slot, red otherwise.
|
||||
const value = this._captureValueAt(zone, this.currentT)
|
||||
const frac = Math.min(1, Math.abs(value) / 100)
|
||||
if (frac <= 0.01) { fill.visible = false; continue }
|
||||
const ownerSlot = value > 0 ? 2 : 1
|
||||
fill.visible = true
|
||||
fill.material.color.set(ownerSlot === this.winnerSlot ? WIN_COLOR : LOSE_COLOR)
|
||||
fill.material.opacity = 0.18 + frac * 0.34
|
||||
const s = Math.sqrt(frac)
|
||||
fill.scale.set(s, s, 1)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- kill lines ----------------------------------------------------------
|
||||
|
||||
_buildKillLines() {
|
||||
this.killLines = []
|
||||
for (const k of this.kills) {
|
||||
const start = this._toWorld(this._renderPoint({ x: k.killerPos.x, y: this.bounds.minY, z: k.killerPos.z }))
|
||||
const end = this._toWorld(this._renderPoint({ x: k.victimPos.x, y: this.bounds.minY, z: k.victimPos.z }))
|
||||
start.y += 12; end.y += 12
|
||||
const vec = end.clone().sub(start)
|
||||
const length = vec.length()
|
||||
if (length < 0.5) continue
|
||||
const color = new THREE.Color(this.players[k.killerId]?.team === this.teamWon ? WIN_COLOR : LOSE_COLOR)
|
||||
const arrow = new THREE.ArrowHelper(vec.clone().normalize(), start, length, color,
|
||||
Math.min(28, Math.max(10, length * 0.12)), Math.min(16, Math.max(7, length * 0.055)))
|
||||
for (const m of [arrow.line.material, arrow.cone.material]) {
|
||||
m.transparent = true; m.opacity = 0; m.depthTest = false; m.depthWrite = false
|
||||
}
|
||||
arrow.renderOrder = 18
|
||||
arrow.visible = false
|
||||
this.killLineGroup.add(arrow)
|
||||
this.killLines.push({ time: k.time, arrow })
|
||||
}
|
||||
}
|
||||
|
||||
_updateKillLines() {
|
||||
for (const { time, arrow } of this.killLines) {
|
||||
const age = this.currentT - time
|
||||
const visible = age >= 0 && age <= KILL_LINE_WINDOW_MS
|
||||
arrow.visible = visible
|
||||
if (!visible) continue
|
||||
const opacity = 1 - age / KILL_LINE_WINDOW_MS
|
||||
arrow.line.material.opacity = 0.18 + opacity * 0.62
|
||||
arrow.cone.material.opacity = 0.24 + opacity * 0.72
|
||||
}
|
||||
}
|
||||
|
||||
// ---- interpolation -------------------------------------------------------
|
||||
|
||||
_findSegment(entity, t) {
|
||||
const path = entity.path
|
||||
if (t < entity.startT || t > entity.endT) return null
|
||||
let lo = 0, hi = path.length - 1
|
||||
while (lo < hi - 1) {
|
||||
const mid = (lo + hi) >> 1
|
||||
if (path[mid].t <= t) lo = mid; else hi = mid
|
||||
}
|
||||
return { index: lo, a: path[lo], b: path[Math.min(lo + 1, path.length - 1)] }
|
||||
}
|
||||
|
||||
_interp(entity, t) {
|
||||
const seg = this._findSegment(entity, t)
|
||||
if (!seg) return null
|
||||
const { index, a, b } = seg
|
||||
const path = entity.path
|
||||
const span = Math.max(1, b.t - a.t)
|
||||
const alpha = Math.min(1, Math.max(0, (t - a.t) / span))
|
||||
const before = path[Math.max(0, index - 1)]
|
||||
const after = path[Math.min(path.length - 1, index + 2)]
|
||||
return {
|
||||
t,
|
||||
x: catmullRom(before.x, a.x, b.x, after.x, alpha),
|
||||
y: catmullRom(before.y, a.y, b.y, after.y, alpha),
|
||||
z: catmullRom(before.z, a.z, b.z, after.z, alpha),
|
||||
}
|
||||
}
|
||||
|
||||
_directionAt(entity, t) {
|
||||
const beforeT = Math.max(entity.startT, t - DIRECTION_SAMPLE_MS)
|
||||
const afterT = Math.min(entity.endT, t + DIRECTION_SAMPLE_MS)
|
||||
if (afterT <= beforeT) return null
|
||||
const before = this._interp(entity, beforeT)
|
||||
const after = this._interp(entity, afterT)
|
||||
if (!before || !after) return null
|
||||
const dir = this._toWorld(this._renderPoint(after)).sub(this._toWorld(this._renderPoint(before)))
|
||||
if (dir.lengthSq() < 0.0001) return null
|
||||
return dir.normalize()
|
||||
}
|
||||
|
||||
_blendedDirection(visual, t) {
|
||||
const raw = this._directionAt(visual.entity, t)
|
||||
if (!raw) return visual.smoothedDirection
|
||||
const reset = visual.lastDirectionT == null || Math.abs(t - visual.lastDirectionT) > 1800
|
||||
if (reset || !visual.smoothedDirection) visual.smoothedDirection = raw.clone()
|
||||
else visual.smoothedDirection.lerp(raw, DIRECTION_BLEND).normalize()
|
||||
visual.lastDirectionT = t
|
||||
return visual.smoothedDirection
|
||||
}
|
||||
|
||||
// ---- highlight / focus ---------------------------------------------------
|
||||
|
||||
_applyHighlight() {
|
||||
const sel = this.selectedPlayerId
|
||||
if (!this.visualEntities) return
|
||||
for (const visual of this.visualEntities) {
|
||||
const isSel = sel != null && visual.entity.playerId === sel
|
||||
const teamColor = this._colorFor(visual.entity)
|
||||
const mat = visual.line.material
|
||||
if (sel == null) {
|
||||
mat.opacity = 0.42; mat.color.set(teamColor); visual.line.renderOrder = 0
|
||||
} else if (isSel) {
|
||||
mat.opacity = 1; mat.color.set(teamColor).lerp(new THREE.Color(0xffffff), 0.35); visual.line.renderOrder = 30
|
||||
} else {
|
||||
mat.opacity = 0.08; mat.color.set(teamColor); visual.line.renderOrder = 0
|
||||
}
|
||||
if (visual.model?.isGroup) {
|
||||
visual.model.traverse((child) => {
|
||||
if (child.isMesh && child.material?.emissive) child.material.emissiveIntensity = isSel ? 2.6 : 1
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
focus(playerId) {
|
||||
this.selectedPlayerId = this.selectedPlayerId === playerId ? null : playerId
|
||||
this._applyHighlight()
|
||||
if (this.selectedPlayerId == null) return
|
||||
const visual = (this.visualEntities || []).find((v) => v.entity.playerId === playerId && v.group.visible)
|
||||
|| (this.visualEntities || []).find((v) => v.entity.playerId === playerId)
|
||||
if (!visual) return
|
||||
const p = this._interp(visual.entity, this.currentT)
|
||||
if (!p) return
|
||||
const world = this._toWorld(this._renderPoint(p))
|
||||
const offset = this.camera.position.clone().sub(this.controls.target)
|
||||
this.controls.target.copy(world)
|
||||
this.camera.position.copy(world.clone().add(offset))
|
||||
this.controls.update()
|
||||
}
|
||||
|
||||
// ---- public API ----------------------------------------------------------
|
||||
|
||||
setTime(t) {
|
||||
this.currentT = t
|
||||
if (!this.visualEntities) return
|
||||
for (const visual of this.visualEntities) {
|
||||
const p = this._interp(visual.entity, t)
|
||||
visual.group.visible = Boolean(p)
|
||||
if (!p) continue
|
||||
visual.group.position.copy(this._toWorld(this._renderPoint(p)))
|
||||
const dir = this._blendedDirection(visual, t)
|
||||
visual.arrow.visible = Boolean(dir)
|
||||
if (dir) {
|
||||
visual.arrow.setDirection(dir)
|
||||
if (visual.model?.isGroup) {
|
||||
const flat = dir.clone(); flat.y = 0
|
||||
if (flat.lengthSq() > 0) {
|
||||
flat.normalize()
|
||||
visual.model.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), flat)
|
||||
visual.model.rotateY(Math.PI)
|
||||
visual.model.rotateY(-Math.PI / 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this._updateCaptureZones()
|
||||
this._updateKillLines()
|
||||
}
|
||||
|
||||
setMode(mode) {
|
||||
const next = mode === 'air' && normalizeCoords(this.data.mapCoords) ? 'air' : 'ground'
|
||||
if (next === this._mode) return
|
||||
this._mode = next
|
||||
this.mapInfo = this._resolveMapInfo(next)
|
||||
this.smoothByEntity.clear()
|
||||
this._buildScene()
|
||||
this._loadMapTexture()
|
||||
this.setTime(this.currentT)
|
||||
}
|
||||
|
||||
resize() {
|
||||
const w = this.container.clientWidth || this.container.offsetWidth || 720
|
||||
const h = this.container.clientHeight || w
|
||||
this.renderer.setSize(w, h, false)
|
||||
this.camera.aspect = w / Math.max(1, h)
|
||||
this.camera.updateProjectionMatrix()
|
||||
}
|
||||
|
||||
_animate() {
|
||||
if (this.disposed) return
|
||||
this.controls.update()
|
||||
this.renderer.render(this.scene, this.camera)
|
||||
this._raf = requestAnimationFrame(this._animate)
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.disposed = true
|
||||
if (this._raf) cancelAnimationFrame(this._raf)
|
||||
this.controls?.dispose()
|
||||
this._clearGroup(this.mapGroup)
|
||||
this._clearGroup(this.pathGroup)
|
||||
this._clearGroup(this.markerGroup)
|
||||
this._clearGroup(this.zoneGroup)
|
||||
this._clearGroup(this.killLineGroup)
|
||||
this.renderer?.dispose()
|
||||
if (this.canvasEl?.parentNode) this.canvasEl.parentNode.removeChild(this.canvasEl)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
# Blog posts
|
||||
|
||||
Add a `.md` file in `frontend/src/blog/posts` and it will appear on `/blog` after the Vite dev server refreshes or the site is rebuilt.
|
||||
|
||||
Use this front matter at the top:
|
||||
|
||||
```md
|
||||
---
|
||||
title: Your post title
|
||||
date: 2026-06-22
|
||||
author: Heidi
|
||||
excerpt: Short one-line summary for the blog list.
|
||||
---
|
||||
|
||||
Write the post here.
|
||||
```
|
||||
|
||||
The URL slug comes from the filename, so `new-feature.md` becomes `/blog/new-feature`. You can override it with `slug: custom-url`.
|
||||
|
||||
## Markdown examples
|
||||
|
||||
Headings:
|
||||
|
||||
```md
|
||||
# Huge heading
|
||||
## Section heading
|
||||
### Small heading
|
||||
```
|
||||
|
||||
Paragraphs:
|
||||
|
||||
```md
|
||||
This is a normal paragraph.
|
||||
|
||||
Leave a blank line to start a new paragraph.
|
||||
```
|
||||
|
||||
Bullet points:
|
||||
|
||||
```md
|
||||
- First bullet
|
||||
- Second bullet
|
||||
- Third bullet
|
||||
```
|
||||
|
||||
Numbered lists:
|
||||
|
||||
```md
|
||||
1. First step
|
||||
2. Second step
|
||||
3. Third step
|
||||
```
|
||||
|
||||
Blockquotes:
|
||||
|
||||
```md
|
||||
> This text gets shown as a quote/callout.
|
||||
```
|
||||
|
||||
Links:
|
||||
|
||||
```md
|
||||
[The homepage](/)
|
||||
[Discord](https://discord.com/)
|
||||
```
|
||||
|
||||
Inline code:
|
||||
|
||||
```md
|
||||
Use `frontend/src/blog/posts` for blog posts.
|
||||
```
|
||||
|
||||
Code blocks:
|
||||
|
||||
````md
|
||||
```js
|
||||
console.log('hello from the blog')
|
||||
```
|
||||
````
|
||||
|
||||
## Images and videos
|
||||
|
||||
Put local images and videos in `frontend/public`. Files in there are served from the site root.
|
||||
|
||||
Example local file paths:
|
||||
|
||||
```txt
|
||||
frontend/public/images/news/screenshot.png
|
||||
frontend/public/videos/news/launch.mp4
|
||||
```
|
||||
|
||||
Embed an image:
|
||||
|
||||
```md
|
||||

|
||||
```
|
||||
|
||||
Embed a local video:
|
||||
|
||||
```md
|
||||
@[video](/videos/news/launch.mp4)
|
||||
```
|
||||
|
||||
Embed YouTube or Vimeo:
|
||||
|
||||
```md
|
||||
@[youtube](https://www.youtube.com/watch?v=VIDEO_ID)
|
||||
|
||||
@[vimeo](https://vimeo.com/123456789)
|
||||
```
|
||||
|
||||
YouTube embeds use the privacy-friendly `youtube-nocookie.com` player. Direct video files support `.mp4`, `.webm`, and `.ogg`.
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Update on Preventing Abuse By Bad Actors
|
||||
date: 2026-06-28
|
||||
author: Heidi
|
||||
excerpt: A conclusion on how we plan to tackle undesireable usage of the site :3
|
||||
---
|
||||
|
||||
|
||||
# ♥ Awruff :3
|
||||
Hi all, again,
|
||||
|
||||
Today we'll be talking about actions taken to prevent and limit usage by undesireables.
|
||||
|
||||
|
||||
# Who is affected
|
||||
```md
|
||||
Team: TPC
|
||||
Users:
|
||||
F-2А, 165569402 , EstonianAviator, Bad Actor Affiliation
|
||||
kаspersky, 86157459, idk, Bad Actor Affiliation
|
||||
Tonitrus_, 33536334, idk, Bad Actor Affiliation
|
||||
xbirbx, 41808996, idk, Bad Actor Affiliation
|
||||
Dеviss, 3651161, DEVISS, PEDOPHILE!!!!!!!
|
||||
```
|
||||
|
||||
This team has been blocked
|
||||
|
||||

|
||||
|
||||
## How does this affect you?
|
||||
Honestly, it shouldn't, on their DEBUT return they set a LEGENDARY kd of 0.3 and their team captain had 0 kills, 0 assists and 0 games won with 6 consecutive deaths, its kinda funny? I don't really know.
|
||||
Love you all!!!!! ♥♥♥
|
||||
|
||||
Remember to join our [Discord](https://discord.gg/kP45rcU2Jx) :3
|
||||
Mwahhh~~
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
title: Preventing Abuse By Bad Actors
|
||||
date: 2026-06-27
|
||||
author: Heidi
|
||||
excerpt: A brief on how we plan to tackle undesireable usage of the site :3
|
||||
---
|
||||
|
||||
# ♥ Awruff :3
|
||||
Hi all, again, sorry for the random blog post being dropped at 10pm on a Saturday, lol.
|
||||
|
||||
Just a brief overview of what we're going to be doing to prevent bad actors from being able to properly utilise the site.
|
||||
|
||||
# Why?
|
||||
A pedophile returned to TSS and I really dont like that, I dont think you should have to see their name on a page :3
|
||||
|
||||
## usage prevention.
|
||||
Currently, my working theory is that we could implement discord sign on, and block specific bad actors (TPC) from being able to utilise the site (blocking their discord accounts), however this would remove a lot of functionality from non logged in users, which I dont reeaally want..
|
||||
|
||||
Alternatively, I could just vandilise their user pages and team page, as well as blocking them from search results..
|
||||
|
||||
Open to suggestions, but I dont really want to have to make an account for everyone.. it would suck if you have to log in :(
|
||||
|
||||
Either way, if you have any ideas or such, feel free to drop them in our [Discord](https://discord.gg/kP45rcU2Jx) :3
|
||||
|
||||
Love you all!!!!!
|
||||
|
||||
Have fun!!!!!!!! ♥♥♥
|
||||
|
||||
|
||||
|
||||
|
||||
Current list of users (to be) blocked:
|
||||
|
||||
```md
|
||||
Team: TPC
|
||||
Users:
|
||||
F-2А, 165569402 , EstonianAviator, Bad Actor Affiliation
|
||||
kаspersky, 86157459, idk, Bad Actor Affiliation
|
||||
Tonitrus_, 33536334, idk, Bad Actor Affiliation
|
||||
xbirbx, 41808996, idk, Bad Actor Affiliation
|
||||
Dеviss, 3651161, DEVISS, PEDOPHILE!!!!!!!
|
||||
```
|
||||
|
||||
Dоn't be a creep :3
|
||||
|
||||

|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Our Launch & The Future
|
||||
date: 2026-06-22
|
||||
author: Heidi
|
||||
excerpt: A brief discussion about the site and the future.
|
||||
---
|
||||
|
||||
# ♥ Awruff :3
|
||||
Hi all, glad to see you all (mostly) like the page :3 (over 1000 page views in 24hrs (allegedly) + nothing but positive feedback)
|
||||
|
||||
Just a brief overview of what we're going to be adding in the future
|
||||
|
||||
## stuff:
|
||||
|
||||
- 3D maps for all played maps (in progress, should be done within the next few weeks)
|
||||
@[video](/videos/news/3d_map_preview.mp4)
|
||||
|
||||
- The ability to predict where a player might go on a map, basically just showing all their prior paths as either a heatmap or a couple lines with % probability, based on their historical games
|
||||
|
||||
- Missile timings to the viewer (time to impact, etc)
|
||||
|
||||
- Generally just more 3D viewer stuff, like chaff deployment, flare deployment
|
||||
|
||||
- accurate 3d models for vehicles, player cones of vision, etc.
|
||||
|
||||
Honestly, I dont really know what to add.. lol, if you have any suggestions for stuff you'd like to see, feel free to suggest them on our [Discord](https://discord.gg/kP45rcU2Jx), basically any suggestion will be reviewed :3
|
||||
|
||||
Have fun!!!!!!!! ♥♥♥
|
||||
@@ -0,0 +1,260 @@
|
||||
// Pure bracket-layout logic for the tournament detail page.
|
||||
//
|
||||
// The TSS API hands us authoritative matches, but `round` is numbered *per
|
||||
// `type_bracket`* — the winner tree, the loser tree, and the special
|
||||
// `LooserFinal`/`Semifinal`/`Final` stages each restart at round 0. Grouping by
|
||||
// raw round therefore collapses unrelated stages into one column (e.g. the loser
|
||||
// Semifinal landing in loser "Round 1"). This module maps each match to a
|
||||
// (side, stage, round) coordinate so columns come out in true bracket order, and
|
||||
// drops structural byes so they never render as "Team vs BYE" nodes.
|
||||
//
|
||||
// Kept framework-free so it can be unit-tested with plain node.
|
||||
|
||||
function lower(value) {
|
||||
return String(value || '').toLowerCase()
|
||||
}
|
||||
|
||||
export function cleanName(value) {
|
||||
return String(value || '').trim()
|
||||
}
|
||||
|
||||
// A "structural bye" is a slot that exists only to pad the bracket: a team that
|
||||
// advanced unopposed, or a placeholder whose feeders were themselves byes. We
|
||||
// hide these. A match with one known team and NO winner yet is *not* a bye —
|
||||
// it's a real pending matchup awaiting an upstream result (grand final, loser
|
||||
// bracket final), so it stays.
|
||||
export function isStructuralBye(match) {
|
||||
const a = cleanName(match.team_a_name)
|
||||
const b = cleanName(match.team_b_name)
|
||||
if (a && b) return false
|
||||
if (!a && !b) return true
|
||||
return Boolean(cleanName(match.winner_name)) || match.status === 'bye'
|
||||
}
|
||||
|
||||
// Map a TSS `type_bracket` to a display side + stage. `stage` orders the special
|
||||
// terminal columns after the numbered rounds within a side:
|
||||
// winner: Winner rounds (0) → grand/championship Final (1)
|
||||
// loser: Looser rounds (0) → LooserFinal (1) → Semifinal/lower final (2)
|
||||
export function classifyBracket(typeBracket, hasLoserSide) {
|
||||
const t = lower(typeBracket)
|
||||
if (t.includes('swiss')) return { side: 'swiss', stage: 0 }
|
||||
if (t.includes('group')) return { side: 'group', stage: 0 }
|
||||
if (t.includes('looserfinal') || t.includes('loserfinal')) return { side: 'loser', stage: 1 }
|
||||
if (t.includes('looser') || t.includes('loser')) return { side: 'loser', stage: 0 }
|
||||
if (t.includes('semifinal')) {
|
||||
// Double-elim: the Semifinal is the lower-bracket final (loser side). Single
|
||||
// elim: it's just a normal winner-side stage.
|
||||
return hasLoserSide ? { side: 'loser', stage: 2 } : { side: 'winner', stage: 0 }
|
||||
}
|
||||
if (t === 'final' || t.endsWith('final')) {
|
||||
// Terminal column of the winner side (championship / grand final).
|
||||
return { side: 'winner', stage: 1 }
|
||||
}
|
||||
if (t.includes('winner')) return { side: 'winner', stage: 0 }
|
||||
return { side: 'winner', stage: 0 }
|
||||
}
|
||||
|
||||
const SIDE_ORDER = { winner: 0, loser: 1, group: 2, swiss: 3, matches: 4 }
|
||||
const SIDE_LABELS = {
|
||||
winner: 'Winner bracket',
|
||||
loser: 'Loser bracket',
|
||||
group: 'Group matches',
|
||||
swiss: 'Swiss matches',
|
||||
matches: 'Matches',
|
||||
}
|
||||
|
||||
function asInt(value, fallback) {
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) ? n : fallback
|
||||
}
|
||||
|
||||
function compareMatches(a, b) {
|
||||
return asInt(a.position, Number.MAX_SAFE_INTEGER) - asInt(b.position, Number.MAX_SAFE_INTEGER)
|
||||
|| String(a.match_id).localeCompare(String(b.match_id))
|
||||
}
|
||||
|
||||
// Label a bracket column. Numbered rounds read "Round N" by their position in
|
||||
// the side; the terminal winner stage reads Final / Grand Final.
|
||||
function columnLabel(side, stage, index, total, hasLoserSide) {
|
||||
if (side === 'winner' && stage === 1) {
|
||||
return hasLoserSide ? 'Grand Final' : 'Final'
|
||||
}
|
||||
return `Round ${index + 1}`
|
||||
}
|
||||
|
||||
// Build the ordered bracket model from authoritative match rows.
|
||||
// Returns { sides: [{ key, label, kind, columns: [{ id, label, matches }] }] }
|
||||
// where kind is 'bracket' (elimination, drawn as a tree) or 'list' (group/swiss,
|
||||
// drawn as a flat card list).
|
||||
export function buildBracket(matches) {
|
||||
const cleaned = (matches || []).filter((m) => !isStructuralBye(m))
|
||||
|
||||
const hasLoserSide = cleaned.some((m) => {
|
||||
const t = lower(m.type_bracket)
|
||||
return t.includes('looser') || t.includes('loser') || lower(m.side) === 'loser'
|
||||
})
|
||||
|
||||
// Group by (side, stage, round) → one column each.
|
||||
const columnMap = new Map()
|
||||
for (const match of cleaned) {
|
||||
const { side, stage } = classifyBracket(match.type_bracket, hasLoserSide)
|
||||
const round = asInt(match.round, 0)
|
||||
const key = `${side}:${stage}:${round}`
|
||||
if (!columnMap.has(key)) {
|
||||
columnMap.set(key, { side, stage, round, matches: [] })
|
||||
}
|
||||
columnMap.get(key).matches.push(match)
|
||||
}
|
||||
|
||||
// Bucket columns by side, ordered by (stage, round).
|
||||
const sideMap = new Map()
|
||||
for (const column of columnMap.values()) {
|
||||
column.matches.sort(compareMatches)
|
||||
if (!sideMap.has(column.side)) sideMap.set(column.side, [])
|
||||
sideMap.get(column.side).push(column)
|
||||
}
|
||||
|
||||
const sides = [...sideMap.entries()]
|
||||
.map(([key, columns]) => {
|
||||
columns.sort((a, b) => a.stage - b.stage || a.round - b.round)
|
||||
const isList = key === 'group' || key === 'swiss' || key === 'matches'
|
||||
return {
|
||||
key,
|
||||
label: SIDE_LABELS[key] || key,
|
||||
kind: isList ? 'list' : 'bracket',
|
||||
columns: columns.map((column, index) => ({
|
||||
id: `${key}:${column.stage}:${column.round}`,
|
||||
label: columnLabel(key, column.stage, index, columns.length, hasLoserSide),
|
||||
matches: column.matches,
|
||||
})),
|
||||
}
|
||||
})
|
||||
.sort((a, b) => (SIDE_ORDER[a.key] ?? 9) - (SIDE_ORDER[b.key] ?? 9))
|
||||
|
||||
return { sides, hasLoserSide }
|
||||
}
|
||||
|
||||
// Which match in the next column a given match feeds into, by slot position.
|
||||
// Winner tree and loser "major" rounds halve (position → floor/2); loser "minor"
|
||||
// rounds (drop-ins, same width) map identically. We infer halving vs identity
|
||||
// from the column node counts. Returns the parent position, or null.
|
||||
export function parentPosition(childPosition, currentCount, nextCount) {
|
||||
if (childPosition == null) return null
|
||||
if (nextCount >= currentCount) return childPosition
|
||||
return Math.floor(childPosition / 2)
|
||||
}
|
||||
|
||||
// The match in `columns[columnIndex + 1]` that a given match feeds into. Found by
|
||||
// slot position (faithful to the real tree even with byes hidden); falls back to
|
||||
// a proportional index if the exact parent slot was itself a hidden bye.
|
||||
export function feederParent(match, columnIndex, columns) {
|
||||
const cur = columns[columnIndex]
|
||||
const next = columns[columnIndex + 1]
|
||||
if (!next) return null
|
||||
const pPos = parentPosition(Number(match.position), cur.matches.length, next.matches.length)
|
||||
const exact = next.matches.find((m) => Number(m.position) === pPos)
|
||||
if (exact) return exact
|
||||
const order = cur.matches.indexOf(match)
|
||||
const idx = Math.min(
|
||||
next.matches.length - 1,
|
||||
Math.floor((order * next.matches.length) / cur.matches.length),
|
||||
)
|
||||
return next.matches[idx] || null
|
||||
}
|
||||
|
||||
export function layoutKey(columnIndex, match) {
|
||||
return `${columnIndex}:${match.match_id}`
|
||||
}
|
||||
|
||||
// Position every match vertically so each one sits centred between the matches
|
||||
// that feed into it — the classic bracket look. Pure: takes measured card heights,
|
||||
// returns absolute `top` offsets keyed by `layoutKey`.
|
||||
//
|
||||
// Column 0 stacks top-to-bottom. Later columns centre each match on the mean of
|
||||
// its feeders' centres. Matches whose feeders were all hidden byes (no anchor)
|
||||
// are *extrapolated* from the nearest anchored sibling using the column's slot
|
||||
// pitch — including above y=0 — rather than stacked at the top, which would shove
|
||||
// the anchored matches away from their feeders and make the connectors fan and
|
||||
// cross. A final per-side shift pulls any negative offsets back on-screen.
|
||||
export function computeBracketLayout(columns, heights, gap = 16) {
|
||||
const heightOf = (c, m) => heights.get(layoutKey(c, m)) || 92
|
||||
const centers = columns.map(() => new Map())
|
||||
|
||||
columns.forEach((column, c) => {
|
||||
const matches = column.matches
|
||||
const hs = matches.map((m) => heightOf(c, m))
|
||||
const pitch = (hs.reduce((a, b) => a + b, 0) / Math.max(1, hs.length)) + gap
|
||||
|
||||
// Anchor = mean of this match's feeders' centres (null when all were byes).
|
||||
const childCenters = new Map()
|
||||
if (c > 0) {
|
||||
for (const child of columns[c - 1].matches) {
|
||||
const parent = feederParent(child, c - 1, columns)
|
||||
if (!parent) continue
|
||||
const center = centers[c - 1].get(child.match_id)
|
||||
if (center == null) continue
|
||||
if (!childCenters.has(parent.match_id)) childCenters.set(parent.match_id, [])
|
||||
childCenters.get(parent.match_id).push(center)
|
||||
}
|
||||
}
|
||||
const center = matches.map((m) => {
|
||||
const kids = childCenters.get(m.match_id)
|
||||
return kids && kids.length ? kids.reduce((a, b) => a + b, 0) / kids.length : null
|
||||
})
|
||||
|
||||
const firstAnchor = center.findIndex((v) => v != null)
|
||||
if (firstAnchor === -1) {
|
||||
// No anchors (column 0, or a fully-bye column): plain stack.
|
||||
let cursor = 0
|
||||
matches.forEach((m, i) => {
|
||||
center[i] = cursor + hs[i] / 2
|
||||
cursor += hs[i] + gap
|
||||
})
|
||||
} else {
|
||||
// Leading byes: extrapolate upward (may go negative — fixed by the shift).
|
||||
for (let i = firstAnchor - 1; i >= 0; i -= 1) center[i] = center[i + 1] - pitch
|
||||
// Trailing / interior byes: extend down / interpolate between anchors.
|
||||
let lastAnchor = firstAnchor
|
||||
for (let i = firstAnchor + 1; i < matches.length; i += 1) {
|
||||
if (center[i] != null) { lastAnchor = i; continue }
|
||||
let next = i
|
||||
while (next < matches.length && center[next] == null) next += 1
|
||||
if (next >= matches.length) {
|
||||
center[i] = center[lastAnchor] + (i - lastAnchor) * pitch
|
||||
} else {
|
||||
const span = next - lastAnchor
|
||||
center[i] = center[lastAnchor] + ((center[next] - center[lastAnchor]) * (i - lastAnchor)) / span
|
||||
}
|
||||
}
|
||||
// Resolve any residual overlap by nudging downward (rare; honours heights).
|
||||
for (let i = 1; i < matches.length; i += 1) {
|
||||
const minC = center[i - 1] + (hs[i - 1] + hs[i]) / 2 + gap
|
||||
if (center[i] < minC) center[i] = minC
|
||||
}
|
||||
}
|
||||
|
||||
matches.forEach((m, i) => centers[c].set(m.match_id, center[i]))
|
||||
})
|
||||
|
||||
// Shift the whole side so the highest match sits at y=0, then size to content.
|
||||
let minTop = Infinity
|
||||
columns.forEach((column, c) => {
|
||||
column.matches.forEach((m) => {
|
||||
minTop = Math.min(minTop, centers[c].get(m.match_id) - heightOf(c, m) / 2)
|
||||
})
|
||||
})
|
||||
const shift = Number.isFinite(minTop) && minTop < 0 ? -minTop : 0
|
||||
|
||||
const tops = new Map()
|
||||
let height = 0
|
||||
columns.forEach((column, c) => {
|
||||
column.matches.forEach((m) => {
|
||||
const h = heightOf(c, m)
|
||||
const top = centers[c].get(m.match_id) - h / 2 + shift
|
||||
tops.set(layoutKey(c, m), top)
|
||||
height = Math.max(height, top + h)
|
||||
})
|
||||
})
|
||||
|
||||
return { tops, centers, height }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './styles.css'
|
||||
import App from './App.jsx'
|
||||
|
||||
createRoot(document.getElementById('root')).render(<App />)
|
||||
File diff suppressed because it is too large
Load Diff
Generated
+3893
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "tssbot-web",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0 --port 3001",
|
||||
"build": "vite build",
|
||||
"serve": "node server.cjs",
|
||||
"webhook": "node webhook.cjs",
|
||||
"preview": "vite preview --host 0.0.0.0 --port 3001",
|
||||
"lint": "eslint ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.8",
|
||||
"@vitejs/plugin-react": "^4.5.0",
|
||||
"better-sqlite3": "^12.10.0",
|
||||
"gsap": "^3.15.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"three": "^0.184.0",
|
||||
"vite": "^6.3.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.27.0",
|
||||
"@types/react": "^19.1.5",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"eslint": "^9.27.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.20",
|
||||
"globals": "^16.1.0"
|
||||
}
|
||||
}
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs/updates the tssbot-web systemd --user units and (re)starts them.
|
||||
# Run this after cloning, and again any time a unit file under systemd/ changes.
|
||||
set -euo pipefail
|
||||
|
||||
repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
unit_dir="${HOME}/.config/systemd/user"
|
||||
mkdir -p "${unit_dir}"
|
||||
|
||||
for unit in tssbot-web tssbot-webhook tssbot-backend; do
|
||||
ln -sf "${repo_dir}/systemd/${unit}.service" "${unit_dir}/${unit}.service"
|
||||
done
|
||||
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now tssbot-web.service tssbot-webhook.service tssbot-backend.service
|
||||
|
||||
if [ "$(loginctl show-user "$(whoami)" -p Linger --value 2>/dev/null)" != "yes" ]; then
|
||||
echo "Linger is not enabled for $(whoami) — user services will stop when you log out."
|
||||
echo "Enable it with: sudo loginctl enable-linger $(whoami)"
|
||||
fi
|
||||
|
||||
systemctl --user status --no-pager tssbot-web.service tssbot-webhook.service tssbot-backend.service
|
||||
Executable
+217
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# verify_game_detail.sh — end-to-end check for the TSSBOT game-detail parity work.
|
||||
#
|
||||
# Spins up a SELF-CONTAINED fixture (temp SQLite DBs, vehicle caches, icons) and
|
||||
# exercises the whole stack: the Python log builder, the Rust backend (dedup fix,
|
||||
# vehicle translation, logs endpoint), and the Node prod server (icon serving +
|
||||
# API proxy allowlist). Touches NO production data. Exits non-zero on any failure.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/verify_game_detail.sh
|
||||
#
|
||||
# Env overrides:
|
||||
# BOTS_REPO path to the BOTS repo (default: ~/GitHub/BOTS, fallback ~/BOTS, /home/deploy/BOTS)
|
||||
# PYTHON python interpreter (default: BOTS venv if present, else python3)
|
||||
# BE_PORT backend port (default 6071)
|
||||
# WEB_PORT node server port (default 3071)
|
||||
|
||||
set -uo pipefail
|
||||
|
||||
WEB_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
BE_PORT="${BE_PORT:-6071}"
|
||||
WEB_PORT="${WEB_PORT:-3071}"
|
||||
|
||||
# ---- locate BOTS repo + python --------------------------------------------
|
||||
if [[ -z "${BOTS_REPO:-}" ]]; then
|
||||
for c in "$HOME/GitHub/BOTS" "$HOME/BOTS" "/home/deploy/BOTS"; do
|
||||
[[ -d "$c" ]] && BOTS_REPO="$c" && break
|
||||
done
|
||||
fi
|
||||
if [[ -z "${BOTS_REPO:-}" || ! -d "$BOTS_REPO" ]]; then
|
||||
echo "FAIL: could not find BOTS repo; set BOTS_REPO=..." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "${PYTHON:-}" ]]; then
|
||||
if [[ -x "$BOTS_REPO/SHARED/.venv/bin/python" ]]; then
|
||||
PYTHON="$BOTS_REPO/SHARED/.venv/bin/python"
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
fi
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
ok() { echo " PASS: $1"; PASS=$((PASS+1)); }
|
||||
bad() { echo " FAIL: $1" >&2; FAIL=$((FAIL+1)); }
|
||||
# assert_eq <label> <actual> <expected>
|
||||
assert_eq() { if [[ "$2" == "$3" ]]; then ok "$1 ($2)"; else bad "$1: got '$2' expected '$3'"; fi; }
|
||||
|
||||
WD="$(mktemp -d)"
|
||||
ICONS="$(mktemp -d)"
|
||||
STORE="$(mktemp -d)"
|
||||
BE_PID=""
|
||||
WEB_PID=""
|
||||
cleanup() {
|
||||
[[ -n "$BE_PID" ]] && kill "$BE_PID" 2>/dev/null
|
||||
[[ -n "$WEB_PID" ]] && kill "$WEB_PID" 2>/dev/null
|
||||
rm -rf "$WD" "$ICONS" "$STORE"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
echo "== TSSBOT game-detail verification =="
|
||||
echo "WEB_REPO=$WEB_REPO BOTS_REPO=$BOTS_REPO PYTHON=$PYTHON"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 1. Python log-builder unit tests =="
|
||||
if "$PYTHON" "$BOTS_REPO/TSSBOT/tests/test_match_logs.py"; then ok "build_match_logs tests"; else bad "build_match_logs tests"; fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 2. Backfill dry-run against a synthetic replay =="
|
||||
SYN="$(mktemp -d)"
|
||||
STORAGE_VOL_PATH="$SYN" "$PYTHON" - "$SYN" <<'PY'
|
||||
import gzip, json, os, pathlib, sys
|
||||
d = pathlib.Path(sys.argv[1]) / "REPLAYS" / "TSS" / "feed"
|
||||
d.mkdir(parents=True)
|
||||
game = {"_id": "feed", "winner": "[WIN]", "loser": "[LOS]",
|
||||
"players": {"1": {"name": "a", "tag": "[WIN]", "team": "1",
|
||||
"units": [{"unit": "ussr_t_34", "used": True}]}},
|
||||
"chat": [{"uid": "1", "type": "ALL", "message": "gg", "time": 1000}],
|
||||
"events": {"kills": []}}
|
||||
gzip.open(d / "replay_data.json.gz", "wb").write(json.dumps(game).encode())
|
||||
PY
|
||||
if STORAGE_VOL_PATH="$SYN" "$PYTHON" "$BOTS_REPO/TSSBOT/scripts/backfill_match_logs.py" --dry-run | grep -q "Would backfill"; then
|
||||
ok "backfill --dry-run runs"
|
||||
else
|
||||
bad "backfill --dry-run"
|
||||
fi
|
||||
rm -rf "$SYN"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 3. cargo tests + binary =="
|
||||
if cargo test --manifest-path "$WEB_REPO/backend/Cargo.toml" >/tmp/vgd_cargo.log 2>&1; then ok "cargo test"; else bad "cargo test (see /tmp/vgd_cargo.log)"; fi
|
||||
# `cargo test` only builds the test harness, not the standalone binary. Prefer the
|
||||
# release binary (built at deploy); otherwise build a debug one.
|
||||
BIN=""
|
||||
if [[ -x "$WEB_REPO/backend/target/release/tssbot-backend" ]]; then
|
||||
BIN="$WEB_REPO/backend/target/release/tssbot-backend"
|
||||
ok "using release binary"
|
||||
else
|
||||
if cargo build --manifest-path "$WEB_REPO/backend/Cargo.toml" >/tmp/vgd_build.log 2>&1; then
|
||||
BIN="$WEB_REPO/backend/target/debug/tssbot-backend"
|
||||
ok "built debug binary"
|
||||
else
|
||||
bad "cargo build (see /tmp/vgd_build.log)"
|
||||
fi
|
||||
fi
|
||||
[[ -n "$BIN" && -x "$BIN" ]] || bad "backend binary unavailable"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 4. Build fixture (multi-vehicle player to catch the double-count bug) =="
|
||||
"$PYTHON" - "$WD" <<'PY'
|
||||
import sqlite3, json, sys
|
||||
wd = sys.argv[1]
|
||||
b = sqlite3.connect(f"{wd}/tss_battles.db")
|
||||
b.executescript("""
|
||||
CREATE TABLE match_summary (session_id TEXT PRIMARY KEY, mission_mode TEXT, mission_name TEXT,
|
||||
level_path TEXT, mission_path TEXT, difficulty TEXT, starttime_unix INT, endtime_unix INT,
|
||||
duration REAL, draw INT DEFAULT 0, winning_slot TEXT, losing_slot TEXT, received_unix INT,
|
||||
tournament_id INT, tournament_name TEXT, match_id TEXT, bracket TEXT);
|
||||
CREATE TABLE player_games_hist (UID TEXT, nick TEXT, team_name TEXT, team_slot TEXT,
|
||||
session_id TEXT, vehicle TEXT, vehicle_internal TEXT, ground_kills INT, air_kills INT,
|
||||
assists INT, captures INT, deaths INT, score INT, missile_evades INT, shell_interceptions INT,
|
||||
team_kills_stat INT, country_id INT, victor_bool TEXT, endtime_unix INT, team_id INT,
|
||||
tss_role TEXT, pvp_ratio REAL);
|
||||
CREATE TABLE match_logs (session_id TEXT PRIMARY KEY, chat_log_json TEXT, battle_log_json TEXT, event_log_json TEXT, built_unix INT);
|
||||
""")
|
||||
b.execute("INSERT INTO match_summary VALUES ('abc','Dom','Test Map','','','',0,1000,420.0,0,'1','2',0,0,'Cup Finals','','')")
|
||||
# alice used TWO vehicles -> two rows, identical per-player stats (score 100).
|
||||
b.execute("INSERT INTO player_games_hist VALUES ('1','alice','TeamWin','1','abc','t34','ussr_t_34',2,0,1,0,0,100,0,0,0,0,'Win',1000,10,'',1.5)")
|
||||
b.execute("INSERT INTO player_games_hist VALUES ('1','alice','TeamWin','1','abc','is2','ussr_is_2',2,0,1,0,0,100,0,0,0,0,'Win',1000,10,'',1.5)")
|
||||
b.execute("INSERT INTO player_games_hist VALUES ('2','bob','TeamLose','2','abc','pz','germ_pz_iv',0,0,0,0,1,10,0,0,0,0,'Loss',1000,11,'',0.5)")
|
||||
b.execute("INSERT INTO match_logs VALUES ('abc', ?, ?, ?, 1000)",
|
||||
(json.dumps(["[00:01] [ALL] [WIN] `alice`: gg"]),
|
||||
json.dumps(["+[00:30] [WIN] alice (T-34) destroyed bob (Pz.IV)"]),
|
||||
json.dumps({"kills": [{"offender_uid": "1", "offender_unit": "ussr_t_34", "offended_uid": "2", "offended_unit": "germ_pz_iv", "crashed": False, "time": 30000}], "damage": [], "chat": [{"uid": "1", "type": "ALL", "message": "gg", "time": 1000}]})))
|
||||
b.commit()
|
||||
t = sqlite3.connect(f"{wd}/tss_teams.db")
|
||||
t.executescript("CREATE TABLE teams_data (team_id INT PRIMARY KEY, name TEXT, members INT DEFAULT 0, captain_uid TEXT);")
|
||||
t.commit()
|
||||
json.dump({"ussr_t_34": {"en": "T-34", "ru": "Т-34"}, "ussr_is_2": {"en": "IS-2"}}, open(f"{wd}/vt.json", "w"))
|
||||
json.dump([["ussr_t_34", "T-34", "ussr_t_34.png", {}], ["ussr_is_2", "IS-2", "ussr_is_2.png", {}]], open(f"{wd}/vc.json", "w"))
|
||||
print("fixture ready")
|
||||
PY
|
||||
printf '\x89PNG' > "$ICONS/ussr_t_34.png"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 5. Start backend + node server against the fixture =="
|
||||
TSS_BATTLES_DB="$WD/tss_battles.db" TSS_TEAMS_DB="$WD/tss_teams.db" \
|
||||
VEHICLE_TRANSLATIONS_JSON="$WD/vt.json" VEHICLE_DATA_CACHE_JSON="$WD/vc.json" \
|
||||
BACKEND_PORT="$BE_PORT" "$BIN" >/tmp/vgd_be.log 2>&1 &
|
||||
BE_PID=$!
|
||||
# Override PUBLIC_ORIGIN so the server's same-origin guard accepts the localhost
|
||||
# test origin. server.cjs's loadEnvFile only fills unset/empty vars, so these
|
||||
# non-empty values win over the prod .env.
|
||||
PORT="$WEB_PORT" API_UPSTREAM="http://127.0.0.1:$BE_PORT" VEHICLE_ICONS_DIR="$ICONS" \
|
||||
UPTIME_STORAGE_DIR="$STORE" PUBLIC_ORIGIN="http://localhost:$WEB_PORT" \
|
||||
node "$WEB_REPO/server.cjs" >/tmp/vgd_web.log 2>&1 &
|
||||
WEB_PID=$!
|
||||
# wait for both to listen
|
||||
for _ in $(seq 1 20); do
|
||||
curl -sf "localhost:$BE_PORT/health" >/dev/null 2>&1 && curl -sf "localhost:$WEB_PORT/health" >/dev/null 2>&1 && break
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 6. Backend: dedup, vehicle translation, logs =="
|
||||
GAME_EN="$(curl -s "localhost:$BE_PORT/api/tss/games/abc?lang=en")"
|
||||
echo "$GAME_EN" | "$PYTHON" - <<PY
|
||||
import json, sys
|
||||
d = json.loads('''$GAME_EN''')
|
||||
def field(name, actual, expected):
|
||||
print((" PASS" if actual==expected else " FAIL")+f": {name}: {actual!r} (expected {expected!r})")
|
||||
return actual==expected
|
||||
alice = [pl for part in d["participants"] for pl in part["players"] if pl["uid"]=="1"][0]
|
||||
win = [p for p in d["participants"] if p["team_name"]=="TeamWin"][0]
|
||||
oks = []
|
||||
oks.append(field("alice score deduped", alice["stats"]["score"], 100))
|
||||
oks.append(field("alice vehicle count", len(alice["vehicles"]), 2))
|
||||
oks.append(field("team total score", win["stats"]["score"], 100))
|
||||
oks.append(field("game total score", d["game"]["stats"]["score"], 110))
|
||||
oks.append(field("tournament_name", d["game"].get("tournament_name"), "Cup Finals"))
|
||||
oks.append(field("duration", d["game"].get("duration"), 420.0))
|
||||
oks.append(field("draw", d["game"]["draw"], False))
|
||||
sys.exit(0 if all(oks) else 1)
|
||||
PY
|
||||
if [[ $? -eq 0 ]]; then ok "backend game detail (en)"; else bad "backend game detail (en)"; fi
|
||||
|
||||
RU_NAME="$(curl -s "localhost:$BE_PORT/api/tss/games/abc?lang=ru" | "$PYTHON" -c "import sys,json; d=json.load(sys.stdin); print([v['name'] for p in d['participants'] for pl in p['players'] for v in pl['vehicles'] if v['cdk']=='ussr_t_34'][0])")"
|
||||
assert_eq "ru translation of ussr_t_34" "$RU_NAME" "Т-34"
|
||||
|
||||
LOG_COUNTS="$(curl -s "localhost:$BE_PORT/api/tss/games/abc/logs" | "$PYTHON" -c "import sys,json; d=json.load(sys.stdin); e=d.get('event_log', {}); print(len(d['chat_log']), len(d['battle_log']), len(e.get('kills', [])), len(e.get('chat', [])))")"
|
||||
assert_eq "logs chat/battle/kill/raw-chat counts" "$LOG_COUNTS" "1 1 1 1"
|
||||
|
||||
MISS="$(curl -s "localhost:$BE_PORT/api/tss/games/deadbeef/logs" | "$PYTHON" -c "import sys,json; d=json.load(sys.stdin); print(len(d['chat_log'])+len(d['battle_log']))")"
|
||||
assert_eq "missing-session logs empty" "$MISS" "0"
|
||||
|
||||
# recent games must list each session ONCE (not once per team)
|
||||
REC="$(curl -s "localhost:$BE_PORT/api/tss/games/recent?limit=50" | "$PYTHON" -c "import sys,json; d=json.load(sys.stdin); ids=[m['session_id'] for m in d['matches']]; print(ids.count('abc'), ([m['player_count'] for m in d['matches'] if m['session_id']=='abc'] or [0])[0])")"
|
||||
assert_eq "recent lists session once + per-side count" "$REC" "1 1"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "== 7. Node prod server: icons + proxy allowlist =="
|
||||
H=(-H "Origin: http://localhost:$WEB_PORT" -H "Referer: http://localhost:$WEB_PORT/games/abc" -H "Sec-Fetch-Site: same-origin")
|
||||
assert_eq "icon served" "$(curl -s -o /dev/null -w '%{http_code}' "localhost:$WEB_PORT/vehicle-icons/ussr_t_34.png")" "200"
|
||||
assert_eq "icon traversal blocked" "$(curl -s --path-as-is -o /dev/null -w '%{http_code}' "localhost:$WEB_PORT/vehicle-icons/..%2f..%2fserver.cjs")" "403"
|
||||
assert_eq "proxy game?lang=en" "$(curl -s "${H[@]}" -o /dev/null -w '%{http_code}' "localhost:$WEB_PORT/api/tss/games/abc?lang=en")" "200"
|
||||
assert_eq "proxy logs" "$(curl -s "${H[@]}" -o /dev/null -w '%{http_code}' "localhost:$WEB_PORT/api/tss/games/abc/logs")" "200"
|
||||
assert_eq "proxy SPA shell" "$(curl -s -o /dev/null -w '%{http_code}' "localhost:$WEB_PORT/games/abc")" "200"
|
||||
# bad param must NOT be 200 (allowlist rejects)
|
||||
BADCODE="$(curl -s "${H[@]}" -o /dev/null -w '%{http_code}' "localhost:$WEB_PORT/api/tss/games/abc?evil=1")"
|
||||
if [[ "$BADCODE" != "200" ]]; then ok "proxy blocks unknown param ($BADCODE)"; else bad "proxy allowed unknown param"; fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
echo
|
||||
echo "== RESULT: $PASS passed, $FAIL failed =="
|
||||
[[ $FAIL -eq 0 ]] || exit 1
|
||||
echo "ALL CHECKS PASSED"
|
||||
+3527
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=tssbot backend API service
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=100
|
||||
StartLimitBurst=10
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=%h/tssbot.web
|
||||
ExecStart=%h/tssbot.web/backend/target/release/tssbot-backend
|
||||
Restart=on-failure
|
||||
RestartSec=200ms
|
||||
RestartSteps=10
|
||||
RestartMaxDelaySec=10s
|
||||
TimeoutStopSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=tssbot-web production server
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=100
|
||||
StartLimitBurst=10
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=%h/tssbot.web
|
||||
ExecStart=/usr/bin/node server.cjs
|
||||
Restart=on-failure
|
||||
RestartSec=200ms
|
||||
RestartSteps=10
|
||||
RestartMaxDelaySec=10s
|
||||
TimeoutStopSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,21 @@
|
||||
[Unit]
|
||||
Description=tssbot-web GitHub deploy webhook
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=100
|
||||
StartLimitBurst=10
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=%h/tssbot.web
|
||||
ExecStart=/usr/bin/node webhook.cjs
|
||||
# Always (not on-failure): the process deliberately exits 0 every 24h so
|
||||
# systemd relaunches it with a clean listener.
|
||||
Restart=always
|
||||
RestartSec=200ms
|
||||
RestartSteps=10
|
||||
RestartMaxDelaySec=10s
|
||||
TimeoutStopSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
import path from 'node:path'
|
||||
import { execSync } from 'node:child_process'
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
const MAX_TEAM_NAME_LENGTH = 80
|
||||
|
||||
function siteVersion() {
|
||||
try {
|
||||
const count = execSync('git rev-list --count HEAD', {
|
||||
cwd: __dirname,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).trim()
|
||||
return `1.0.${Number(count) || 0}`
|
||||
} catch {
|
||||
return '1.0.0'
|
||||
}
|
||||
}
|
||||
|
||||
function isAllowedApiUrl(req) {
|
||||
const url = new URL(req.url, 'http://localhost')
|
||||
const params = url.searchParams
|
||||
|
||||
if (url.pathname === '/api/viewers' && (req.method === 'GET' || req.method === 'HEAD')) return true
|
||||
if (url.pathname === '/api/viewers/event' && req.method === 'POST') return true
|
||||
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') return false
|
||||
|
||||
if (url.pathname === '/api/tss/tournaments') return true
|
||||
if (/^\/api\/tss\/tournaments\/[^/]+$/.test(url.pathname)) return true
|
||||
|
||||
if (url.pathname === '/api/tss/leaderboard/teams') {
|
||||
const keys = [...params.keys()]
|
||||
const limit = Number(params.get('limit') || 100)
|
||||
return keys.every((key) => key === 'limit') && Number.isInteger(limit) && limit >= 1 && limit <= 100
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/tss/leaderboard/players') {
|
||||
const keys = [...params.keys()]
|
||||
const limit = Number(params.get('limit') || 100)
|
||||
return keys.every((key) => key === 'limit') && Number.isInteger(limit) && limit >= 1 && limit <= 100
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/tss/games/recent') {
|
||||
const keys = [...params.keys()]
|
||||
const limit = Number(params.get('limit') || 50)
|
||||
return keys.every((key) => key === 'limit') && Number.isInteger(limit) && limit >= 1 && limit <= 100
|
||||
}
|
||||
|
||||
if (/^\/api\/tss\/games\/[A-Za-z0-9_-]{1,96}$/.test(url.pathname)) {
|
||||
const keys = [...params.keys()]
|
||||
const lang = params.get('lang') || 'en'
|
||||
return keys.every((key) => key === 'lang') && /^[A-Za-z-]{2,8}$/.test(lang)
|
||||
}
|
||||
|
||||
if (/^\/api\/tss\/games\/[A-Za-z0-9_-]{1,96}\/logs$/.test(url.pathname)) {
|
||||
return [...params.keys()].length === 0
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/tss/teams/resolve') {
|
||||
const keys = [...params.keys()]
|
||||
const name = params.get('name') || ''
|
||||
return keys.every((key) => key === 'name') && name.length >= 2 && name.length <= MAX_TEAM_NAME_LENGTH
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/tss/teams/search') {
|
||||
const keys = [...params.keys()]
|
||||
const query = params.get('q') || params.get('name') || ''
|
||||
const limit = Number(params.get('limit') || 10)
|
||||
return (
|
||||
keys.every((key) => ['q', 'name', 'limit'].includes(key)) &&
|
||||
query.length >= 2 &&
|
||||
query.length <= MAX_TEAM_NAME_LENGTH &&
|
||||
Number.isInteger(limit) &&
|
||||
limit >= 1 &&
|
||||
limit <= 20
|
||||
)
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/tss/players/search') {
|
||||
const keys = [...params.keys()]
|
||||
const query = params.get('q') || params.get('name') || ''
|
||||
const limit = Number(params.get('limit') || 25)
|
||||
return (
|
||||
keys.every((key) => ['q', 'name', 'limit'].includes(key)) &&
|
||||
query.length >= 2 &&
|
||||
query.length <= MAX_TEAM_NAME_LENGTH &&
|
||||
Number.isInteger(limit) &&
|
||||
limit >= 1 &&
|
||||
limit <= 25
|
||||
)
|
||||
}
|
||||
|
||||
if (/^\/api\/tss\/player\/[0-9]{1,32}$/.test(url.pathname)) {
|
||||
return [...params.keys()].length === 0
|
||||
}
|
||||
|
||||
if ([...params.keys()].length) return false
|
||||
|
||||
try {
|
||||
const match = url.pathname.match(/^\/api\/tss\/teams\/([^/]+)(?:\/(history|games))?$/)
|
||||
const teamName = match ? decodeURIComponent(match[1]) : ''
|
||||
return Boolean(teamName) && teamName.length <= MAX_TEAM_NAME_LENGTH
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function apiGuard() {
|
||||
return {
|
||||
name: 'api-guard',
|
||||
configureServer(server) {
|
||||
server.middlewares.use(async (req, res, next) => {
|
||||
if (!req.url?.startsWith('/api/')) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
if (isAllowedApiUrl(req)) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
res.writeHead(404, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'x-content-type-options': 'nosniff',
|
||||
})
|
||||
res.end(JSON.stringify({ error: 'API route not found' }))
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
root: path.resolve(__dirname, 'frontend'),
|
||||
publicDir: path.resolve(__dirname, 'frontend/public'),
|
||||
plugins: [apiGuard(), react(), tailwindcss()],
|
||||
define: {
|
||||
'import.meta.env.VITE_SITE_VERSION': JSON.stringify(siteVersion()),
|
||||
},
|
||||
build: {
|
||||
outDir: path.resolve(__dirname, 'dist'),
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: process.env.VITE_API_TARGET ?? 'http://localhost:6000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/health': {
|
||||
target: process.env.VITE_API_TARGET ?? 'http://localhost:6000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
+847
@@ -0,0 +1,847 @@
|
||||
const crypto = require('node:crypto')
|
||||
const fs = require('node:fs')
|
||||
const http = require('node:http')
|
||||
const https = require('node:https')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { spawn } = require('node:child_process')
|
||||
|
||||
function loadEnvFile() {
|
||||
const envPath = path.join(__dirname, '.env')
|
||||
if (!fs.existsSync(envPath)) return
|
||||
|
||||
const lines = fs.readFileSync(envPath, 'utf8').split(/\r?\n/)
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed || trimmed.startsWith('#')) continue
|
||||
|
||||
const separatorIndex = trimmed.indexOf('=')
|
||||
if (separatorIndex === -1) continue
|
||||
|
||||
const key = trimmed.slice(0, separatorIndex).trim()
|
||||
let value = trimmed.slice(separatorIndex + 1).trim()
|
||||
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1)
|
||||
}
|
||||
|
||||
if (key && (!process.env[key] || process.env[key] === '')) {
|
||||
process.env[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadEnvFile()
|
||||
|
||||
const PORT = Number(process.env.WEBHOOK_PORT || 3011)
|
||||
const SECRET = process.env.GITHUB_WEBHOOK_SECRET || ''
|
||||
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || ''
|
||||
const DISCORD_INCLUDE_PATCH = /^(1|true|yes)$/i.test(String(process.env.DISCORD_INCLUDE_PATCH || ''))
|
||||
const RESTART_TARGETS = (process.env.RESTART_TARGETS || 'tssbot-web,tssbot-backend')
|
||||
.split(',')
|
||||
.map((target) => target.trim())
|
||||
.filter((target) => /^[A-Za-z0-9_.:-]{1,80}$/.test(target))
|
||||
.filter(Boolean)
|
||||
|
||||
// This webhook's own systemd unit name — never restart it inline during its own deploy.
|
||||
const SELF_SERVICE_NAME = process.env.WEBHOOK_SERVICE_NAME || 'tssbot-webhook'
|
||||
const DIST_DIR = path.join(__dirname, 'dist')
|
||||
const NEXT_DIST_DIR = path.join(__dirname, 'dist-next')
|
||||
const PREVIOUS_DIST_DIR = path.join(__dirname, 'dist-previous')
|
||||
const MAX_WEBHOOK_BODY_BYTES = Number(process.env.WEBHOOK_MAX_BODY_BYTES || 1024 * 1024)
|
||||
const WEBHOOK_REQUEST_TIMEOUT_MS = Number(process.env.WEBHOOK_REQUEST_TIMEOUT_MS || 30000)
|
||||
const WEBHOOK_HEADERS_TIMEOUT_MS = Number(process.env.WEBHOOK_HEADERS_TIMEOUT_MS || 10000)
|
||||
// No deploy step may hang forever. A stalled `npm ci` (a native postinstall that
|
||||
// never returns) would otherwise block for hours with node_modules already
|
||||
// deleted — which is exactly what took the site down. These cap each step so a
|
||||
// hang fails fast and aborts the deploy before any systemctl restart.
|
||||
const DEPLOY_STEP_TIMEOUT_MS = Number(process.env.DEPLOY_STEP_TIMEOUT_MS || 15 * 60 * 1000)
|
||||
const DEPLOY_INSTALL_TIMEOUT_MS = Number(process.env.DEPLOY_INSTALL_TIMEOUT_MS || 8 * 60 * 1000)
|
||||
const ALLOWED_REFS = new Set(
|
||||
(process.env.GITHUB_WEBHOOK_REFS || 'refs/heads/main')
|
||||
.split(',')
|
||||
.map((ref) => ref.trim())
|
||||
.filter(Boolean),
|
||||
)
|
||||
const ALLOWED_REPOSITORY = (process.env.GITHUB_WEBHOOK_REPOSITORY || '').trim()
|
||||
const RESTART_AFTER_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
let deploying = false
|
||||
let queuedPush = null
|
||||
|
||||
function json(res, status, body) {
|
||||
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
||||
res.end(JSON.stringify(body))
|
||||
}
|
||||
|
||||
function safeJsonParse(rawBody) {
|
||||
try {
|
||||
return JSON.parse(rawBody.toString('utf8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function shortSha(value) {
|
||||
return value ? String(value).slice(0, 7) : 'unknown'
|
||||
}
|
||||
|
||||
function branchName(ref) {
|
||||
return String(ref || '').replace(/^refs\/heads\//, '') || 'unknown'
|
||||
}
|
||||
|
||||
function truncate(value, maxLength = 900) {
|
||||
const text = String(value || '')
|
||||
if (text.length <= maxLength) return text
|
||||
return `${text.slice(0, maxLength - 3)}...`
|
||||
}
|
||||
|
||||
function codeBlock(value, language = '', maxLength = 1000) {
|
||||
const fence = language ? `\`\`\`${language}\n` : '```\n'
|
||||
const suffix = '\n```'
|
||||
const body = truncate(value || 'No diff returned', maxLength - fence.length - suffix.length)
|
||||
return `${fence}${body}${suffix}`
|
||||
}
|
||||
|
||||
function validGitSha(value) {
|
||||
return /^[0-9a-f]{7,40}$/i.test(String(value || ''))
|
||||
}
|
||||
|
||||
function verifySignature(rawBody, signature) {
|
||||
if (!SECRET) {
|
||||
console.error('GITHUB_WEBHOOK_SECRET is not set — rejecting webhook')
|
||||
return false
|
||||
}
|
||||
if (!signature || !signature.startsWith('sha256=')) return false
|
||||
|
||||
const expected = `sha256=${crypto.createHmac('sha256', SECRET).update(rawBody).digest('hex')}`
|
||||
const signatureBuffer = Buffer.from(signature)
|
||||
const expectedBuffer = Buffer.from(expected)
|
||||
|
||||
return (
|
||||
signatureBuffer.length === expectedBuffer.length &&
|
||||
crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
|
||||
)
|
||||
}
|
||||
|
||||
function executableExists(filePath) {
|
||||
try {
|
||||
return fs.existsSync(filePath) && fs.statSync(filePath).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function cargoExecutableName() {
|
||||
return process.platform === 'win32' ? 'cargo.exe' : 'cargo'
|
||||
}
|
||||
|
||||
function pathDirectories() {
|
||||
const pathValue = process.env.PATH || process.env.Path || ''
|
||||
return pathValue.split(path.delimiter).filter(Boolean)
|
||||
}
|
||||
|
||||
function cargoCandidates() {
|
||||
const executableName = cargoExecutableName()
|
||||
const candidates = []
|
||||
|
||||
if (process.env.CARGO) {
|
||||
candidates.push(process.env.CARGO)
|
||||
}
|
||||
|
||||
if (process.env.CARGO_HOME) {
|
||||
candidates.push(path.join(process.env.CARGO_HOME, 'bin', executableName))
|
||||
}
|
||||
|
||||
candidates.push(path.join(os.homedir(), '.cargo', 'bin', executableName))
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
try {
|
||||
for (const homeEntry of fs.readdirSync('/home', { withFileTypes: true })) {
|
||||
if (homeEntry.isDirectory()) {
|
||||
candidates.push(path.join('/home', homeEntry.name, '.cargo', 'bin', executableName))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Some hosts do not expose /home to this process; the fixed paths below still cover system installs.
|
||||
}
|
||||
|
||||
candidates.push(
|
||||
'/root/.cargo/bin/cargo',
|
||||
'/usr/local/cargo/bin/cargo',
|
||||
'/usr/local/bin/cargo',
|
||||
'/usr/bin/cargo',
|
||||
)
|
||||
}
|
||||
|
||||
for (const directory of pathDirectories()) {
|
||||
candidates.push(path.join(directory, executableName))
|
||||
}
|
||||
|
||||
return [...new Set(candidates)]
|
||||
}
|
||||
|
||||
function cargoCommand() {
|
||||
for (const candidate of cargoCandidates()) {
|
||||
if (executableExists(candidate)) return candidate
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function commandFor(command) {
|
||||
if (command === 'cargo') {
|
||||
const resolvedCommand = cargoCommand()
|
||||
if (!resolvedCommand) throw new Error(commandNotFoundMessage(command))
|
||||
return resolvedCommand
|
||||
}
|
||||
if (process.platform !== 'win32') return command
|
||||
if (command === 'npm') return 'npm.cmd'
|
||||
return command
|
||||
}
|
||||
|
||||
function commandNotFoundMessage(command) {
|
||||
if (command !== 'cargo') return `${command} was not found`
|
||||
return [
|
||||
'cargo was not found by the deploy webhook',
|
||||
'Install Rust on the host, or set CARGO to the absolute cargo binary path',
|
||||
`Checked ${cargoCandidates().join(', ')}`,
|
||||
].join('. ')
|
||||
}
|
||||
|
||||
function restartTargetsInclude(target) {
|
||||
return RESTART_TARGETS.some((candidate) => candidate === target)
|
||||
}
|
||||
|
||||
function pushTouchesWebhookRuntime(push) {
|
||||
const runtimeFiles = new Set(['webhook.cjs', 'systemd/tssbot-webhook.service'])
|
||||
const commits = Array.isArray(push?.commits) ? push.commits : []
|
||||
return commits.some((commit) => {
|
||||
const changed = [
|
||||
...(Array.isArray(commit.added) ? commit.added : []),
|
||||
...(Array.isArray(commit.modified) ? commit.modified : []),
|
||||
...(Array.isArray(commit.removed) ? commit.removed : []),
|
||||
]
|
||||
return changed.some((file) => runtimeFiles.has(String(file || '').replace(/^\/+/, '')))
|
||||
})
|
||||
}
|
||||
|
||||
function scheduleSelfRestart(reason) {
|
||||
console.log(`scheduling ${SELF_SERVICE_NAME} restart: ${reason}`)
|
||||
// Delayed + detached: `systemctl --user restart` sends SIGTERM to this very
|
||||
// process once it starts, so fire it after this tick unrefs and let the
|
||||
// deploy's response/notifications land first.
|
||||
setTimeout(() => {
|
||||
const child = spawn('systemctl', ['--user', 'restart', `${SELF_SERVICE_NAME}.service`], {
|
||||
cwd: __dirname,
|
||||
env: process.env,
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
})
|
||||
child.unref()
|
||||
}, 1000).unref()
|
||||
}
|
||||
|
||||
function run(command, args, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const label = [command, ...args].join(' ')
|
||||
console.log(`deploy step started: ${label}`)
|
||||
|
||||
let resolvedCommand
|
||||
try {
|
||||
resolvedCommand = commandFor(command)
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
const child = spawn(resolvedCommand, args, {
|
||||
cwd: __dirname,
|
||||
env: { ...process.env, ...options.env },
|
||||
shell: process.platform === 'win32',
|
||||
stdio: 'inherit',
|
||||
})
|
||||
|
||||
// Kill the step if it hangs so deploy() aborts before any systemctl restart instead
|
||||
// of wedging here indefinitely (see DEPLOY_STEP_TIMEOUT_MS above).
|
||||
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEPLOY_STEP_TIMEOUT_MS
|
||||
let timedOut = false
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true
|
||||
console.error(`deploy step timed out after ${timeoutMs}ms, killing: ${label}`)
|
||||
child.kill('SIGTERM')
|
||||
setTimeout(() => child.kill('SIGKILL'), 5000).unref()
|
||||
}, timeoutMs)
|
||||
timer.unref()
|
||||
|
||||
child.on('error', (error) => {
|
||||
clearTimeout(timer)
|
||||
if (error.code === 'ENOENT') {
|
||||
reject(new Error(commandNotFoundMessage(command)))
|
||||
return
|
||||
}
|
||||
reject(error)
|
||||
})
|
||||
child.on('exit', (code, signal) => {
|
||||
clearTimeout(timer)
|
||||
if (timedOut) {
|
||||
reject(new Error(`${label} timed out after ${timeoutMs}ms and was killed`))
|
||||
} else if (code === 0) {
|
||||
console.log(`deploy step completed: ${label}`)
|
||||
resolve()
|
||||
} else {
|
||||
reject(new Error(`${label} exited with ${code}${signal ? ` via ${signal}` : ''}`))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function runCapture(command, args, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const label = [command, ...args].join(' ')
|
||||
let resolvedCommand
|
||||
try {
|
||||
resolvedCommand = commandFor(command)
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
const child = spawn(resolvedCommand, args, {
|
||||
cwd: __dirname,
|
||||
env: { ...process.env, ...options.env },
|
||||
shell: process.platform === 'win32',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
|
||||
child.stdout.on('data', (chunk) => {
|
||||
stdout += chunk
|
||||
})
|
||||
child.stderr.on('data', (chunk) => {
|
||||
stderr += chunk
|
||||
})
|
||||
child.on('error', reject)
|
||||
child.on('exit', (code) => {
|
||||
if (code === 0) {
|
||||
resolve(stdout.trim())
|
||||
} else {
|
||||
reject(new Error(`${label} exited with ${code}: ${truncate(stderr || stdout, 500)}`))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Files that, when changed, require a fresh `npm ci`. package.json is included
|
||||
// because npm ci refuses to run against a package.json/lockfile that are out of
|
||||
// sync, so a change to either should trigger a reinstall.
|
||||
const DEPENDENCY_FILES = ['package.json', 'package-lock.json']
|
||||
|
||||
// Resolve the modules the build relies on. Returns the first missing module's
|
||||
// name, or null if all are present. Used to validate after install.
|
||||
function missingBuildDependency() {
|
||||
try {
|
||||
require.resolve('@vitejs/plugin-react')
|
||||
} catch {
|
||||
return '@vitejs/plugin-react'
|
||||
}
|
||||
|
||||
if (process.platform === 'linux' && process.arch === 'x64') {
|
||||
const libc = process.report?.getReport?.().header?.glibcVersionRuntime ? 'gnu' : 'musl'
|
||||
const rollup = `@rollup/rollup-linux-x64-${libc}`
|
||||
try {
|
||||
require.resolve(rollup)
|
||||
} catch {
|
||||
return rollup
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// True when any dependency file changed between previousHead and the current
|
||||
// HEAD. Defaults to true (reinstall) whenever we can't determine the range, so
|
||||
// an uncertain state never skips a needed install.
|
||||
async function dependencyFilesChanged(previousHead) {
|
||||
if (!validGitSha(previousHead)) return true
|
||||
try {
|
||||
const changed = await runCapture('git', [
|
||||
'diff',
|
||||
'--name-only',
|
||||
`${previousHead}..HEAD`,
|
||||
'--',
|
||||
...DEPENDENCY_FILES,
|
||||
])
|
||||
return changed.trim().length > 0
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// True when the native better-sqlite3 addon actually LOADS. require.resolve()
|
||||
// isn't enough — the package can exist while its compiled .node binary is
|
||||
// missing, which is the "Could not locate the bindings file" crash that
|
||||
// repeatedly took tssbot-web down. Load it in a child process so this reflects
|
||||
// exactly what server.cjs does at startup.
|
||||
async function betterSqliteLoads() {
|
||||
try {
|
||||
await run(
|
||||
process.execPath,
|
||||
['-e', "new (require('better-sqlite3'))(':memory:').close()"],
|
||||
{ env: { NODE_ENV: 'production' }, timeoutMs: 60000 },
|
||||
)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureBuildDependencies(previousHead) {
|
||||
const depsChanged = await dependencyFilesChanged(previousHead)
|
||||
// Skip the clean reinstall (which wipes node_modules and rebuilds native
|
||||
// modules like better-sqlite3 — the fragile step that took the site down) only
|
||||
// when nothing dependency-related changed AND the existing node_modules already
|
||||
// has everything the build and runtime need. A broken/missing better-sqlite3
|
||||
// binary forces the reinstall so a skip can never leave a dead tree.
|
||||
const canSkip =
|
||||
!depsChanged && missingBuildDependency() === null && (await betterSqliteLoads())
|
||||
|
||||
if (canSkip) {
|
||||
console.log('deploy step skipped: npm ci (no package.json/package-lock.json changes, node_modules intact)')
|
||||
return
|
||||
}
|
||||
|
||||
await run('npm', ['ci'], {
|
||||
env: {
|
||||
NODE_ENV: 'development',
|
||||
npm_config_omit: '',
|
||||
npm_config_production: 'false',
|
||||
npm_config_fund: 'false',
|
||||
npm_config_audit: 'false',
|
||||
},
|
||||
timeoutMs: DEPLOY_INSTALL_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
const missing = missingBuildDependency()
|
||||
if (missing) {
|
||||
throw new Error(`${missing} is missing after npm install; dependencies were not installed`)
|
||||
}
|
||||
|
||||
// Hard gate: better-sqlite3 must actually load after the install, or abort the
|
||||
// deploy here — before promoteBuiltDist()/systemctl restart — so a broken native build
|
||||
// can never be promoted to the running workers (which still hold a good binary).
|
||||
if (!(await betterSqliteLoads())) {
|
||||
throw new Error(
|
||||
'better-sqlite3 failed to load after npm ci — native binary missing or broken; aborting deploy before reload',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function copyMissingFiles(fromDir, toDir) {
|
||||
if (!fs.existsSync(fromDir) || !fs.existsSync(toDir)) return
|
||||
|
||||
for (const entry of fs.readdirSync(fromDir, { withFileTypes: true })) {
|
||||
const source = path.join(fromDir, entry.name)
|
||||
const target = path.join(toDir, entry.name)
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
fs.mkdirSync(target, { recursive: true })
|
||||
copyMissingFiles(source, target)
|
||||
continue
|
||||
}
|
||||
|
||||
if (!fs.existsSync(target)) {
|
||||
fs.copyFileSync(source, target)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function promoteBuiltDist() {
|
||||
const previousAssetsDir = path.join(DIST_DIR, 'assets')
|
||||
const nextAssetsDir = path.join(NEXT_DIST_DIR, 'assets')
|
||||
let movedCurrentDist = false
|
||||
|
||||
copyMissingFiles(previousAssetsDir, nextAssetsDir)
|
||||
|
||||
fs.rmSync(PREVIOUS_DIST_DIR, { recursive: true, force: true })
|
||||
|
||||
try {
|
||||
if (fs.existsSync(DIST_DIR)) {
|
||||
fs.renameSync(DIST_DIR, PREVIOUS_DIST_DIR)
|
||||
movedCurrentDist = true
|
||||
}
|
||||
|
||||
fs.renameSync(NEXT_DIST_DIR, DIST_DIR)
|
||||
} catch (error) {
|
||||
if (movedCurrentDist && !fs.existsSync(DIST_DIR) && fs.existsSync(PREVIOUS_DIST_DIR)) {
|
||||
fs.renameSync(PREVIOUS_DIST_DIR, DIST_DIR)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function syncVehicleIcons() {
|
||||
// Point the served icon dir at the bot-managed SHARED/ICONS/VEHICLES so the
|
||||
// scoreboard can render vehicle icons without bloating this repo. Symlink when
|
||||
// possible; fall back to skipping (icons hide gracefully) if the source is absent.
|
||||
const src = process.env.VEHICLE_ICONS_SRC || '/home/deploy/BOTS/SHARED/ICONS/VEHICLES'
|
||||
const dst = path.resolve(
|
||||
__dirname,
|
||||
process.env.VEHICLE_ICONS_DIR || path.join('dist', 'vehicle-icons'),
|
||||
)
|
||||
if (!fs.existsSync(src)) {
|
||||
console.warn(`vehicle icons source missing, skipping: ${src}`)
|
||||
return
|
||||
}
|
||||
try {
|
||||
fs.rmSync(dst, { recursive: true, force: true })
|
||||
fs.mkdirSync(path.dirname(dst), { recursive: true })
|
||||
fs.symlinkSync(src, dst)
|
||||
console.log(`linked vehicle icons ${dst} -> ${src}`)
|
||||
} catch (error) {
|
||||
console.error(`vehicle icon sync failed: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
function validateBuiltDist() {
|
||||
const indexPath = path.join(NEXT_DIST_DIR, 'index.html')
|
||||
if (!fs.existsSync(indexPath)) {
|
||||
throw new Error('Frontend build did not produce dist-next/index.html')
|
||||
}
|
||||
|
||||
const html = fs.readFileSync(indexPath, 'utf8')
|
||||
if (/\sintegrity=(["'])sha(?:256|384|512)-[^"']+\1/i.test(html)) {
|
||||
throw new Error('Frontend build contains unsupported integrity attributes')
|
||||
}
|
||||
|
||||
const assetPaths = [...html.matchAll(/(?:src|href)=(["'])\/(assets\/[^"']+)\1/g)]
|
||||
.map((match) => match[2])
|
||||
|
||||
for (const assetPath of assetPaths) {
|
||||
if (!fs.existsSync(path.join(NEXT_DIST_DIR, assetPath))) {
|
||||
throw new Error(`Frontend build references missing asset: /${assetPath}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function postDiscordWebhook(payload) {
|
||||
if (!DISCORD_WEBHOOK_URL) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let url
|
||||
try {
|
||||
url = new URL(DISCORD_WEBHOOK_URL)
|
||||
} catch (error) {
|
||||
console.error('Discord restart webhook URL is invalid:', error.message)
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
const body = Buffer.from(JSON.stringify(payload))
|
||||
const client = url.protocol === 'http:' ? http : https
|
||||
const req = client.request(
|
||||
url,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'content-length': body.length,
|
||||
'user-agent': 'tssbot-webhook',
|
||||
},
|
||||
timeout: 5000,
|
||||
},
|
||||
(res) => {
|
||||
res.resume()
|
||||
res.on('end', resolve)
|
||||
},
|
||||
)
|
||||
|
||||
req.on('timeout', () => {
|
||||
req.destroy(new Error('Discord restart webhook timed out'))
|
||||
})
|
||||
req.on('error', (error) => {
|
||||
console.error('Discord restart webhook failed:', error.message)
|
||||
resolve()
|
||||
})
|
||||
req.end(body)
|
||||
})
|
||||
}
|
||||
|
||||
function notifyDiscordRestart() {
|
||||
const startedAt = new Date()
|
||||
|
||||
sendDiscordEmbed({
|
||||
title: 'Webhook listener restarted',
|
||||
color: 0x00f2ff,
|
||||
fields: [
|
||||
{ name: 'Host', value: os.hostname(), inline: true },
|
||||
{ name: 'Port', value: String(PORT), inline: true },
|
||||
{ name: 'Restart targets', value: RESTART_TARGETS.join(', ') || 'none', inline: false },
|
||||
],
|
||||
timestamp: startedAt.toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
function sendDiscordEmbed(embed) {
|
||||
return postDiscordWebhook({
|
||||
username: 'tssbot webhook',
|
||||
embeds: [embed],
|
||||
})
|
||||
}
|
||||
|
||||
function deployFields(push) {
|
||||
const headCommit = push?.head_commit
|
||||
const fields = [
|
||||
{ name: 'Host', value: os.hostname(), inline: true },
|
||||
{ name: 'Branch', value: branchName(push?.ref), inline: true },
|
||||
{ name: 'Commit', value: shortSha(push?.after || headCommit?.id), inline: true },
|
||||
{ name: 'Restart targets', value: RESTART_TARGETS.join(', ') || 'none', inline: false },
|
||||
]
|
||||
|
||||
if (push?.sender?.login) {
|
||||
fields.push({ name: 'Sender', value: push.sender.login, inline: true })
|
||||
}
|
||||
|
||||
if (headCommit?.message) {
|
||||
fields.push({ name: 'Message', value: truncate(headCommit.message), inline: false })
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
async function deployDiff(push) {
|
||||
const before = push?.before
|
||||
const after = push?.after
|
||||
|
||||
if (!validGitSha(before) || !validGitSha(after) || /^0+$/.test(before)) {
|
||||
return {
|
||||
summary: 'Diff unavailable for this push range',
|
||||
patch: push?.compare ? `Compare: ${push.compare}` : '',
|
||||
}
|
||||
}
|
||||
|
||||
const range = `${before}..${after}`
|
||||
const [nameStatus, shortStat, patch] = await Promise.all([
|
||||
runCapture('git', ['diff', '--name-status', '--find-renames', range]),
|
||||
runCapture('git', ['diff', '--shortstat', range]),
|
||||
runCapture('git', ['diff', '--find-renames', '--unified=1', range]),
|
||||
])
|
||||
|
||||
return {
|
||||
summary: [shortStat, nameStatus].filter(Boolean).join('\n'),
|
||||
patch,
|
||||
}
|
||||
}
|
||||
|
||||
function diffFields(diff) {
|
||||
if (!diff) return []
|
||||
|
||||
const fields = []
|
||||
if (diff.summary) {
|
||||
fields.push({ name: 'Diff summary', value: codeBlock(diff.summary, 'diff'), inline: false })
|
||||
}
|
||||
if (DISCORD_INCLUDE_PATCH && diff.patch) {
|
||||
fields.push({ name: 'Patch preview', value: codeBlock(diff.patch, 'diff'), inline: false })
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
async function notifyDeployStarted(push) {
|
||||
await sendDiscordEmbed({
|
||||
title: 'GitHub push deploy started',
|
||||
color: 0xf4ee3e,
|
||||
fields: deployFields(push),
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
async function notifyDeployCompleted(push, diff) {
|
||||
await sendDiscordEmbed({
|
||||
title: 'GitHub push deploy completed',
|
||||
color: 0x00f2ff,
|
||||
fields: [...deployFields(push), ...diffFields(diff)],
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
async function notifyDeployFailed(push, error, diff) {
|
||||
await sendDiscordEmbed({
|
||||
title: 'GitHub push deploy failed',
|
||||
color: 0xe82517,
|
||||
fields: [
|
||||
...deployFields(push),
|
||||
...diffFields(diff),
|
||||
{ name: 'Error', value: truncate(error?.message || error), inline: false },
|
||||
],
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
async function deploy(push) {
|
||||
let diff = null
|
||||
|
||||
try {
|
||||
await notifyDeployStarted(push)
|
||||
// Capture HEAD before the pull so we can tell whether this push actually
|
||||
// changed dependency files (and thus needs a fresh npm ci).
|
||||
const previousHead = await runCapture('git', ['rev-parse', 'HEAD']).catch(() => null)
|
||||
await run('git', ['pull', '--ff-only'])
|
||||
diff = await deployDiff(push)
|
||||
await ensureBuildDependencies(previousHead)
|
||||
await run('npm', ['run', 'build', '--', '--outDir', '../dist-next'])
|
||||
validateBuiltDist()
|
||||
await run('cargo', ['build', '--manifest-path', 'backend/Cargo.toml', '--release'])
|
||||
promoteBuiltDist()
|
||||
syncVehicleIcons()
|
||||
|
||||
// Each restarted service re-reads .env itself on startup, so a plain
|
||||
// `systemctl restart` always picks up the committed env changes.
|
||||
// Exclude this webhook process from the awaited restart: killing the process
|
||||
// running this deploy mid-command can interrupt the remaining restarts.
|
||||
const restartTargets = RESTART_TARGETS.filter((t) => t !== SELF_SERVICE_NAME)
|
||||
if (restartTargets.length) {
|
||||
await run('systemctl', ['--user', 'restart', ...restartTargets.map((t) => `${t}.service`)])
|
||||
}
|
||||
|
||||
await notifyDeployCompleted(push, diff)
|
||||
if (restartTargetsInclude(SELF_SERVICE_NAME) || pushTouchesWebhookRuntime(push)) {
|
||||
scheduleSelfRestart(
|
||||
restartTargetsInclude(SELF_SERVICE_NAME)
|
||||
? `${SELF_SERVICE_NAME} is listed in RESTART_TARGETS`
|
||||
: 'webhook runtime files changed',
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
error.deployDiff = diff
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function runDeployQueue(initialPush) {
|
||||
let push = initialPush
|
||||
|
||||
while (push) {
|
||||
queuedPush = null
|
||||
|
||||
try {
|
||||
await deploy(push)
|
||||
console.log('GitHub push deploy completed')
|
||||
} catch (error) {
|
||||
console.error('GitHub push deploy failed:', error)
|
||||
try {
|
||||
await notifyDeployFailed(push, error, error.deployDiff)
|
||||
} catch (notificationError) {
|
||||
console.error('Failed to send deploy failure notification:', notificationError)
|
||||
}
|
||||
}
|
||||
|
||||
push = queuedPush
|
||||
}
|
||||
}
|
||||
|
||||
const webhookServer = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/health') {
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
deploying,
|
||||
queued: Boolean(queuedPush),
|
||||
restart_targets: RESTART_TARGETS,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (req.method !== 'POST' || req.url !== '/github') {
|
||||
json(res, 404, { error: 'Not found' })
|
||||
return
|
||||
}
|
||||
|
||||
const chunks = []
|
||||
let size = 0
|
||||
let tooLarge = false
|
||||
req.on('data', (chunk) => {
|
||||
size += chunk.length
|
||||
if (size > MAX_WEBHOOK_BODY_BYTES) {
|
||||
tooLarge = true
|
||||
json(res, 413, { error: 'Webhook body too large' })
|
||||
req.destroy()
|
||||
return
|
||||
}
|
||||
chunks.push(chunk)
|
||||
})
|
||||
req.on('end', () => {
|
||||
if (tooLarge) return
|
||||
const rawBody = Buffer.concat(chunks)
|
||||
const push = safeJsonParse(rawBody)
|
||||
const event = String(req.headers['x-github-event'] || '')
|
||||
const pushRef = String(push?.ref || '')
|
||||
const repoFullName = String(push?.repository?.full_name || '')
|
||||
const delivery = String(req.headers['x-github-delivery'] || 'unknown')
|
||||
|
||||
if (!verifySignature(rawBody, req.headers['x-hub-signature-256'])) {
|
||||
console.warn(`webhook delivery rejected: invalid signature delivery=${delivery} event=${event || '(missing)'}`)
|
||||
json(res, 401, { error: 'Invalid signature' })
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`webhook delivery received: delivery=${delivery} event=${event || '(missing)'} ref=${pushRef || '(missing)'} repo=${repoFullName || '(missing)'}`)
|
||||
|
||||
if (event !== 'push') {
|
||||
console.log(`webhook delivery skipped: delivery=${delivery} reason=non-push event=${event || '(missing)'}`)
|
||||
json(res, 202, { skipped: true, reason: 'Only push events trigger deploys' })
|
||||
return
|
||||
}
|
||||
|
||||
if (!ALLOWED_REFS.has(pushRef)) {
|
||||
console.log(`webhook delivery skipped: delivery=${delivery} reason=ref ref=${pushRef || '(missing)'} allowed=${[...ALLOWED_REFS].join(',')}`)
|
||||
json(res, 202, { skipped: true, reason: `Ignoring ref ${pushRef || '(missing)'}` })
|
||||
return
|
||||
}
|
||||
|
||||
if (ALLOWED_REPOSITORY) {
|
||||
if (repoFullName !== ALLOWED_REPOSITORY) {
|
||||
console.log(`webhook delivery skipped: delivery=${delivery} reason=repository repo=${repoFullName || '(missing)'} allowed=${ALLOWED_REPOSITORY}`)
|
||||
json(res, 202, { skipped: true, reason: `Ignoring repository ${repoFullName || '(missing)'}` })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (push?.deleted) {
|
||||
console.log(`webhook delivery skipped: delivery=${delivery} reason=branch-delete ref=${pushRef}`)
|
||||
json(res, 202, { skipped: true, reason: 'Ignoring branch-delete push' })
|
||||
return
|
||||
}
|
||||
|
||||
if (deploying) {
|
||||
queuedPush = push
|
||||
console.log(`webhook deploy queued: delivery=${delivery} ref=${pushRef} repo=${repoFullName || '(missing)'}`)
|
||||
json(res, 202, { queued: true, deploying: true })
|
||||
return
|
||||
}
|
||||
|
||||
deploying = true
|
||||
console.log(`webhook deploy accepted: delivery=${delivery} ref=${pushRef} repo=${repoFullName || '(missing)'} restart_targets=${RESTART_TARGETS.join(',') || 'none'}`)
|
||||
json(res, 202, { accepted: true, restart_targets: RESTART_TARGETS })
|
||||
|
||||
runDeployQueue(push)
|
||||
.finally(() => {
|
||||
deploying = false
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
webhookServer.requestTimeout = WEBHOOK_REQUEST_TIMEOUT_MS
|
||||
webhookServer.headersTimeout = WEBHOOK_HEADERS_TIMEOUT_MS
|
||||
|
||||
webhookServer.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`tssbot webhook listening on http://localhost:${PORT}/github`)
|
||||
console.log(`restart targets: ${RESTART_TARGETS.join(', ')}`)
|
||||
notifyDiscordRestart()
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
console.log('24 hour webhook refresh reached; exiting for systemd restart')
|
||||
process.exit(0)
|
||||
}, RESTART_AFTER_MS).unref()
|
||||
Reference in New Issue
Block a user