From 6eb59cd2b79daf9fef0e79a3a4e379dd21c0ef93 Mon Sep 17 00:00:00 2001 From: Maho Yoshino <62778359+Maho-Yoshino@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:00:31 +0200 Subject: [PATCH 01/91] Beginning --- app/api/v1/backends/users.py | 114 ++++++++++++++++++++++++++++++++++- app/api/v1/users_router.py | 69 +-------------------- 2 files changed, 115 insertions(+), 68 deletions(-) diff --git a/app/api/v1/backends/users.py b/app/api/v1/backends/users.py index 02d17577..acc55385 100644 --- a/app/api/v1/backends/users.py +++ b/app/api/v1/backends/users.py @@ -1,10 +1,120 @@ from utils.connection import Request from utils.auth import LoginEntry -from api.v1.models.users import TerseReturnModel +from utils.helper import Keymod +from api.v1.backends.clans import getClan, Platforms +from api.v1.models.clans import RolesDisplay, Roles +from api.v1.models.users import TerseReturnModel, PlayerRank async def get_terse(user:LoginEntry, *userIds:int|str) -> dict[str, TerseReturnModel]: - return await Request.send_template( + data = await Request.send_template( user, "get_users_terse_info", usersList = ";".join(str(i) for i in userIds) ) + return data + +async def get_self(user:LoginEntry): + data = {} + userData = await Request.send_template( + user, + "get_public_userstat", + userId = user.uidHint + ) + data["nick"] = userData["nick"] + data["userid"] = int(userData["userid"]) + data["penaltyStatus"] = userData["penaltyStatus"] + data["registerDay"] = userData["registerDay"] + data["lastDay"] = userData["lastDay"] + level = PlayerRank.get_level(userData["exp"]) + data["level"] = { + "name": PlayerRank.from_level(level).label, + "rank": level + } + data["acedVehicles"] = userData["numEliteUnits"] + + data["unitsData"] = {} + for k in userData["era"]: + data["unitsData"].setdefault(k, {}) + data["unitsData"][k]["max_rank"] = userData["era"][k] + for k in userData["unitsPerCountry"]: + data["unitsData"].setdefault(k, {}) + data["unitsData"][k]["collection"] = { + "overall": userData["unitsPerCountry"][k]["numUnits"], + "aced": userData["unitsPerCountry"][k]["numEliteUnits"] + } + + if "clanId" in userData: + data["squadron"] = { + "tag": userData["clanTag"], + "id": int(userData["clanId"]), + "name": userData["clanName"], + "type": userData["clanType"] + } + data["squadron"]["user"] = {} + clanData = await getClan(user, data["squadron"]["id"]) + for cuser in clanData["members"]: + if cuser["uid"] != str(user.uidHint): + continue + + role = Roles(cuser["role"]) + platform = Platforms(cuser["platform"]) + data["squadron"]["user"] = { + "initiator": int(cuser["initiator"]) if isinstance(cuser["initiator"], str) else None, + "join_timestamp": cuser["date"], + "role": { + "name": RolesDisplay[role.name].value, + "value": role.value + }, + "platform": { + "name": platform.name, + "value": platform.value + } + } + break + + data["squadron"]["user"]["activity"] = clanData.get("activity", {}).get(str(user.uidHint), {}).get("total", 0) + data["squadron"]["user"]["sqb_activity"] = clanData.get("member_ratings", {}).get(str(user.uidHint), {}).get("dr_era5_hist", 0.0) + + return data + +async def get_user(user:LoginEntry, userid: int): + data = await Request.send_template( + user, + "get_public_userstat", + userId = userid + ) + SANITIZE = ( + Keymod("clanId", convert=lambda x: int(x)), + Keymod("shcType", rm=True), + Keymod("background", rm=True), + Keymod("frame", rm=True), + Keymod("icon", rm=True), + Keymod("iconName", rm=True), + Keymod("title", rm=True), + Keymod("closedUnlocks", rm=True), + Keymod("unlocks", rm=True), + Keymod("titles", rm=True), + Keymod("classinessAwards", rm=True), + Keymod("leaderboard", rm=True) + ) + data = Keymod.run_all(data, SANITIZE) + if "userstat" in data: + VEHICLE_SANITIZE = ( + Keymod("was_in_session", rm=True), + # No clue how this calculates to battles, + # These numbers are different from the in-game "battles" values + Keymod("flyouts", new_name="respawns"), + Keymod("wp_total", new_name="total_sl"), + Keymod("online_exp_total", new_name="total_rp") + ) + + data["userstat"] = Keymod("new", rm=True).run(data["userstat"]) + for mode in data["userstat"]: + m_data: dict[str, dict[str, int]] = data["userstat"][mode].pop("total") + for vehicle, v_data in m_data.items(): + m_data[vehicle] = Keymod.run_all(v_data, VEHICLE_SANITIZE) + data["userstat"][mode] = m_data + pass + + return data + diff --git a/app/api/v1/users_router.py b/app/api/v1/users_router.py index 0b58709e..573797ff 100644 --- a/app/api/v1/users_router.py +++ b/app/api/v1/users_router.py @@ -7,10 +7,8 @@ from utils.connection import Request from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.models.users import TerseReturnModel, getUserDirectModel, PlayerRank, SelfUserDataModel -from api.v1.models.clans import Roles, RolesDisplay, Platforms -from api.v1.backends.users import get_terse -from api.v1.backends.clans import getClan +from api.v1.models.users import TerseReturnModel, getUserDirectModel, SelfUserDataModel +from api.v1.backends.users import get_terse, get_user, get_self router = APIRouter( prefix="/users", @@ -46,68 +44,7 @@ async def get_self_meta( request: faRequest, user: TokenBearer ): - data = {} - userData = await Request.send_template( - user, - "get_public_userstat", - userId = user.uidHint - ) - data["nick"] = userData["nick"] - data["userid"] = int(userData["userid"]) - data["penaltyStatus"] = userData["penaltyStatus"] - data["registerDay"] = userData["registerDay"] - data["lastDay"] = userData["lastDay"] - level = PlayerRank.get_level(userData["exp"]) - data["level"] = { - "name": PlayerRank.from_level(level).label, - "rank": level - } - data["acedVehicles"] = userData["numEliteUnits"] - - data["unitsData"] = {} - for k in userData["era"]: - data["unitsData"].setdefault(k, {}) - data["unitsData"][k]["max_rank"] = userData["era"][k] - for k in userData["unitsPerCountry"]: - data["unitsData"].setdefault(k, {}) - data["unitsData"][k]["collection"] = { - "overall": userData["unitsPerCountry"][k]["numUnits"], - "aced": userData["unitsPerCountry"][k]["numEliteUnits"] - } - - if "clanId" in userData: - data["squadron"] = { - "tag": userData["clanTag"], - "id": int(userData["clanId"]), - "name": userData["clanName"], - "type": userData["clanType"] - } - data["squadron"]["user"] = {} - clanData = await getClan(user, data["squadron"]["id"]) - for cuser in clanData["members"]: - if cuser["uid"] != str(user.uidHint): - continue - - role = Roles(cuser["role"]) - platform = Platforms(cuser["platform"]) - data["squadron"]["user"] = { - "initiator": int(cuser["initiator"]) if isinstance(cuser["initiator"], str) else None, - "join_timestamp": cuser["date"], - "role": { - "name": RolesDisplay[role.name].value, - "value": role.value - }, - "platform": { - "name": platform.name, - "value": platform.value - } - } - break - - data["squadron"]["user"]["activity"] = clanData.get("activity", {}).get(str(user.uidHint), {}).get("total", 0) - data["squadron"]["user"]["sqb_activity"] = clanData.get("member_ratings", {}).get(str(user.uidHint), {}).get("dr_era5_hist", 0.0) - - return data + return await get_self(user) @router.get("/{userid}", summary="Get user by ID") @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") From 2e2c9b009b31339e4b8e1eedb41eb1a4b46158d9 Mon Sep 17 00:00:00 2001 From: Maho Yoshino <62778359+Maho-Yoshino@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:02:03 +0200 Subject: [PATCH 02/91] Rename 'app' to 'src' This better fits the whole project's scope, and it is a more standardized name --- AGENTS.md | 160 +++++++++--------- Dockerfile | 8 +- {app => src}/api/__init__.py | 0 {app => src}/api/root.py | 0 {app => src}/api/shared.py | 0 {app => src}/api/v1/__init__.py | 0 {app => src}/api/v1/auth_router.py | 0 {app => src}/api/v1/backends/clans.py | 0 {app => src}/api/v1/backends/general.py | 0 {app => src}/api/v1/backends/marketplace.py | 0 {app => src}/api/v1/backends/replay.py | 0 {app => src}/api/v1/backends/shared.py | 0 {app => src}/api/v1/backends/users.py | 0 {app => src}/api/v1/clans_router.py | 0 {app => src}/api/v1/general_router.py | 0 {app => src}/api/v1/marketplace_router.py | 0 {app => src}/api/v1/models/auth.py | 0 {app => src}/api/v1/models/base.py | 0 {app => src}/api/v1/models/clans.py | 0 {app => src}/api/v1/models/general.py | 0 {app => src}/api/v1/models/marketplace.py | 0 {app => src}/api/v1/models/replay.py | 0 {app => src}/api/v1/models/units.py | 0 {app => src}/api/v1/models/users.py | 0 {app => src}/api/v1/replays_router.py | 0 {app => src}/api/v1/units_router.py | 0 {app => src}/api/v1/users_router.py | 0 {app => src}/config.py | 0 {app => src}/main.py | 0 {app => src}/swagger_ui_modify.css | 0 {app => src}/swagger_ui_modify.js | 0 {app => src}/utils/__init__.py | 0 {app => src}/utils/auth.py | 0 {app => src}/utils/connection/__init__.py | 0 {app => src}/utils/connection/blk_utils.py | 0 {app => src}/utils/connection/const.py | 0 .../utils/connection/default_network_cfg.json | 0 {app => src}/utils/connection/network.py | 0 .../templates/GetAssetClassInfo.json | 0 .../connection/templates/GetBalance.json | 0 .../templates/GetContextContents.json | 0 .../connection/templates/GetContexts.json | 0 .../utils/connection/templates/__init__.py | 0 .../clan_accept_membership_request.json | 0 .../templates/clan_change_member_role.json | 0 .../templates/clan_dismiss_member.json | 0 .../templates/clan_find_by_prefix.json | 0 .../utils/connection/templates/clan_get.json | 0 .../templates/clan_get_leaderboard.json | 0 .../connection/templates/clan_get_log.json | 0 .../connection/templates/clan_leave.json | 0 .../templates/clan_membership_request.json | 0 .../clan_reject_membership_request.json | 0 .../connection/templates/cln_books_brief.json | 0 .../templates/cln_get_pair_stat.json | 0 .../connection/templates/cln_market_buy.json | 0 .../templates/cln_market_get_asset_class.json | 0 .../connection/templates/cln_market_info.json | 0 .../templates/cln_market_search.json | 0 .../connection/templates/cln_market_sell.json | 0 .../templates/find_users_by_nick_prefix.json | 0 .../templates/get_public_userstat.json | 0 .../templates/get_users_terse_info.json | 0 .../templates/market_view_item1.json | 0 .../templates/market_view_item2.json | 0 .../connection/templates/replays_search.json | 0 {app => src}/utils/connection/websocket.py | 0 {app => src}/utils/geo.py | 0 {app => src}/utils/helper.py | 0 {app => src}/utils/news.py | 0 {app => src}/utils/replayParser/.gitignore | 0 {app => src}/utils/replayParser/__init__.py | 0 {app => src}/utils/replayParser/parser.py | 0 {app => src}/utils/users_create.sql | 0 {app => src}/utils/vehicleParser/.gitignore | 0 {app => src}/utils/vehicleParser/__init__.py | 0 {app => src}/utils/vehicleParser/__main__.py | 0 {app => src}/utils/vehicleParser/constants.py | 0 {app => src}/utils/vehicleParser/schema.py | 0 .../utils/vehicleParser/vehiclesProcessor.py | 0 80 files changed, 84 insertions(+), 84 deletions(-) rename {app => src}/api/__init__.py (100%) rename {app => src}/api/root.py (100%) rename {app => src}/api/shared.py (100%) rename {app => src}/api/v1/__init__.py (100%) rename {app => src}/api/v1/auth_router.py (100%) rename {app => src}/api/v1/backends/clans.py (100%) rename {app => src}/api/v1/backends/general.py (100%) rename {app => src}/api/v1/backends/marketplace.py (100%) rename {app => src}/api/v1/backends/replay.py (100%) rename {app => src}/api/v1/backends/shared.py (100%) rename {app => src}/api/v1/backends/users.py (100%) rename {app => src}/api/v1/clans_router.py (100%) rename {app => src}/api/v1/general_router.py (100%) rename {app => src}/api/v1/marketplace_router.py (100%) rename {app => src}/api/v1/models/auth.py (100%) rename {app => src}/api/v1/models/base.py (100%) rename {app => src}/api/v1/models/clans.py (100%) rename {app => src}/api/v1/models/general.py (100%) rename {app => src}/api/v1/models/marketplace.py (100%) rename {app => src}/api/v1/models/replay.py (100%) rename {app => src}/api/v1/models/units.py (100%) rename {app => src}/api/v1/models/users.py (100%) rename {app => src}/api/v1/replays_router.py (100%) rename {app => src}/api/v1/units_router.py (100%) rename {app => src}/api/v1/users_router.py (100%) rename {app => src}/config.py (100%) rename {app => src}/main.py (100%) rename {app => src}/swagger_ui_modify.css (100%) rename {app => src}/swagger_ui_modify.js (100%) rename {app => src}/utils/__init__.py (100%) rename {app => src}/utils/auth.py (100%) rename {app => src}/utils/connection/__init__.py (100%) rename {app => src}/utils/connection/blk_utils.py (100%) rename {app => src}/utils/connection/const.py (100%) rename {app => src}/utils/connection/default_network_cfg.json (100%) rename {app => src}/utils/connection/network.py (100%) rename {app => src}/utils/connection/templates/GetAssetClassInfo.json (100%) rename {app => src}/utils/connection/templates/GetBalance.json (100%) rename {app => src}/utils/connection/templates/GetContextContents.json (100%) rename {app => src}/utils/connection/templates/GetContexts.json (100%) rename {app => src}/utils/connection/templates/__init__.py (100%) rename {app => src}/utils/connection/templates/clan_accept_membership_request.json (100%) rename {app => src}/utils/connection/templates/clan_change_member_role.json (100%) rename {app => src}/utils/connection/templates/clan_dismiss_member.json (100%) rename {app => src}/utils/connection/templates/clan_find_by_prefix.json (100%) rename {app => src}/utils/connection/templates/clan_get.json (100%) rename {app => src}/utils/connection/templates/clan_get_leaderboard.json (100%) rename {app => src}/utils/connection/templates/clan_get_log.json (100%) rename {app => src}/utils/connection/templates/clan_leave.json (100%) rename {app => src}/utils/connection/templates/clan_membership_request.json (100%) rename {app => src}/utils/connection/templates/clan_reject_membership_request.json (100%) rename {app => src}/utils/connection/templates/cln_books_brief.json (100%) rename {app => src}/utils/connection/templates/cln_get_pair_stat.json (100%) rename {app => src}/utils/connection/templates/cln_market_buy.json (100%) rename {app => src}/utils/connection/templates/cln_market_get_asset_class.json (100%) rename {app => src}/utils/connection/templates/cln_market_info.json (100%) rename {app => src}/utils/connection/templates/cln_market_search.json (100%) rename {app => src}/utils/connection/templates/cln_market_sell.json (100%) rename {app => src}/utils/connection/templates/find_users_by_nick_prefix.json (100%) rename {app => src}/utils/connection/templates/get_public_userstat.json (100%) rename {app => src}/utils/connection/templates/get_users_terse_info.json (100%) rename {app => src}/utils/connection/templates/market_view_item1.json (100%) rename {app => src}/utils/connection/templates/market_view_item2.json (100%) rename {app => src}/utils/connection/templates/replays_search.json (100%) rename {app => src}/utils/connection/websocket.py (100%) rename {app => src}/utils/geo.py (100%) rename {app => src}/utils/helper.py (100%) rename {app => src}/utils/news.py (100%) rename {app => src}/utils/replayParser/.gitignore (100%) rename {app => src}/utils/replayParser/__init__.py (100%) rename {app => src}/utils/replayParser/parser.py (100%) rename {app => src}/utils/users_create.sql (100%) rename {app => src}/utils/vehicleParser/.gitignore (100%) rename {app => src}/utils/vehicleParser/__init__.py (100%) rename {app => src}/utils/vehicleParser/__main__.py (100%) rename {app => src}/utils/vehicleParser/constants.py (100%) rename {app => src}/utils/vehicleParser/schema.py (100%) rename {app => src}/utils/vehicleParser/vehiclesProcessor.py (100%) diff --git a/AGENTS.md b/AGENTS.md index 1774a3d1..b8e184d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,88 +1,88 @@ -# AGENTS instructions -This repository contains a python application using FastAPI. This project acts as a "translation layer" between Gaijin Entertainment's proprietary `blk` format, and a usable `json` format. Due to the nature of this API it is very hard to automate testing, therefore all testing is to be done manually +# AGENTS instructions +This repository contains a python application using FastAPI. This project acts as a "translation layer" between Gaijin Entertainment's proprietary `blk` format, and a usable `json` format. Due to the nature of this API it is very hard to automate testing, therefore all testing is to be done manually -## Testing -Manual testing can be done through the Swagger UI interface found on `/` or `/docs` -The templates in `app/utils/connection/http/templates/` (and `app/utils/connection/tcp/templates/`) can NOT be used directly in curl requests, they are in a proprietary format +## Testing +Manual testing can be done through the Swagger UI interface found on `/` or `/docs` +The templates in `src/utils/connection/http/templates/` (and `src/utils/connection/tcp/templates/`) can NOT be used directly in curl requests, they are in a proprietary format -## Structure -The repository has the following directories at its root: -- `app` - The application source code: - - `api` - The FastAPI routers (`v1`, `backends/`, `models/`) - - `utils` - A set of utilities used in the code, like: - - `connection/` - Network + BLK conversion (`network.py`, `blk_utils.py`, `const.py`, `http/`, `tcp/`, `default_network_cfg.json`) - - `geo.py` - Geolocation utility - - `auth.py` - Database and authentication management utility - - `news.py` - News parsing - - `helper.py` - Shared helpers - - `websocket.py` - WebSocket handling - - `replayParser/` - Replay parsing - - `vehicleParser/` - Vehicle data parsing - - `main.py` - Main entry point of the code - - `config.py` - Configuration / path constants -- `tools` - External binaries (`wt_ext_cli`, `binBlk`) used for BLK conversion -- `dev_tools` - Development-only tooling, regular users will never trigger any code within this directory -- `data` - Runtime data (logs, users.db, news.json, GeoLite2 DB, vehicle cache) -The root directory also includes the following files: -- `gaijin_api_endpoints.md` - Documentation on Gaijin Entertainment's internal endpoints, their usage and response -- `app/main.py` - Main entry point of the code -- `requirements.txt` - PyPI package requirements for the server -- `Dockerfile` - Docker image definition -- `compose.yml` - Docker Compose definition (also referenced by `systemd.service`) -- `.example.env` - Example .env file, that can be copied. Includes the following variables: - - `PORT` - The port to run on - - `HOST` - The IP to be listening on - - `MACHINE_ID` - Value sent when logging in, doesn't matter much - - `TOKEN_ENC_KEY` - Encryption key used in the database. Do not lose this, as losing it will mean the code can't decrypt sensitive values used in the backend logic - - `WT_EXT_CLI_PATH` - wt_ext_cli path, if not found in `tools/` or is named differently - - `BINBLK_PATH` - binBlk path, if not found in `tools/` or is named differently - - `LOGIN_RATE_LIMIT` - Rate limit for the login endpoints - - `REGULAR_RATE_LIMIT` - Rate limit for the rest of the endpoints - - `LOG_LEVEL` - The log level of the logger. For hosting `WARNING` is fine, as it still shows issues that have to be handled -- `LICENSE` - The license the repository falls under -- `README.md` - The README of the repository, contains some extra context -- `app/swagger_ui_modify.css` / `app/swagger_ui_modify.js` - Content used to modify the Swagger UI interface, to support websockets -The following directories/files appear only after running the server at least once: -- `.env` - The .env file used by the code -- `data/logs/` - Logs directory -- `data/users.db` - Authentication database -- `data/news.json` - Last sent news storage -- `data/GeoLite2-City.*` - Geolocation database +## Structure +The repository has the following directories at its root: +- `app` - The application source code: + - `api` - The FastAPI routers (`v1`, `backends/`, `models/`) + - `utils` - A set of utilities used in the code, like: + - `connection/` - Network + BLK conversion (`network.py`, `blk_utils.py`, `const.py`, `http/`, `tcp/`, `default_network_cfg.json`) + - `geo.py` - Geolocation utility + - `auth.py` - Database and authentication management utility + - `news.py` - News parsing + - `helper.py` - Shared helpers + - `websocket.py` - WebSocket handling + - `replayParser/` - Replay parsing + - `vehicleParser/` - Vehicle data parsing + - `main.py` - Main entry point of the code + - `config.py` - Configuration / path constants +- `tools` - External binaries (`wt_ext_cli`, `binBlk`) used for BLK conversion +- `dev_tools` - Development-only tooling, regular users will never trigger any code within this directory +- `data` - Runtime data (logs, users.db, news.json, GeoLite2 DB, vehicle cache) +The root directory also includes the following files: +- `gaijin_api_endpoints.md` - Documentation on Gaijin Entertainment's internal endpoints, their usage and response +- `src/main.py` - Main entry point of the code +- `requirements.txt` - PyPI package requirements for the server +- `Dockerfile` - Docker image definition +- `compose.yml` - Docker Compose definition (also referenced by `systemd.service`) +- `.example.env` - Example .env file, that can be copied. Includes the following variables: + - `PORT` - The port to run on + - `HOST` - The IP to be listening on + - `MACHINE_ID` - Value sent when logging in, doesn't matter much + - `TOKEN_ENC_KEY` - Encryption key used in the database. Do not lose this, as losing it will mean the code can't decrypt sensitive values used in the backend logic + - `WT_EXT_CLI_PATH` - wt_ext_cli path, if not found in `tools/` or is named differently + - `BINBLK_PATH` - binBlk path, if not found in `tools/` or is named differently + - `LOGIN_RATE_LIMIT` - Rate limit for the login endpoints + - `REGULAR_RATE_LIMIT` - Rate limit for the rest of the endpoints + - `LOG_LEVEL` - The log level of the logger. For hosting `WARNING` is fine, as it still shows issues that have to be handled +- `LICENSE` - The license the repository falls under +- `README.md` - The README of the repository, contains some extra context +- `src/swagger_ui_modify.css` / `src/swagger_ui_modify.js` - Content used to modify the Swagger UI interface, to support websockets +The following directories/files appear only after running the server at least once: +- `.env` - The .env file used by the code +- `data/logs/` - Logs directory +- `data/users.db` - Authentication database +- `data/news.json` - Last sent news storage +- `data/GeoLite2-City.*` - Geolocation database -## External tools -This project uses the following external binaries: -- `wt_ext_cli` - - Autodiscovered in the `tools` directory - - If not in said directory, it will look at the `WT_EXT_CLI_PATH` environment variable - - The program will stop if this binary is not found at startup - - Found at `https://github.com/Warthunder-Open-Source-Foundation/wt_ext_cli` -- `binBlk` - - Gaijin Entertainment's uploaded `blk` tool - - Autodiscovered in the `tools` directory - - If not in said directory, it will look at the `BINBLK_PATH` environment variable - - The program will stop if this binary is not found at startup - - Found at `https://github.com/GaijinEntertainment/DagorEngine/releases/latest` release body, as `tools-prebuilt-${platform}-${arch}.7z` +## External tools +This project uses the following external binaries: +- `wt_ext_cli` + - Autodiscovered in the `tools` directory + - If not in said directory, it will look at the `WT_EXT_CLI_PATH` environment variable + - The program will stop if this binary is not found at startup + - Found at `https://github.com/Warthunder-Open-Source-Foundation/wt_ext_cli` +- `binBlk` + - Gaijin Entertainment's uploaded `blk` tool + - Autodiscovered in the `tools` directory + - If not in said directory, it will look at the `BINBLK_PATH` environment variable + - The program will stop if this binary is not found at startup + - Found at `https://github.com/GaijinEntertainment/DagorEngine/releases/latest` release body, as `tools-prebuilt-${platform}-${arch}.7z` -## Gaijin-imposed restrictions -- Tokens have to be refreshed once every hour. The refreshing is done by the code itself, the token just has to be used on any endpoint, and the backend handles the rest +## Gaijin-imposed restrictions +- Tokens have to be refreshed once every hour. The refreshing is done by the code itself, the token just has to be used on any endpoint, and the backend handles the rest -## File conventions -- Files use `tabs` for indentation, not spaces -- Importing is generally done with `from ... import ...`, to reduce the extra entries in IntelliSense -- Rate limiting via `app.api.shared.limiter` -- Use the module-level `logger` for logging -- In `app/utils/vehicleParser/`, trailing `pass` statements are intentional debug breakpoint anchors — do not remove them +## File conventions +- Files use `tabs` for indentation, not spaces +- Importing is generally done with `from ... import ...`, to reduce the extra entries in IntelliSense +- Rate limiting via `app.api.shared.limiter` +- Use the module-level `logger` for logging +- In `src/utils/vehicleParser/`, trailing `pass` statements are intentional debug breakpoint anchors — do not remove them -## Sensitive data -Sensitive data, like session tokens and emails are stored, see `README.md#privacy-policy` +## Sensitive data +Sensitive data, like session tokens and emails are stored, see `README.md#privacy-policy` -## Running the server -- Copy `.example.env` to `.env` (`cp ./.example.env ./.env`) and edit as needed -- `docker compose up -d` — builds and starts the server; API docs at `/` and `/docs` -- Or run directly: `python app/main.py` +## Running the server +- Copy `.example.env` to `.env` (`cp ./.example.env ./.env`) and edit as needed +- `docker compose up -d` — builds and starts the server; API docs at `/` and `/docs` +- Or run directly: `python src/main.py` -## Architecture -Request flow: `app/api/v1` router => `app/api/v1/backends/` => `app/utils/connection/blk_utils.py` (BLK <=> JSON) => Gaijin backend -- `app/api/v1/backends/` — per-domain backend logic (clans, general, marketplace, replay, users) -- `app/api/v1/models/` — Pydantic response/request models -- `app/utils/connection/blk_utils.py` — BLK fetch/conversion (depends on `wt_ext_cli` / `binBlk`) +## Architecture +Request flow: `src/api/v1` router => `src/api/v1/backends/` => `src/utils/connection/blk_utils.py` (BLK <=> JSON) => Gaijin backend +- `src/api/v1/backends/` — per-domain backend logic (clans, general, marketplace, replay, users) +- `src/api/v1/models/` — Pydantic response/request models +- `src/utils/connection/blk_utils.py` — BLK fetch/conversion (depends on `wt_ext_cli` / `binBlk`) diff --git a/Dockerfile b/Dockerfile index 00eb2e2b..b714c500 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,17 +1,17 @@ FROM python:3.14-slim -WORKDIR /app +WORKDIR /src -COPY ./requirements.txt /app/requirements.txt +COPY ./requirements.txt /src/requirements.txt RUN pip install --no-cache-dir -r requirements.txt RUN apt-get update \ && apt-get install -y --no-install-recommends git \ && rm -rf /var/lib/apt/lists/* -COPY app/ ./app +COPY src/ ./src COPY tools/ /opt/tools/ RUN chmod +x /opt/tools/wt_ext_cli /opt/tools/binBlk -CMD ["python", "app/main.py"] +CMD ["python", "src/main.py"] diff --git a/app/api/__init__.py b/src/api/__init__.py similarity index 100% rename from app/api/__init__.py rename to src/api/__init__.py diff --git a/app/api/root.py b/src/api/root.py similarity index 100% rename from app/api/root.py rename to src/api/root.py diff --git a/app/api/shared.py b/src/api/shared.py similarity index 100% rename from app/api/shared.py rename to src/api/shared.py diff --git a/app/api/v1/__init__.py b/src/api/v1/__init__.py similarity index 100% rename from app/api/v1/__init__.py rename to src/api/v1/__init__.py diff --git a/app/api/v1/auth_router.py b/src/api/v1/auth_router.py similarity index 100% rename from app/api/v1/auth_router.py rename to src/api/v1/auth_router.py diff --git a/app/api/v1/backends/clans.py b/src/api/v1/backends/clans.py similarity index 100% rename from app/api/v1/backends/clans.py rename to src/api/v1/backends/clans.py diff --git a/app/api/v1/backends/general.py b/src/api/v1/backends/general.py similarity index 100% rename from app/api/v1/backends/general.py rename to src/api/v1/backends/general.py diff --git a/app/api/v1/backends/marketplace.py b/src/api/v1/backends/marketplace.py similarity index 100% rename from app/api/v1/backends/marketplace.py rename to src/api/v1/backends/marketplace.py diff --git a/app/api/v1/backends/replay.py b/src/api/v1/backends/replay.py similarity index 100% rename from app/api/v1/backends/replay.py rename to src/api/v1/backends/replay.py diff --git a/app/api/v1/backends/shared.py b/src/api/v1/backends/shared.py similarity index 100% rename from app/api/v1/backends/shared.py rename to src/api/v1/backends/shared.py diff --git a/app/api/v1/backends/users.py b/src/api/v1/backends/users.py similarity index 100% rename from app/api/v1/backends/users.py rename to src/api/v1/backends/users.py diff --git a/app/api/v1/clans_router.py b/src/api/v1/clans_router.py similarity index 100% rename from app/api/v1/clans_router.py rename to src/api/v1/clans_router.py diff --git a/app/api/v1/general_router.py b/src/api/v1/general_router.py similarity index 100% rename from app/api/v1/general_router.py rename to src/api/v1/general_router.py diff --git a/app/api/v1/marketplace_router.py b/src/api/v1/marketplace_router.py similarity index 100% rename from app/api/v1/marketplace_router.py rename to src/api/v1/marketplace_router.py diff --git a/app/api/v1/models/auth.py b/src/api/v1/models/auth.py similarity index 100% rename from app/api/v1/models/auth.py rename to src/api/v1/models/auth.py diff --git a/app/api/v1/models/base.py b/src/api/v1/models/base.py similarity index 100% rename from app/api/v1/models/base.py rename to src/api/v1/models/base.py diff --git a/app/api/v1/models/clans.py b/src/api/v1/models/clans.py similarity index 100% rename from app/api/v1/models/clans.py rename to src/api/v1/models/clans.py diff --git a/app/api/v1/models/general.py b/src/api/v1/models/general.py similarity index 100% rename from app/api/v1/models/general.py rename to src/api/v1/models/general.py diff --git a/app/api/v1/models/marketplace.py b/src/api/v1/models/marketplace.py similarity index 100% rename from app/api/v1/models/marketplace.py rename to src/api/v1/models/marketplace.py diff --git a/app/api/v1/models/replay.py b/src/api/v1/models/replay.py similarity index 100% rename from app/api/v1/models/replay.py rename to src/api/v1/models/replay.py diff --git a/app/api/v1/models/units.py b/src/api/v1/models/units.py similarity index 100% rename from app/api/v1/models/units.py rename to src/api/v1/models/units.py diff --git a/app/api/v1/models/users.py b/src/api/v1/models/users.py similarity index 100% rename from app/api/v1/models/users.py rename to src/api/v1/models/users.py diff --git a/app/api/v1/replays_router.py b/src/api/v1/replays_router.py similarity index 100% rename from app/api/v1/replays_router.py rename to src/api/v1/replays_router.py diff --git a/app/api/v1/units_router.py b/src/api/v1/units_router.py similarity index 100% rename from app/api/v1/units_router.py rename to src/api/v1/units_router.py diff --git a/app/api/v1/users_router.py b/src/api/v1/users_router.py similarity index 100% rename from app/api/v1/users_router.py rename to src/api/v1/users_router.py diff --git a/app/config.py b/src/config.py similarity index 100% rename from app/config.py rename to src/config.py diff --git a/app/main.py b/src/main.py similarity index 100% rename from app/main.py rename to src/main.py diff --git a/app/swagger_ui_modify.css b/src/swagger_ui_modify.css similarity index 100% rename from app/swagger_ui_modify.css rename to src/swagger_ui_modify.css diff --git a/app/swagger_ui_modify.js b/src/swagger_ui_modify.js similarity index 100% rename from app/swagger_ui_modify.js rename to src/swagger_ui_modify.js diff --git a/app/utils/__init__.py b/src/utils/__init__.py similarity index 100% rename from app/utils/__init__.py rename to src/utils/__init__.py diff --git a/app/utils/auth.py b/src/utils/auth.py similarity index 100% rename from app/utils/auth.py rename to src/utils/auth.py diff --git a/app/utils/connection/__init__.py b/src/utils/connection/__init__.py similarity index 100% rename from app/utils/connection/__init__.py rename to src/utils/connection/__init__.py diff --git a/app/utils/connection/blk_utils.py b/src/utils/connection/blk_utils.py similarity index 100% rename from app/utils/connection/blk_utils.py rename to src/utils/connection/blk_utils.py diff --git a/app/utils/connection/const.py b/src/utils/connection/const.py similarity index 100% rename from app/utils/connection/const.py rename to src/utils/connection/const.py diff --git a/app/utils/connection/default_network_cfg.json b/src/utils/connection/default_network_cfg.json similarity index 100% rename from app/utils/connection/default_network_cfg.json rename to src/utils/connection/default_network_cfg.json diff --git a/app/utils/connection/network.py b/src/utils/connection/network.py similarity index 100% rename from app/utils/connection/network.py rename to src/utils/connection/network.py diff --git a/app/utils/connection/templates/GetAssetClassInfo.json b/src/utils/connection/templates/GetAssetClassInfo.json similarity index 100% rename from app/utils/connection/templates/GetAssetClassInfo.json rename to src/utils/connection/templates/GetAssetClassInfo.json diff --git a/app/utils/connection/templates/GetBalance.json b/src/utils/connection/templates/GetBalance.json similarity index 100% rename from app/utils/connection/templates/GetBalance.json rename to src/utils/connection/templates/GetBalance.json diff --git a/app/utils/connection/templates/GetContextContents.json b/src/utils/connection/templates/GetContextContents.json similarity index 100% rename from app/utils/connection/templates/GetContextContents.json rename to src/utils/connection/templates/GetContextContents.json diff --git a/app/utils/connection/templates/GetContexts.json b/src/utils/connection/templates/GetContexts.json similarity index 100% rename from app/utils/connection/templates/GetContexts.json rename to src/utils/connection/templates/GetContexts.json diff --git a/app/utils/connection/templates/__init__.py b/src/utils/connection/templates/__init__.py similarity index 100% rename from app/utils/connection/templates/__init__.py rename to src/utils/connection/templates/__init__.py diff --git a/app/utils/connection/templates/clan_accept_membership_request.json b/src/utils/connection/templates/clan_accept_membership_request.json similarity index 100% rename from app/utils/connection/templates/clan_accept_membership_request.json rename to src/utils/connection/templates/clan_accept_membership_request.json diff --git a/app/utils/connection/templates/clan_change_member_role.json b/src/utils/connection/templates/clan_change_member_role.json similarity index 100% rename from app/utils/connection/templates/clan_change_member_role.json rename to src/utils/connection/templates/clan_change_member_role.json diff --git a/app/utils/connection/templates/clan_dismiss_member.json b/src/utils/connection/templates/clan_dismiss_member.json similarity index 100% rename from app/utils/connection/templates/clan_dismiss_member.json rename to src/utils/connection/templates/clan_dismiss_member.json diff --git a/app/utils/connection/templates/clan_find_by_prefix.json b/src/utils/connection/templates/clan_find_by_prefix.json similarity index 100% rename from app/utils/connection/templates/clan_find_by_prefix.json rename to src/utils/connection/templates/clan_find_by_prefix.json diff --git a/app/utils/connection/templates/clan_get.json b/src/utils/connection/templates/clan_get.json similarity index 100% rename from app/utils/connection/templates/clan_get.json rename to src/utils/connection/templates/clan_get.json diff --git a/app/utils/connection/templates/clan_get_leaderboard.json b/src/utils/connection/templates/clan_get_leaderboard.json similarity index 100% rename from app/utils/connection/templates/clan_get_leaderboard.json rename to src/utils/connection/templates/clan_get_leaderboard.json diff --git a/app/utils/connection/templates/clan_get_log.json b/src/utils/connection/templates/clan_get_log.json similarity index 100% rename from app/utils/connection/templates/clan_get_log.json rename to src/utils/connection/templates/clan_get_log.json diff --git a/app/utils/connection/templates/clan_leave.json b/src/utils/connection/templates/clan_leave.json similarity index 100% rename from app/utils/connection/templates/clan_leave.json rename to src/utils/connection/templates/clan_leave.json diff --git a/app/utils/connection/templates/clan_membership_request.json b/src/utils/connection/templates/clan_membership_request.json similarity index 100% rename from app/utils/connection/templates/clan_membership_request.json rename to src/utils/connection/templates/clan_membership_request.json diff --git a/app/utils/connection/templates/clan_reject_membership_request.json b/src/utils/connection/templates/clan_reject_membership_request.json similarity index 100% rename from app/utils/connection/templates/clan_reject_membership_request.json rename to src/utils/connection/templates/clan_reject_membership_request.json diff --git a/app/utils/connection/templates/cln_books_brief.json b/src/utils/connection/templates/cln_books_brief.json similarity index 100% rename from app/utils/connection/templates/cln_books_brief.json rename to src/utils/connection/templates/cln_books_brief.json diff --git a/app/utils/connection/templates/cln_get_pair_stat.json b/src/utils/connection/templates/cln_get_pair_stat.json similarity index 100% rename from app/utils/connection/templates/cln_get_pair_stat.json rename to src/utils/connection/templates/cln_get_pair_stat.json diff --git a/app/utils/connection/templates/cln_market_buy.json b/src/utils/connection/templates/cln_market_buy.json similarity index 100% rename from app/utils/connection/templates/cln_market_buy.json rename to src/utils/connection/templates/cln_market_buy.json diff --git a/app/utils/connection/templates/cln_market_get_asset_class.json b/src/utils/connection/templates/cln_market_get_asset_class.json similarity index 100% rename from app/utils/connection/templates/cln_market_get_asset_class.json rename to src/utils/connection/templates/cln_market_get_asset_class.json diff --git a/app/utils/connection/templates/cln_market_info.json b/src/utils/connection/templates/cln_market_info.json similarity index 100% rename from app/utils/connection/templates/cln_market_info.json rename to src/utils/connection/templates/cln_market_info.json diff --git a/app/utils/connection/templates/cln_market_search.json b/src/utils/connection/templates/cln_market_search.json similarity index 100% rename from app/utils/connection/templates/cln_market_search.json rename to src/utils/connection/templates/cln_market_search.json diff --git a/app/utils/connection/templates/cln_market_sell.json b/src/utils/connection/templates/cln_market_sell.json similarity index 100% rename from app/utils/connection/templates/cln_market_sell.json rename to src/utils/connection/templates/cln_market_sell.json diff --git a/app/utils/connection/templates/find_users_by_nick_prefix.json b/src/utils/connection/templates/find_users_by_nick_prefix.json similarity index 100% rename from app/utils/connection/templates/find_users_by_nick_prefix.json rename to src/utils/connection/templates/find_users_by_nick_prefix.json diff --git a/app/utils/connection/templates/get_public_userstat.json b/src/utils/connection/templates/get_public_userstat.json similarity index 100% rename from app/utils/connection/templates/get_public_userstat.json rename to src/utils/connection/templates/get_public_userstat.json diff --git a/app/utils/connection/templates/get_users_terse_info.json b/src/utils/connection/templates/get_users_terse_info.json similarity index 100% rename from app/utils/connection/templates/get_users_terse_info.json rename to src/utils/connection/templates/get_users_terse_info.json diff --git a/app/utils/connection/templates/market_view_item1.json b/src/utils/connection/templates/market_view_item1.json similarity index 100% rename from app/utils/connection/templates/market_view_item1.json rename to src/utils/connection/templates/market_view_item1.json diff --git a/app/utils/connection/templates/market_view_item2.json b/src/utils/connection/templates/market_view_item2.json similarity index 100% rename from app/utils/connection/templates/market_view_item2.json rename to src/utils/connection/templates/market_view_item2.json diff --git a/app/utils/connection/templates/replays_search.json b/src/utils/connection/templates/replays_search.json similarity index 100% rename from app/utils/connection/templates/replays_search.json rename to src/utils/connection/templates/replays_search.json diff --git a/app/utils/connection/websocket.py b/src/utils/connection/websocket.py similarity index 100% rename from app/utils/connection/websocket.py rename to src/utils/connection/websocket.py diff --git a/app/utils/geo.py b/src/utils/geo.py similarity index 100% rename from app/utils/geo.py rename to src/utils/geo.py diff --git a/app/utils/helper.py b/src/utils/helper.py similarity index 100% rename from app/utils/helper.py rename to src/utils/helper.py diff --git a/app/utils/news.py b/src/utils/news.py similarity index 100% rename from app/utils/news.py rename to src/utils/news.py diff --git a/app/utils/replayParser/.gitignore b/src/utils/replayParser/.gitignore similarity index 100% rename from app/utils/replayParser/.gitignore rename to src/utils/replayParser/.gitignore diff --git a/app/utils/replayParser/__init__.py b/src/utils/replayParser/__init__.py similarity index 100% rename from app/utils/replayParser/__init__.py rename to src/utils/replayParser/__init__.py diff --git a/app/utils/replayParser/parser.py b/src/utils/replayParser/parser.py similarity index 100% rename from app/utils/replayParser/parser.py rename to src/utils/replayParser/parser.py diff --git a/app/utils/users_create.sql b/src/utils/users_create.sql similarity index 100% rename from app/utils/users_create.sql rename to src/utils/users_create.sql diff --git a/app/utils/vehicleParser/.gitignore b/src/utils/vehicleParser/.gitignore similarity index 100% rename from app/utils/vehicleParser/.gitignore rename to src/utils/vehicleParser/.gitignore diff --git a/app/utils/vehicleParser/__init__.py b/src/utils/vehicleParser/__init__.py similarity index 100% rename from app/utils/vehicleParser/__init__.py rename to src/utils/vehicleParser/__init__.py diff --git a/app/utils/vehicleParser/__main__.py b/src/utils/vehicleParser/__main__.py similarity index 100% rename from app/utils/vehicleParser/__main__.py rename to src/utils/vehicleParser/__main__.py diff --git a/app/utils/vehicleParser/constants.py b/src/utils/vehicleParser/constants.py similarity index 100% rename from app/utils/vehicleParser/constants.py rename to src/utils/vehicleParser/constants.py diff --git a/app/utils/vehicleParser/schema.py b/src/utils/vehicleParser/schema.py similarity index 100% rename from app/utils/vehicleParser/schema.py rename to src/utils/vehicleParser/schema.py diff --git a/app/utils/vehicleParser/vehiclesProcessor.py b/src/utils/vehicleParser/vehiclesProcessor.py similarity index 100% rename from app/utils/vehicleParser/vehiclesProcessor.py rename to src/utils/vehicleParser/vehiclesProcessor.py From 6f65bc0124daee90f7b32690a4ea04fd41297d30 Mon Sep 17 00:00:00 2001 From: Maho Yoshino <62778359+Maho-Yoshino@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:04:49 +0200 Subject: [PATCH 03/91] Finish AGENTS.md migration to new structure --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b8e184d2..a561e0fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ The templates in `src/utils/connection/http/templates/` (and `src/utils/connecti ## Structure The repository has the following directories at its root: -- `app` - The application source code: +- `src` - The application source code: - `api` - The FastAPI routers (`v1`, `backends/`, `models/`) - `utils` - A set of utilities used in the code, like: - `connection/` - Network + BLK conversion (`network.py`, `blk_utils.py`, `const.py`, `http/`, `tcp/`, `default_network_cfg.json`) @@ -69,7 +69,7 @@ This project uses the following external binaries: ## File conventions - Files use `tabs` for indentation, not spaces - Importing is generally done with `from ... import ...`, to reduce the extra entries in IntelliSense -- Rate limiting via `app.api.shared.limiter` +- Rate limiting via `src.api.shared.limiter` - Use the module-level `logger` for logging - In `src/utils/vehicleParser/`, trailing `pass` statements are intentional debug breakpoint anchors — do not remove them From 53f1345108d134c9793791011c0980dc456f37eb Mon Sep 17 00:00:00 2001 From: Maho Yoshino <62778359+Maho-Yoshino@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:40:50 +0200 Subject: [PATCH 04/91] Major dict helper rewrite Now it is less monolithic in design, with separate classes for different actions --- src/api/v1/backends/clans.py | 50 +++++------ src/api/v1/backends/users.py | 99 +++++++++++++++------- src/api/v1/models/users.py | 157 +++++++++++++---------------------- src/api/v1/users_router.py | 68 ++++++++++++--- src/utils/helper.py | 73 ++++++++++------ 5 files changed, 253 insertions(+), 194 deletions(-) diff --git a/src/api/v1/backends/clans.py b/src/api/v1/backends/clans.py index 23c0855d..ec330f36 100644 --- a/src/api/v1/backends/clans.py +++ b/src/api/v1/backends/clans.py @@ -9,7 +9,7 @@ from utils.connection import Request from utils.auth import LoginEntry from utils.geo import lookup_city, lookup_utc_offset -from utils.helper import Keymod +from utils.helper import dictUtil from api.v1.models.clans import ClanModel, Roles, Platforms, Actions, ClanLeaderboardModel, ClanSearchResultModel import utils.connection.network as Network @@ -172,17 +172,17 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: ) SANITIZE = ( - Keymod("candidates", new_name="applicants", convert=lambda x: sanitizeApplicants(x)), - Keymod("members", convert=lambda x: sanitizeMembers(x)), - Keymod("transactions", rm=True), - Keymod("namel", rm=True), - Keymod("regionl", rm=True), - Keymod("tagl", rm=True), - Keymod("currentTagRegalia", rm=True), - Keymod("interlockid", rm=True), - Keymod("type", rm=True) + dictUtil.KeyMod("candidates", new_name="applicants", convert=lambda x: sanitizeApplicants(x)), + dictUtil.KeyMod("members", convert=lambda x: sanitizeMembers(x)), + dictUtil.KeyRem("transactions"), + dictUtil.KeyRem("namel"), + dictUtil.KeyRem("regionl"), + dictUtil.KeyRem("tagl"), + dictUtil.KeyRem("currentTagRegalia"), + dictUtil.KeyRem("interlockid"), + dictUtil.KeyRem("type") ) - data = Keymod.run_all(data, SANITIZE) + data = dictUtil.run_all(data, SANITIZE) return data @@ -263,23 +263,23 @@ def sanitizeMembers(members:dict|list): members = [members,] SANITIZATION = ( - Keymod("uid", convert=lambda x: int(x)), - Keymod("nick", new_name="nickname"), - Keymod("role", new_name="rank", convert=lambda x: { + dictUtil.KeyMod("uid", convert=lambda x: int(x)), + dictUtil.KeyMod("nick", new_name="nickname"), + dictUtil.KeyMod("role", new_name="rank", convert=lambda x: { "name": Roles(x).name, "value": x }), - Keymod("platform", convert=lambda x: { + dictUtil.KeyMod("platform", convert=lambda x: { "name": Platforms(x).name, "value": x }, default=Platforms.PC.value), - Keymod("initiator", new_name="accepted_by", convert=lambda x: int(x) if x is not None else x, default=None), - Keymod("initiator_nick", new_name="accepted_by_nick", default=None), - Keymod("date", new_name="joined_at") + dictUtil.KeyMod("initiator", new_name="accepted_by", convert=lambda x: int(x) if x is not None else x, default=None), + dictUtil.KeyMod("initiator_nick", new_name="accepted_by_nick", default=None), + dictUtil.KeyMod("date", new_name="joined_at") ) for i, member in enumerate(members): - members[i] = Keymod.run_all(member, SANITIZATION) + members[i] = dictUtil.run_all(member, SANITIZATION) return members @@ -302,14 +302,14 @@ def _ip_to_geo(x: str) -> dict[str, Any] | None: } SANITIZATION = ( - Keymod("uid", convert=lambda x: int(x)), - Keymod("nick", new_name="nickname"), - Keymod("comments", new_name="comment", default=""), - Keymod("date", new_name="timestamp"), - Keymod("ip", new_name="geo", convert=lambda x: _ip_to_geo(x)) + dictUtil.KeyMod("uid", convert=lambda x: int(x)), + dictUtil.KeyMod("nick", new_name="nickname"), + dictUtil.KeyMod("comments", new_name="comment", default=""), + dictUtil.KeyMod("date", new_name="timestamp"), + dictUtil.KeyMod("ip", new_name="geo", convert=lambda x: _ip_to_geo(x)) ) for i, applicant in enumerate(applicants): - applicants[i] = Keymod.run_all(applicant, SANITIZATION) + applicants[i] = dictUtil.run_all(applicant, SANITIZATION) return applicants diff --git a/src/api/v1/backends/users.py b/src/api/v1/backends/users.py index acc55385..847dd11d 100644 --- a/src/api/v1/backends/users.py +++ b/src/api/v1/backends/users.py @@ -1,6 +1,7 @@ +from datetime import datetime, UTC from utils.connection import Request from utils.auth import LoginEntry -from utils.helper import Keymod +from utils.helper import dictUtil from api.v1.backends.clans import getClan, Platforms from api.v1.models.clans import RolesDisplay, Roles from api.v1.models.users import TerseReturnModel, PlayerRank @@ -84,37 +85,75 @@ async def get_user(user:LoginEntry, userid: int): userId = userid ) SANITIZE = ( - Keymod("clanId", convert=lambda x: int(x)), - Keymod("shcType", rm=True), - Keymod("background", rm=True), - Keymod("frame", rm=True), - Keymod("icon", rm=True), - Keymod("iconName", rm=True), - Keymod("title", rm=True), - Keymod("closedUnlocks", rm=True), - Keymod("unlocks", rm=True), - Keymod("titles", rm=True), - Keymod("classinessAwards", rm=True), - Keymod("leaderboard", rm=True) + dictUtil.KeyMod("userid", new_name="id", convert=lambda x: int(x)), + dictUtil.KeyRem("shcType"), + dictUtil.KeyRem("background"), + dictUtil.KeyRem("frame"), + dictUtil.KeyRem("icon"), + dictUtil.KeyRem("iconName"), + dictUtil.KeyRem("title"), + dictUtil.KeyRem("closedUnlocks"), + dictUtil.KeyRem("unlocks"), + dictUtil.KeyRem("titles"), + dictUtil.KeyRem("classinessAwards"), + dictUtil.KeyRem("leaderboard"), + dictUtil.KeyRem("aircrafts"), + dictUtil.KeyMod("userstat", new_name="statistics"), + dictUtil.KeyRem("era"), + dictUtil.KeyRem("slots"), + dictUtil.KeyRem("unitsPerCountry"), + dictUtil.KeyMod("lastDay", new_name="last_login", convert=lambda x: datetime.fromtimestamp(x, UTC).date()), + dictUtil.KeyMod("registerDay", new_name="registered_at", convert=lambda x: datetime.fromtimestamp(x, UTC)), + dictUtil.KeyRem("clanId"), + dictUtil.KeyRem("clanMemberRole"), + dictUtil.KeyRem("clanName"), + dictUtil.KeyRem("clanType"), + dictUtil.KeyRem("clanTag"), + dictUtil.KeyRem("exp"), + dictUtil.KeyRem("expConverted") ) - data = Keymod.run_all(data, SANITIZE) - if "userstat" in data: - VEHICLE_SANITIZE = ( - Keymod("was_in_session", rm=True), - # No clue how this calculates to battles, - # These numbers are different from the in-game "battles" values - Keymod("flyouts", new_name="respawns"), - Keymod("wp_total", new_name="total_sl"), - Keymod("online_exp_total", new_name="total_rp") - ) + new_countries_data = {} + for country in data["era"]: + new_countries_data[country.removeprefix("country_")] = { + "max_ranks": data["era"][country], + "numUnits": data["unitsPerCountry"].get(country, {}).get("numUnits", 0), + "numEliteUnits": data["unitsPerCountry"].get(country, {}).get("numEliteUnits", 0), + "current_lineup": tuple(data["slots"].get(country, {}).keys()), + "units": tuple(data["aircrafts"].get(country, {}).keys()) + } + data["countries"] = new_countries_data + del new_countries_data + + data["clan"] = { + "tag": data["clanTag"], + "name": data["clanName"], + "type": data["clanType"], + "role": data["clanMemberRole"], + "id": int(data["clanId"]) + } + level = PlayerRank.get_level(data["exp"]) + data["level"] = { + "title": PlayerRank.from_level(level).name, + "level": level + } + + VEHICLE_SANITIZE = ( + dictUtil.KeyRem("was_in_session"), + # No clue how this calculates to battles, + # These numbers are different from the in-game "battles" values + dictUtil.KeyMod("flyouts", new_name="respawns"), + dictUtil.KeyMod("wp_total", new_name="total_sl"), + dictUtil.KeyMod("online_exp_total", new_name="total_rp") + ) + + data["userstat"] = dictUtil.KeyRem("new").run(data["userstat"]) + for mode in data["userstat"]: + m_data: dict[str, dict[str, int]] = data["userstat"][mode].pop("total") + for vehicle, v_data in m_data.items(): + m_data[vehicle] = dictUtil.run_all(v_data, VEHICLE_SANITIZE) + data["userstat"][mode] = m_data - data["userstat"] = Keymod("new", rm=True).run(data["userstat"]) - for mode in data["userstat"]: - m_data: dict[str, dict[str, int]] = data["userstat"][mode].pop("total") - for vehicle, v_data in m_data.items(): - m_data[vehicle] = Keymod.run_all(v_data, VEHICLE_SANITIZE) - data["userstat"][mode] = m_data - pass + data = dictUtil.run_all(data, SANITIZE) return data diff --git a/src/api/v1/models/users.py b/src/api/v1/models/users.py index 74d14b90..cb75c033 100644 --- a/src/api/v1/models/users.py +++ b/src/api/v1/models/users.py @@ -5,6 +5,7 @@ from enum import Enum from bisect import bisect_right from .clans import PLATFORM_NAMES +from datetime import datetime, date COUNTRIES = Literal[ "country_usa", @@ -28,6 +29,7 @@ "italy", "france", "sweden", + "israel" ] GAMEMODES = Literal[ "arcade", @@ -65,7 +67,7 @@ "human" ] -class getUserDirectModel(BaseModel): +class getUserDirect: class summaryModel(BaseModel): class summaryGameModeModel(BaseModel): class vehicleModel(BaseModel): @@ -101,110 +103,65 @@ class vehicleModel(BaseModel): builder_played: dict[GAMEMODES, summaryGameModeModel] other_played: dict[GAMEMODES, summaryGameModeModel] - nick: str - lastDay: int - registerDay: int - userid: IntString - exp: int - expConverted: int - numEliteUnits: int - title: str - icon: int - iconName: str - frame: str - background: str - shcType: str - penaltyStatus: str - era: dict[ - COUNTRIES, - dict[ - Literal[ - "Aircraft", - "Tank", - "Ship", - "Helicopter", - "Boat", - "Human" - ], int - ]] - unitsPerCountry: dict[COUNTRIES, dict[Literal["numUnits", "numEliteUnits"], int]] - aircrafts: dict[COUNTRIES, dict[str, int]] - slots: dict[COUNTRIES, dict[str, int]] - summary: summaryModel - unlocks: dict[str, dict[Literal["type"], Literal["achievement", "challenge"]]] - closedUnlocks: dict - titles: dict - userstat: dict - classinessAwards: dict - leaderboard: dict[str, dict[str, dict]] + class statisticsModel(BaseModel): + class unitStatModel(BaseModel): + victories: int = 0 + deaths: int = 0 + defeats: int = 0 + air_kills: int = 0 + ground_kills: int = 0 + naval_kills: int = 0 + respawns: int = 0 + total_sl: int = 0 + total_rp: int = 0 -class TerseReturnModel(BaseModel): - #region Showcase Models - class Showcase_FavMode_Model(BaseModel): # Favorite Mode - class ModeStatsModel(BaseModel): - each_player_session: int - each_player_victories: int - flyouts: int - kills_ai: int - kills_player_or_bot: int - score: int - mode: GAMEMODES - modeValue: ModeStatsModel = Field(description="Key value is the value set for `mode`") - class Showcase_BH_Model(BaseModel): # Battle-Hardened - class ModeStatsModel(BaseModel): - average_score: float - avg_rel_position: float - each_player_session: int - each_player_victories: int - efficiency_vs_ai: float - efficiency_vs_players: float - h_mode: GAMEMODES - h_modeValue: ModeStatsModel = Field(description="Key value is the value set for `h_mode`") - class Showcase_FavUnit_Model(BaseModel): # Favorite vehicle - difficulty: GAMEMODES - vehicle: str = Field( - description="Internal name of the vehicle", - examples=["saab_jas39e", "germ_leopard_2pl", "tiger_had_spain"] - ) - class Showcase_NukeDrop_Model(BaseModel): # Atomic Ace - atomic_ace__counter: int = Field(description="Number of times the user has dropped a nuke") - class Showcase_NukeKill_Model(BaseModel): # Peacemaker - peacemaker__counter: int = Field(description="Number of nuke carriers killed") - class Showcase_unitCollector_Model(BaseModel): # Vehicle collector - units: list[str] = Field( - description="List of internal names of the vehicles showcased", - examples=[ - ["ussr_object_279", "ussr_pt_76_57", "douglas_a_1h"], - ["germ_panther_II","germ_pzkpfw_VI_ausf_b_tiger_IIh_kwk46","germ_flakpanzer_V_Coelian"] - ]) - counts: dict[COUNTRIES, int] = Field(description="Number of vehicles collected per country") - class Showcase_AceOfSpades_Model(BaseModel): # Ace of spades - class AcedUnitsModel(BaseModel): - filteredTotal: int - Aircraft: dict[SIMPLE_COUNTRIES, int] - Boat: dict[SIMPLE_COUNTRIES, int] - Helicopter: dict[SIMPLE_COUNTRIES, int] - Ship: dict[SIMPLE_COUNTRIES, int] - Tank: dict[SIMPLE_COUNTRIES, int] - aced_units: AcedUnitsModel - class Showcase_Medalist_Model(BaseModel): # Medalist - medals: list[str] - total_medals: int - class Showcase_Achievement_Model(BaseModel): # Achievement Hunter - achievements: list[str] - total_steam_achievements: int - #endregion + arcade: dict[str, unitStatModel] = {} + historical: dict[str, unitStatModel] = {} + simulator: dict[str, unitStatModel] = {} + + class countriesModel(BaseModel): + class maxRanksModel(BaseModel): + Aircraft: int + Tank: int + Ship: int + Helicopter: int + Boat: int + Human: int + max_ranks: maxRanksModel + numUnits: int = 0 + numEliteUnits: int = 0 + current_lineup: tuple[str, ...] = tuple() + units: tuple[str, ...] = tuple() - background: str + class metaModel(BaseModel): + class _clanDataModel(BaseModel): + name: str + tag: str + type: int + role: int + id: int + + class _playerLevelModel(BaseModel): + title: str + level: int + + nick: str + last_login: date + registered_at: datetime + id: int + level: _playerLevelModel + clan: _clanDataModel + numEliteUnits: int + penaltyStatus: str + #summary: _summaryModel + #statistics: _statisticsModel + #countries: dict[SIMPLE_COUNTRIES, _countriesModel] + +class TerseReturnModel(BaseModel): clanName: str = Field(description="Name of the clan the user is in, if applicable", examples=["Order Of The Birb", ""]) clanTag: str = Field(description="Clan tag of the clan the user is in, if applicable. Includes border. Key doesn't exist if user is not in a clan", examples=["┾PECK┿"]) - frame: str nick: str - pilotIcon: str - pilotId: int - shcType: str - title: str - showcase: Showcase_FavMode_Model | Showcase_BH_Model | Showcase_FavUnit_Model | Showcase_NukeDrop_Model | Showcase_NukeKill_Model | Showcase_unitCollector_Model | Showcase_AceOfSpades_Model | Showcase_Medalist_Model | Showcase_Achievement_Model + class SelfUserDataModel(BaseModel): class LevelModel(BaseModel): diff --git a/src/api/v1/users_router.py b/src/api/v1/users_router.py index 573797ff..56715784 100644 --- a/src/api/v1/users_router.py +++ b/src/api/v1/users_router.py @@ -4,10 +4,11 @@ from fastapi.responses import JSONResponse from urllib.parse import unquote +from utils.helper import dictUtil from utils.connection import Request from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.models.users import TerseReturnModel, getUserDirectModel, SelfUserDataModel +from api.v1.models.users import TerseReturnModel, getUserDirect, SelfUserDataModel from api.v1.backends.users import get_terse, get_user, get_self router = APIRouter( @@ -16,7 +17,10 @@ responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} ) -@router.get("/terse", summary="Get several users by ID") +@router.get( + "/terse", + summary="Get several users by ID" +) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") async def get_users_terse_info( request: faRequest, @@ -29,7 +33,7 @@ async def get_users_terse_info( ], ) -> dict[str, TerseReturnModel]: """Get terse information about users by their IDs.""" - return JSONResponse(await get_terse(user, *id)) + return await get_terse(user, *id) @router.get( "/self", @@ -46,20 +50,60 @@ async def get_self_meta( ): return await get_self(user) -@router.get("/{userid}", summary="Get user by ID") +@router.get( + "/{userid}/meta", + summary="Gets metadata about a user" +) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") -async def get_user_direct( +async def get_user_direct_meta( request: faRequest, user: ServerBearer, userid: Annotated[int, Path(title="The ID of the user to get information about", description="The ID of the user to get information about", gt=0)], -) -> getUserDirectModel: - return JSONResponse( - await Request.send_template( - user, - "get_public_userstat", - userId = userid - ) +) -> getUserDirect.metaModel: + data = await get_user(user, userid) + SANITIZE = ( + dictUtil.KeyRem("summary"), + dictUtil.KeyRem("statistics"), + dictUtil.KeyRem("countries") ) + return dictUtil.run_all(data, SANITIZE) + +@router.get( + "/{userid}/stats", + summary="Gets statistics about a user" +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +async def get_user_direct_stats( + request: faRequest, + user: ServerBearer, + userid: Annotated[int, Path(title="The ID of the user to get information about", description="The ID of the user to get information about", gt=0)], +) -> getUserDirect.statisticsModel: + return (await get_user(user, userid))["statistics"] + +@router.get( + "/{userid}/countries", + summary="Gets country data about a user" +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +async def get_user_direct_countries( + request: faRequest, + user: ServerBearer, + userid: Annotated[int, Path(title="The ID of the user to get information about", description="The ID of the user to get information about", gt=0)], +) -> getUserDirect.countriesModel: + return (await get_user(user, userid))["countries"] + + +@router.get( + "/{userid}/summary", + summary="Gets a summary of a user's statistics per-mode" +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +async def get_user_direct_summary( + request: faRequest, + user: ServerBearer, + userid: Annotated[int, Path(title="The ID of the user to get information about", description="The ID of the user to get information about", gt=0)], +) -> getUserDirect.summaryModel: + return (await get_user(user, userid))["summary"] @router.get( "/search/{nick}", diff --git a/src/utils/helper.py b/src/utils/helper.py index 4e15f6da..f5e7f7b4 100644 --- a/src/utils/helper.py +++ b/src/utils/helper.py @@ -12,40 +12,59 @@ class AuthenticationError(HTTPException): def __init__(self, status_code, detail = None, headers = None): super().__init__(status_code, detail, headers) -class Keymod: - key: str - new_name: str - convert: Callable[[Any], Any] - default: Any - rm: bool - - def __init__(self, key: str, /, *, new_name: str = None, convert: Callable[[Any], Any] = lambda x: x, default: Any = ..., rm: bool = False): - self.key = key - if new_name: - self.new_name = new_name - else: - self.new_name = key - self.convert = convert - self.rm = rm - if not self.rm: - self.default = default - else: - self.default = None +class dictUtil: + class KeyRem: + key: str + + def __init__(self, key: str, /): + self.key = key + + def run(self, obj: dict[str, Any]): + obj.pop(self.key, None) + return obj + + class KeyAdd: + key: str + value: Any + + def __init__(self, key: str, value: Any, /): + self.key = key + self.value = value - def run(self, obj:dict[str, Any]) -> dict[str, Any]: - if self.key not in obj: - if self.default is not ... and not self.rm: - obj[self.new_name] = self.convert(self.default) + def run(self, obj: dict[str, Any]): + if self.key in obj: + raise KeyError(f"Key '{self.key}' already in object") + obj[self.key] = self.value return obj - new_val = self.convert(obj.pop(self.key)) + class KeyMod: + key: str + new_name: str + convert: Callable[[Any], Any] + default: Any + + def __init__(self, key: str, /, *, new_name: str = None, convert: Callable[[Any], Any] = lambda x: x, default: Any = ...): + self.key = key + if new_name: + self.new_name = new_name + else: + self.new_name = key + self.convert = convert + self.default = default + + def run(self, obj: dict[str, Any]): + if self.key not in obj: + if self.default is not ...: + obj[self.new_name] = self.convert(self.default) + return obj + + new_val = self.convert(obj.pop(self.key)) - if not self.rm: obj[self.new_name] = new_val - return obj + return obj @staticmethod - def run_all(obj:dict[str, Any], changes:Iterable[Keymod]): + def run_all(obj: dict[str, Any], changes:Iterable[KeyMod|KeyRem|KeyAdd]): for change in changes: obj = change.run(obj) return obj From c833b498637d68ae0107ad38afa37c3b718c5e79 Mon Sep 17 00:00:00 2001 From: Maho Yoshino <62778359+Maho-Yoshino@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:09:52 +0100 Subject: [PATCH 05/91] more dict util improvements --- src/api/v1/backends/clans.py | 16 ++-- src/api/v1/backends/users.py | 142 +++++++++++++++++++++-------------- src/api/v1/models/users.py | 16 ++-- src/api/v1/users_router.py | 14 ++-- src/utils/helper.py | 41 ++++++---- 5 files changed, 137 insertions(+), 92 deletions(-) diff --git a/src/api/v1/backends/clans.py b/src/api/v1/backends/clans.py index ec330f36..394c374c 100644 --- a/src/api/v1/backends/clans.py +++ b/src/api/v1/backends/clans.py @@ -174,13 +174,15 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: SANITIZE = ( dictUtil.KeyMod("candidates", new_name="applicants", convert=lambda x: sanitizeApplicants(x)), dictUtil.KeyMod("members", convert=lambda x: sanitizeMembers(x)), - dictUtil.KeyRem("transactions"), - dictUtil.KeyRem("namel"), - dictUtil.KeyRem("regionl"), - dictUtil.KeyRem("tagl"), - dictUtil.KeyRem("currentTagRegalia"), - dictUtil.KeyRem("interlockid"), - dictUtil.KeyRem("type") + dictUtil.KeyRem( + "transactions", + "namel", + "regionl", + "tagl", + "currentTagRegalia", + "interlockid", + "type" + ), ) data = dictUtil.run_all(data, SANITIZE) diff --git a/src/api/v1/backends/users.py b/src/api/v1/backends/users.py index 847dd11d..2a03d3de 100644 --- a/src/api/v1/backends/users.py +++ b/src/api/v1/backends/users.py @@ -1,4 +1,5 @@ from datetime import datetime, UTC +from typing import Any from utils.connection import Request from utils.auth import LoginEntry from utils.helper import dictUtil @@ -12,6 +13,21 @@ async def get_terse(user:LoginEntry, *userIds:int|str) -> dict[str, TerseReturnM "get_users_terse_info", usersList = ";".join(str(i) for i in userIds) ) + SANITIZE = ( + dictUtil.KeyRem( + "background", + "showcase", + "title", + "shcType", + "pilotId", + "pilotIcon", + "frame" + ), + dictUtil.KeyMod("nick", new_name="username") + ) + for k in data: + data[int(k)] = dictUtil.run_all(data.pop(k), SANITIZE) + return data async def get_self(user:LoginEntry): @@ -21,45 +37,40 @@ async def get_self(user:LoginEntry): "get_public_userstat", userId = user.uidHint ) - data["nick"] = userData["nick"] - data["userid"] = int(userData["userid"]) - data["penaltyStatus"] = userData["penaltyStatus"] - data["registerDay"] = userData["registerDay"] - data["lastDay"] = userData["lastDay"] - level = PlayerRank.get_level(userData["exp"]) - data["level"] = { - "name": PlayerRank.from_level(level).label, - "rank": level - } - data["acedVehicles"] = userData["numEliteUnits"] - - data["unitsData"] = {} - for k in userData["era"]: - data["unitsData"].setdefault(k, {}) - data["unitsData"][k]["max_rank"] = userData["era"][k] - for k in userData["unitsPerCountry"]: - data["unitsData"].setdefault(k, {}) - data["unitsData"][k]["collection"] = { - "overall": userData["unitsPerCountry"][k]["numUnits"], - "aced": userData["unitsPerCountry"][k]["numEliteUnits"] + def create_level(obj): + _ = PlayerRank.get_level(obj["exp"]) + return { + "name": PlayerRank.from_level(_).label, + "rank": _ } - - if "clanId" in userData: - data["squadron"] = { - "tag": userData["clanTag"], - "id": int(userData["clanId"]), - "name": userData["clanName"], - "type": userData["clanType"] + def create_unitsdata(obj:dict[str, Any]): + data = {} + for k in userData["era"]: + data.setdefault(k, {}) + data[k]["max_rank"] = userData["era"][k] + for k in userData["unitsPerCountry"]: + data.setdefault(k, {}) + data[k]["collection"] = { + "overall": userData["unitsPerCountry"][k]["numUnits"], + "aced": userData["unitsPerCountry"][k]["numEliteUnits"] + } + return data + async def create_clan(obj:dict[str, Any]): + data = { + "tag": obj["clanTag"], + "id": int(obj["clanId"]), + "name": obj["clanName"], + "type": obj["clanType"] } - data["squadron"]["user"] = {} - clanData = await getClan(user, data["squadron"]["id"]) + data["user"] = {} + clanData = await getClan(user, data["id"]) for cuser in clanData["members"]: if cuser["uid"] != str(user.uidHint): continue role = Roles(cuser["role"]) platform = Platforms(cuser["platform"]) - data["squadron"]["user"] = { + data["user"] = { "initiator": int(cuser["initiator"]) if isinstance(cuser["initiator"], str) else None, "join_timestamp": cuser["date"], "role": { @@ -73,10 +84,24 @@ async def get_self(user:LoginEntry): } break - data["squadron"]["user"]["activity"] = clanData.get("activity", {}).get(str(user.uidHint), {}).get("total", 0) - data["squadron"]["user"]["sqb_activity"] = clanData.get("member_ratings", {}).get(str(user.uidHint), {}).get("dr_era5_hist", 0.0) + data["user"]["activity"] = clanData.get("activity", {}).get(str(user.uidHint), {}).get("total", 0) + data["user"]["sqb_activity"] = clanData.get("member_ratings", {}).get(str(user.uidHint), {}).get("dr_era5_hist", 0.0) + return data - return data + + SANITIZE = ( + dictUtil.KeyMod("userid", convert=lambda x: int(x)), + dictUtil.KeyMod("nick", new_name="username"), + dictUtil.KeyMod("lastDay", new_name="last_login_date", convert=lambda x: datetime.fromtimestamp(x, UTC).date()), + dictUtil.KeyMod("registerDay", new_name="registered_at", convert=lambda x: datetime.fromtimestamp(x, UTC)), + dictUtil.KeyMod("acedVehicles", new_name="numEliteUnits"), + dictUtil.KeyAdd("unitsData", create_unitsdata), + dictUtil.KeyAdd("level", create_level), + dictUtil.KeyAdd("squadron", create_clan) if "clanId" in userData else None, + dictUtil.KeyRem("exp", "era", "unitsPerCountry") + ) + + return dictUtil.run_all(userData, SANITIZE) async def get_user(user:LoginEntry, userid: int): data = await Request.send_template( @@ -86,31 +111,33 @@ async def get_user(user:LoginEntry, userid: int): ) SANITIZE = ( dictUtil.KeyMod("userid", new_name="id", convert=lambda x: int(x)), - dictUtil.KeyRem("shcType"), - dictUtil.KeyRem("background"), - dictUtil.KeyRem("frame"), - dictUtil.KeyRem("icon"), - dictUtil.KeyRem("iconName"), - dictUtil.KeyRem("title"), - dictUtil.KeyRem("closedUnlocks"), - dictUtil.KeyRem("unlocks"), - dictUtil.KeyRem("titles"), - dictUtil.KeyRem("classinessAwards"), - dictUtil.KeyRem("leaderboard"), - dictUtil.KeyRem("aircrafts"), dictUtil.KeyMod("userstat", new_name="statistics"), - dictUtil.KeyRem("era"), - dictUtil.KeyRem("slots"), - dictUtil.KeyRem("unitsPerCountry"), dictUtil.KeyMod("lastDay", new_name="last_login", convert=lambda x: datetime.fromtimestamp(x, UTC).date()), dictUtil.KeyMod("registerDay", new_name="registered_at", convert=lambda x: datetime.fromtimestamp(x, UTC)), - dictUtil.KeyRem("clanId"), - dictUtil.KeyRem("clanMemberRole"), - dictUtil.KeyRem("clanName"), - dictUtil.KeyRem("clanType"), - dictUtil.KeyRem("clanTag"), - dictUtil.KeyRem("exp"), - dictUtil.KeyRem("expConverted") + dictUtil.KeyRem( + "shcType" + "background", + "frame", + "icon", + "iconName", + "title", + "closedUnlocks", + "unlocks", + "titles", + "classinessAwards", + "leaderboard", + "aircrafts", + "era", + "slots", + "unitsPerCountry", + "clanId", + "clanMemberRole", + "clanName", + "clanType", + "clanTag", + "exp", + "expConverted" + ), ) new_countries_data = {} for country in data["era"]: @@ -152,6 +179,9 @@ async def get_user(user:LoginEntry, userid: int): for vehicle, v_data in m_data.items(): m_data[vehicle] = dictUtil.run_all(v_data, VEHICLE_SANITIZE) data["userstat"][mode] = m_data + data["userstat"] = dictUtil.KeyMod("simulation", new_name="simulator").run(data["userstat"]) + for mode in data["summary"]: + data["summary"][mode] = dictUtil.KeyMod("hardcore", new_name="simulator").run(data["summary"][mode]) data = dictUtil.run_all(data, SANITIZE) diff --git a/src/api/v1/models/users.py b/src/api/v1/models/users.py index cb75c033..838b9f03 100644 --- a/src/api/v1/models/users.py +++ b/src/api/v1/models/users.py @@ -34,7 +34,7 @@ GAMEMODES = Literal[ "arcade", "realistic", - "hardcore" + "simulator" ] SPECIFIC_GAMEMODES = Literal[ "air_arcade", @@ -121,12 +121,12 @@ class unitStatModel(BaseModel): class countriesModel(BaseModel): class maxRanksModel(BaseModel): - Aircraft: int - Tank: int - Ship: int - Helicopter: int - Boat: int - Human: int + Aircraft: int = -1 + Tank: int = -1 + Ship: int = -1 + Helicopter: int = -1 + Boat: int = -1 + Human: int = -1 max_ranks: maxRanksModel numUnits: int = 0 numEliteUnits: int = 0 @@ -160,7 +160,7 @@ class _playerLevelModel(BaseModel): class TerseReturnModel(BaseModel): clanName: str = Field(description="Name of the clan the user is in, if applicable", examples=["Order Of The Birb", ""]) clanTag: str = Field(description="Clan tag of the clan the user is in, if applicable. Includes border. Key doesn't exist if user is not in a clan", examples=["┾PECK┿"]) - nick: str + username: str class SelfUserDataModel(BaseModel): diff --git a/src/api/v1/users_router.py b/src/api/v1/users_router.py index 56715784..dd3ec2bf 100644 --- a/src/api/v1/users_router.py +++ b/src/api/v1/users_router.py @@ -8,7 +8,7 @@ from utils.connection import Request from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.models.users import TerseReturnModel, getUserDirect, SelfUserDataModel +from api.v1.models.users import TerseReturnModel, getUserDirect, SelfUserDataModel, SIMPLE_COUNTRIES from api.v1.backends.users import get_terse, get_user, get_self router = APIRouter( @@ -31,7 +31,7 @@ async def get_users_terse_info( min_length=1, max_length=50) ], -) -> dict[str, TerseReturnModel]: +) -> dict[int, TerseReturnModel]: """Get terse information about users by their IDs.""" return await get_terse(user, *id) @@ -62,15 +62,13 @@ async def get_user_direct_meta( ) -> getUserDirect.metaModel: data = await get_user(user, userid) SANITIZE = ( - dictUtil.KeyRem("summary"), - dictUtil.KeyRem("statistics"), - dictUtil.KeyRem("countries") + dictUtil.KeyRem("summary", "statistics", "countries") ) return dictUtil.run_all(data, SANITIZE) @router.get( "/{userid}/stats", - summary="Gets statistics about a user" + summary="Gets per-vehicle statistics about a user" ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") async def get_user_direct_stats( @@ -89,13 +87,13 @@ async def get_user_direct_countries( request: faRequest, user: ServerBearer, userid: Annotated[int, Path(title="The ID of the user to get information about", description="The ID of the user to get information about", gt=0)], -) -> getUserDirect.countriesModel: +) -> dict[SIMPLE_COUNTRIES, getUserDirect.countriesModel]: return (await get_user(user, userid))["countries"] @router.get( "/{userid}/summary", - summary="Gets a summary of a user's statistics per-mode" + summary="Gets a summary of a user's statistics per-difficulty and per-vehicle type" ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") async def get_user_direct_summary( diff --git a/src/utils/helper.py b/src/utils/helper.py index f5e7f7b4..3b94e2df 100644 --- a/src/utils/helper.py +++ b/src/utils/helper.py @@ -1,6 +1,7 @@ +from inspect import isawaitable from datetime import datetime from fastapi import HTTPException -from typing import Any, Callable +from typing import Any, Callable, Coroutine from collections.abc import Iterable def dtToTimestamp(dt:datetime) -> int: @@ -14,27 +15,32 @@ def __init__(self, status_code, detail = None, headers = None): class dictUtil: class KeyRem: - key: str + keys: tuple[str, ...] - def __init__(self, key: str, /): - self.key = key + def __init__(self, *keys: str): + self.keys = tuple(keys) - def run(self, obj: dict[str, Any]): - obj.pop(self.key, None) + async def run(self, obj: dict[str, Any]): + for key in self.keys: + obj.pop(key, None) return obj class KeyAdd: key: str - value: Any + value: Any | Callable[[dict[str, Any]], Any] - def __init__(self, key: str, value: Any, /): + def __init__(self, key: str, value: Any | Callable[[dict[str, Any]], Any], /): self.key = key self.value = value - def run(self, obj: dict[str, Any]): + def _resolve(self) -> Any: + return self.value() if callable(self.value) else self.value + + async def run(self, obj: dict[str, Any]): if self.key in obj: raise KeyError(f"Key '{self.key}' already in object") - obj[self.key] = self.value + + obj[self.key] = dictUtil._await_maybe(self.value) return obj class KeyMod: @@ -52,7 +58,7 @@ def __init__(self, key: str, /, *, new_name: str = None, convert: Callable[[Any] self.convert = convert self.default = default - def run(self, obj: dict[str, Any]): + async def run(self, obj: dict[str, Any]): if self.key not in obj: if self.default is not ...: obj[self.new_name] = self.convert(self.default) @@ -64,7 +70,16 @@ def run(self, obj: dict[str, Any]): return obj @staticmethod - def run_all(obj: dict[str, Any], changes:Iterable[KeyMod|KeyRem|KeyAdd]): + async def run_all(obj: dict[str, Any], changes:Iterable[KeyMod|KeyRem|KeyAdd|None]): for change in changes: - obj = change.run(obj) + if change is None: + continue + tmp = await change.run(obj) + return obj + + @staticmethod + async def _await_maybe(value): + if isawaitable(value): + return await value + return value From c3f89ee92620cadbdb48d83c9a61bd0185b7b35a Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:10:42 +0100 Subject: [PATCH 06/91] Hosting files improvements --- systemd.service | 2 +- update | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/systemd.service b/systemd.service index f093591c..070b9bb9 100644 --- a/systemd.service +++ b/systemd.service @@ -5,7 +5,7 @@ After=docker.service network-online.target [Service] Type=exec -ExecStart=/usr/bin/docker compose up +ExecStart=/usr/bin/docker compose up thunderapi WorkingDirectory={DIRECTORY} Restart=on-failure RestartSec=10 diff --git a/update b/update index f929771a..ad5a3882 100755 --- a/update +++ b/update @@ -2,6 +2,6 @@ git pull -/usr/bin/docker compose down -/usr/bin/docker compose build -/usr/bin/docker compose up -d +/usr/bin/docker compose down thunderapi +/usr/bin/docker compose build thunderapi +/usr/bin/docker compose up thunderapi -d From b74b104c847b9249cdc280494e80a9c04e8dec53 Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:38:26 +0100 Subject: [PATCH 07/91] Endpoints return data cleanup work --- src/api/v1/backends/clans.py | 14 ++--- src/api/v1/backends/users.py | 104 +++++++---------------------------- src/api/v1/models/users.py | 51 +---------------- src/api/v1/users_router.py | 10 ++-- src/utils/helper.py | 17 ++++-- 5 files changed, 43 insertions(+), 153 deletions(-) diff --git a/src/api/v1/backends/clans.py b/src/api/v1/backends/clans.py index 394c374c..8a14e5a5 100644 --- a/src/api/v1/backends/clans.py +++ b/src/api/v1/backends/clans.py @@ -172,8 +172,8 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: ) SANITIZE = ( - dictUtil.KeyMod("candidates", new_name="applicants", convert=lambda x: sanitizeApplicants(x)), - dictUtil.KeyMod("members", convert=lambda x: sanitizeMembers(x)), + dictUtil.KeyMod("candidates", new_name="applicants", convert=lambda x: (await sanitizeApplicants(x) for _ in '_').__anext__()), + dictUtil.KeyMod("members", convert=lambda x: (await sanitizeMembers(x) for _ in '_').__anext__()), dictUtil.KeyRem( "transactions", "namel", @@ -184,7 +184,7 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: "type" ), ) - data = dictUtil.run_all(data, SANITIZE) + data = await dictUtil.run_all(data, SANITIZE) return data @@ -257,7 +257,7 @@ async def current_sqb_br() -> dict[str, datetime|float]: return week raise HTTPException(status.HTTP_404_NOT_FOUND, "Could not find current bracket data") -def sanitizeMembers(members:dict|list): +async def sanitizeMembers(members:dict|list): if members is None: return [] @@ -281,11 +281,11 @@ def sanitizeMembers(members:dict|list): ) for i, member in enumerate(members): - members[i] = dictUtil.run_all(member, SANITIZATION) + members[i] = await dictUtil.run_all(member, SANITIZATION) return members -def sanitizeApplicants(applicants:dict|list|None): +async def sanitizeApplicants(applicants:dict|list|None): if applicants is None: return [] @@ -312,6 +312,6 @@ def _ip_to_geo(x: str) -> dict[str, Any] | None: ) for i, applicant in enumerate(applicants): - applicants[i] = dictUtil.run_all(applicant, SANITIZATION) + applicants[i] = await dictUtil.run_all(applicant, SANITIZATION) return applicants diff --git a/src/api/v1/backends/users.py b/src/api/v1/backends/users.py index 2a03d3de..4dcc8c8a 100644 --- a/src/api/v1/backends/users.py +++ b/src/api/v1/backends/users.py @@ -25,83 +25,15 @@ async def get_terse(user:LoginEntry, *userIds:int|str) -> dict[str, TerseReturnM ), dictUtil.KeyMod("nick", new_name="username") ) - for k in data: - data[int(k)] = dictUtil.run_all(data.pop(k), SANITIZE) + for k in dict(data): + data[int(k)] = await dictUtil.run_all(data.pop(k), SANITIZE) return data async def get_self(user:LoginEntry): - data = {} - userData = await Request.send_template( - user, - "get_public_userstat", - userId = user.uidHint - ) - def create_level(obj): - _ = PlayerRank.get_level(obj["exp"]) - return { - "name": PlayerRank.from_level(_).label, - "rank": _ - } - def create_unitsdata(obj:dict[str, Any]): - data = {} - for k in userData["era"]: - data.setdefault(k, {}) - data[k]["max_rank"] = userData["era"][k] - for k in userData["unitsPerCountry"]: - data.setdefault(k, {}) - data[k]["collection"] = { - "overall": userData["unitsPerCountry"][k]["numUnits"], - "aced": userData["unitsPerCountry"][k]["numEliteUnits"] - } - return data - async def create_clan(obj:dict[str, Any]): - data = { - "tag": obj["clanTag"], - "id": int(obj["clanId"]), - "name": obj["clanName"], - "type": obj["clanType"] - } - data["user"] = {} - clanData = await getClan(user, data["id"]) - for cuser in clanData["members"]: - if cuser["uid"] != str(user.uidHint): - continue - - role = Roles(cuser["role"]) - platform = Platforms(cuser["platform"]) - data["user"] = { - "initiator": int(cuser["initiator"]) if isinstance(cuser["initiator"], str) else None, - "join_timestamp": cuser["date"], - "role": { - "name": RolesDisplay[role.name].value, - "value": role.value - }, - "platform": { - "name": platform.name, - "value": platform.value - } - } - break - - data["user"]["activity"] = clanData.get("activity", {}).get(str(user.uidHint), {}).get("total", 0) - data["user"]["sqb_activity"] = clanData.get("member_ratings", {}).get(str(user.uidHint), {}).get("dr_era5_hist", 0.0) - return data - + userData = await get_user(user, user.uidHint) - SANITIZE = ( - dictUtil.KeyMod("userid", convert=lambda x: int(x)), - dictUtil.KeyMod("nick", new_name="username"), - dictUtil.KeyMod("lastDay", new_name="last_login_date", convert=lambda x: datetime.fromtimestamp(x, UTC).date()), - dictUtil.KeyMod("registerDay", new_name="registered_at", convert=lambda x: datetime.fromtimestamp(x, UTC)), - dictUtil.KeyMod("acedVehicles", new_name="numEliteUnits"), - dictUtil.KeyAdd("unitsData", create_unitsdata), - dictUtil.KeyAdd("level", create_level), - dictUtil.KeyAdd("squadron", create_clan) if "clanId" in userData else None, - dictUtil.KeyRem("exp", "era", "unitsPerCountry") - ) - - return dictUtil.run_all(userData, SANITIZE) + return await dictUtil.KeyRem("summary", "statistics", "countries").run(userData) async def get_user(user:LoginEntry, userid: int): data = await Request.send_template( @@ -115,7 +47,7 @@ async def get_user(user:LoginEntry, userid: int): dictUtil.KeyMod("lastDay", new_name="last_login", convert=lambda x: datetime.fromtimestamp(x, UTC).date()), dictUtil.KeyMod("registerDay", new_name="registered_at", convert=lambda x: datetime.fromtimestamp(x, UTC)), dictUtil.KeyRem( - "shcType" + "shcType", "background", "frame", "icon", @@ -151,13 +83,15 @@ async def get_user(user:LoginEntry, userid: int): data["countries"] = new_countries_data del new_countries_data - data["clan"] = { - "tag": data["clanTag"], - "name": data["clanName"], - "type": data["clanType"], - "role": data["clanMemberRole"], - "id": int(data["clanId"]) - } + if "clanTag" in data: # User is a squadron member + data["clan"] = { + "tag": data["clanTag"], + "name": data["clanName"], + "type": data["clanType"], + "role": data["clanMemberRole"], + "id": int(data["clanId"]) + } + level = PlayerRank.get_level(data["exp"]) data["level"] = { "title": PlayerRank.from_level(level).name, @@ -173,17 +107,17 @@ async def get_user(user:LoginEntry, userid: int): dictUtil.KeyMod("online_exp_total", new_name="total_rp") ) - data["userstat"] = dictUtil.KeyRem("new").run(data["userstat"]) + data["userstat"] = await dictUtil.KeyRem("new").run(data["userstat"]) for mode in data["userstat"]: m_data: dict[str, dict[str, int]] = data["userstat"][mode].pop("total") for vehicle, v_data in m_data.items(): - m_data[vehicle] = dictUtil.run_all(v_data, VEHICLE_SANITIZE) + m_data[vehicle] = await dictUtil.run_all(v_data, VEHICLE_SANITIZE) data["userstat"][mode] = m_data - data["userstat"] = dictUtil.KeyMod("simulation", new_name="simulator").run(data["userstat"]) + data["userstat"] = await dictUtil.KeyMod("simulation", new_name="simulator").run(data["userstat"]) for mode in data["summary"]: - data["summary"][mode] = dictUtil.KeyMod("hardcore", new_name="simulator").run(data["summary"][mode]) + data["summary"][mode] = await dictUtil.KeyMod("hardcore", new_name="simulator").run(data["summary"][mode]) - data = dictUtil.run_all(data, SANITIZE) + data = await dictUtil.run_all(data, SANITIZE) return data diff --git a/src/api/v1/models/users.py b/src/api/v1/models/users.py index 838b9f03..6782cd28 100644 --- a/src/api/v1/models/users.py +++ b/src/api/v1/models/users.py @@ -150,7 +150,7 @@ class _playerLevelModel(BaseModel): registered_at: datetime id: int level: _playerLevelModel - clan: _clanDataModel + clan: _clanDataModel | None = Field(default=None, exclude_if=lambda x: x is None) numEliteUnits: int penaltyStatus: str #summary: _summaryModel @@ -162,55 +162,6 @@ class TerseReturnModel(BaseModel): clanTag: str = Field(description="Clan tag of the clan the user is in, if applicable. Includes border. Key doesn't exist if user is not in a clan", examples=["┾PECK┿"]) username: str - -class SelfUserDataModel(BaseModel): - class LevelModel(BaseModel): - name: Literal["Rookie", "Lieutenant", "Captain", "Major", "Colonel", "Commander", "Commodore", "General", "Marshal"] - rank: int - class UnitsDataModel(BaseModel): - class maxRankModel(BaseModel): - Aircraft: int = -1 - Tank: int = -1 - Ship: int = -1 - Helicopter: int = -1 - Boat: int = -1 - Human: int = -1 - class collectionModel(BaseModel): - overall: int = 0 - aced: int = 0 - max_rank: maxRankModel = Field(default_factory=maxRankModel) - collection: collectionModel = Field(default_factory=collectionModel) - class SquadronModel(BaseModel): - class SquadronUserModel(BaseModel): - class SquadronRoleModel(BaseModel): - name: Literal["Private", "Sergeant", "Officer", "Deputy", "Commander"] - value: int - class SquadronPlatformModel(BaseModel): - name: PLATFORM_NAMES - value: int - initiator: int | None = None - join_timestamp: int - role: SquadronRoleModel - platform: SquadronPlatformModel - activity: int - sqb_activity: float - - tag: str - id: int - name: str - type: int - user: SquadronUserModel - - nick: str - userid: int - penaltyStatus: str - registerDay: int - lastDay: int - level: LevelModel - acedVehicles: int - unitsData: dict[COUNTRIES, UnitsDataModel] - squadron: Optional[SquadronModel] = None - USER_RANK: tuple[int] = ( 0, 500, 1800, 5000, 11600, 23500, 42700, 71700, 113200, 170100, 245600, 322600, 401400, 482100, 564600, 648900, 735000, 822900, 912700, 1004300, diff --git a/src/api/v1/users_router.py b/src/api/v1/users_router.py index dd3ec2bf..ea5f823a 100644 --- a/src/api/v1/users_router.py +++ b/src/api/v1/users_router.py @@ -8,7 +8,7 @@ from utils.connection import Request from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.models.users import TerseReturnModel, getUserDirect, SelfUserDataModel, SIMPLE_COUNTRIES +from api.v1.models.users import TerseReturnModel, getUserDirect, SIMPLE_COUNTRIES from api.v1.backends.users import get_terse, get_user, get_self router = APIRouter( @@ -39,9 +39,9 @@ async def get_users_terse_info( "/self", summary="Get metadata about the logged in user", responses={ - 200: {"model": SelfUserDataModel} + 200: {"model": getUserDirect.metaModel} }, - response_model=SelfUserDataModel + response_model=getUserDirect.metaModel ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") async def get_self_meta( @@ -62,9 +62,9 @@ async def get_user_direct_meta( ) -> getUserDirect.metaModel: data = await get_user(user, userid) SANITIZE = ( - dictUtil.KeyRem("summary", "statistics", "countries") + dictUtil.KeyRem("summary", "statistics", "countries"), ) - return dictUtil.run_all(data, SANITIZE) + return await dictUtil.run_all(data, SANITIZE) @router.get( "/{userid}/stats", diff --git a/src/utils/helper.py b/src/utils/helper.py index 3b94e2df..5e3975d6 100644 --- a/src/utils/helper.py +++ b/src/utils/helper.py @@ -28,19 +28,22 @@ async def run(self, obj: dict[str, Any]): class KeyAdd: key: str value: Any | Callable[[dict[str, Any]], Any] + force: bool - def __init__(self, key: str, value: Any | Callable[[dict[str, Any]], Any], /): + def __init__(self, key: str, value: Any | Callable[[dict[str, Any]], Any], /, *, force:bool = False): self.key = key self.value = value - - def _resolve(self) -> Any: - return self.value() if callable(self.value) else self.value + self.force = force async def run(self, obj: dict[str, Any]): - if self.key in obj: + if self.key in obj and not self.force: raise KeyError(f"Key '{self.key}' already in object") - obj[self.key] = dictUtil._await_maybe(self.value) + val = self.value(obj) if callable(self.value) else self.value + if isawaitable(val): + val = await val + + obj[self.key] = val return obj class KeyMod: @@ -75,6 +78,8 @@ async def run_all(obj: dict[str, Any], changes:Iterable[KeyMod|KeyRem|KeyAdd|Non if change is None: continue tmp = await change.run(obj) + if tmp: + obj = tmp return obj From 4b647cc7f5942842a3285e9259b27d0c9371c3ba Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:41:19 +0100 Subject: [PATCH 08/91] Major news utility rework Removed the part, which stores the latest IDs in an external JSON file This code used to be part of [PECK Bot](https://github.com/Order-Of-The-Birb/peck-bot), however the API doesn't require any persistent check for already-sent data Added forum parsing Implemented parralel fetching to speed it up Restructured the code --- requirements.txt | 2 +- src/config.py | 1 - src/utils/news.py | 396 ++++++++++++++++++++++++++++++++++------------ 3 files changed, 292 insertions(+), 107 deletions(-) diff --git a/requirements.txt b/requirements.txt index 28b7e173..52e59899 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,11 +8,11 @@ uvicorn apscheduler python-multipart PyGithub -bs4 # Data processing lz4 bs4 +lxml pandas pydantic[email] cryptography diff --git a/src/config.py b/src/config.py index 27b6cf7d..5f8e5a0b 100644 --- a/src/config.py +++ b/src/config.py @@ -15,7 +15,6 @@ class _usersDB: USERS_DB = _usersDB() VEHICLES = DATA_DIR / "vehicles" -NEWS_JSON = DATA_DIR / "news.json" class _geoLitePaths: DB = DATA_DIR / "GeoLite2-City.mmdb" diff --git a/src/utils/news.py b/src/utils/news.py index b0a56256..59dcd8d4 100644 --- a/src/utils/news.py +++ b/src/utils/news.py @@ -1,16 +1,13 @@ -from asyncio import Task, Lock, CancelledError +import re, asyncio from logging import getLogger, Logger from aiohttp.client_exceptions import ClientResponseError -from datetime import datetime, time, UTC +from datetime import datetime, time, UTC, timedelta from asyncio import sleep from typing import Literal, Any from dataclasses import dataclass, asdict -from enum import IntEnum, Enum -from re import search as re_search, IGNORECASE -from json import loads, dumps +from enum import IntEnum from bs4 import BeautifulSoup, Tag from utils.helper import dtToTimestamp -from config import NEWS_JSON from utils.connection.websocket import WebsocketManager import utils.connection.network as Network @@ -35,10 +32,10 @@ class ImportanceLevel(IntEnum): link:str # URL pinned:bool images:list['Image'] # Attached images - tags:list[Literal["Event", "Development", "Video", "Shop", "Fixed", "eSport", "Market", "Special", "Warbonds", "Fair Play", "Update"]] # Attached tags - platforms:list[str] # Affected platforms + tags:set[Literal["Event", "Development", "Video", "Shop", "Fixed", "eSport", "Market", "Special", "Warbonds", "Fair Play", "Update"]] # Attached tags + platforms:set[Literal["pc", "ps4", "ps5"]] # Affected platforms project:str # Game (100% of the time War Thunder with different version numbers) - type:Literal["news", "changelog"] # Article Type + type:Literal["news", "changelog", "forum"] # Article Type created:datetime # Article Creation Time importance:ImportanceLevel = ImportanceLevel.REGULAR @dataclass(slots=True) @@ -57,21 +54,76 @@ def to_json(self): return asdict(self) @classmethod def from_json(cls, data:dict[str, Any]): + tags = set(data.get('tags', [])) + title:str = data["title"] + while title.strip()[0] == "[": + tag = re.search(r"\[([A-z]+)\]", title, re.IGNORECASE) + if tag is not None: + title = re.sub(r"\[([A-z]+)\]", "", title, 1, re.IGNORECASE) + tags.add(tag.group(1)) + else: + raise RuntimeError(f"Somehow the first character is still '[' in \"{title}\", with no tags left") + self = cls( id = int(data['id']), anons = data['anons'], - title = data['title'], + title = title.strip(), link = data['link'], pinned = data.get('pinned', False), images = [cls.Image.from_json(i) for i in data['images']], - tags = data.get('tags', []), - platforms = data.get('platforms', []), + tags = tags, + platforms = set(data.get('platforms', [])), project = data.get('project', "warthunder_en"), type = data['type'], created = datetime.strptime(data['created'], "%Y-%m-%dT%H:%M:%S%z") ) self.importance = self._getImportance() return self + @classmethod + async def from_forum(cls, id: int): + """### Technical limitation: Only works on "Planned Battle Rating Changes" posts""" + async with Network.get(f"https://forum.warthunder.com/t/{id}") as resp: + document = BeautifulSoup(await resp.text(), "lxml") + + post = document.select_one("div>div.topic-body") + # select first div, which is main post + + title = document.select_one("div#topic-title>h1>a") + + meta = post.select_one("div.crawler-post-meta>span.crawler-post-infos") + created = datetime.fromisoformat(meta.select_one("time.post-time").get("datetime")) + + desc = post.select_one("div.post") + + # first paragraph is image + # last 2 paragraphs are junk + # 3rd from last paragraph's wording only works with the site's implementation + desc_text = "\n\n".join([i.text for i in desc.select("p")[1:-3]]) + + img = post.select("img") + images = [] + for image in img: + images.append(cls.Image( + src=image.get("src"), + width=int(image.get("width", -1)), + height=int(image.get("height", -1)) + )) + + return cls( + id=id, + anons=desc_text, + title=title.get_text(), + link=f"https://forum.warthunder.com/t/{id}", + pinned=False, + images=images, + tags=set(["Development",]), + platforms=set(), + project="warthunder", + type="forum", + created=created, + importance=cls.ImportanceLevel.REGULAR + ) + def to_json(self): obj = asdict(self) obj["created"] = dtToTimestamp(self.created) @@ -101,7 +153,7 @@ def _getImportance(self) -> ImportanceLevel: "black friday" in title ) ) or ( - re_search("Meet the “[A-z0-9 ]+” Major Update!", title, IGNORECASE) is not None and self.pinned + re.search("Meet the “[A-z0-9 ]+” Major Update!", title, re.IGNORECASE) is not None and self.pinned ) ): return self.ImportanceLevel.MAJOR @@ -113,102 +165,154 @@ def _getImportance(self) -> ImportanceLevel: _changelog_maintenance: bool = False _news_endpoint_down: bool = False +_cache_lifetime: timedelta = timedelta(minutes=15) class NewsManager: + @dataclass(slots=True) + class LastSentIDs: + NEWS: int = 0 + CHANGELOG: int = 0 + MAJOR_CHANGELOG: int = 0 + PLANNED_BR_CHANGES: int = 0 + _API_URL = "http://newslist.gaijin.net:8080/news/warthunder/en/js" _CHANGELOG_URL = "https://warthunder.com/en/game/changelog/" - class _IDTYPE(Enum): - NEWS = 0, "lastNews" - CHANGELOG = 1, "lastChangelog" - MAJOR_CHLOG = 2, "lastMajorChLog" - lastNews:int - lastChangelog:int __logger: Logger - task:Task - _lock: Lock + _sentIDs: LastSentIDs + task:asyncio.Task websocket_mgr: WebsocketManager + __CACHED_RETURN: tuple[NewsEntry] | None = None + __CACHE_EXPIRE: datetime | None = None + __CACHE_LOCK: asyncio.Lock + def __init__(self): self.__logger = getLogger(__name__) - self._lock = Lock() self.websocket_mgr = WebsocketManager() - - if (not NEWS_JSON.exists()): - NEWS_JSON.write_text(dumps({ - self._IDTYPE.NEWS.value[1]: 0, - self._IDTYPE.CHANGELOG.value[1]: 0, - self._IDTYPE.MAJOR_CHLOG.value[1]: 0 - })) - content = loads(NEWS_JSON.read_text()) - self.lastNews = int(content.get(self._IDTYPE.NEWS.value[1], 0)) - self.lastChangelog = int(content.get(self._IDTYPE.CHANGELOG.value[1], 0)) - self.lastMajorChLog = int(content.get(self._IDTYPE.MAJOR_CHLOG.value[1], 0)) + self._sentIDs = self.LastSentIDs() + self.__CACHE_LOCK = asyncio.Lock() self.__logger.debug("NewsAPI initialized") async def mainloop(self): while True: + latest_news: list[NewsEntry] = [] + latest_changelogs: list[NewsEntry] = [] + latest_major_chlog: NewsEntry | None = None + latest_forum: list[NewsEntry] = [] try: - if (latest := await self._get_new_news()): + changelogs = await self.fetchChangelogs() + latest_news, latest_changelogs, latest_major_chlog, latest_forum = await asyncio.gather( + self._get_new_news(), + self._get_new_changelogs(changelogs), + self._get_major_changelog(changelogs), + self._get_new_forum(), + return_exceptions=True + ) + except asyncio.CancelledError: + raise + except Exception: + self.__logger.exception("An exception occurred during data fetching") + + for _name, _result in ( + ("news", latest_news), + ("changelogs", latest_changelogs), + ("major changelog", latest_major_chlog), + ("forum", latest_forum) + ): + if isinstance(_result, BaseException): + self.__logger.exception(f"An exception occurred during {_name} fetching", exc_info=_result) + + latest_news = [] if isinstance(latest_news, BaseException) else latest_news + latest_changelogs = [] if isinstance(latest_changelogs, BaseException) else latest_changelogs + latest_major_chlog = None if isinstance(latest_major_chlog, BaseException) else latest_major_chlog + latest_forum = [] if isinstance(latest_forum, BaseException) else latest_forum + + if latest_news or latest_changelogs or latest_major_chlog or latest_forum: + await self.clear_cache() + + try: + if latest_news: self.__logger.debug("News have been posted since last check") - for news in latest: + for news in latest_news: await self.websocket_mgr.broadcast(news.to_json()) - except CancelledError: + except asyncio.CancelledError: raise except Exception: - self.__logger.exception("An exception occurred during news fetching") + self.__logger.exception("An exception occurred during news processing") try: - changelogs = await self.fetchChangelogs() + if latest_changelogs: + self.__logger.debug("Changelogs have been posted since last check") + for news in latest_changelogs: + await self.websocket_mgr.broadcast(news.to_json()) + except asyncio.CancelledError: + raise + except Exception: + self.__logger.exception("An exception occurred during changelogs processing") + + try: + if latest_major_chlog: + self.__logger.debug("New major update changelog posted") + await self.websocket_mgr.broadcast(latest_major_chlog.to_json()) + except asyncio.CancelledError: + raise + except Exception: + self.__logger.exception("An exception occurred during changelogs processing") - try: - if (latest := await self._get_new_changelogs(changelogs)): - self.__logger.debug("Changelogs have been posted since last check") - for news in latest: - await self.websocket_mgr.broadcast(news.to_json()) - except CancelledError: - raise - except Exception: - self.__logger.exception("An exception occurred during changelog processing") - - try: - if (latest := await self._get_major_changelog(changelogs)): - self.__logger.debug("New major update changelog posted") - await self.websocket_mgr.broadcast(latest.to_json()) - except CancelledError: - raise - except Exception: - self.__logger.exception("An exception occurred during major changelog processing") - - except CancelledError: + try: + if latest_forum: + self.__logger.debug("New planned battle rating changes posted") + for post in latest_forum: + await self.websocket_mgr.broadcast(post.to_json()) + except asyncio.CancelledError: raise except Exception: - self.__logger.exception("An exception occurred during changelog fetching") + self.__logger.exception("An exception occurred during forum processing") await sleep(self.__calcDelay()) async def fetch(self) -> list[NewsEntry]: """Merges news and changelogs into one list""" - all_news = await self.fetchNews() - all_changelogs = await self.fetchChangelogs() - - pinned: list[NewsEntry] = [] - unpinned: list[NewsEntry] = [] - for news in all_news: - if news.pinned: - pinned.append(news) - else: - unpinned.append(news) - for changelog in all_changelogs: - if changelog.pinned: - pinned.append(changelog) - else: - unpinned.append(changelog) + cache = await self.check_cache() + if cache is not None: + return list(cache) + + async with self.__CACHE_LOCK: + # Re-check: another task may have filled the cache while we waited + if self.__CACHE_EXPIRE is not None and self.__CACHE_EXPIRE >= datetime.now(UTC): + return list(self.__CACHED_RETURN) + + all_news, all_changelogs, planned_changes = await asyncio.gather( + self.fetchNews(), + self.fetchChangelogs(), + self.fetchForum(), + ) + + pinned: list[NewsEntry] = [] + unpinned: list[NewsEntry] = [] + for news in all_news: + if news.pinned: + pinned.append(news) + else: + unpinned.append(news) + for changelog in all_changelogs: + if changelog.pinned: + pinned.append(changelog) + else: + unpinned.append(changelog) + if planned_changes is not None: + unpinned.append(planned_changes) + + pinned.sort(key=lambda x: x.created, reverse=True) + unpinned.sort(key=lambda x: x.created, reverse=True) + combined = pinned + unpinned + + self.__CACHED_RETURN = tuple(combined) + self.__CACHE_EXPIRE = datetime.now(UTC) + _cache_lifetime - pinned.sort(key=lambda x: x.created, reverse=True) - unpinned.sort(key=lambda x: x.created, reverse=True) - combined = pinned + unpinned return combined + #region News async def fetchNews(self) -> list[NewsEntry]: """Gets all the latest news""" global _news_endpoint_down @@ -226,6 +330,26 @@ async def fetchNews(self) -> list[NewsEntry]: self.__logger.error("Gaijin's news endpoint is currently down. Returning emptry until it is back") _news_endpoint_down = True return news + async def _get_new_news(self): + news = await self.fetchNews() + + if len(news) == 0: + return [] + + if self._sentIDs.NEWS == 0: + self._sentIDs.NEWS = news[0].id + return [] + + for i, item in enumerate(news): + if item.id == self._sentIDs.NEWS: + self._sentIDs.NEWS = news[0].id + return news[:i] + + # None of the news have been posted yet + self._sentIDs.NEWS = news[0].id + return [] + #endregion + #region Changelogs async def fetchChangelogs(self) -> list[NewsEntry]: """Gets the latest changelog""" global _changelog_maintenance @@ -236,7 +360,7 @@ async def fetchChangelogs(self) -> list[NewsEntry]: self.__logger.info("Changelog page is no longer under maintenance") _changelog_maintenance = False - parsed = BeautifulSoup(await resp.text(), 'html.parser') + parsed = BeautifulSoup(await resp.text(), 'lxml') changelogs = parsed.select("div.showcase__content-wrapper>div.showcase__item.widget") if len(changelogs) < 2: raise RuntimeError("Less, than 2 changelogs found (somehow)") @@ -277,56 +401,118 @@ async def processChangelog(chlog:Tag) -> NewsEntry: if not _changelog_maintenance: self.__logger.exception("An error occurred while parsing changelogs") return [] - async def _get_major_changelog(self, changelogs:list[NewsEntry]) -> None|NewsEntry: + async def _get_major_changelog(self, changelogs:list[NewsEntry]) -> NewsEntry | None: """Returns `None` if no new major update changelog has been posted""" # i[0] is the pinned major update changelog if not changelogs: return None majorChLog = changelogs[0] - if majorChLog.id != self.lastMajorChLog: - await self._writeID(majorChLog.id, self._IDTYPE.MAJOR_CHLOG) + + if self._sentIDs.MAJOR_CHANGELOG == 0: + self._sentIDs.MAJOR_CHANGELOG = majorChLog.id + return None + + if majorChLog.id != self._sentIDs.MAJOR_CHANGELOG: + self._sentIDs.MAJOR_CHANGELOG = majorChLog.id return majorChLog - return None - async def _get_new_changelogs(self, changelogs:list[NewsEntry]): + return None + async def _get_new_changelogs(self, changelogs:list[NewsEntry]) -> list[NewsEntry]: # i[1:] is the latest actual changelogs if not changelogs or len(changelogs) <= 1: return [] changelogs = changelogs[1:] + if self._sentIDs.CHANGELOG == 0: + self._sentIDs.CHANGELOG = changelogs[0].id + return [] + for i, item in enumerate(changelogs): - if item.id == self.lastChangelog: - await self._writeID(changelogs[0], self._IDTYPE.CHANGELOG) + if item.id == self._sentIDs.CHANGELOG: + self._sentIDs.CHANGELOG = changelogs[0].id return changelogs[:i] # None of the changelogs have been posted yet - await self._writeID(changelogs[0], self._IDTYPE.CHANGELOG) + self._sentIDs.CHANGELOG = changelogs[0].id return [] - async def _get_new_news(self): - news = await self.fetchNews() + #endregion + #region Forum + async def fetchForumIDs(self) -> tuple[int, ...]: + """Gets the latest "planned battle rating changes" post's ID""" + async with Network.get("https://forum.warthunder.com/tag/br-changes") as resp: + document = BeautifulSoup(await resp.text(), "lxml") + rows = document.select("tr.topic-list-item") + # Ordered by date by default - if len(news) == 0: - return [] + ids = [] + for row in rows: - for i, item in enumerate(news): - if item.id == self.lastNews: - await self._writeID(news[0], self._IDTYPE.NEWS) - return news[:i] + tags = row.select("div.discourse-tags>a") + # Includes update posts, that are handled by other code, so they get filtered out + # Update posts always have other tags with them (e.g. 'server-update', 'client-update') + if len(tags) > 1: + continue - # None of the news have been posted yet - await self._writeID(news[0], self._IDTYPE.NEWS) - return [] + title = row.select_one("a.title.raw-link") + if title is None: + continue + href = title.get("href") + if href is None: + continue + try: + # URL is formatted as "https://forum.warthunder.com/t/planned-battle-rating-changes-october-2026-aircraft-and-ground-vehicle-decompression/360129" + ids.append(int(href.split("/")[-1])) + except ValueError: + continue + + return tuple(ids) + async def fetchForum(self) -> NewsEntry | None: # HTTP: just the latest + """Gets the latest planned battle rating changes""" + try: + ids = await self.fetchForumIDs() + return await NewsEntry.from_forum(ids[0]) if ids else None + except Exception: + self.__logger.exception("An exception occurred during forum fetching") + return None + async def _get_new_forum(self) -> list[NewsEntry]: # WS: only the new ones + ids = await self.fetchForumIDs() + if not ids: + return [] + if self._sentIDs.PLANNED_BR_CHANGES == 0: + self._sentIDs.PLANNED_BR_CHANGES = ids[0] + return [] + new = [] + for i in ids: + if i == self._sentIDs.PLANNED_BR_CHANGES: + break + new.append(i) + else: + # Sentinel fell off the listing — advance without re-broadcasting everything + self._sentIDs.PLANNED_BR_CHANGES = ids[0] + return [] + entries = await asyncio.gather(*(NewsEntry.from_forum(i) for i in new)) + self._sentIDs.PLANNED_BR_CHANGES = ids[0] + return entries + #endregion - async def _writeID(self, ID:int|NewsEntry, _type:_IDTYPE): - ID = ID if isinstance(ID, int) else ID.id - self.__logger.debug(f"Writing value {ID} for {_type.name}") + #region Cache + async def clear_cache(self): + async with self.__CACHE_LOCK: + self.__CACHE_EXPIRE = None + self.__CACHED_RETURN = None + async def check_cache(self) -> tuple[NewsEntry] | None: + async with self.__CACHE_LOCK: + now = datetime.now(UTC) + if self.__CACHE_EXPIRE is None: + return None - async with self._lock: - content = loads(NEWS_JSON.read_text()) - content[_type.value[1]] = ID - NEWS_JSON.write_text(dumps(content, indent=4)) + if self.__CACHE_EXPIRE < now: + self.__CACHE_EXPIRE = None + self.__CACHED_RETURN = None + return None + return self.__CACHED_RETURN + #endregion - self.__setattr__(_type.value[1], ID) def __calcDelay(self) -> int: rn = datetime.now(UTC) From 689c5db92d401a306583b4abb0bcf52a1522e7fc Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:44:55 +0100 Subject: [PATCH 09/91] A lot of fixes + cache module Got tired of writing caches manually --- src/api/v1/backends/clans.py | 29 ++++--- src/api/v1/backends/users.py | 2 +- src/api/v1/clans_router.py | 3 +- src/api/v1/models/replay.py | 123 ++++++++++++++--------------- src/api/v1/models/users.py | 2 +- src/api/v1/replays_router.py | 50 +++++++++++- src/main.py | 20 ++--- src/utils/cache.py | 77 ++++++++++++++++++ src/utils/helper.py | 7 +- src/utils/replayParser/__init__.py | 25 +++--- 10 files changed, 239 insertions(+), 99 deletions(-) create mode 100644 src/utils/cache.py diff --git a/src/api/v1/backends/clans.py b/src/api/v1/backends/clans.py index 8a14e5a5..5747bdaa 100644 --- a/src/api/v1/backends/clans.py +++ b/src/api/v1/backends/clans.py @@ -156,7 +156,7 @@ async def searchClan(user: LoginEntry, clanName: str | None = None, clanTag: str "id": int(clan["_id"]), "name": clan["name"], "tag": clan["tag"], - "members": sanitizeMembers(clan["members"]), + "members": await sanitizeMembers(clan["members"]), "desc": clan["desc"], "slogan": clan["slogan"], "region": clan["region"] @@ -172,8 +172,8 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: ) SANITIZE = ( - dictUtil.KeyMod("candidates", new_name="applicants", convert=lambda x: (await sanitizeApplicants(x) for _ in '_').__anext__()), - dictUtil.KeyMod("members", convert=lambda x: (await sanitizeMembers(x) for _ in '_').__anext__()), + dictUtil.KeyMod("candidates", new_name="applicants", convert=lambda x: sanitizeApplicants(x)), + dictUtil.KeyMod("members", convert=lambda x: sanitizeMembers(x)), dictUtil.KeyRem( "transactions", "namel", @@ -204,14 +204,25 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: async def get_sqb_brackets() -> tuple[dict[str, datetime|float]]: async def get_brackets(): async with Network.get("https://forum.warthunder.com/t/season-schedule-for-squadron-battles/4446", headers={ - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 OPR/117.0.0.0" + "User-Agent": "Thunderapi/1.0" }) as resp: resp.raise_for_status() response = await resp.text() - bs = BeautifulSoup(response, 'html.parser') - title = bs.find("div", class_="title-wrapper").find("h1").find("a", class_="fancy-title") - year = re_search(r"\([0-9\. ]+ - ([0-9]+\.[0-9]+\.[0-9]+)\)", title.text, IGNORECASE) + document = BeautifulSoup(response, 'lxml') + + post = document.select_one("div.topic-body.crawler-post") + meta = post.select_one("span.crawler-post-infos>meta[itemprop='dateModified']") + if not meta: + raise RuntimeError() + + body = post.select("div.post>p") + if len(body) < 2: + raise RuntimeError() + + + title = document.find("meta", itemprop="headline").get("content") + year = re_search(r"\([0-9\. ]+ - ([0-9]+\.[0-9]+\.[0-9]+)\)", title, IGNORECASE) if not year: raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not fetch forum post title") end_date = datetime.strptime(year.group(1), "%d.%m.%Y").date() @@ -219,8 +230,8 @@ async def get_brackets(): if end_date < datetime.now(UTC).date(): raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Forum post data is outdated. Please try again later.") - post = str(bs.find("div", class_="post").find_all("p")[1]).removeprefix("

").removesuffix("

").replace("
","").split("\n") - del bs + post = str(document.find("div", class_="post").find_all("p")[1]).removeprefix("

").removesuffix("

").replace("
","").split("\n") + del document weeks = [] for week in post: diff --git a/src/api/v1/backends/users.py b/src/api/v1/backends/users.py index 4dcc8c8a..010dbcf8 100644 --- a/src/api/v1/backends/users.py +++ b/src/api/v1/backends/users.py @@ -93,7 +93,7 @@ async def get_user(user:LoginEntry, userid: int): } level = PlayerRank.get_level(data["exp"]) - data["level"] = { + data["rank"] = { "title": PlayerRank.from_level(level).name, "level": level } diff --git a/src/api/v1/clans_router.py b/src/api/v1/clans_router.py index 100a09ee..773b1e79 100644 --- a/src/api/v1/clans_router.py +++ b/src/api/v1/clans_router.py @@ -94,7 +94,6 @@ async def get_applicants( applicants = clanData.get("applicants") if applicants is None: return [] - return applicants @router.post( "/accept/{userId}", @@ -266,7 +265,7 @@ async def get_clan_leaderboard_position( async def get_brackets( request: faRequest, user: ServerBearer -) -> tuple[SQBTimeBracket]: +) -> tuple[SQBTimeBracket, ...]: return await get_sqb_brackets() @router.get( diff --git a/src/api/v1/models/replay.py b/src/api/v1/models/replay.py index c10ed674..e9ad83f1 100644 --- a/src/api/v1/models/replay.py +++ b/src/api/v1/models/replay.py @@ -44,75 +44,74 @@ class PaginationModel(BaseModel): partsCount: int visible: int id: str -class DataModel(BaseModel): - status: Literal["OK"] = "OK" - class MatchModel(BaseModel): + +class ResultsModel(BaseModel): + class UserModel(BaseModel): + class StatsModel(BaseModel): + kills: int + groundKills: int + humanKills: int + navalKills: int + teamKills: int + aiKills: int + aiGroundKills: int + aiNavalKills: int + assists: int + deaths: int + captureZone: int + damageZone: int + score: int + awardDamage: int + missileEvades: int + ammoInterceptions: int + class LineupModel(BaseModel): + class VehicleModel(BaseModel): + rank: int + battlerating: float + vehicles: dict[str, VehicleModel] = Field( + description="Vehicles in the lineup of the player. Key is the internal name of the vehicle, such as `germ_leopard_2pl`", + examples=[ + { + "ef_2000_block_10": { + "rank": 9, + "battlerating": 13.3 + }, + }, { + "germ_leopard_2pl": { + "rank": 8, + "battlerating": 11.3 + }, + }, { + "tiger_had_spain": { + "rank": 7, + "battlerating": 9.7 + } + }] + ) + maxBr: float = Field(description="Maximum battle rating of the user's lineup", examples=[6.7, 8.0, 9.7]) + clanTag: str | None = Field(default=None, description="Clan tag of the user, if applicable. Includes border", examples=["┾PECK┿", ""]) + userId: int + autosquad: bool = Field(description="Whether the user was assigned into a squad automatically") + squadId: int = Field(description="Squad ID of the user. Number is still generated if not in a squad. Looks like 4000+ are players playing alone", examples=[1001, 1002, 1000, 4096, 4097, 4098]) + stats: StatsModel + lineup: LineupModel + + team1: dict[str, UserModel] + team2: dict[str, UserModel] +class MatchModel(BaseModel): version: int = Field(description="Game version of the match, represented as an integer.", examples=[101374]) map: str = Field(description="Map of the match. Uses internal name", examples=["levels/avg_abandoned_factory.bin", "levels/avg_tunisia_desert.bin"]) mapSettings: str = Field(description="Map settings of the match.", examples=["gamedata/missions/cta/tanks/abandoned_factory/abandoned_factory_dom.blk", "gamedata/missions/cta/tanks/tunisia/tunisia_02_bttl.blk"]) - type: str = Field(description="Gamemode of the match, seems to be derived from `mapSettings`", examples=["tunisia_02_Bttl", "abandoned_factory_dom"]) + mapType: str = Field(description="Gamemode of the match, seems to be derived from `mapSettings`", examples=["tunisia_02_Bttl", "abandoned_factory_dom"]) difficulty: str = Field(description="Gamemode of the match, such as `Arcade`, `Realistic`, `Simulator`", examples=["Arcade", "Realistic", "Simulator"]) - sessionType: int = Field(description="Unknown integer", examples=[0]) - timeLimit: int = Field(description="Time limit in seconds", examples=[1500]) - scoreLimit: int - battleClass: str - class ResultsModel(BaseModel): - class UserModel(BaseModel): - class StatsModel(BaseModel): - kills: int - groundKills: int - humanKills: int - navalKills: int - teamKills: int - aiKills: int - aiGroundKills: int - aiNavalKills: int - assists: int - deaths: int - captureZone: int - damageZone: int - score: int - awardDamage: int - missileEvades: int - ammoInterceptions: int - class LineupModel(BaseModel): - class VehicleModel(BaseModel): - rank: int - battlerating: float - vehicles: dict[str, VehicleModel] = Field( - description="Vehicles in the lineup of the player. Key is the internal name of the vehicle, such as `germ_leopard_2pl`", - examples=[ - { - "ef_2000_block_10": { - "rank": 9, - "battlerating": 13.3 - }, - }, { - "germ_leopard_2pl": { - "rank": 8, - "battlerating": 11.3 - }, - }, { - "tiger_had_spain": { - "rank": 7, - "battlerating": 9.7 - } - }] - ) - maxBr: float = Field(description="Maximum battle rating of the user's lineup", examples=[6.7, 8.0, 9.7]) - clanTag: str | None = Field(default=None, description="Clan tag of the user, if applicable. Includes border", examples=["┾PECK┿", ""]) - userId: int - autosquad: bool = Field(description="Whether the user was assigned into a squad automatically") - squadId: int = Field(description="Squad ID of the user. Number is still generated if not in a squad. Looks like 4000+ are players playing alone", examples=[1001, 1002, 1000, 4096, 4097, 4098]) - stats: StatsModel - lineup: LineupModel + battleType: str +class DataModel(BaseModel): + status: Literal["OK"] = "OK" - team1: dict[str, UserModel] - team2: dict[str, UserModel] matchId: int - match: MatchModel - results: ResultsModel + match: MatchModel = Field(exclude_if=lambda x: x is None) + results: ResultsModel = Field(exclude_if=lambda x: x is None) class ReplayNotFoundModel(BaseModel): detail: str = "Replay could not be found" status: Literal["NOT_FOUND"] = "NOT_FOUND" diff --git a/src/api/v1/models/users.py b/src/api/v1/models/users.py index 6782cd28..0c86bce0 100644 --- a/src/api/v1/models/users.py +++ b/src/api/v1/models/users.py @@ -149,7 +149,7 @@ class _playerLevelModel(BaseModel): last_login: date registered_at: datetime id: int - level: _playerLevelModel + rank: _playerLevelModel clan: _clanDataModel | None = Field(default=None, exclude_if=lambda x: x is None) numEliteUnits: int penaltyStatus: str diff --git a/src/api/v1/replays_router.py b/src/api/v1/replays_router.py index c124d8b3..517f12a3 100644 --- a/src/api/v1/replays_router.py +++ b/src/api/v1/replays_router.py @@ -3,11 +3,11 @@ from fastapi import APIRouter, Path, Request as faRequest, Query, status from utils.replayParser import Replay +from utils.helper import dictUtil from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer from api.v1.backends.replay import search_replay, ReplayType, ReplayMode, ReplayTechType -from api.v1.models.replay import SearchModel, DataModel, ReplayNotFoundModel - +from api.v1.models.replay import SearchModel, DataModel, ReplayNotFoundModel, ResultsModel, MatchModel router = APIRouter( prefix="/replay", @@ -102,3 +102,49 @@ async def get_replay( ], ): return await Replay.get(replayId) + +@router.get( + "/{replayId}/teams", + summary="Gets results from a specified replay", + responses={ + status.HTTP_200_OK: {"model": ResultsModel}, + status.HTTP_404_NOT_FOUND: {"model": ReplayNotFoundModel, "description": "Replay not found"}, + status.HTTP_425_TOO_EARLY: {"description": "Replay probably hasn't ended yet, since it isn't properly parseable yet"} + }) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") +async def get_replay( + request: faRequest, + user: ServerBearer, + replayId: Annotated[ + str, + Path( + title="The replay's ID to get", + pattern=r"^[0-9a-fA-F]{1,16}$", + description="Must be given in HEX format" + ), + ] +): + return await Replay.get(replayId)["results"] + +@router.get( + "/{replayId}/match", + summary="Gets match data from a specified replay", + responses={ + status.HTTP_200_OK: {"model": ResultsModel}, + status.HTTP_404_NOT_FOUND: {"model": ReplayNotFoundModel, "description": "Replay not found"}, + status.HTTP_425_TOO_EARLY: {"description": "Replay probably hasn't ended yet, since it isn't properly parseable yet"} + }) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") +async def get_replay( + request: faRequest, + user: ServerBearer, + replayId: Annotated[ + str, + Path( + title="The replay's ID to get", + pattern=r"^[0-9a-fA-F]{1,16}$", + description="Must be given in HEX format" + ), + ] +): + return await Replay.get(replayId)["match"] diff --git a/src/main.py b/src/main.py index 063fedbb..48bb6b5e 100644 --- a/src/main.py +++ b/src/main.py @@ -20,6 +20,7 @@ from utils.auth import scheduler, ServerAuth import utils.connection.network as Network import utils +import utils.cache as Cache from utils.geo import update_db from utils.connection import _populate_serverlist from utils.connection.blk_utils import Decompress @@ -91,22 +92,17 @@ async def lifespan(app: FastAPI): del content #endregion - newsManager.task = asyncio.create_task(newsManager.mainloop()) - geolocation_task = asyncio.create_task(update_db()) + Cache.LONG_RUNNING = ( + asyncio.create_task(newsManager.mainloop()), + asyncio.create_task(update_db()) + ) + + await Cache.start() try: yield finally: - newsManager.task.cancel() - geolocation_task.cancel() - try: - await newsManager.task - except asyncio.CancelledError: - pass - try: - await geolocation_task - except (asyncio.CancelledError, RuntimeError): - pass + await Cache.stop() scheduler.shutdown() await users_auth.close() diff --git a/src/utils/cache.py b/src/utils/cache.py new file mode 100644 index 00000000..31eca258 --- /dev/null +++ b/src/utils/cache.py @@ -0,0 +1,77 @@ +import asyncio +from typing import Callable, Any, Coroutine +from collections import deque +from dataclasses import dataclass, field +from datetime import datetime, UTC, timedelta +from logging import getLogger + +_logger = getLogger(__name__) + +@dataclass(slots=True) +class Cache[T]: + + @dataclass(slots=True) + class Entry[T]: + key: str + obj: T + created: datetime = field(default_factory=lambda: datetime.now(UTC)) + + ON_EMPTY: Callable[[], Any] = lambda: ... + queue: deque[Entry] = field(default_factory=lambda: deque()) + CLEANUP_AFTER: timedelta = field(default_factory=lambda: timedelta(minutes=15)) + LOCK: asyncio.Lock = field(default_factory=lambda: asyncio.Lock()) + async def cleanup(self): + now = datetime.now(UTC) + before_len = len(self.queue) + async with self.LOCK: + while len(self.queue) > 0 and (now - self.queue[0].created) > self.CLEANUP_AFTER: + self.queue.popleft() + if len(self.queue) == 0 and before_len != 0: + self.ON_EMPTY() + + async def add(self, key: str, obj: T) -> None: + async with self.LOCK: + self.queue.append( + self.Entry(key, obj) + ) + async def clear(self) -> None: + async with self.LOCK: + self.queue.clear() + + async def get(self, key: str) -> Entry | None: + await self.cleanup() + async with self.LOCK: + for entry in self.queue: + if entry.key == key: + return entry + return None + + +LONG_RUNNING: tuple[asyncio.Task] = () # Set in main.py +CACHES: dict[str, Cache] = { + "replay": Cache() +} + +runtime_task: asyncio.Task = None +async def start(): + global runtime_task + async def inner_loop(): + while True: + try: + tasks: list[Coroutine[Any, Any, None]] = [] + for cache in CACHES.values(): + tasks.append(cache.cleanup()) + await asyncio.gather(*tasks) + except asyncio.CancelledError: + return + except Exception: + _logger.exception("An exception occurred during cache cleanup") + + await asyncio.sleep(15*60) + runtime_task = asyncio.create_task(inner_loop()) +async def stop(): + global runtime_task, LONG_RUNNING + for task in LONG_RUNNING: + task.cancel() + runtime_task.cancel() + await asyncio.gather(runtime_task, *LONG_RUNNING, return_exceptions=True) diff --git a/src/utils/helper.py b/src/utils/helper.py index 5e3975d6..d33f82fd 100644 --- a/src/utils/helper.py +++ b/src/utils/helper.py @@ -64,10 +64,15 @@ def __init__(self, key: str, /, *, new_name: str = None, convert: Callable[[Any] async def run(self, obj: dict[str, Any]): if self.key not in obj: if self.default is not ...: - obj[self.new_name] = self.convert(self.default) + val = self.convert(self.default) + if isawaitable(val): + val = await val + obj[self.new_name] = val return obj new_val = self.convert(obj.pop(self.key)) + if isawaitable(new_val): + new_val = await new_val obj[self.new_name] = new_val return obj diff --git a/src/utils/replayParser/__init__.py b/src/utils/replayParser/__init__.py index 2461e138..45860ccf 100644 --- a/src/utils/replayParser/__init__.py +++ b/src/utils/replayParser/__init__.py @@ -1,8 +1,9 @@ +from asyncio import sleep from logging import getLogger from utils.replayParser.parser import ReplayParser import utils.connection.network as Network from fastapi import HTTPException, status -from asyncio import sleep +import utils.cache as Cache _logger = getLogger(__name__) @@ -11,9 +12,6 @@ 5: "Realistic", 10: "Simulator" } -sessionTypeDict = { - 0: "SQB" -} class Replay(dict): def __init__(self): @@ -24,6 +22,10 @@ async def get(cls, replay_id:int|str): if isinstance(replay_id, str): replay_id = int(replay_id, 16) # Forces lowercase hex replay_id = f"{replay_id:016x}" + cache = await self.get_cached(replay_id) + if cache is not None: + return cache + #region wrpl download async def get_data(): async with Network.operation() as session: @@ -76,12 +78,9 @@ async def get_data(): "version": resultsData.header.version, "map": resultsData.header.level, "mapSettings": resultsData.header.levelSettings, - "type": resultsData.header.battleType, + "mapType": resultsData.header.battleType, "difficulty": difficultyDict.get(resultsData.header.diff.difficulty, "Unknown"), - "sessionType": resultsData.header.sessionType, - "timeLimit": resultsData.header.timeLimit * 60, - "scoreLimit": resultsData.header.scoreLimit, - "battleClass": resultsData.header.battleClass + "battleType": resultsData.header.battleClass }, "results": { "team1": {}, @@ -137,4 +136,12 @@ async def get_data(): add_obj["lineup"]["maxBr"] = max(i["battlerating"] for i in add_obj["lineup"]["vehicles"].values()) self["results"][f"team{user["team"]}"][user["name"]] = add_obj # endregion + await Cache.CACHES["replay"].add(replay_id, self) return self + + @staticmethod + async def get_cached(replay_id: int|str) -> Replay | None: + if isinstance(replay_id, str): replay_id = int(replay_id, 16) # Forces lowercase hex + replay_id = f"{replay_id:016x}" + entry = await Cache.CACHES["replay"].get(replay_id) + return entry.obj if entry is not None else None From bf1558538b04f2cfc0701ac4c4dc9ca58ec49cf4 Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:46:29 +0100 Subject: [PATCH 10/91] Fix error between brackets on `/v1/clans/sqb/current` --- src/api/v1/backends/clans.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/v1/backends/clans.py b/src/api/v1/backends/clans.py index 5747bdaa..c0a1fe08 100644 --- a/src/api/v1/backends/clans.py +++ b/src/api/v1/backends/clans.py @@ -264,7 +264,10 @@ async def current_sqb_br() -> dict[str, datetime|float]: weeks = await get_sqb_brackets() rn = datetime.now(UTC) for week in weeks: - if week["start"] < rn < week["end"]: + if week["start"] <= rn <= week["end"]: + return week + for week in weeks: + if week["start"] > rn: return week raise HTTPException(status.HTTP_404_NOT_FOUND, "Could not find current bracket data") From 16c0800df8ce7b3c8f59ec5a3d1acc650296d6e3 Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:12:54 +0100 Subject: [PATCH 11/91] implement cache into news module --- src/utils/cache.py | 29 +++++++++++--- src/utils/news.py | 95 ++++++++++++++++------------------------------ 2 files changed, 55 insertions(+), 69 deletions(-) diff --git a/src/utils/cache.py b/src/utils/cache.py index 31eca258..928d26bd 100644 --- a/src/utils/cache.py +++ b/src/utils/cache.py @@ -1,5 +1,5 @@ import asyncio -from typing import Callable, Any, Coroutine +from typing import Callable, Any, Coroutine, Awaitable from collections import deque from dataclasses import dataclass, field from datetime import datetime, UTC, timedelta @@ -38,18 +38,33 @@ async def clear(self) -> None: async with self.LOCK: self.queue.clear() + def _find(self, key: str) -> Entry | None: + for entry in self.queue: + if entry.key == key: + return entry + return None + async def get(self, key: str) -> Entry | None: await self.cleanup() async with self.LOCK: - for entry in self.queue: - if entry.key == key: - return entry - return None + return self._find(key) + async def get_or_compute(self, key: str, factory: Callable[[], Awaitable[T]]) -> T: + entry = await self.get(key) + if entry is not None: + return entry.obj + async with self.LOCK: + entry = self._find(key) + if entry is not None: + return entry.obj + value = await factory() + self.queue.append(self.Entry(key, value)) + return value LONG_RUNNING: tuple[asyncio.Task] = () # Set in main.py CACHES: dict[str, Cache] = { - "replay": Cache() + "replay": Cache(), + "news": Cache() } runtime_task: asyncio.Task = None @@ -69,6 +84,8 @@ async def inner_loop(): await asyncio.sleep(15*60) runtime_task = asyncio.create_task(inner_loop()) +def get(key: str): + return CACHES.get(key) async def stop(): global runtime_task, LONG_RUNNING for task in LONG_RUNNING: diff --git a/src/utils/news.py b/src/utils/news.py index 59dcd8d4..1f19d0e0 100644 --- a/src/utils/news.py +++ b/src/utils/news.py @@ -10,6 +10,7 @@ from utils.helper import dtToTimestamp from utils.connection.websocket import WebsocketManager import utils.connection.network as Network +import utils.cache as Cache fasterUpdate = ( time(hour=11, minute=0, tzinfo=UTC), # Start @@ -165,7 +166,6 @@ def _getImportance(self) -> ImportanceLevel: _changelog_maintenance: bool = False _news_endpoint_down: bool = False -_cache_lifetime: timedelta = timedelta(minutes=15) class NewsManager: @dataclass(slots=True) class LastSentIDs: @@ -181,15 +181,10 @@ class LastSentIDs: task:asyncio.Task websocket_mgr: WebsocketManager - __CACHED_RETURN: tuple[NewsEntry] | None = None - __CACHE_EXPIRE: datetime | None = None - __CACHE_LOCK: asyncio.Lock - def __init__(self): self.__logger = getLogger(__name__) self.websocket_mgr = WebsocketManager() self._sentIDs = self.LastSentIDs() - self.__CACHE_LOCK = asyncio.Lock() self.__logger.debug("NewsAPI initialized") @@ -228,7 +223,7 @@ async def mainloop(self): latest_forum = [] if isinstance(latest_forum, BaseException) else latest_forum if latest_news or latest_changelogs or latest_major_chlog or latest_forum: - await self.clear_cache() + await Cache.get("news").clear() try: if latest_news: @@ -273,44 +268,37 @@ async def mainloop(self): async def fetch(self) -> list[NewsEntry]: """Merges news and changelogs into one list""" - cache = await self.check_cache() - if cache is not None: - return list(cache) - - async with self.__CACHE_LOCK: - # Re-check: another task may have filled the cache while we waited - if self.__CACHE_EXPIRE is not None and self.__CACHE_EXPIRE >= datetime.now(UTC): - return list(self.__CACHED_RETURN) - - all_news, all_changelogs, planned_changes = await asyncio.gather( - self.fetchNews(), - self.fetchChangelogs(), - self.fetchForum(), - ) + cache = Cache.get("news") + if cache is None: + raise RuntimeError("Could not retrieve cache") + + return list(await cache.get_or_compute("news", self._compute_news)) - pinned: list[NewsEntry] = [] - unpinned: list[NewsEntry] = [] - for news in all_news: - if news.pinned: - pinned.append(news) - else: - unpinned.append(news) - for changelog in all_changelogs: - if changelog.pinned: - pinned.append(changelog) - else: - unpinned.append(changelog) - if planned_changes is not None: - unpinned.append(planned_changes) - - pinned.sort(key=lambda x: x.created, reverse=True) - unpinned.sort(key=lambda x: x.created, reverse=True) - combined = pinned + unpinned - - self.__CACHED_RETURN = tuple(combined) - self.__CACHE_EXPIRE = datetime.now(UTC) + _cache_lifetime - - return combined + async def _compute_news(self) -> list[NewsEntry]: + all_news, all_changelogs, planned_changes = await asyncio.gather( + self.fetchNews(), + self.fetchChangelogs(), + self.fetchForum(), + ) + + pinned: list[NewsEntry] = [] + unpinned: list[NewsEntry] = [] + for news in all_news: + if news.pinned: + pinned.append(news) + else: + unpinned.append(news) + for changelog in all_changelogs: + if changelog.pinned: + pinned.append(changelog) + else: + unpinned.append(changelog) + if planned_changes is not None: + unpinned.append(planned_changes) + + pinned.sort(key=lambda x: x.created, reverse=True) + unpinned.sort(key=lambda x: x.created, reverse=True) + return pinned + unpinned #region News async def fetchNews(self) -> list[NewsEntry]: @@ -495,25 +483,6 @@ async def _get_new_forum(self) -> list[NewsEntry]: # WS: only the new ones return entries #endregion - #region Cache - async def clear_cache(self): - async with self.__CACHE_LOCK: - self.__CACHE_EXPIRE = None - self.__CACHED_RETURN = None - async def check_cache(self) -> tuple[NewsEntry] | None: - async with self.__CACHE_LOCK: - now = datetime.now(UTC) - if self.__CACHE_EXPIRE is None: - return None - - if self.__CACHE_EXPIRE < now: - self.__CACHE_EXPIRE = None - self.__CACHED_RETURN = None - return None - return self.__CACHED_RETURN - #endregion - - def __calcDelay(self) -> int: rn = datetime.now(UTC) weekday = rn.weekday() From 1aa8a2ff90357d7a6b90ca0f8247d80567b91eed Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:33:16 +0100 Subject: [PATCH 12/91] Fixes --- src/api/v1/auth_router.py | 5 +++-- src/api/v1/backends/clans.py | 4 ++-- src/api/v1/clans_router.py | 5 +++-- src/api/v1/models/clans.py | 2 +- src/api/v1/replays_router.py | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/api/v1/auth_router.py b/src/api/v1/auth_router.py index 46da2afc..8143fe99 100644 --- a/src/api/v1/auth_router.py +++ b/src/api/v1/auth_router.py @@ -10,6 +10,7 @@ from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer from api.v1.models.auth import Login, LoginToken +from api.v1.models.base import GenericEmptyResponse router = APIRouter( tags=["authentication"], @@ -72,7 +73,7 @@ async def answer_2fa( email: Annotated[EmailStr, Form(title="The email address for the account")], password: Annotated[str, Form(title="The password of the account, used as a sort of protection")], code: Annotated[int, Form(title="The 2FA code")] -): +) -> None: if email not in _PENDING_2FA: raise HTTPException(status.HTTP_404_NOT_FOUND, "You are not pending 2FA verification. Please try to log in first.") if _PENDING_2FA[email].check_password(password): @@ -89,7 +90,7 @@ async def answer_2fa( async def remove_login( request: Request, user: TokenBearer -): +) -> GenericEmptyResponse: if (await users_auth.remove_entry(user)): return JSONResponse({"success": True}) raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An error occurred during login deletion") diff --git a/src/api/v1/backends/clans.py b/src/api/v1/backends/clans.py index c0a1fe08..d47a7b4b 100644 --- a/src/api/v1/backends/clans.py +++ b/src/api/v1/backends/clans.py @@ -97,12 +97,12 @@ async def getLogs(user: LoginEntry, clanId: int, limit: int = 10, fromEntry: str } if item.get("uId") is not None and not (action == Actions.rem and item.get("uid") is not None and item["uId"] == item["uid"]): logEntry["admin"] = { - "_id": item["uId"], + "id": item["uId"], "nickname": item["uN"] } if item.get("uid") is not None: logEntry["affected"] = { - "_id": item["uid"], + "id": item["uid"], "nickname": item["nick"], } match action: diff --git a/src/api/v1/clans_router.py b/src/api/v1/clans_router.py index 773b1e79..d5521fe2 100644 --- a/src/api/v1/clans_router.py +++ b/src/api/v1/clans_router.py @@ -189,13 +189,14 @@ async def kick_member( user: TokenBearer, userId: gaijinUserId, reason: Annotated[str, Form(title="The reason for kicking")] = "", -): - return await Request.send_template( +) -> SuccessEmptyDict: + data = await Request.send_template( user, "clan_dismiss_member", userid = userId, comments = reason ) + return data @router.get( "/logs/{clanId}", diff --git a/src/api/v1/models/clans.py b/src/api/v1/models/clans.py index 575b50a4..bdc681d3 100644 --- a/src/api/v1/models/clans.py +++ b/src/api/v1/models/clans.py @@ -62,7 +62,7 @@ class LogsModel(BaseModel): logs: list[ClanLogs] class ClanLogs(BaseModel): class _userEntry(BaseModel): - _id: int + id: int nickname: str class _action(BaseModel): value: int diff --git a/src/api/v1/replays_router.py b/src/api/v1/replays_router.py index 517f12a3..63de3b4f 100644 --- a/src/api/v1/replays_router.py +++ b/src/api/v1/replays_router.py @@ -105,7 +105,7 @@ async def get_replay( @router.get( "/{replayId}/teams", - summary="Gets results from a specified replay", + summary="Gets the results from a specified replay", responses={ status.HTTP_200_OK: {"model": ResultsModel}, status.HTTP_404_NOT_FOUND: {"model": ReplayNotFoundModel, "description": "Replay not found"}, From 59d9d09e5620ad539e4dd1f77f13ef96c485be77 Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:20:18 +0100 Subject: [PATCH 13/91] Marketplace endpoints improvements Also added new functionality while i was at it --- gaijin_api_endpoints.md | 49 ++- src/api/v1/backends/marketplace.py | 396 +++++++++++++++--- src/api/v1/marketplace_router.py | 276 +++++------- src/api/v1/models/base.py | 1 + src/api/v1/models/marketplace.py | 111 +++-- src/utils/connection/__init__.py | 13 +- .../connection/templates/cancel_order.json | 13 + .../templates/cln_get_user_open_orders.json | 9 + 8 files changed, 585 insertions(+), 283 deletions(-) create mode 100644 src/utils/connection/templates/cancel_order.json create mode 100644 src/utils/connection/templates/cln_get_user_open_orders.json diff --git a/gaijin_api_endpoints.md b/gaijin_api_endpoints.md index 3af11648..24d4c220 100644 --- a/gaijin_api_endpoints.md +++ b/gaijin_api_endpoints.md @@ -614,6 +614,23 @@ Not all endpoints shall be documented, as it would take forever to decode and do - `auction` - `seen` #### cln_get_user_open_orders +- `POST` request +- Form data + - `token` +- Response format + - `success` (bool, `true`) + - `response` + - `mid` + - `txId` (Transaction id) + - `currency` (`GJN`) + - `amount` + - `market` (Hash name of item) + - `id` (Used for cancelling) + - `type` (`BUY` or `SELL`) + - `appid` (`1067`) + - `pairId` (Used for cancelling) + - `localPrice` (The buy price *10000) + - `time` (timestamp) #### cln_market_sell - `POST` request - Form data @@ -831,23 +848,23 @@ Not all endpoints shall be documented, as it would take forever to decode and do - `meta` (only sends metadata, such as creation location, CC URL used, registration IP, etc.) - `v` (Unsure what this does) - `2step` (2FA verification code) -- 2FA Auth flow - - Response form schema, if the account is protected by 2FA, and isn't authenticated yet - ```json - { - "status": "2STEP", - "error": "2-step authentication code lost", - "hasGjPass": true, - "hasTwoStepEmail": false, - "hasWTR": false, - "requestId": "REQUEST_ID", - "userId": 00000000 - } - ``` - - Send the `requestId` and `userId` to the [2FA request endpoint](#httpsauthgaijinentcomapiauthrequesttwostep) to request the current 2FA code - - Resend this request, this time with the `code` value filled in, that is returned by the previous endpoint +- 2FA Auth flow + - Response form schema, if the account is protected by 2FA, and isn't authenticated yet + ```json + { + "status": "2STEP", + "error": "2-step authentication code lost", + "hasGjPass": true, + "hasTwoStepEmail": false, + "hasWTR": false, + "requestId": "REQUEST_ID", + "userId": 00000000 + } + ``` + - Send the `requestId` and `userId` to the [2FA request endpoint](#httpsauthgaijinentcomapiauthrequesttwostep) to request the current 2FA code + - Resend this request, this time with the `code` value filled in, that is returned by the previous endpoint - Response form schema: - - `` + - `` ```json { "auth": "login", diff --git a/src/api/v1/backends/marketplace.py b/src/api/v1/backends/marketplace.py index e551d617..f126f257 100644 --- a/src/api/v1/backends/marketplace.py +++ b/src/api/v1/backends/marketplace.py @@ -1,9 +1,14 @@ +import asyncio, math from fastapi import HTTPException, status -from typing import Any -from dataclasses import dataclass, asdict +from random import randint +from typing import Any, TypedDict +from dataclasses import dataclass, asdict, field +from enum import StrEnum +from datetime import datetime, UTC from utils.connection import Request from utils.auth import LoginEntry +from utils.helper import dictUtil, dtToTimestampMs import utils.connection.network as Network from api.v1.backends.shared import IntString @@ -13,10 +18,169 @@ async def get_asset_class(user: LoginEntry, hash:str) -> list[dict[str, str|IntS "cln_market_get_asset_class", name = hash ) +@dataclass(slots=True) +class Item: + hash_name: str + name: str + commodity: bool + icon: str + buy_price: float + buy_orders: int + sell_price: float + sell_orders: int + tags: dict[str, str|bool] + className: str + classValue: str + @classmethod + def from_dict(cls, data:dict[str, Any]): + tags = {} + for tag in data["tags"]: + tag:str + if tag.count(":") != 1: + ... # TODO: Figure out something here + return + key, value = tag.split(":") + if value == "yes": + tags[key] = True + elif value == "no": + tags[key] = False + else: + tags[key] = value + + return cls( + hash_name = data["hash_name"], + name = data["name"], + commodity = data.get("commodity", False), + icon = data["icon"], + buy_price = data["buy_price"] / 100000000, + buy_orders = data["buy_depth"], + sell_price = data["price"] / 100000000, + sell_orders = data["depth"], + tags = tags, + className = data["asset_class"][0]["name"], + classValue = data["asset_class"][0]["value"] + ) + @classmethod + def from_assetdata(cls, assetData:dict[str, Any], ordersData: dict[str, Any], classValues: dict[str, str]): + + return cls( + hash_name = assetData["market_hash_name"], + name = assetData["market_name"], + commodity = assetData.get("commodity", False), + icon = assetData.get("icon_url_large", assetData.get("icon_url", None)), + buy_price = max(i[0] for i in ordersData.get("BUY", [])) / 10000, + buy_orders = ordersData["depth"].get("BUY", 0), + sell_price = min(i[0] for i in ordersData.get("SELL", [])) / 10000, + sell_orders = ordersData["depth"].get("SELL", 0), + tags = {i["category"]:i["internal_name"] for i in assetData.get("tags", [])}, + className = classValues[0]["name"], + classValue = classValues[0]["value"] + ) + + async def to_json(self): + data = asdict(self) + + SANITIZE = ( + dictUtil.KeyRem("className", "classValue", "LOGIN"), + ) + + return await dictUtil.run_all(data, SANITIZE) + + @staticmethod + async def search(user: LoginEntry, name: str, count: int = 25, page: int = 0) -> tuple[Item]: + data = await Request.send_template( + user, + "cln_market_search", + count = count, + skip = count*page, + text = name + ) + if "response" in data: + data:list[dict[str, Any]] = data["response"]["assets"] + else: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get item data") + + items = [] + for item in data: + items.append(Item.from_dict(item)) + return tuple(items) + + @staticmethod + async def get(user: LoginEntry, itemHash: str) -> Item | None: + hashData = await Request.send_template( + user, + "cln_market_get_asset_class", + name = itemHash + ) + if "response" not in hashData or "asset_class" not in hashData["response"]: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found") + hashData = hashData["response"]["asset_class"] + if len(hashData) <= 0: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found") + + resp, books_brief = await asyncio.gather( + Request.send_template( + user, + "GetAssetClassInfo", + class_name0 = hashData[0]["name"], + class_value0 = hashData[0]["value"] + ), + Request.send_template( + user, + "cln_books_brief", + market_name = itemHash + ) + ) + + if "result" not in resp or "asset" not in resp["result"]: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item data could not be obtained") + resp = resp["result"]["asset"] + + if "response" in books_brief: + books_brief = books_brief["response"] + else: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") + + return Item.from_assetdata(resp, books_brief, hashData) + + async def buy(self, user: LoginEntry, price: float, count: int = 1, anonymous: bool = False): + agree_stamp = dtToTimestampMs(datetime.now(UTC)) + resp = await Request.send_template( + user, + "cln_market_buy", + transactid = randint(10**6, 10**15), + reqstamp = dtToTimestampMs(datetime.now(UTC)), + market_name = self.hash_name, + amount = count, + price = int(price*10000), + agree_stamp = agree_stamp, + privateMode = anonymous + ) + if "response" not in resp: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") + resp = resp["response"] + if "error" in resp: + if resp["error"] == "ASSET_NOT_FOUND": + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item doesn't exist") + elif "details" in resp and resp["details"] == "NOT_ENOUGH_FUNDS": + raise HTTPException(status.HTTP_403_FORBIDDEN, "Not enough funds") + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, resp["error"]) + if resp.get("success", False): + return { + "success": True + } + raise HTTPException(status.HTTP_400_BAD_REQUEST, "Failed to put up buy order") #region Inventory @dataclass(slots=True) class InventoryItem: + class SellData(TypedDict): + item: str + success: bool + price: float + seller_gets: float + + LOGIN: LoginEntry commodity:bool description: str icon_url: str @@ -28,74 +192,186 @@ class InventoryItem: type: str marketable: bool name_color: str - _class_name: str - _class_value: int + class_name: str + class_value: int ids:list[int] - contextid: str + contextid: int @classmethod - def from_json(cls, data:dict[str, Any], classdata:dict[str, str|int], id:int, context:str): - cname = classdata["name"] - cval = classdata["value"] + def from_json(cls, data:dict[str, Any], user: LoginEntry, itemData: dict[str, Any], context: int): + pass + assetData: dict[str, Any] = data["result"]["asset"] + classData: dict[str, Any] = itemData["class"][0] + return cls( - commodity=data.get("commodity"), - description=data["descriptions"][0]["value"], - icon_url=data.get("icon_url"), - icon_url_large=data.get("icon_url_large"), - hash=data.get("market_hash_name"), - name=data.get("market_name"), - display_name=data.get("name"), - tags=data.get("tags", []), - marketable=data.get("marketable", False), - type=data.get("type", ""), - name_color=data.get("name_color"), - _class_name=cname, - _class_value=cval, - ids=[id,], + LOGIN=user, + commodity=assetData.get("commodity"), + description=assetData["descriptions"][0]["value"], + icon_url=assetData.get("icon_url"), + icon_url_large=assetData.get("icon_url_large"), + hash=assetData.get("market_hash_name"), + name=assetData.get("market_name"), + display_name=assetData.get("name"), + tags=assetData.get("tags", []), + marketable=assetData.get("marketable", False), + type=assetData.get("type", None), + name_color=assetData.get("name_color"), + class_name=classData["name"], + class_value=classData["value"], + ids=[int(itemData["id"]),], contextid=context ) - def to_json(self): - return asdict(self) -async def get_inventory(user: LoginEntry) -> list[InventoryItem]: - items:list[InventoryItem] = [] - async with Network.operation() as session: - contexts = await Request.send_template( - user, - "GetContexts", - session=session + + async def sell(self, price: float, count: int, anonymous: bool = False) -> tuple[SellData]: + agree_stamp = dtToTimestampMs(datetime.now(UTC)) + + gaijin_fee = price*0.15 + seller_should_get = int((price-gaijin_fee)*10000//100*100) + + soldItems = [] + sold = 0 + if len(self.ids) < count: + raise HTTPException(status.HTTP_403_FORBIDDEN, f"Requested selling {count} items, but user only has {len(self.ids)} items in their inventory") + + for id in list(self.ids): + resp = await Request.send_template( + self.LOGIN, + "cln_market_sell", + transactid = randint(10**6, 10**15), + reqstamp = dtToTimestampMs(datetime.now(UTC)), + assetid = id, + amount = 1, + price = int(price*10000), + seller_should_get = seller_should_get, + agree_stamp = agree_stamp, + privateMode = anonymous, + contextid = self.contextid + ) + self.ids.remove(id) + if resp.get("status", False): + soldItems.append({ + "item": str(id), + "success": "response" in resp and resp["response"].get("success", False), + "price": price, + "seller_gets": seller_should_get + }) + sold += 1 + + if sold >= count: + break + + return tuple(soldItems) + + async def to_json(self): + SANITIZE = ( + dictUtil.KeyRem("ids", "class_name", "class_value", "contextid", "LOGIN"), + dictUtil.KeyMod("ids", convert=lambda x: [str(i) for i in x]) ) - if "result" not in contexts or not contexts["result"].get("success", False): - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get contexts") - for context in contexts["result"]["contexts"]: - ctx_data = await Request.send_template( + return await dictUtil.run_all(asdict(self), SANITIZE) + + @staticmethod + async def get(user: LoginEntry) -> tuple[InventoryItem]: + items:list[InventoryItem] = [] + async with Network.operation() as session: + contexts = await Request.send_template( user, - "GetContextContents", - session=session, - contextid = context["id"] + "GetContexts", + session=session ) - if "result" not in ctx_data: - continue - for item in ctx_data["result"]["assets"]: - item_data = await Request.send_template( + if "result" not in contexts or not contexts["result"].get("success", False): + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get contexts") + for context in contexts["result"]["contexts"]: + ctx_data = await Request.send_template( user, - "GetAssetClassInfo", + "GetContextContents", session=session, - class_name0 = item["class"][0]["name"], - class_value0 = item["class"][0]["value"] + contextid = context["id"] ) - if "result" not in item_data: + if "result" not in ctx_data: continue - for invitem in items: - if invitem._class_name == item["class"][0]["name"] and invitem._class_value == item["class"][0]["value"]: - invitem.ids.append(int(item["id"])) - break - else: - items.append(InventoryItem.from_json(item_data["result"]["asset"], item["class"][0], int(item["id"]), context["id"])) - return items - -async def item_in_inventory(user: LoginEntry, item_hash:str) -> InventoryItem|None: - inventory = await get_inventory(user) - for item in inventory: - if item.hash == item_hash: - return item - return None + for item in ctx_data["result"]["assets"]: + item_data = await Request.send_template( + user, + "GetAssetClassInfo", + session=session, + class_name0 = item["class"][0]["name"], + class_value0 = item["class"][0]["value"] + ) + if "result" not in item_data: + continue + for invitem in items: + if invitem.class_name == item["class"][0]["name"] and invitem.class_value == item["class"][0]["value"]: + invitem.ids.append(int(item["id"])) + break + else: + items.append(InventoryItem.from_json(item_data, user, item, int(context["id"]))) + return tuple(items) + + @staticmethod + async def balance(user: LoginEntry) -> float: + data = await Request.send_template( + user, + "GetBalance" + ) + if data.get("status") == "OK": + return data["balance"]/10000 + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to get balance") #endregion + +class Order: + class Type(StrEnum): + BUY = "buy" + SELL = "sell" + @dataclass(frozen=True, slots=True) + class Entry: + LOGIN: LoginEntry + market_hash: str + id: IntString + type: Order.Type + pairId: IntString + price: float + timestamp: datetime + amount: int = field(default=1) + + @classmethod + def from_dict(cls, obj: dict[str, Any], login: LoginEntry): + return cls( + LOGIN=login, + market_hash=obj["market"], + id=int(obj["id"]), + type=Order.Type[obj["type"]], + pairId=int(obj["pairId"]), + price=int(obj["localPrice"])/10000, + timestamp=datetime.fromtimestamp(obj["time"], UTC), + amount=int(obj["amount"]) + ) + + @staticmethod + async def get_orders(login: LoginEntry) -> tuple[Order.Entry]: + data = await Request.send_template(login, "cln_get_user_open_orders") + if (not data.get("success", False)) or "response" not in data: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get user's orders") + + orders = [] + for entry in data["response"]: + orders.append(Order.Entry.from_dict(entry, login)) + return tuple(orders) + + async def cancel(self) -> bool: + data = await Request.send_template( + self.LOGIN, + "cancel_order", + transactid=1, + reqstamp=int(datetime.now(UTC).timestamp()), + pairId=self.pairId, + orderId=self.id + ) + if "response" in data: + return data["response"].get("success", False) + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An error occurred while trying to cancel this order.") + + async def to_json(self): + SANITIZE = ( + dictUtil.KeyRem("LOGIN", "pairId"), + dictUtil.KeyMod("id", convert=lambda x: str(x)), + ) + return await dictUtil.run_all(asdict(self), SANITIZE) diff --git a/src/api/v1/marketplace_router.py b/src/api/v1/marketplace_router.py index 69fc79de..0d657a54 100644 --- a/src/api/v1/marketplace_router.py +++ b/src/api/v1/marketplace_router.py @@ -1,6 +1,5 @@ from os import getenv from typing_extensions import Annotated -from typing import Any from random import randint from datetime import datetime, UTC from fastapi import APIRouter, Query, Path, Request as faRequest, HTTPException, status @@ -9,8 +8,8 @@ from utils.helper import dtToTimestampMs from api.shared import limiter from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.backends.marketplace import item_in_inventory, get_inventory -from api.v1.models.marketplace import SellModel, ItemModel +from api.v1.backends.marketplace import Order, InventoryItem, Item +from api.v1.models.marketplace import Models from api.v1.models.base import GenericEmptyResponse router = APIRouter( @@ -20,102 +19,57 @@ ) @router.post( - "/sell/{itemHash}", - summary="Puts up a sell order for the given `itemHash`", - responses={ - status.HTTP_200_OK: {"description": "Sell order has successfully been placed", "model": list[SellModel]}, - status.HTTP_400_BAD_REQUEST: {"description": "Count is too high"}, - status.HTTP_404_NOT_FOUND: {"description": "Item could not be found in the inventory"} - } + "/orders/{orderId}/cancel", + summary="Cancels an order" ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -async def sell_item( +async def cancel_order( request: faRequest, user: TokenBearer, - itemHash: Annotated[str, Path(description="The item's hash value")], - price: Annotated[float, Query(description="The price in GJN to sell for (Includes gaijin's fee, not the value you get)", ge=0.1, le=2000)], - count: Annotated[int, Query(description="The amount to sell at once", gt=0)] = 1, - anonymous: Annotated[bool, Query(description="Appear as an anonymous seller")] = False -): - agree_stamp = dtToTimestampMs(datetime.now(UTC)) - - itemsInInv = await item_in_inventory(user, itemHash) - if itemsInInv is None: - raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found in inventory") - if len(itemsInInv.ids) < count: - raise HTTPException(status.HTTP_400_BAD_REQUEST, "Count is higher than the items in inventory") - - price = price - gaijin_fee = price*0.15 - seller_should_get = price-gaijin_fee + orderId: Annotated[int, Path(description="The order ID")] +) -> GenericEmptyResponse: + orders = await Order.Entry.get_orders(user) + for order in orders: + if order.id == orderId: + await order.cancel() + return {"success": True} + raise HTTPException(status.HTTP_404_NOT_FOUND, "Order ID not found") - solditems = [] - for i in range(count): - assetId = itemsInInv.ids.pop() - resp = await Request.send_template( - user, - "cln_market_sell", - transactid = randint(10**6, 10**15), - reqstamp = dtToTimestampMs(datetime.now(UTC)), - assetid = assetId, - amount = 1, - price = int(price*10000), - seller_should_get = int(seller_should_get*10000), - agree_stamp = agree_stamp, - privateMode = anonymous, - contextid = itemsInInv.contextid - ) - solditems.append({ - "item": assetId, - "success": "response" in resp and resp["response"].get("success", False), - "price": price, - "seller_gets": seller_should_get - }) - return solditems +@router.get( + "/orders/{orderId}", + summary="Gets information about an order" +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def get_order( + request: faRequest, user: TokenBearer, + orderId: Annotated[int, Path(description="The order ID")] +): + orders = await Order.Entry.get_orders(user) + for order in orders: + if order.id == orderId: + return await order.to_json() + raise HTTPException(status.HTTP_404_NOT_FOUND, "Order ID not found") -@router.post( - "/buy/{itemHash}", - summary="Puts up a buy order for the given `itemHash`", +@router.get( + "/orders", + summary="Gets the currently active orders", responses={ - status.HTTP_200_OK: {"description": "The buy order has successfully been placed", "model": GenericEmptyResponse}, - status.HTTP_400_BAD_REQUEST: {"description": "Something prevented the buy order from being placed"}, - status.HTTP_403_FORBIDDEN: {"description": "Not enough funds"}, - status.HTTP_404_NOT_FOUND: {"description": "The given item doesn't exist"} + status.HTTP_200_OK: {"model": list[Models.OrderModel]} } ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -async def buy_item( +async def get_orders( request: faRequest, user: TokenBearer, - itemHash: Annotated[str, Path(description="The item's hash value")], - price: Annotated[float, Query(description="The price in GJN to buy for", ge=0.1, le=2000)], - count: Annotated[int, Query(description="The amount to buy", gt=0)] = 1, - anonymous: Annotated[bool, Query(description="Appear as an anonymous buyer")] = False -) -> GenericEmptyResponse: - agree_stamp = dtToTimestampMs(datetime.now(UTC)) - resp = await Request.send_template( - user, - "cln_market_buy", - transactid = randint(10**6, 10**15), - reqstamp = dtToTimestampMs(datetime.now(UTC)), - market_name = itemHash, - amount = count, - price = int(price*10000), - agree_stamp = agree_stamp, - privateMode = anonymous - ) - if "response" not in resp: - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") - resp = resp["response"] - if "error" in resp: - if resp["error"] == "ASSET_NOT_FOUND": - raise HTTPException(status.HTTP_404_NOT_FOUND, "Item doesn't exist") - elif "details" in resp and resp["details"] == "NOT_ENOUGH_FUNDS": - raise HTTPException(status.HTTP_403_FORBIDDEN, "Not enough funds") - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, resp["error"]) - if resp.get("success", False): - return { - "success": True - } - raise HTTPException(status.HTTP_400_BAD_REQUEST, "Failed to put up buy order") + orderType: Annotated[Order.Type | None, Query()] = None +) -> list[Models.OrderModel]: + orders = await Order.Entry.get_orders(user) + if orderType is None: + return [await order.to_json() for order in orders] + + display_orders = [] + for order in orders: + if order.type == orderType: + display_orders.append(await order.to_json()) + return display_orders @router.get( "/inventory", @@ -124,9 +78,9 @@ async def buy_item( @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") async def getInventory( request: faRequest, user: TokenBearer -): - inv = await get_inventory(user) - return [i.to_json() for i in inv] +) -> list[Models.InventoryItemModel]: + inv = await InventoryItem.get(user) + return [await i.to_json() for i in inv] @router.get( "/balance", @@ -148,7 +102,7 @@ async def get_balance( "/search", summary="Searches the marketplace for a given item", responses={ - status.HTTP_200_OK: {"model": list[ItemModel]} + status.HTTP_200_OK: {"model": list[Models.ItemModel]} } ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") @@ -158,58 +112,18 @@ async def searchItem( count: Annotated[int, Query(title="Amount to get at once")] = 25, page: Annotated[int, Query(title="Pagination page. Works based off of `count`")] = 0, ): - data = await Request.send_template( - user, - "cln_market_search", - count = count, - skip = count*page, - text = name - ) - if "response" in data: - data:list[dict[str, Any]] = data["response"]["assets"] - else: - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get item data") - for item in data: - item["sell_price"] = item["price"] / 100000000 - item["buy_price"] = item["buy_price"] / 100000000 - item.pop("price") - - item["sell_orders"] = item["depth"] - item["buy_orders"] = item["buy_depth"] - item.pop("depth") - item.pop("buy_depth") - - item.pop("appid") - item.pop("color") - item.pop("asset_class") - - new_tags = {} - for tag in item["tags"]: - tag:str - if tag.count(":") != 1: - ... # TODO: Figure out something here - return - key, value = tag.split(":") - if value == "yes": - new_tags[key] = True - elif value == "no": - new_tags[key] = False - else: - new_tags[key] = value - item["tags"] = new_tags - del new_tags - - return data + data = await Item.search(user, name, count, page) + return [await i.to_json() for i in data] @router.get( - "/{itemHash}/orders/history", + "/{itemHash}/history", summary="Retrieves marketplace history data about the given item" ) @limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") async def get_item_history( request: faRequest, user: ServerBearer, itemHash: Annotated[str, Path(title="The item to look up")], -): +) -> Models.OrderHistoryModel: pairData = await Request.send_template( user, "cln_get_pair_stat", @@ -246,7 +160,7 @@ async def get_item_history( async def get_item_orders( request: faRequest, user: ServerBearer, itemHash: Annotated[str, Path(title="The item to look up")], -): +) -> Models.OrdersModel: books_brief = await Request.send_template( user, "cln_books_brief", @@ -302,6 +216,52 @@ async def view_item( ) return resp.get("status") == "ok" +@router.post( + "/{itemHash}/sell", + summary="Puts up a sell order for the given `itemHash`", + responses={ + status.HTTP_200_OK: {"description": "Sell order has successfully been placed", "model": list[Models.SellModel]}, + status.HTTP_400_BAD_REQUEST: {"description": "Count is too high"}, + status.HTTP_404_NOT_FOUND: {"description": "Item could not be found in the inventory"} + } +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def sell_item( + request: faRequest, user: TokenBearer, + itemHash: Annotated[str, Path(description="The item's hash value")], + price: Annotated[float, Query(description="The price in GJN to sell for (Includes gaijin's fee, not the value you get)", ge=0.1, le=2000)], + count: Annotated[int, Query(description="The amount to sell at once", gt=0)] = 1, + anonymous: Annotated[bool, Query(description="Appear as an anonymous seller")] = False +): + inventoryItems = await InventoryItem.get(user) + for item in inventoryItems: + if item.hash == itemHash: + return await item.sell(price=price, count=count, anonymous=anonymous) + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found in inventory") + +@router.post( + "/{itemHash}/buy", + summary="Puts up a buy order for the given `itemHash`", + responses={ + status.HTTP_200_OK: {"description": "The buy order has successfully been placed", "model": GenericEmptyResponse}, + status.HTTP_400_BAD_REQUEST: {"description": "Something prevented the buy order from being placed"}, + status.HTTP_403_FORBIDDEN: {"description": "Not enough funds"}, + status.HTTP_404_NOT_FOUND: {"description": "The given item doesn't exist"} + } +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def buy_item( + request: faRequest, user: TokenBearer, + itemHash: Annotated[str, Path(description="The item's hash value")], + price: Annotated[float, Query(description="The price in GJN to buy for", ge=0.1, le=2000)], + count: Annotated[int, Query(description="The amount to buy", gt=0)] = 1, + anonymous: Annotated[bool, Query(description="Appear as an anonymous buyer")] = False +) -> GenericEmptyResponse: + item = await Item.get(user, itemHash) + if item: + return await item.buy(user, price=price, count=count, anonymous=anonymous) + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found") + @router.get( "/{itemHash}", summary="Gets metadata about the given item" @@ -310,38 +270,8 @@ async def view_item( async def get_item( request: faRequest, user: ServerBearer, itemHash: Annotated[str, Path(title="The item to look up")], -): - hashData = await Request.send_template( - user, - "cln_market_get_asset_class", - name = itemHash - ) - if "response" not in hashData or "asset_class" not in hashData["response"]: - raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found") - hashData = hashData["response"]["asset_class"] - if len(hashData) <= 0: - raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found") - resp = await Request.send_template( - user, - "GetAssetClassInfo", - class_name0 = hashData[0]["name"], - class_value0 = hashData[0]["value"] - ) - if "result" not in resp or "asset" not in resp["result"]: - raise HTTPException(status.HTTP_404_NOT_FOUND, "Item data could not be obtained") - resp = resp["result"]["asset"] - ret_data = {} - - ret_data["description"] = resp["descriptions"][0]["value"] - ret_data["tags"] = resp["tags"] - ret_data["sellable"] = bool(resp["marketable"]) - ret_data["hash"] = resp["market_hash_name"] - ret_data["market_name"] = resp["market_name"] - ret_data["display_name"] = resp["name"] - ret_data["images"] = { - "icon": resp["icon_url"], - "image": resp["icon_url_large"] - } - ret_data["type"] = resp["type"] - - return ret_data +) -> Models.ItemModel: + item = await Item.get(user, itemHash) + if item is not None: + return await item.to_json() + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found") diff --git a/src/api/v1/models/base.py b/src/api/v1/models/base.py index ac4eccb7..401432ea 100644 --- a/src/api/v1/models/base.py +++ b/src/api/v1/models/base.py @@ -4,4 +4,5 @@ class SuccessEmptyDict(BaseModel): status:Literal["success"] = "success" class GenericEmptyResponse(BaseModel): + """Basic `{"success":true}` response""" success: bool diff --git a/src/api/v1/models/marketplace.py b/src/api/v1/models/marketplace.py index 2f295f77..ebcdf4e3 100644 --- a/src/api/v1/models/marketplace.py +++ b/src/api/v1/models/marketplace.py @@ -1,35 +1,84 @@ +from datetime import datetime from pydantic import BaseModel, Field from ..backends.shared import IntString -class SellModel(BaseModel): - item: IntString - success: bool - price: float - seller_gets: float +class TagsModel(BaseModel): + internal_name: str + category: str + category_name: str | None = Field(default=None, exclude_if=lambda x: x is None) + category_sort_index: int | None = Field(default=None, exclude_if=lambda x: x is None) + name: str | None = Field(default=None, exclude_if=lambda x: x is None) + color: str | None = Field(default=None, exclude_if=lambda x: x is None) + sort_index: int | None = Field(default=None, exclude_if=lambda x: x is None) -class ItemModel(BaseModel): - hash_name: str = Field(description="The internal name of the item", examples=["ugcitem_1000574", "Object 279 (USSR)", "id50257_object_292_ussr"]) - name: str = Field(description="The display name of the item", examples=["Object 279 'Sledgehammer'", "Object 279 (USSR)", "Object 292 (USSR)"]) - commodity: bool - icon: str = Field(description="The URL to the icon of said item") - buy_price: float = Field(description="The highest 'buy' price") - buy_orders: int = Field(description="The amount of buy orders on this item") - sell_price: float = Field(description="The lowest 'sell' price") - sell_orders: int = Field(description="The amount of sell orders on this item") - tags: dict = Field(description="The tags associated with this item", examples=[ - { - "type": "skin", - "quality": "junk", - "vehicleType": "tank", - "country": "ussr", - "inGamePreview": True, - "eventName": "camo_trophy_2_37", - "authenticity": "fictional" - }, - { - "type": "tank", - "quality": "ultraRare", - "country": "ussr", - "inGamePreview": True - }, - ]) +class Models: + class SellModel(BaseModel): + item: IntString + success: bool + price: float + seller_gets: float + + class ItemModel(BaseModel): + hash_name: str = Field(description="The internal name of the item", examples=["ugcitem_1000574", "Object 279 (USSR)", "id50257_object_292_ussr"]) + name: str = Field(description="The display name of the item", examples=["Object 279 'Sledgehammer'", "Object 279 (USSR)", "Object 292 (USSR)"]) + commodity: bool + icon: str = Field(description="The URL to the icon of said item") + buy_price: float = Field(description="The highest 'buy' price") + buy_orders: int = Field(description="The amount of buy orders on this item") + sell_price: float = Field(description="The lowest 'sell' price") + sell_orders: int = Field(description="The amount of sell orders on this item") + tags: dict = Field(description="The tags associated with this item", examples=[ + { + "type": "skin", + "quality": "junk", + "vehicleType": "tank", + "country": "ussr", + "inGamePreview": True, + "eventName": "camo_trophy_2_37", + "authenticity": "fictional" + }, + { + "type": "tank", + "quality": "ultraRare", + "country": "ussr", + "inGamePreview": True + }, + ]) + + class InventoryItemModel(BaseModel): + commodity: bool + description: str + icon_url: str + icon_url_large: str + hash: str + name: str + display_name: str + tags: list[TagsModel] + type: str | None + marketable: bool + name_color: str + + class OrderModel(BaseModel): + market_hash: str + id: IntString + type: str + price: float + timestamp: datetime + amount: int + + class OrderHistoryModel(BaseModel): + class HistoryModel(BaseModel): + timestamp: int + price: float + transactions_count: int + short: list[HistoryModel] + whole: list[HistoryModel] + + class OrdersModel(BaseModel): + class PriceModel(BaseModel): + price: float + amount: int + buy_orders: int + sell_orders: int + buy_prices: list[PriceModel] + sell_prices: list[PriceModel] diff --git a/src/utils/connection/__init__.py b/src/utils/connection/__init__.py index c246a2c1..bc0a92b3 100644 --- a/src/utils/connection/__init__.py +++ b/src/utils/connection/__init__.py @@ -96,7 +96,7 @@ def __init__( self.session = session @classmethod - async def from_template(cls, user:LoginEntry, template: str, session:ClientSession|None=None, *, remove_keys: set[str] = set(), **data:str|dict[str, Any]) -> "Request": + async def from_template(cls, user:LoginEntry, template: str, /, *, session:ClientSession|None=None, remove_keys: set[str] = set(), **data:str|dict[str, Any]) -> "Request": if user.entry is not None and user.entry.timeLeft() <= timedelta(minutes=30): await user.entry.refresh() if template not in TEMPLATES: @@ -139,13 +139,20 @@ async def from_template(cls, user:LoginEntry, template: str, session:ClientSessi return self @staticmethod - async def send_template(user:LoginEntry, template: str, session:ClientSession|None=None, *, remove_keys: set[str] = set(), **data:str|dict[str, Any]) -> dict: + async def send_template(user:LoginEntry, template: str, /, *, session:ClientSession|None=None, remove_keys: set[str] = set(), **data:str|dict[str, Any]) -> dict: cls = await Request.from_template(user, template, session=session, remove_keys=remove_keys, **data) return await cls.send() def replace(self, key: str, value: Any): if key in self.body and key in self.headers: - raise RuntimeError(f"Key `{key}` found in both headers and body for template `{self.__template}`") + if (self.body[key].lower() == "") and not (self.headers[key].lower() == ""): + self.body[key] = value + elif not (self.body[key].lower() == "") and (self.headers[key].lower() == ""): + self.headers[key] = value + elif not (self.body[key].lower() == "") and not (self.headers[key].lower() == ""): + return + else: + raise RuntimeError(f"Key `{key}` found in both headers and body for template `{self.__template}`") elif key in self.body: self.body[key] = value elif key in self.headers: diff --git a/src/utils/connection/templates/cancel_order.json b/src/utils/connection/templates/cancel_order.json new file mode 100644 index 00000000..8a6711a2 --- /dev/null +++ b/src/utils/connection/templates/cancel_order.json @@ -0,0 +1,13 @@ +{ + "headers": { + "Content-Type": "application/x-www-form-urlencoded" + }, + "body": { + "action": "cancel_order", + "token": "", + "transactid": "", + "reqstamp": "", + "pairId": "", + "orderId": "" + } +} diff --git a/src/utils/connection/templates/cln_get_user_open_orders.json b/src/utils/connection/templates/cln_get_user_open_orders.json new file mode 100644 index 00000000..f2cab788 --- /dev/null +++ b/src/utils/connection/templates/cln_get_user_open_orders.json @@ -0,0 +1,9 @@ +{ + "headers": { + "Content-Type": "application/x-www-form-urlencoded" + }, + "body": { + "action": "cln_get_user_open_orders", + "token": "" + } +} From 5e433f5b37034de130ea118d68a118cf6f78d32e Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:07:26 +0100 Subject: [PATCH 14/91] Fixes --- src/api/v1/backends/marketplace.py | 37 +++++++++++++++--------------- src/api/v1/marketplace_router.py | 8 +------ 2 files changed, 20 insertions(+), 25 deletions(-) diff --git a/src/api/v1/backends/marketplace.py b/src/api/v1/backends/marketplace.py index f126f257..4208f3b5 100644 --- a/src/api/v1/backends/marketplace.py +++ b/src/api/v1/backends/marketplace.py @@ -68,9 +68,9 @@ def from_assetdata(cls, assetData:dict[str, Any], ordersData: dict[str, Any], cl name = assetData["market_name"], commodity = assetData.get("commodity", False), icon = assetData.get("icon_url_large", assetData.get("icon_url", None)), - buy_price = max(i[0] for i in ordersData.get("BUY", [])) / 10000, + buy_price = max((i[0] for i in ordersData.get("BUY", [])), default=0) / 10000, buy_orders = ordersData["depth"].get("BUY", 0), - sell_price = min(i[0] for i in ordersData.get("SELL", [])) / 10000, + sell_price = min((i[0] for i in ordersData.get("SELL", [])), default=0) / 10000, sell_orders = ordersData["depth"].get("SELL", 0), tags = {i["category"]:i["internal_name"] for i in assetData.get("tags", [])}, className = classValues[0]["name"], @@ -230,7 +230,7 @@ async def sell(self, price: float, count: int, anonymous: bool = False) -> tuple soldItems = [] sold = 0 if len(self.ids) < count: - raise HTTPException(status.HTTP_403_FORBIDDEN, f"Requested selling {count} items, but user only has {len(self.ids)} items in their inventory") + raise HTTPException(status.HTTP_400_BAD_REQUEST, f"Requested selling {count} items, but user only has {len(self.ids)} items in their inventory") for id in list(self.ids): resp = await Request.send_template( @@ -263,8 +263,8 @@ async def sell(self, price: float, count: int, anonymous: bool = False) -> tuple async def to_json(self): SANITIZE = ( - dictUtil.KeyRem("ids", "class_name", "class_value", "contextid", "LOGIN"), - dictUtil.KeyMod("ids", convert=lambda x: [str(i) for i in x]) + dictUtil.KeyRem("class_name", "class_value", "contextid", "LOGIN"), + ) return await dictUtil.run_all(asdict(self), SANITIZE) @@ -325,9 +325,9 @@ class Type(StrEnum): class Entry: LOGIN: LoginEntry market_hash: str - id: IntString + id: int type: Order.Type - pairId: IntString + pairId: int price: float timestamp: datetime amount: int = field(default=1) @@ -345,17 +345,6 @@ def from_dict(cls, obj: dict[str, Any], login: LoginEntry): amount=int(obj["amount"]) ) - @staticmethod - async def get_orders(login: LoginEntry) -> tuple[Order.Entry]: - data = await Request.send_template(login, "cln_get_user_open_orders") - if (not data.get("success", False)) or "response" not in data: - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get user's orders") - - orders = [] - for entry in data["response"]: - orders.append(Order.Entry.from_dict(entry, login)) - return tuple(orders) - async def cancel(self) -> bool: data = await Request.send_template( self.LOGIN, @@ -375,3 +364,15 @@ async def to_json(self): dictUtil.KeyMod("id", convert=lambda x: str(x)), ) return await dictUtil.run_all(asdict(self), SANITIZE) + + @staticmethod + async def get(login: LoginEntry) -> tuple[Order.Entry]: + data = await Request.send_template(login, "cln_get_user_open_orders") + if (not data.get("success", False)) or "response" not in data: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Could not get user's orders") + + orders = [] + for entry in data["response"]: + orders.append(Order.Entry.from_dict(entry, login)) + return tuple(orders) + diff --git a/src/api/v1/marketplace_router.py b/src/api/v1/marketplace_router.py index 0d657a54..c35638a1 100644 --- a/src/api/v1/marketplace_router.py +++ b/src/api/v1/marketplace_router.py @@ -90,13 +90,7 @@ async def getInventory( async def get_balance( request: faRequest, user: TokenBearer ) -> float: - data = await Request.send_template( - user, - "GetBalance" - ) - if data.get("status") == "OK": - return data["balance"]/10000 - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to get balance") + return await InventoryItem.balance(user) @router.get( "/search", From 7da503dbedfbb23c285f846cd1b838296695d9b3 Mon Sep 17 00:00:00 2001 From: "[yoshino-home] Maho-Yoshino" <62778359+Maho-Yoshino@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:32:31 +0100 Subject: [PATCH 15/91] Fix Swagger UI modify js Now websockets get hidden properly --- src/swagger_ui_modify.js | 662 +++++++++++++-------------------------- 1 file changed, 222 insertions(+), 440 deletions(-) diff --git a/src/swagger_ui_modify.js b/src/swagger_ui_modify.js index 6b5774f5..bbe70044 100644 --- a/src/swagger_ui_modify.js +++ b/src/swagger_ui_modify.js @@ -5,30 +5,26 @@ const OPENAPI_URL = "/openapi.json"; - // ============================================================ // Load WebSocket definitions // ============================================================ - const schema = await fetch(OPENAPI_URL).then(response => response.json()); + const schema = await fetch(OPENAPI_URL).then((response) => response.json()); const websocketEndpoints = []; for (const [path, definition] of Object.entries(schema.paths ?? {})) { const websocket = definition["x-websocket"]; - if (!websocket) - continue; + if (!websocket) continue; websocketEndpoints.push({ path, - ...websocket + ...websocket, }); } - if (websocketEndpoints.length === 0) - return; - + if (websocketEndpoints.length === 0) return; // ============================================================ // Wait until Swagger UI has rendered its operation groups @@ -37,80 +33,105 @@ const waitForSwagger = setInterval(() => { const swagger = document.querySelector("#swagger-ui .swagger-ui"); - if (!swagger) - return; + if (!swagger) return; - const tagSections = swagger.querySelectorAll( - ".opblock-tag-section" - ); + const tagSections = swagger.querySelectorAll(".opblock-tag-section"); - if (tagSections.length === 0) - return; + if (tagSections.length === 0) return; clearInterval(waitForSwagger); for (const endpoint of websocketEndpoints) { - insertWebSocketEndpoint( - endpoint, - tagSections - ); + insertWebSocketEndpoint(endpoint, tagSections); } }, 50); - // ============================================================ // Insert WebSocket into its Swagger tag/category // ============================================================ function insertWebSocketEndpoint(endpoint, tagSections) { const tags = - Array.isArray(endpoint.tags) && - endpoint.tags.length > 0 + Array.isArray(endpoint.tags) && endpoint.tags.length > 0 ? endpoint.tags : ["default"]; const tag = tags[0]; - const targetSection = findTagSection( - tag, - tagSections - ); + const targetSection = findTagSection(tag, tagSections); if (!targetSection) { console.warn( `Swagger UI: could not find tag "${tag}" ` + - `for WebSocket ${endpoint.path}` + `for WebSocket ${endpoint.path}`, ); return; } - const operationId = createOperationId( - tag, - endpoint.path - ); + const operationId = createOperationId(tag, endpoint.path); // Prevent duplicates in case this script is somehow // executed more than once. - if (document.getElementById(operationId)) - return; + if (document.getElementById(operationId)) return; - const block = createWebSocketBlock( - endpoint, - tag, - operationId - ); + const block = createWebSocketBlock(endpoint, tag, operationId); /* - * Swagger's operations are direct children of the - * .opblock-tag-section after the tag heading. + * Swagger UI renders its operations inside a .no-margin + * container that is a direct child of the + * .opblock-tag-section, right after the tag heading. + * + * When a category is collapsed, React unmounts that + * container entirely and renders a