diff --git a/.editorconfig b/.editorconfig index 883bd762..fd3409fe 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,9 +1,19 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file root = true [*] -insert_final_newline = true +indent_style = tabs +indent_size = 4 +end_of_line = lf +charset = utf-8 trim_trailing_whitespace = true -indent_style = tab +insert_final_newline = true [*.md] -trim_trailing_whitespace = false # keep the two-space markdown line breaks +# keep the two-space markdown line breaks +trim_trailing_whitespace = false + +[*.yaml] +indent_style = space diff --git a/.example.env b/.example.env index f3d63290..e0b85f00 100644 --- a/.example.env +++ b/.example.env @@ -1,15 +1,11 @@ # Hosting settings PORT=8001 HOST=127.0.0.1 - +FORWARDED_ALLOW_IPS= # Logging level (INFO recommended unless developing) LOG_LEVEL=INFO -# IPs to trust for X-Forwarded-For (proxies like a Cloudflare tunnel). Use "*" to trust all, -# or a CIDR/subnet like "172.18.0.0/16" to only trust the Docker network. -FORWARDED_ALLOW_IPS=* - # Rate limiting LOGIN_RATE_LIMIT=25/minute REGULAR_RATE_LIMIT=100/minute @@ -21,3 +17,8 @@ SERVER_PASS= # Linux Systemd/Docker settings UID= GID= + +# Contact details +CONTACT_NAME= +CONTACT_URL= +CONTACT_EMAIL= diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml new file mode 100644 index 00000000..44ed7209 --- /dev/null +++ b/.github/workflows/linter.yaml @@ -0,0 +1,32 @@ +name: Ruff linter +on: pull_request + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.14"] + steps: + - uses: actions/checkout@v7 + with: + ref: refs/pull/${{ github.event.pull_request.number }}/head + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: pip install ruff + - name: Auto-fix with Ruff + if: github.event.pull_request.head.repo.full_name == github.repository + run: ruff check src/ --fix + - name: Check with Ruff (forks) + if: github.event.pull_request.head.repo.full_name != github.repository + run: ruff check src/ + - name: Commit and push fixes + if: github.event.pull_request.head.repo.full_name == github.repository + uses: stefanzweifel/git-auto-commit-action@v7 + with: + commit_message: "style: apply ruff fixes" + permissions: + contents: write diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 00000000..6c7f19fb --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,22 @@ +name: Pytest +on: pull_request + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.14"] + steps: + - uses: actions/checkout@v7 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt pytest pytest-asyncio httpx + - name: Run Pytest + run: | + python -m pytest diff --git a/AGENTS.md b/AGENTS.md index 1774a3d1..a561e0fb 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: +- `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`) + - `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 `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 -## 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/README.md b/README.md index d914e7f7..61cd61c3 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,8 @@ docker compose build docker compose up -d ``` +If you set `SERVER_EMAIL` and `SERVER_PASS`, you can approve Gaijin Pass requests on your device while the server runs in the background. If the server account uses an email code, start the service with an interactive terminal and enter the code within 15 minutes. + ## Contributions Contributions are welcome. Pull requests that improve ThunderAPI without breaking existing functionality are encouraged diff --git a/app/api/root.py b/app/api/root.py deleted file mode 100644 index de4ce6e1..00000000 --- a/app/api/root.py +++ /dev/null @@ -1,16 +0,0 @@ -from fastapi import APIRouter, status -from fastapi.responses import RedirectResponse - -router = APIRouter( - prefix="", - tags=[], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -@router.get("/privacy") -def privacy_policy(): - return RedirectResponse("https://github.com/Order-Of-The-Birb/ThunderAPI/README.md#privacy-policy", status.HTTP_301_MOVED_PERMANENTLY) - -@router.get("/github", summary="Redirects to the github source code") -async def github_redirect(): - return RedirectResponse("https://github.com/Order-Of-The-Birb/ThunderAPI", status.HTTP_301_MOVED_PERMANENTLY) diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py deleted file mode 100644 index b1eb062b..00000000 --- a/app/api/v1/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -from fastapi import APIRouter - -from .auth_router import router as authRouter -from .clans_router import router as clanRouter -from .general_router import router as generalRouter -from .marketplace_router import router as tradeRouter -from .replays_router import router as replayRouter -from .units_router import router as unitRouter -from .users_router import router as userRouter - -router = APIRouter( - prefix="/v1" -) -router.include_router(authRouter) -router.include_router(clanRouter) -router.include_router(generalRouter) -router.include_router(tradeRouter) -router.include_router(replayRouter) -#router.include_router(unitRouter) -router.include_router(userRouter) diff --git a/app/api/v1/auth_router.py b/app/api/v1/auth_router.py deleted file mode 100644 index 46da2afc..00000000 --- a/app/api/v1/auth_router.py +++ /dev/null @@ -1,95 +0,0 @@ -from os import getenv -from typing_extensions import Annotated -from fastapi import APIRouter, Form, HTTPException, Request, status -from fastapi.responses import JSONResponse -from pydantic import EmailStr - -from utils import users_auth -from utils.auth import _PENDING_2FA -from utils.helper import dtToTimestamp -from api.shared import limiter -from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.models.auth import Login, LoginToken - -router = APIRouter( - tags=["authentication"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -@router.post( - "/login", - summary="Get a token to use in other endpoints", - description="You can use this token for the endpoints. If given user has 2FA enabled, they must provide the 2FA code along with their credentials through either `Gaijin pass` or the `/v1/answer-2fa` endpoint. If you generated a token that hasn't expired yet, the endpoint will just give back the cached token.", - responses={ - status.HTTP_200_OK: {"model": Login.LoginResponse}, - status.HTTP_401_UNAUTHORIZED: {"model": Login.Fail2FAResponse, "description": "Unauthorized. Account has 2FA enabled, and needs to go through the 2FA process."}, - status.HTTP_408_REQUEST_TIMEOUT: {"description": "Account has Two Factor Authentication, and authentication timed out"}, - status.HTTP_429_TOO_MANY_REQUESTS: {"description": "Rate limit exceeded. Please wait a bit before trying again."}, - } -) -@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) -async def login_post( - request: Request, - email: Annotated[EmailStr, Form()], - password: Annotated[str, Form(min_length=6, max_length=64, json_schema_extra={"format": "password"})] -): - token, uidHint = await users_auth.login(email, password) - - return JSONResponse({ - "status": "OK", - "token": token, - "user_id": uidHint - }, status_code=status.HTTP_200_OK) - -@router.post( - "/refresh-token", - summary="Refresh your token so it stays alive for longer. This is essentially a 'No op', just to keep the token active.", - description="If you are cached it will refresh the token. The game generally refreshes the token every 30 minutes. Returns an UNIX timestamp of the new token expiry", - responses={ - status.HTTP_200_OK: {"model": LoginToken.LoginTokenResponse, "description": "Token refreshed successfully"}, - status.HTTP_404_NOT_FOUND: {"model": LoginToken.LoginFailResponse, "description": "Invalid token provided. The token is either expired or invalid."}, - status.HTTP_429_TOO_MANY_REQUESTS: {"description": "Rate limit exceeded. Please wait a bit before trying again."} - } -) -@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) -async def login_token( - request: Request, - user: TokenBearer -): - await user.entry.refresh() - return { - "expires": dtToTimestamp(user.entry.expires), - "status": "OK" - } - -@router.post( - "/answer-2fa", - summary="Provide 2FA code to finish login in case of a 2FA account without gaijin pass" -) -@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) -async def answer_2fa( - request: Request, - 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")] -): - 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): - _PENDING_2FA[email].code = code - else: - raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid password") - ... # TODO: Implement. Due to the nature of the 2FA system, it is hard to implement - -@router.delete( - "/remove", - summary="Removes your login entry from our system" -) -@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) -async def remove_login( - request: Request, - user: TokenBearer -): - 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/app/api/v1/backends/general.py b/app/api/v1/backends/general.py deleted file mode 100644 index 0b01e231..00000000 --- a/app/api/v1/backends/general.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Literal -import utils.connection.network as Network - -async def getLatestGameVer(branch: Literal["dev", "dev-stable"]|None): - if branch is None: branch = "" - async with Network.get(f"https://yupmaster.gaijinent.com/yuitem/get_version.php?proj=warthunder&tag={branch}") as response: - response = await response.text() - return response diff --git a/app/api/v1/backends/marketplace.py b/app/api/v1/backends/marketplace.py deleted file mode 100644 index e551d617..00000000 --- a/app/api/v1/backends/marketplace.py +++ /dev/null @@ -1,101 +0,0 @@ -from fastapi import HTTPException, status -from typing import Any -from dataclasses import dataclass, asdict - -from utils.connection import Request -from utils.auth import LoginEntry -import utils.connection.network as Network -from api.v1.backends.shared import IntString - -async def get_asset_class(user: LoginEntry, hash:str) -> list[dict[str, str|IntString]]: - return await Request.send_template( - user, - "cln_market_get_asset_class", - name = hash - ) - -#region Inventory -@dataclass(slots=True) -class InventoryItem: - commodity:bool - description: str - icon_url: str - icon_url_large: str - hash: str - name: str - display_name:str - tags: list[dict[str, str|int]] - type: str - marketable: bool - name_color: str - _class_name: str - _class_value: int - ids:list[int] - contextid: str - @classmethod - def from_json(cls, data:dict[str, Any], classdata:dict[str, str|int], id:int, context:str): - cname = classdata["name"] - cval = classdata["value"] - 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,], - 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 - ) - 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, - "GetContextContents", - session=session, - contextid = context["id"] - ) - if "result" not in ctx_data: - continue - 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["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 -#endregion diff --git a/app/api/v1/backends/shared.py b/app/api/v1/backends/shared.py deleted file mode 100644 index 2132d8f1..00000000 --- a/app/api/v1/backends/shared.py +++ /dev/null @@ -1,78 +0,0 @@ -from fastapi import HTTPException, Depends, status -from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials -from typing_extensions import Annotated -from pydantic import StringConstraints, Field -from datetime import datetime, UTC -import utils -from utils import users_auth -from utils.auth import LoginEntry - -security = HTTPBearer(description="Get the token from `POST /v1/login`") -optional_security = HTTPBearer(auto_error=False) - -class Authentication: - @staticmethod - async def _track_usage(user: LoginEntry): - # move the existing flush/counter block here - if user.entry is None: - raise HTTPException(status.HTTP_409_CONFLICT, "You must be logged in") - flush = False - async with users_auth._auth_used_lock: - cache = users_auth._auth_used_cache.setdefault(user.entry.hashed, {"cnt": 0}) - cache["cnt"] += 1 - cache["used"] = datetime.now(UTC) - if cache["cnt"] >= 10: - user.entry.requests_count += cache["cnt"] - user.entry.last_used = cache["used"] - cache["cnt"] = 0 - flush = True - if flush: - await user.entry._write_values() - - @staticmethod - async def get_auth(credentials: HTTPAuthorizationCredentials = Depends(security)): - user = await users_auth.get(credentials.credentials) - if not user: - raise HTTPException(status.HTTP_401_UNAUTHORIZED, "User not found") - user = user.getEntry() - await Authentication._track_usage(user) - return user - - @staticmethod - async def get_server_auth() -> LoginEntry: - if utils.server_auth is None: - raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Server account not configured") - - entry = utils.server_auth.getLogin() - if entry is None: - raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Server account not configured") - return entry - - @staticmethod - async def get_optional_auth( - credentials: HTTPAuthorizationCredentials | None = Depends(optional_security), - ) -> LoginEntry: - if credentials is not None: - user = await users_auth.get(credentials.credentials) - if user is not None: - user = user.getEntry() - await Authentication._track_usage(user) - return user - raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token") - return await Authentication.get_server_auth() - - -TokenBearer = Annotated[LoginEntry, Depends(Authentication.get_auth) ] -ServerBearer = Annotated[LoginEntry, Depends(Authentication.get_server_auth) ] -OptionalAuth = Annotated[LoginEntry, Depends(Authentication.get_optional_auth) ] - -IntString = Annotated[ - str, - StringConstraints(pattern=r"^\d+$"), - Field(description="Integer value represented as a string", examples=["10016", "652677", "62762477"]), -] -IpString = Annotated[ - str, - StringConstraints(pattern=r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"), - Field(description="IP address represented as a string", examples=["0.0.0.0", "192.168.0.1", "127.0.0.1"]) -] diff --git a/app/api/v1/backends/users.py b/app/api/v1/backends/users.py deleted file mode 100644 index 02d17577..00000000 --- a/app/api/v1/backends/users.py +++ /dev/null @@ -1,10 +0,0 @@ -from utils.connection import Request -from utils.auth import LoginEntry -from api.v1.models.users import TerseReturnModel - -async def get_terse(user:LoginEntry, *userIds:int|str) -> dict[str, TerseReturnModel]: - return await Request.send_template( - user, - "get_users_terse_info", - usersList = ";".join(str(i) for i in userIds) - ) diff --git a/app/api/v1/clans_router.py b/app/api/v1/clans_router.py deleted file mode 100644 index 100a09ee..00000000 --- a/app/api/v1/clans_router.py +++ /dev/null @@ -1,308 +0,0 @@ -from os import getenv -from typing_extensions import Annotated -from fastapi import APIRouter, Path, Query, Form, HTTPException, Request as faRequest, status -from datetime import datetime, UTC - -from utils.connection import Request -from api.shared import limiter -from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -from api.v1.models.clans import LogsModel, ClanModel, Roles, ApplicantModel, RolesDisplay, ClanLeaderboardModel, ClanSearchResultModel, SQBTimeBracket, CurrentSQBBracket -from api.v1.models.base import SuccessEmptyDict -from api.v1.backends.clans import getClan, searchClan, getLeaderboard, getLogs, get_sqb_brackets, current_sqb_br, SQB_BRACKET_TIMES - - -squadronId = Annotated[int, Path(title="The squadron's ID", gt=0)] -gaijinUserId = Annotated[int, Path(title="The user's ID", gt=0)] - -router = APIRouter( - prefix="/clans", - tags=["clans"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -@router.post( - "/apply/{clanId}", - summary="Sends an application to the squadron, if allowed", - responses={ - status.HTTP_409_CONFLICT: {"description": "User is already in a squadron"} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def send_application( - request: faRequest, - user: TokenBearer, - clanId: squadronId, - comment: Annotated[str, Query(description="The message sent with the application. Doesn't appear ingame, only through this API, so if the squadron isn't using an API, they won't see it")] -) -> bool: - response = await Request.send_template( - user, - "clan_membership_request", - remove_keys=("cancelRequest"), - _id=clanId, - comments=comment - ) - return response.get("clanTag") is not None - -@router.post( - "/cancelApply", - summary="Cancels the current squadron application", - responses={ - status.HTTP_409_CONFLICT: {"description": "User is already accepted into the squadron. Use the `leave` endpoint instead"} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def unsend_application( - request: faRequest, - user: TokenBearer, - comment: str = "" -) -> bool: - response = await Request.send_template( - user, - "clan_membership_request", - remove_keys=("_id"), - comments=comment, - cancelRequest=True - ) - return response.get("clanTag") is None - -@router.post( - "/leave", - summary="Leaves the current squadron" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def leave_squadron( - request: faRequest, - user: TokenBearer -) -> bool: - response = await Request.send_template( - user, - "clan_leave" - ) - return response.get("clanTag") is None - -@router.get( - "/applicants/{clanId}", - summary="Gets the currently applying members" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_applicants( - request: faRequest, - user: ServerBearer, - clanId: squadronId -) -> list[ApplicantModel]: - clanData = await getClan(user, clanId) - applicants = clanData.get("applicants") - if applicants is None: - return [] - - return applicants -@router.post( - "/accept/{userId}", - responses={ - status.HTTP_200_OK: { - "model": SuccessEmptyDict, - "description": "Successfully accepted the applicant", - }, - status.HTTP_403_FORBIDDEN: { - "description": "You do not have permission to accept applicants" - }, - status.HTTP_404_NOT_FOUND: { - "description": "The given user is not an applicant" - } - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def accept_applicant( - request: faRequest, - user: TokenBearer, - userId: gaijinUserId, - role:RolesDisplay = RolesDisplay.PRIVATE -): - squadronId = await user.entry.getSquadronId() - if squadronId is None: - raise HTTPException(403, "User is not part of a squadron") - return await Request.send_template( - user, - "clan_accept_membership_request", - userId = userId, - _id = squadronId, - role=Roles[role.name.upper()].value - ) - -@router.post( - "/reject/{userId}", - responses={ - status.HTTP_200_OK: {"model": SuccessEmptyDict, "description":"Successfully rejected user"}, - status.HTTP_404_NOT_FOUND: {"description":"Applicant could not be found"}, - status.HTTP_403_FORBIDDEN: {"description":"You do not have permission to reject applicants"} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def reject_applicant( - request: faRequest, - user: TokenBearer, - userId: gaijinUserId, - message: Annotated[str, Query(title="Message to include alongside rejection")] = "", -): - squadronId = await user.entry.getSquadronId() - if squadronId is None: - raise HTTPException(403, "User is not part of a squadron") - return await Request.send_template( - user, - "clan_reject_membership_request", - userId = userId, - _id = squadronId, - comments = message - ) - -@router.post( - "/role/{userId}", - summary="Set a member's role", - description="Requires `Deputy` or `Commander` level in squadron", - responses={ - status.HTTP_200_OK: {"model": SuccessEmptyDict}, - status.HTTP_403_FORBIDDEN: {"description": "You do not have the required permissions"} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def change_role( - request: faRequest, - user: TokenBearer, - userId: gaijinUserId, - role: Annotated[RolesDisplay, Query(title="The role to assign")], -): - role = Roles[role.name] - return await Request.send_template( - user, - "clan_change_member_role", - userid = userId, - role = role.value - ) - -@router.post( - "/kick/{userId}", - summary="Kicks the given user", - description="Requires either `Officer`, `Deputy` or `Commander` rank to remove someone else" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def kick_member( - request: faRequest, - user: TokenBearer, - userId: gaijinUserId, - reason: Annotated[str, Form(title="The reason for kicking")] = "", -): - return await Request.send_template( - user, - "clan_dismiss_member", - userid = userId, - comments = reason - ) - -@router.get( - "/logs/{clanId}", - summary="Gets the squadron logs" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_clan_logs( - request: faRequest, - user: OptionalAuth, - clanId: squadronId, - limit: Annotated[int, Query(title="The max ammount to get at once", gt=0, le=50)] = 10, - fromEntry: Annotated[str, Query(title="The last call's 'lastLog' value to begin searching from")] = None, -) -> LogsModel: - return await getLogs(user, clanId, limit, fromEntry) - -@router.get("/search", summary="Search for squadron") -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_clan_search( - request: faRequest, - user: ServerBearer, - clanName: Annotated[str, Query(title="Squadron name to look up")] = None, - clanTag: Annotated[str, Query(title="Squadron tag to look up")] = None, - limit: Annotated[int, Query(title="Amount of squadrons to return", gt=0, lt=50)] = 10, - page: Annotated[int, Query(title="The page to display. Count starts from 0", ge=0)] = 0, -) -> list[ClanSearchResultModel]: - return await searchClan(user, clanName=clanName, clanTag=clanTag, limit=limit, page=page) - -@router.get( - "/leaderboard", - summary="Gets the leaderboard of squadrons.", -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_clan_leaderboard( - request: faRequest, - user: ServerBearer, - limit: Annotated[int, Query(title="The max amount to get at once", gt=0, le=50)] = 20, - page: Annotated[int, Query(title="The page to look up. Starts from 0.", ge=0)] = 0, -) -> list[ClanLeaderboardModel]: - return await getLeaderboard(user, limit, page) - -@router.get( - "/leaderboard/{clanId}", - summary="Gets the leaderboard position of a given squadron.", - responses={ - 404: {"description": "Clan not found"} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_clan_leaderboard_position( - request: faRequest, - user: ServerBearer, - clanId: Annotated[int, Path(title="The squadron's ID")], -) -> ClanLeaderboardModel: - r = await getLeaderboard(user, clanId=clanId) - - if r is None or len(r) < 1: - raise HTTPException(404, "Clan not found") - - return r[0] - -@router.get( - "/sqb", - summary="Returns the current season's SQB/SRB battle rating brackets", - description="Data is obtained from the forum post, if this data is outdated here, it is probably outdated there" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_brackets( - request: faRequest, - user: ServerBearer -) -> tuple[SQBTimeBracket]: - return await get_sqb_brackets() - -@router.get( - "/sqb/current", - summary="Returns the current SQB/SRB bracket, and if one is open, also returns it's start and end time", - description="Data is obtained from the forum post, if this data is outdated here, it is probably outdated there" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_current_br( - request: faRequest, - user: ServerBearer -) -> CurrentSQBBracket: - bracket = await current_sqb_br() - - rn = datetime.now(UTC) - for start, end in SQB_BRACKET_TIMES: - start_dt = datetime.combine(rn.date(), start, UTC) - end_dt = datetime.combine(rn.date(), end, UTC) - if start_dt <= rn <= end_dt: - return { - "bracket": bracket, - "start": start_dt, - "end": end_dt - } - return { - "bracket": bracket - } - -@router.get( - "/{clanId}", - summary="Gets data about the given squadron" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") -async def get_clan( - request: faRequest, - user: ServerBearer, - clanId: Annotated[int, Path(title="The squadron's ID")], -) -> ClanModel: - return await getClan(user, clanId) diff --git a/app/api/v1/general_router.py b/app/api/v1/general_router.py deleted file mode 100644 index 93491bb4..00000000 --- a/app/api/v1/general_router.py +++ /dev/null @@ -1,41 +0,0 @@ -from os import getenv -from typing_extensions import Annotated -from typing import Literal -from fastapi import APIRouter, Query, Request, WebSocket, status - -from utils import newsManager -from utils.news import NewsEntry -from api.shared import limiter -from api.v1.backends.shared import ServerBearer, IpString -from api.v1.backends.general import getLatestGameVer - - -router = APIRouter( - tags=["general"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -@router.get("/latestGameVersion", summary="Get latest game version") -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "general") -async def get_latest_game_ver( - request: Request, user: ServerBearer, - branch: Annotated[Literal["dev", "dev-stable"], Query(title="The game version to get")] = None, -) -> IpString: - return await getLatestGameVer(branch) - -@router.get( - "/news", - summary="Gets the latest news from gaijin", - description="Puts the pinned news first (Current update changelog + latest big news). There is additionally a `/v1/news_ws` websocket, that doesn't require any authentication, and provides the news through there. This websocket is the single exception to the 'token auth everywhere' rule. Websocket returns the same format for an entry like this endpoint" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "general") -async def get_news(request: Request, user: ServerBearer) -> list[NewsEntry]: - return await newsManager.fetch() - -@router.websocket( - "/news_ws", - name="News stream" -) -async def news_ws(websocket: WebSocket): - async for msg in newsManager.websocket_mgr.connect(websocket): - pass # Ignore all messages diff --git a/app/api/v1/marketplace_router.py b/app/api/v1/marketplace_router.py deleted file mode 100644 index 69fc79de..00000000 --- a/app/api/v1/marketplace_router.py +++ /dev/null @@ -1,347 +0,0 @@ -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 - -from utils.connection import Request -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.models.base import GenericEmptyResponse - -router = APIRouter( - prefix="/market", - tags=["marketplace"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -@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"} - } -) -@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 -): - 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 - - 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.post( - "/buy/{itemHash}", - 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: - 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") - -@router.get( - "/inventory", - summary="Gets the account's inventory contents" -) -@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] - -@router.get( - "/balance", - summary="Gets the account's balance" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -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") - -@router.get( - "/search", - summary="Searches the marketplace for a given item", - responses={ - status.HTTP_200_OK: {"model": list[ItemModel]} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -async def searchItem( - request: faRequest, user: ServerBearer, - name: Annotated[str, Query(title="The item to search for. Leave empty to search for ALL units")] = "", - 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 - -@router.get( - "/{itemHash}/orders/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")], -): - pairData = await Request.send_template( - user, - "cln_get_pair_stat", - market_name = itemHash - ) - if "response" in pairData: - pairData = pairData["response"] - else: - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") - - ret_data = { - "short":[], - "whole":[] - } - for i in pairData["1h"]: - ret_data["short"].append({ - "timestamp": i[0], - "price": i[1]/10000, - "transactions_count": i[2] - }) - for i in pairData["1d"]: - ret_data["whole"].append({ - "timestamp": i[0], - "price": i[1]/10000, - "transactions_count": i[2] - }) - return ret_data - -@router.get( - "/{itemHash}/orders", - summary="Retrieves marketplace data about the given item" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -async def get_item_orders( - request: faRequest, user: ServerBearer, - itemHash: Annotated[str, Path(title="The item to look up")], -): - books_brief = await Request.send_template( - user, - "cln_books_brief", - market_name = itemHash - ) - if "response" in books_brief: - books_brief = books_brief["response"] - else: - raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") - - ret_data = {} - ret_data["buy_orders"] = books_brief["depth"]["BUY"] - ret_data["sell_orders"] = books_brief["depth"]["SELL"] - ret_data["buy_prices"] = [{"price":i[0]/10000,"amount":i[1]} for i in books_brief["BUY"]] - ret_data["sell_prices"] = [{"price":i[0]/10000,"amount":i[1]} for i in books_brief["SELL"]] - return ret_data - -@router.get( - "/{itemHash}/view", - summary="Views the item ingame" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -async def view_item( - request: faRequest, user: TokenBearer, - itemHash: Annotated[str, Path(title="The item's hash to view")], -) -> bool: - 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, - "market_view_item1", - params = { - "appId": "1067", - "assetClass": [ - { - "name": hashData[0]["name"], - "value": hashData[0]["value"] - } - ] - } - ) - await Request.send_template( - user, - "market_view_item2" - ) - return resp.get("status") == "ok" - -@router.get( - "/{itemHash}", - summary="Gets metadata about the given item" -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") -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 diff --git a/app/api/v1/models/auth.py b/app/api/v1/models/auth.py deleted file mode 100644 index 5e44fc32..00000000 --- a/app/api/v1/models/auth.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Literal -from pydantic import Field, BaseModel - -class Login: # /v1/login endpoint - class LoginResponse(BaseModel): - status: Literal["OK"] = "OK" - token: str - user_id: int - class Fail2FAResponse(BaseModel): - types: set[Literal["GaijinPass", "Email", "WTR"]] = Field(description="The types of 2FA that the account has enabled.") - status: Literal["2STEP"] = "2STEP" - requestId: str = Field(description="The requestId to be used in the 2FA process") - userId: int = Field(description="The userId of the account") -class LoginToken: # /v1/login-token endpoint - class LoginTokenResponse(BaseModel): - expires: int = Field(description="UNIX timestamp of the new token expiry") - status: Literal["OK"] = "OK" - class LoginFailResponse(BaseModel): - status: Literal["FAIL"] = "FAIL" - detail: str diff --git a/app/api/v1/models/base.py b/app/api/v1/models/base.py deleted file mode 100644 index ac4eccb7..00000000 --- a/app/api/v1/models/base.py +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Literal -from pydantic import BaseModel - -class SuccessEmptyDict(BaseModel): - status:Literal["success"] = "success" -class GenericEmptyResponse(BaseModel): - success: bool diff --git a/app/api/v1/models/general.py b/app/api/v1/models/general.py deleted file mode 100644 index 104159e0..00000000 --- a/app/api/v1/models/general.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Literal -from pydantic import BaseModel, Field -from datetime import datetime - -# Currently unused diff --git a/app/api/v1/models/marketplace.py b/app/api/v1/models/marketplace.py deleted file mode 100644 index 2f295f77..00000000 --- a/app/api/v1/models/marketplace.py +++ /dev/null @@ -1,35 +0,0 @@ -from pydantic import BaseModel, Field -from ..backends.shared import IntString - -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 - }, - ]) diff --git a/app/api/v1/models/replay.py b/app/api/v1/models/replay.py deleted file mode 100644 index c10ed674..00000000 --- a/app/api/v1/models/replay.py +++ /dev/null @@ -1,118 +0,0 @@ -from typing import Literal -from pydantic import BaseModel, Field -from ..backends.shared import IntString, IpString - -class SearchModel(BaseModel): - class ReplayEntry(BaseModel): - class PlayerEntry(BaseModel): - userId: IntString - name: str - fakeName: str - sessionId: str - sessionIdHex: str - policy: int - title: str - missionName: str - missionDescription: str - tournamentName: str - startTime: int - endTime: int - totalViews: int - statisticGroup: str - url: str - version: int - teamNames: None - gameVersion: IpString - clanBattle: bool - isCompleted: bool - isNewbies: bool - gameType: str - gameMode: str - players: dict[Literal["team_1", "team_2"], list[PlayerEntry]] - - class PaginationModel(BaseModel): - nextNum: int - first_page: int - items: list[int] - sumPages: int - offset: int - limit: int - items: list[ReplayEntry] - count: int - total_count: int - pagination: PaginationModel - partsCount: int - visible: int - id: str -class DataModel(BaseModel): - status: Literal["OK"] = "OK" - 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"]) - 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 - - team1: dict[str, UserModel] - team2: dict[str, UserModel] - - matchId: int - match: MatchModel - results: ResultsModel -class ReplayNotFoundModel(BaseModel): - detail: str = "Replay could not be found" - status: Literal["NOT_FOUND"] = "NOT_FOUND" diff --git a/app/api/v1/models/units.py b/app/api/v1/models/units.py deleted file mode 100644 index 104159e0..00000000 --- a/app/api/v1/models/units.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Literal -from pydantic import BaseModel, Field -from datetime import datetime - -# Currently unused diff --git a/app/api/v1/models/users.py b/app/api/v1/models/users.py deleted file mode 100644 index 74d14b90..00000000 --- a/app/api/v1/models/users.py +++ /dev/null @@ -1,304 +0,0 @@ -from __future__ import annotations -from typing import Literal, Optional -from pydantic import BaseModel, Field -from ..backends.shared import IntString -from enum import Enum -from bisect import bisect_right -from .clans import PLATFORM_NAMES - -COUNTRIES = Literal[ - "country_usa", - "country_germany", - "country_ussr", - "country_britain", - "country_japan", - "country_china", - "country_italy", - "country_france", - "country_sweden", - "country_israel" -] -SIMPLE_COUNTRIES = Literal[ - "usa", - "germany", - "ussr", - "britain", - "japan", - "china", - "italy", - "france", - "sweden", -] -GAMEMODES = Literal[ - "arcade", - "realistic", - "hardcore" -] -SPECIFIC_GAMEMODES = Literal[ - "air_arcade", - "air_realistic", - "air_simulation", - "tank_arcade", - "tank_realistic", - "tank_simulation", - "test_ship_arcade", - "test_ship_realistic", - "helicopter_arcade" -] -VEHICLE_TYPES = Literal[ - "fighter", - "bomber", - "assault", - "tank", - "heavy_tank", - "tank_destroyer", - "SPAA", - "ship", - "torpedo_boat", - "gun_boat", - "torpedo_gun_boat", - "submarine_chaser", - "destroyer", - "naval_ferry_barge", - "helicopter", - "cruiser", - "human" -] - -class getUserDirectModel(BaseModel): - class summaryModel(BaseModel): - class summaryGameModeModel(BaseModel): - class vehicleModel(BaseModel): - timePlayed: int - air_kills: int - ground_kills: int - naval_kills: int - respawns: int - missionsComplete: int - victories: int - fighter:vehicleModel - bomber: vehicleModel - assault: vehicleModel - tank: vehicleModel - heavy_tank: vehicleModel - tank_destroyer: vehicleModel - SPAA: vehicleModel - ship: vehicleModel - torpedo_boat: vehicleModel - gun_boat: vehicleModel - torpedo_gun_boat: vehicleModel - submarine_chaser: vehicleModel - destroyer: vehicleModel - naval_ferry_barge: vehicleModel - helicopter: vehicleModel - cruiser: vehicleModel - human: vehicleModel - single_played: dict[GAMEMODES, summaryGameModeModel] - pvp_played: dict[GAMEMODES, summaryGameModeModel] - skirmish_played: dict[GAMEMODES, summaryGameModeModel] - campaign_played: dict[GAMEMODES, summaryGameModeModel] - dynamic_played: dict[GAMEMODES, summaryGameModeModel] - 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 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 - - background: str - 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): - 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, - 1097700, 1192900, 1290000, 1388900, 1489600, 1592100, 1696500, 1802700, 1910700, 2020500, - 2132200, 2245700, 2361000, 2478100, 2597100, 2717900, 2840500, 2964900, 3091200, 3219300, - 3349200, 3480900, 3614500, 3749900, 3887100, 4026100, 4167000, 4309700, 4454200, 4600500, - 4748700, 4898700, 5050500, 5204100, 5359600, 5516900, 5676000, 5836900, 5999600, 6164200, - 6330600, 6498800, 6668800, 6840700, 7014400, 7189900, 7367200, 7546400, 7727400, 7910200, - 8094800, 8281300, 8469600, 8659700, 8851600, 9045400, 9241000, 9438400, 9637600, 9838700, - 10041600, 10246300, 10452800, 10661200, 10871400, 11083400, 11297200, 11512900, 11730400, 11949700, - 12170800, 12393800, 12618600, 12845200, 13073600, 13303900, 13536000, 13769900, 14005600, 14243100, - 14482500 -) - -class PlayerRank(Enum): - ROOKIE = 0, 11, "Rookie" - LIEUTENANT = 12, 23, "Lieutenant" - CAPTAIN = 24, 35, "Captain" - MAJOR = 36, 47, "Major" - COLONEL = 48, 59, "Colonel" - COMMANDER = 60, 71, "Commander" - COMMODORE = 72, 83, "Commodore" - GENERAL = 84, 99, "General" - MARSHAL = 100, 100, "Marshal" - - def __new__(cls, rank_from: int, rank_to: int, label: str): - obj = object.__new__(cls) - obj._value_ = rank_from # `.value` == rank_from - obj.rank_from = rank_from - obj.rank_to = rank_to - obj.label = label - return obj - - @classmethod - def from_level(cls, level: int) -> "PlayerRank": - if level < 0: - level = 0 - for rank in cls: - if rank.rank_from <= level <= rank.rank_to: - return rank - raise ValueError(f"No rank for level {level}") - - @staticmethod - def get_level(exp: int) -> int: - """Map raw account XP to the numeric player level (0–100).""" - if exp < 0: - exp = 0 - return bisect_right(USER_RANK, exp) - 1 diff --git a/app/api/v1/replays_router.py b/app/api/v1/replays_router.py deleted file mode 100644 index c124d8b3..00000000 --- a/app/api/v1/replays_router.py +++ /dev/null @@ -1,104 +0,0 @@ -from os import getenv -from typing_extensions import Annotated -from fastapi import APIRouter, Path, Request as faRequest, Query, status - -from utils.replayParser import Replay -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 - - -router = APIRouter( - prefix="/replay", - tags=["replays"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -""" -@router.get( - "/search", - summary="Searches for replays based on given parameters", - responses={ - status.HTTP_200_OK: {"model": SearchModel}, - status.HTTP_403_FORBIDDEN: {"description": "The token has no associated `identity_sid` value associated, required for replay lookup. Get one from `/v1/get-sid`"}, - } -) -""" # FIXME: Temporarily removed due to issues with identity_sid generation -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") -async def search_replays( - request: faRequest, - user: TokenBearer, - uid: Annotated[ - int, - Query(title="The UID of the user to search replays for") - ] = None, - nickname: Annotated[ - str, - Query(title="The nickname of the user to search replays for") - ] = None, - gameType: Annotated[ - ReplayType, - Query( - title="The type of game to search replays for", - description="If not provided, will search for random battles", - min_length=1 - ) - ] = ReplayType.RANDOM_BATTLE, - techType: Annotated[ - ReplayTechType, - Query( - title="The type of tech to search replays for", - description="If not provided, will search for all tech types", - min_length=1 - ) - ] = ReplayTechType.ALL, - mode: Annotated[ - set[ReplayMode] | None, - Query( - title="The game modes to filter by", - description="If not provided, will search for all game modes", - ) - ] = None, - limit: Annotated[ - int, - Query( - title="The maximum number of replays to return", - description="Must be between 1 and 100", - ge=1, - le=100 - ) - ] = 25, - page: Annotated[ - int, - Query( - title="The page of results to return", - description="Must be 0 or greater", - ge=0 - ) - ] = 0, -): - return await search_replay(user, uid, nickname, gameType, techType, mode, limit, page) - -@router.get( - "/{replayId}", - summary="Gets data from a specified replay", - responses={ - status.HTTP_200_OK: {"model": DataModel}, - 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) diff --git a/app/api/v1/units_router.py b/app/api/v1/units_router.py deleted file mode 100644 index 8a079f9a..00000000 --- a/app/api/v1/units_router.py +++ /dev/null @@ -1,30 +0,0 @@ -from os import getenv -from typing_extensions import Annotated -from fastapi import APIRouter, Path, Request, status - -from utils import vehicle_cache -from api.shared import limiter -from api.v1.backends.shared import ServerBearer, OptionalAuth, TokenBearer -#from api.models.units import # Currently no models have been implemented - -router = APIRouter( - tags=["units"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}}, - prefix="/units" -) - -@router.get( - "/{vehicleId}", - summary="Gets a specific vehicle's data", - responses={ - status.HTTP_200_OK: {} - } -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "units") -async def getVehicle( - request: Request, - user: ServerBearer, - vehicleId: Annotated[str, Path(title="The vehicle's ID", examples=["saab_jas39e", "yak-7k"])] -): - await vehicle_cache.getVehicle(vehicleId) - pass diff --git a/app/api/v1/users_router.py b/app/api/v1/users_router.py deleted file mode 100644 index 0b58709e..00000000 --- a/app/api/v1/users_router.py +++ /dev/null @@ -1,147 +0,0 @@ -from os import getenv -from typing_extensions import Annotated -from fastapi import APIRouter, Path, Query, Request as faRequest, status -from fastapi.responses import JSONResponse -from urllib.parse import unquote - -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 - -router = APIRouter( - prefix="/users", - tags=["users"], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} -) - -@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, - user: ServerBearer, - id: Annotated[list[int], Query( - title="The ID of the users to get information about", - description="Provide multiple IDs to get information about multiple users at once", - min_length=1, - max_length=50) - ], -) -> dict[str, TerseReturnModel]: - """Get terse information about users by their IDs.""" - return JSONResponse(await get_terse(user, *id)) - -@router.get( - "/self", - summary="Get metadata about the logged in user", - responses={ - 200: {"model": SelfUserDataModel} - }, - response_model=SelfUserDataModel -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") -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 - -@router.get("/{userid}", summary="Get user by ID") -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") -async def get_user_direct( - 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 - ) - ) - -@router.get( - "/search/{nick}", - summary="Get users by name", - responses={} -) -@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") -async def get_users_search( - request: faRequest, - user: ServerBearer, - nick: Annotated[str, Path(title="The nickname to search for")], - limit: Annotated[int, Query(title="How many users to retrieve", ge=2, le=50)] = 10, -) -> dict[str, TerseReturnModel]: - response = await Request.send_template( - user, - "find_users_by_nick_prefix", - nick = unquote(nick), - maxCount = limit - ) - - terseInfo = await get_terse(user, *list(response.keys())) - return JSONResponse(terseInfo) diff --git a/app/utils/__init__.py b/app/utils/__init__.py deleted file mode 100644 index 05c751ca..00000000 --- a/app/utils/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from utils.auth import UserAuth, AuthenticationError, ServerAuth -users_auth = UserAuth() -server_auth: ServerAuth | None = None # Start is deferred to app lifetime - -from utils.vehicleParser import Vehicles -vehicle_cache = Vehicles() - -from utils.news import NewsManager -newsManager = NewsManager() diff --git a/app/utils/connection/network.py b/app/utils/connection/network.py deleted file mode 100644 index ce066e5e..00000000 --- a/app/utils/connection/network.py +++ /dev/null @@ -1,104 +0,0 @@ -from aiohttp import ClientResponse, ClientSession -from aiohttp.cookiejar import DummyCookieJar -from fastapi.concurrency import asynccontextmanager -from fastapi import HTTPException -from asyncio import Lock, Event -from typing import Any, Literal, overload -from json import loads - -class NetworkError(HTTPException): pass - -__session: ClientSession | None = None -__closing = False -__active_ops = 0 -__active_ops_done = Event() -__active_ops_done.set() -__lock = Lock() - -@asynccontextmanager -async def post(url:str, **kwargs): - async with request("POST", url, **kwargs) as resp: - yield resp - -@asynccontextmanager -async def get(url:str, **kwargs): - async with request("GET", url, **kwargs) as resp: - yield resp - -@asynccontextmanager -async def request(method:str, url:str, **kwargs): - async with operation() as session: - async with session.request(method, url, **kwargs) as resp: - resp.raise_for_status() - yield resp - -@asynccontextmanager -async def operation(): - session = await _enter_op() - try: - yield session - finally: - await _exit_op() - -async def start(): - global __session, __closing - async with __lock: - if __session is not None and not __session.closed: - return - __closing = False - __session = ClientSession(headers={"User-Agent": "ThunderAPI/1.0"}, cookie_jar=DummyCookieJar()) - -async def close(): - global __closing, __session - async with __lock: - __closing = True - - await __active_ops_done.wait() - - async with __lock: - if __session is not None and not __session.closed: - await __session.close() - __session = None - -#region handle_response -@overload -async def handle_response(resp: ClientResponse, autoconvert: Literal[True] = True) -> dict[str, Any]: ... -@overload -async def handle_response(resp: ClientResponse, autoconvert: Literal[False]) -> bytes: ... -@overload -async def handle_response(resp: ClientResponse, autoconvert: bool = True) -> dict[str, Any]|bytes: ... -async def handle_response(resp:ClientResponse, autoconvert:bool = True) -> dict[str, Any]|bytes: - content = await resp.read() - - if resp.status >= 400: - raise NetworkError(400, f"Request failed: {resp.status}") - if content.startswith(b"!ERROR"): - raise NetworkError(400, f"Request failed: {content}") - - if autoconvert: - return loads(content) - return content -#endregion - -async def _enter_op(): - global __active_ops - async with __lock: - if __closing: - raise RuntimeError("NetworkManager is shutting down") - - if __session is None or __session.closed: - raise RuntimeError("NetworkManager is not started") - - __active_ops += 1 - __active_ops_done.clear() - - return __session - -async def _exit_op(): - global __active_ops - async with __lock: - __active_ops -= 1 - - if __active_ops <= 0: - __active_ops = 0 - __active_ops_done.set() diff --git a/app/utils/geo.py b/app/utils/geo.py deleted file mode 100644 index 0b09b729..00000000 --- a/app/utils/geo.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Library code for geolocation""" -from os import replace as file_replace -from asyncio import to_thread -from geoip2.database import Reader -from geoip2.models import City -from geoip2.errors import AddressNotFoundError -from asyncio import sleep -from github import Github -from datetime import datetime, UTC -from zoneinfo import ZoneInfo -from threading import Lock -from logging import getLogger -from config import GEOLITE - -_logger = getLogger(__name__) -_reader = None -_lock = Lock() -_github_repo = None - -def lookup_city(ip: str) -> City | None: - global _reader - with _lock: - if _reader is None: - if not GEOLITE.DB.exists(): - return None - _reader = Reader(str(GEOLITE.DB)) - try: - return _reader.city(ip) - except AddressNotFoundError: - return None -def lookup_utc_offset(zone: str) -> int | None: - """Converts an IANA spec timezone into an UTC offset""" - rn = datetime.now(UTC) - utcdiff = ZoneInfo(zone).utcoffset(rn) - return utcdiff.total_seconds() // (60*60) - -async def update_db(): - global _reader, _lock, _github_repo - - while _github_repo is None: - try: - _github_repo = await to_thread(lambda: Github().get_repo("P3TERX/GeoLite.mmdb")) - except Exception: - _logger.error(f"Failed to get GeoLite repository, retrying in 1 minute") - await sleep(60) - - while True: - try: - latest = await to_thread(_github_repo.get_latest_release) - if not GEOLITE.HASH.exists(): - GEOLITE.HASH.write_text("0") - if not GEOLITE.DB.exists() or latest.id != int(GEOLITE.HASH.read_text()): - for asset in latest.assets: - if asset.name != "GeoLite2-City.mmdb": - continue - await to_thread(lambda: asset.download_asset(GEOLITE.TMP)) - with _lock: - file_replace(GEOLITE.TMP, GEOLITE.DB) - GEOLITE.HASH.write_text(str(latest.id)) - if _reader is not None: - _reader.close() - _reader = None - break - else: - _logger.error(f"No file under the name 'GeoLite2-City.mmdb' found under the latest release ({latest.url})\nRetrying in 1 hour") - await sleep(1*60*60) - continue - await sleep(12*60*60) - except Exception: - _logger.exception("Failed to get repository's latest release, retrying in 5 minutes") - await sleep(5*60) - continue diff --git a/app/utils/helper.py b/app/utils/helper.py deleted file mode 100644 index 4e15f6da..00000000 --- a/app/utils/helper.py +++ /dev/null @@ -1,51 +0,0 @@ -from datetime import datetime -from fastapi import HTTPException -from typing import Any, Callable -from collections.abc import Iterable - -def dtToTimestamp(dt:datetime) -> int: - return int(dt.timestamp()) -def dtToTimestampMs(dt:datetime) -> int: - return int(dt.timestamp()*1000) - -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 - - 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) - return obj - - new_val = self.convert(obj.pop(self.key)) - - if not self.rm: - obj[self.new_name] = new_val - return obj - - @staticmethod - def run_all(obj:dict[str, Any], changes:Iterable[Keymod]): - for change in changes: - obj = change.run(obj) - return obj diff --git a/app/utils/news.py b/app/utils/news.py deleted file mode 100644 index b0a56256..00000000 --- a/app/utils/news.py +++ /dev/null @@ -1,338 +0,0 @@ -from asyncio import Task, Lock, CancelledError -from logging import getLogger, Logger -from aiohttp.client_exceptions import ClientResponseError -from datetime import datetime, time, UTC -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 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 - -fasterUpdate = ( - time(hour=11, minute=0, tzinfo=UTC), # Start - time(hour=21, minute=30, tzinfo=UTC) # End -) -excludeFastWeekdays = (5,6) # Zero-indexed number of weekday -fastCheck = 5*60 # Every 5 mins -slowCheck = 30*60 # Every 30 mins - -@dataclass(slots=True) -class NewsEntry: - class ImportanceLevel(IntEnum): - REGULAR = 0 - MINOR = 1 - EVENT = 2 - MAJOR = 3 - id:int - anons:str # Short description - title:str # Title - 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 - project:str # Game (100% of the time War Thunder with different version numbers) - type:Literal["news", "changelog"] # Article Type - created:datetime # Article Creation Time - importance:ImportanceLevel = ImportanceLevel.REGULAR - @dataclass(slots=True) - class Image: - src: str - width: int - height: int - @classmethod - def from_json(cls, data:dict[str, Any]): - return cls( - src=data["src"], - width=int(data["width"]), - height=int(data["height"]) - ) - def to_json(self): - return asdict(self) - @classmethod - def from_json(cls, data:dict[str, Any]): - self = cls( - id = int(data['id']), - anons = data['anons'], - title = data['title'], - 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', []), - 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 - def to_json(self): - obj = asdict(self) - obj["created"] = dtToTimestamp(self.created) - obj["importance"] = int(self.importance) - return obj - - def _getImportance(self) -> ImportanceLevel: - title = self.title.lower() - if ( - ( - "Video" in self.tags and - ( - "trailer" in title or - "teaser" in title - ) - ) or - ( - ("Shop" in self.tags or "Event" in self.tags) and - ( - ( - ( - any(i in title for i in ["winter", "summer", "may", "holiday"]) or - ("war thunder" in title and "birthday" in title) - ) and - any(i in title for i in ["sale", "discount", "celebrate"]) - ) or - "black friday" in title - ) - ) or ( - re_search("Meet the “[A-z0-9 ]+” Major Update!", title, IGNORECASE) is not None and self.pinned - ) - ): - return self.ImportanceLevel.MAJOR - if ("Event" in self.tags and "pages" not in title): - return self.ImportanceLevel.EVENT - if ("discount" in title and ("Shop" in self.tags or "Special" in self.tags)): - return self.ImportanceLevel.MINOR - return self.ImportanceLevel.REGULAR - -_changelog_maintenance: bool = False -_news_endpoint_down: bool = False -class NewsManager: - _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 - websocket_mgr: WebsocketManager - - 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.__logger.debug("NewsAPI initialized") - - async def mainloop(self): - while True: - try: - if (latest := await self._get_new_news()): - self.__logger.debug("News 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 news fetching") - - try: - changelogs = await self.fetchChangelogs() - - 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: - raise - except Exception: - self.__logger.exception("An exception occurred during changelog fetching") - - 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) - - pinned.sort(key=lambda x: x.created, reverse=True) - unpinned.sort(key=lambda x: x.created, reverse=True) - combined = pinned + unpinned - return combined - - async def fetchNews(self) -> list[NewsEntry]: - """Gets all the latest news""" - global _news_endpoint_down - news:list[NewsEntry] = [] - try: - async with Network.get(self._API_URL) as response: - if _news_endpoint_down: - self.__logger.info("Gaijin's news endpoint is back online") - _news_endpoint_down = False - data = await response.json() - for item in data["items"]: - news.append(NewsEntry.from_json(item)) - except ClientResponseError: - if not _news_endpoint_down: - self.__logger.error("Gaijin's news endpoint is currently down. Returning emptry until it is back") - _news_endpoint_down = True - return news - async def fetchChangelogs(self) -> list[NewsEntry]: - """Gets the latest changelog""" - global _changelog_maintenance - final_changelogs = [] - try: - async with Network.get(self._CHANGELOG_URL) as resp: - if _changelog_maintenance: - self.__logger.info("Changelog page is no longer under maintenance") - _changelog_maintenance = False - - parsed = BeautifulSoup(await resp.text(), 'html.parser') - changelogs = parsed.select("div.showcase__content-wrapper>div.showcase__item.widget") - if len(changelogs) < 2: - raise RuntimeError("Less, than 2 changelogs found (somehow)") - async def processChangelog(chlog:Tag) -> NewsEntry: - ChLogURL:str = chlog.select_one("a.widget__link")["href"] - content = chlog.select_one("div.widget__content") - title = content.select_one("div.widget__title").get_text(strip=True) - anons = content.select_one("div.widget__comment").get_text(strip=True) - datetext = content.select_one("ul.widget__meta.widget-meta").select_one("li.widget-meta__item.widget-meta__item--right").get_text(strip=True) - date = datetime.strptime(datetext, "%d %B %Y").replace(tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S%z") - del datetext - src = chlog.select_one("div.widget__poster>img").attrs["data-src"] - pinned = chlog.select_one("div.widget__pin") is not None - return NewsEntry.from_json({ - "id":int(ChLogURL.split("/")[-1]), - "anons":anons, - "title":title, - "link":f"https://warthunder.com{ChLogURL}", - "tags":["Update"], - "images":[{ - "src":src, - "width": 0, - "height": 0 - }], - "type":"changelog", - "created":date, - "pinned": pinned - }) - for chlog in changelogs: - final_changelogs.append(await processChangelog(chlog)) - return final_changelogs - except ClientResponseError: - if not _changelog_maintenance: - self.__logger.error("Changelogs page is under maintenance, returning empty until maintenance is over") - _changelog_maintenance = True - return [] - except RuntimeError: - 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: - """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) - return majorChLog - return None - - async def _get_new_changelogs(self, changelogs:list[NewsEntry]): - # i[1:] is the latest actual changelogs - if not changelogs or len(changelogs) <= 1: - return [] - changelogs = changelogs[1:] - - for i, item in enumerate(changelogs): - if item.id == self.lastChangelog: - await self._writeID(changelogs[0], self._IDTYPE.CHANGELOG) - return changelogs[:i] - - # None of the changelogs have been posted yet - await self._writeID(changelogs[0], self._IDTYPE.CHANGELOG) - return [] - async def _get_new_news(self): - news = await self.fetchNews() - - if len(news) == 0: - return [] - - for i, item in enumerate(news): - if item.id == self.lastNews: - await self._writeID(news[0], self._IDTYPE.NEWS) - return news[:i] - - # None of the news have been posted yet - await self._writeID(news[0], self._IDTYPE.NEWS) - return [] - - 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}") - - async with self._lock: - content = loads(NEWS_JSON.read_text()) - content[_type.value[1]] = ID - NEWS_JSON.write_text(dumps(content, indent=4)) - - self.__setattr__(_type.value[1], ID) - - def __calcDelay(self) -> int: - rn = datetime.now(UTC) - weekday = rn.weekday() - rn = rn.timetz() - start, end = fasterUpdate - if start <= rn <= end and weekday not in excludeFastWeekdays: - return fastCheck - return slowCheck diff --git a/app/utils/vehicleParser/__init__.py b/app/utils/vehicleParser/__init__.py deleted file mode 100644 index b765e1ad..00000000 --- a/app/utils/vehicleParser/__init__.py +++ /dev/null @@ -1,62 +0,0 @@ -from __future__ import annotations -from dataclasses import dataclass -from logging import getLogger -from pathlib import Path -from utils.vehicleParser.vehiclesProcessor import Vehicle, Weapon, Sensor -from config import VEHICLES - -_logger = getLogger(__name__) - -class DatabasePaths: - @dataclass(frozen=True, slots=True) - class _dbpaths: - ROOT: Path - VEHICLES: Path - WEAPONS: Path - SENSORS: Path - ALL: Path - - DATABASE:_dbpaths = _dbpaths( - VEHICLES / "database", - VEHICLES / "database" / "units", - VEHICLES / "database" / "weapons", - VEHICLES / "database" / "sensors", - VEHICLES / "database" / "all.json" - ) - GAMEFILES:Path = VEHICLES / "gamefiles" - -class Vehicles: - def __init__(self): - _logger.debug("Vehicles object created") - - async def setup(self): - DatabasePaths.GAMEFILES.mkdir(mode=0o755, exist_ok=True) - - if not (DatabasePaths.GAMEFILES / ".git").exists(): - - _logger.info(f"Set up git repo in {DatabasePaths.GAMEFILES}") - - if (not DatabasePaths.DATABASE.ROOT.exists()): - if (not DatabasePaths.DATABASE.ALL.exists()): - DatabasePaths.DATABASE.ALL.write_text("{}") - - async def getVehicle(self, unit:str) -> Vehicle|None: - try: - vehicle = await Vehicle.from_id(unit) - except LookupError: - return - return vehicle - - async def getWeapon(self, weapon:str) -> Weapon|None: - try: - weapon = Weapon.from_id(weapon) - except LookupError: - return - return weapon - - async def getSensor(self, sensor:str) -> Sensor|None: - try: - sensor = await Sensor.from_id(sensor) - except LookupError: - return - return sensor diff --git a/app/utils/vehicleParser/__main__.py b/app/utils/vehicleParser/__main__.py deleted file mode 100644 index 4617b4f6..00000000 --- a/app/utils/vehicleParser/__main__.py +++ /dev/null @@ -1,20 +0,0 @@ -# This file is purely used for debugging the units database unit -from asyncio import new_event_loop, set_event_loop - -async def runtime(): - from . import Vehicles - vehicles = Vehicles() - #await vehicles.setup() - result = await vehicles.getVehicle("saab_jas39e") - tmp1 = result.get_sensors() - tmp2 = result.get_weapons() - pass # Used for breakpoint - ... -def main(): - loop = new_event_loop() - set_event_loop(loop) - loop.run_until_complete(runtime()) - pass # Used for breakpoint - -if __name__ == '__main__': - main() diff --git a/app/utils/vehicleParser/schema.py b/app/utils/vehicleParser/schema.py deleted file mode 100644 index 2f506a3a..00000000 --- a/app/utils/vehicleParser/schema.py +++ /dev/null @@ -1,287 +0,0 @@ -from enum import StrEnum -from typing import ClassVar - -class _tableColumns(StrEnum): - __table__: ClassVar[str] - - @classmethod - def t(cls) -> str: - return cls.__table__ - @classmethod - def q(cls, column: "_tableColumns") -> str: - return f"{cls.__table__}.{column.value}" - -#region Versioning -class GitVerions(_tableColumns): - __table__ = "git_versions" - - VER = "version" - HASH = "git_hash" -#endregion - -#region Weapons -class Weapons(_tableColumns): - __table__ = "weapons" - - NAME = "name" - TYPE = "type" -class Ammo(_tableColumns): - __table__ = "ammo" - - WEAPON = "weapon" - AMMO_INDEX = "ammo_index" - NAME = "name" - TYPE = "type" - CALIBER = "caliber" - MASS = "mass" - SPEED = "speed" - MAX_DISTANCE = "max_distance" - EXPLOSIVE_TYPE = "explosive_type" - EXPLOSIVE_MASS = "explosive_mass" -#endregion - -#region Sensors -class Sensors(_tableColumns): - __table__ = "sensors" - - NAME = "name" - TYPE = "type" - MAX_TGT = "max_targets" - MSL_AIM_LEAD = "missile_aim_lead" -class Sensor_signals(_tableColumns): - __table__ = "sensor_signals" - - SENSOR = "sensor" - MODE = "mode" - GROUNDCLUTTER = "ground_clutter" - AIRCRAFT_AS_TGT = "aircraft_as_target" - IFF = "iff" - TGT_ID = "target_id" - MIN_DIST = "min_distance" - MAX_DIST = "max_distance" - MIN_PD_SPD = "min_doppler_speed" - MAX_PD_SPD = "max_doppler_speed" - RANGEFINDER = "rangefinder" -class Sensor_scan_patterns(_tableColumns): - __table__ = "sensor_scan_patterns" - - SENSOR = "sensor" - NAME = "name" - TYPE = "type" - AZ_MIN = "azimuthMin" - AZ_MAX = "azimuthMax" - EL_MIN = "elevationMin" - EL_MAX = "elevationMax" - ROLL_STAB_LIMIT = "roll_stab_limit" - PITCH_STAB_LIMIT = "pitch_stab_limit" - PATTERN = "pattern" -class Sensor_unitId(_tableColumns): - __table__ = "sensor_unit_id" - - SENSOR = "sensor" - TGT_NAME = "target_name" -#endregion - -#region Units -class Units(_tableColumns): - __table__ = "units" - - UNIT = "id" - COUNTRY = "country" - TYPE = "type" - RELEASE = "release_date" - VER = "version" - RANK = "rank" - EVENT = "event" - CREW_CNT = "crew_count" - VISIBILITY = "visibility" - HULL_ARMOR = "hull_armor" - TURRET_ARMOR = "turret_armor" - MASS = "mass" - REQUIRED_VEHICLE = "required_vehicle" - HAS_CUSTOMIZABLE_WEAPONS = "has_customizable_weapons" - DATA_VER = "data_version" -class UnitSubtypes(_tableColumns): - __table__ = "unit_subtypes" - - UNIT = "unit" - TYPE = "type" -class UnitBattleratings(_tableColumns): - __table__ = "unit_battleratings" - - UNIT = "unit" - ARCADE = "arcade" - REALISTIC = "realistic" - REALISTIC_G = "realistic_ground" - SIMULATOR = "simulator" - SIMULATOR_G = "simulator_ground" -class UnitEconomy(_tableColumns): - __table__ = "unit_economy" - - UNIT = "unit" - IS_PREMIUM = "is_premium" - IS_PACK = "is_pack" - IS_MARKETPLACE = "is_marketplace" - IS_SQUADRON = "is_squadron" - PRICE = "price" - RP_COST = "rp_cost" - GE_COST = "ge_cost" - TRAIN_COST = "train_cost" - EXPERT = "expert_cost" - ACE_GE = "ace_cost_ge" - ACE_RP = "ace_cost_rp" - SL_MULT_A = "sl_mul_arcade" - SL_MULT_R = "sl_mul_realistic" - SL_MULT_S = "sl_mul_simulator" - EXP_MULT = "exp_mult" - REPAIR_T_A = "repair_time_arcade" - REPAIR_T_R = "repair_time_realistic" - REPAIR_T_S = "repair_time_simulator" - REPAIR_TNC_A = "repair_time_no_crew_arcade" - REPAIR_TNC_R = "repair_time_no_crew_realistic" - REPAIR_TNC_S = "repair_time_no_crew_simulator" - REPAIR_C_A = "repair_cost_arcade" - REPAIR_C_R = "repair_cost_realistic" - REPAIR_C_S = "repair_cost_simulator" - REPAIR_CPM_A = "repair_cost_per_min_arcade" - REPAIR_CPM_R = "repair_cost_per_min_realistic" - REPAIR_CPM_S = "repair_cost_per_min_simulator" - REPAIR_CFU_A = "repair_cost_full_upgraded_arcade" - REPAIR_CFU_R = "repair_cost_full_upgraded_realistic" - REPAIR_CFU_S = "repair_cost_full_upgraded_simulator" -class UnitEngines(_tableColumns): - __table__ = "unit_engines" - - UNIT = "unit" - HP_A = "hp_ab" - HP_RS = "hp_rb_sb" - MAX_RPM = "max_rpm" - MIN_RPM = "min_rpm" - MAX_SPEED_A = "max_speed_ab" - MAX_RSPEED_A = "max_reverse_speed_ab" - MAX_SPEED_RS = "max_speed_rb_sb" - MAX_RSPEED_RS = "max_reverse_speed_rb_sb" -class UnitModifications(_tableColumns): - __table__ = "unit_modifications" - - UNIT = "unit" - NAME = "name" - TIER = "tier" - REPAIR_COEFF = "repair_coeff" - PRICE = "price" - RP_COST = "rp_cost" - GE_COST = "ge_cost" - REQ_MOD = "required_modification" - MOD_CLASS = "mod_class" - ICON = "icon" -class UnitNV(_tableColumns): - __table__ = "unit_nv" - - UNIT = "unit" - COMMANDER = "commander" - DRIVER = "driver" - PILOT = "pilot" - SIGHT = "sight" - TGT_POD = "tgt_pod" - GUNNER = "gunner" -class UnitThermal(_tableColumns): - __table__ = "unit_thermal" - - UNIT = "unit" - COMMANDER = "commander" - DRIVER = "driver" - PILOT = "pilot" - SIGHT = "sight" - TGT_POD = "tgt_pod" - GUNNER = "gunner" -class UnitComputers(_tableColumns): - __table__ = "unit_ballistic_computer" - - UNIT = "unit" - GUN_CCIP = "gun_ccip" - TURRET_CCIP = "turret_ccip" - BOMBS_CCIP = "bombs_ccip" - ROCKET_CCIP = "rocket_ccip" - GUN_CCRP = "gun_ccrp" - TURRET_CCRP = "turret_ccrp" - BOMBS_CCRP = "bombs_ccrp" - ROCKET_CCRP = "rocket_ccrp" - LASER_DESIGNATOR = "laser_designator" - POI_DESIGNATOR = "poi_designator" - POI_MEM = "poi_memory" - AIMING_POINT_MEM = "aiming_point_memory" - GYRO_SIGHT = "gyro_sight" - -class UnitAero(_tableColumns): - __table__ = "unit_aerodynamics" - - UNIT = "unit" - LENGTH = "length" - WINGSPAN = "wingspan" - WING_AREA = "wing_area" - EMPTY_WEIGHT = "empty_weight" - MAX_TAKEOFF_WEIGHT = "max_takeoff_weight" - MAX_ALTITUDE = "max_altitude" - TURN_TIME = "turn_time" - RUNWAY_LENGTH_REQ = "runway_length_req" - MAX_SPEED_AT_ALTITUDE = "max_speed_at_altitude" - -class UnitPresets(_tableColumns): - __table__ = "unit_presets" - - UNIT = "unit" - NAME = "name" -class UnitPresetsWeapons(_tableColumns): - __table__ = "unit_presets_weapons" - - PRESET = "preset" - WEAPON = "weapon" - COUNT = "count" -class UnitCustomizablePresetsMeta(_tableColumns): - __table__ = "unit_customizable_presets_meta" - - UNIT = "unit" - MAX_LOAD = "max_load" - MAX_LOAD_LEFT_WING = "max_load_left_wing" - MAX_LOAD_RIGHT_WING = "max_load_right_wing" - MAX_DISBALANCE = "max_disbalance" -class UnitCustomizablePresetsPylons(_tableColumns): - __table__ = "unit_customizable_presets_pylons" - - UNIT = "unit" - PYLON_INDEX = "pylon_index" - USED_FOR_DISBALANCE = "used_for_disbalance" -class UnitCustomizablePresetsPylonsWeapons(_tableColumns): - __table__ = "unit_customizable_presets_pylons_weapons" - - UNIT = "unit" - PYLON_INDEX = "pylon_index" - WEAPON = "weapon" - COUNT = "count" -#endregion -#region Localization -class UnitLoc(_tableColumns): - __table__ = "unit_localization" - - UNIT = "unit" - LANG = "lang" - VALUE = "value" -class WeaponLoc(_tableColumns): - __table__ = "weapon_localization" - - WEAPON = "weapon" - LANG = "lang" - VALUE = "value" -class AmmoLoc(_tableColumns): - __table__ = "ammo_localization" - - AMMO = "ammo" - LANG = "lang" - VALUE = "value" -class ExplosivesLoc(_tableColumns): - __table__ = "explosives_localization" - - EXPLOSIVE = "explosive" - LANG = "lang" - VALUE = "value" -#endregion diff --git a/app/utils/vehicleParser/vehiclesProcessor.py b/app/utils/vehicleParser/vehiclesProcessor.py deleted file mode 100644 index 954460a9..00000000 --- a/app/utils/vehicleParser/vehiclesProcessor.py +++ /dev/null @@ -1,1325 +0,0 @@ -from asyncio import get_running_loop -from logging import getLogger -from typing import Literal, Any -from pathlib import Path -from orjson import loads -from dataclasses import dataclass, asdict -from re import compile -from packaging.version import Version -from subprocess import run as sub_run, PIPE -from datetime import datetime, UTC -from time import perf_counter -from pandas import read_csv, DataFrame -from .constants import * -import utils.connection.network as Network -from config import VEHICLES - -_logger = getLogger(__name__) - -#region Startup checks -def git_check(): - git_ver = sub_run( - ["git", "version"], - stdout=PIPE, - stderr=PIPE - ) - if git_ver.returncode != 0: - raise EnvironmentError("No git installed on this system. Install it before running the server") - _logger.debug(git_ver.stdout.decode()) -git_check() -#endregion -#region Module setup -gamefiles = VEHICLES / "gamefiles" -gamefiles.mkdir(exist_ok=True, parents=True) -CACHED_VALIDITY_UNTIL:int -@dataclass(frozen=True, init=False) -class DataLocations: - @dataclass(frozen=True, slots=True) - class VehicleData: - DATA:Path - IMAGE:Path - PRESETS:Path - SENSORS:Path - - TT_IMAGES:Path = gamefiles / "atlases.vromfs.bin_u" / "units" - AIR_DATA: VehicleData = VehicleData( - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "flightmodels", - gamefiles / "tex.vromfs.bin_u" / "aircrafts", - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "flightmodels" / "weaponpresets", - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "sensors" - ) - GROUND_DATA: VehicleData = VehicleData( - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "units" / "tankmodels", - gamefiles / "tex.vromfs.bin_u" / "tanks", - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "units" / "weaponpresets", - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "sensors" - ) - NAVY_DATA: VehicleData = VehicleData( - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "units" / "ships", - gamefiles / "tex.vromfs.bin_u" / "ships", - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "units" / "weaponpresets", - gamefiles / "aces.vromfs.bin_u" / "gamedata" / "sensors" / "naval" - ) - WEAPON_DATA: Path = gamefiles / "aces.vromfs.bin_u" / "gamedata" / "weapons" - VEHICLE_DATA: Path = gamefiles / "char.vromfs.bin_u" / "config" / "unittags.blkx" - SENSOR_DATA: Path = gamefiles / "aces.vromfs.bin_u" / "gamedata" / "sensors" - TT_LINES: Path = gamefiles / "char.vromfs.bin_u" / "config" / "shop.blkx" - WPCOST: Path = gamefiles / "char.vromfs.bin_u" / "config" / "wpcost.blkx" - LOC_META: Path = gamefiles / "lang.vromfs.bin_u" / "lang" / "localization.blkx" - VEHICLE_LOC: Path = gamefiles / "lang.vromfs.bin_u" / "lang" / "units.csv" - WEAPON_LOC: Path = gamefiles / "lang.vromfs.bin_u" / "lang" / "units_weaponry.csv" - MODIFICATION_LOC: Path = gamefiles / "lang.vromfs.bin_u" / "lang" / "units_modifications.csv" - VERSION: Path = gamefiles / "version" -vehicle_data_loc = DataLocations() -gamefiles.mkdir(exist_ok=True) -if not (gamefiles / ".git").exists(): - _logger.warning(f"{gamefiles} doesn't have a git repository set up. Setting up automatically") - tracked_paths = [ # Put a / before single files - "aces.vromfs.bin_u/gamedata/flightmodels", - "aces.vromfs.bin_u/gamedata/units/tankmodels", - "aces.vromfs.bin_u/gamedata/units/ships", - "aces.vromfs.bin_u/gamedata/sensors", - "aces.vromfs.bin_u/gamedata/weapons", - "atlases.vromfs.bin_u/units", - "/char.vromfs.bin_u/config/shop.blkx", - "/char.vromfs.bin_u/config/unittags.blkx", - "/char.vromfs.bin_u/config/wpcost.blkx", - "/lang.vromfs.bin_u/lang/localization.blkx", - "/lang.vromfs.bin_u/lang/units.csv", - "/lang.vromfs.bin_u/lang/units_weaponry.csv", - "/lang.vromfs.bin_u/lang/units_modifications.csv", - "tex.vromfs.bin_u/aircrafts", - "tex.vromfs.bin_u/ships", - "tex.vromfs.bin_u/tanks", - "/version" - ] - - sub_run( - "git clone --filter=blob:none --sparse https://github.com/gszabi99/War-Thunder-Datamine.git ./ &&" + - f"git sparse-checkout set --no-cone {" ".join(tracked_paths)}", - check=True, - shell=True, - cwd=gamefiles - ) - CACHED_VALIDITY_UNTIL = int(datetime.now(UTC).timestamp()) + 10*60 -else: - CACHED_VALIDITY_UNTIL = 0 -VERSION = Version((gamefiles / "version").read_text()) -REMOTE_VERSION_URL = "https://raw.githubusercontent.com/gszabi99/War-Thunder-Datamine/refs/heads/master/version" - -WPCOST: dict[str, dict[str, Any]] = loads(vehicle_data_loc.WPCOST.read_text()) -VEHICLE_DATA: dict[str, dict[str, Any]] = loads(vehicle_data_loc.VEHICLE_DATA.read_text()) -LOC_META: dict[str, str|list[str]|dict] = loads(vehicle_data_loc.LOC_META.read_text()) - -UNIT_LOC: DataFrame = read_csv(vehicle_data_loc.VEHICLE_LOC, delimiter=';', encoding='utf-8') -UNIT_LOC.set_index("", inplace=True) - -WEAPON_LOC = read_csv(vehicle_data_loc.WEAPON_LOC, delimiter=";", encoding="utf-8") -WEAPON_LOC.set_index("", inplace=True) - -MOD_LOC = read_csv(vehicle_data_loc.MODIFICATION_LOC, delimiter=";", encoding="utf-8") -MOD_LOC.set_index("", inplace=True) - -async def update_gamefiles(): - global VERSION, CACHED_VALIDITY_UNTIL, UNIT_LOC, WEAPON_LOC, MOD_LOC, WPCOST, VEHICLE_DATA, LOC_META - if (CACHED_VALIDITY_UNTIL >= int(datetime.now(UTC).timestamp())): - return - CACHED_VALIDITY_UNTIL = int(datetime.now(UTC).timestamp()) + 10*60 # 10 minutes of cached version data - async with Network.get(REMOTE_VERSION_URL) as response: - remote_ver = Version(await response.text("utf-8")) - loop = get_running_loop() - - await loop.run_in_executor(None, lambda: sub_run("git pull", cwd=gamefiles, shell=True, check=True)) - VERSION = remote_ver - - WPCOST = await loop.run_in_executor(None, lambda: loads(vehicle_data_loc.WPCOST.read_text())) - VEHICLE_DATA = await loop.run_in_executor(None, lambda: loads(vehicle_data_loc.VEHICLE_DATA.read_text())) - LOC_META = await loop.run_in_executor(None, lambda: loads(vehicle_data_loc.LOC_META.read_text())) - - UNIT_LOC = await loop.run_in_executor(None, lambda: read_csv(vehicle_data_loc.VEHICLE_LOC, delimiter=';', encoding='utf-8')) - UNIT_LOC.set_index("", inplace=True) - - WEAPON_LOC = await loop.run_in_executor(None, lambda: read_csv(vehicle_data_loc.WEAPON_LOC, delimiter=";", encoding="utf-8")) - WEAPON_LOC.set_index("", inplace=True) - - MOD_LOC = await loop.run_in_executor(None, lambda: read_csv(vehicle_data_loc.MODIFICATION_LOC, delimiter=";", encoding="utf-8")) - MOD_LOC.set_index("", inplace=True) - -#endregion - -def getMultipleKeys(obj:dict, *keys:str, default:Any = None, raise_on_missing:bool = False): - for key in keys: - if key in obj: - return obj[key] - if raise_on_missing: - raise KeyError("Could not find any of the keys provided within the object") - return default - -csv_vehicle_pattern = compile(r"^(?P[A-Za-z0-9_-]+?)(?:_(?Pshop|[0-3]))?$") -@dataclass(frozen=True, slots=True) -class VehiclePaths: - vehicle_id:str - @dataclass(frozen=True, slots=True) - class Images: - techtree: Path - statcard: Path - images: Images - vehicleData: Path - presets: tuple[Path] -def referenceToPath(reference:str) -> Path: - if not reference.endswith(".blk"): reference += ".blk" - return gamefiles / "aces.vromfs.bin_u" / (reference.lower().replace("blk", "blkx")) -def get_vehicle_paths(vehicle_id:str) -> VehiclePaths|None: - def ext(text:str, ext:Literal["png", "blkx"]): return text+"."+ext - - #region Vehicle type assessment - vtype:DataLocations.VehicleData|None = None - - if ((vtype := vehicle_data_loc.AIR_DATA).DATA / ext(vehicle_id, "blkx")).exists(): pass - elif ((vtype := vehicle_data_loc.GROUND_DATA).DATA / ext(vehicle_id, "blkx")).exists(): pass - elif ((vtype := vehicle_data_loc.NAVY_DATA).DATA / ext(vehicle_id, "blkx")).exists(): pass - else: return None - vehiclePath = vtype.DATA / ext(vehicle_id, "blkx") - #endregion - - return VehiclePaths( - vehicle_id, - VehiclePaths.Images( - vehicle_data_loc.TT_IMAGES / ext(vehicle_id, "png"), - vtype.IMAGE / ext(vehicle_id, "blkx") - ), - vehiclePath, - tuple(vtype.PRESETS.rglob(fr"{vehicle_id}_*.blkx")) - ) - -@dataclass(frozen=True, slots=True) -class _limit: - maxValue: int|float - minValue: int|float - - @classmethod - def from_values(cls, value1:int|float, value2:int|float): - return cls( - max(value1, value2), - min(value1, value2) - ) - @classmethod - def from_list(cls, data:list[int|float]|None): - if data is None: - return - return cls.from_values(max(data), min(data)) - - def to_json(self): - return asdict(self) - -_sensor_data_cache: dict[Path, dict[str, Any]] = {} -_weapon_data_cache: dict[Path, dict[str, Any]] = {} - -@dataclass(frozen=True, slots=True) -class Sensor: - @dataclass(frozen=True, slots=True) - class Antenna: - angleHalfSens: float - sideLobesSensitivity: float - - def to_json(self): - return asdict(self) - @dataclass(slots=True) - class _transiversEntry: - type: str - sideLobesAttenuation: float | None - power: float - pulseWidth: float | None - bands: list[int] - rcs: float - ranges: dict[str, float] - rangeMax: float - multipathEffect: list[float] - antenna: Sensor.Antenna | dict[str, Sensor.Antenna] - visibilityType: Literal["infraRed", "radarIntercept", "optic"] - @classmethod - def from_json(cls, _type:str, data:dict[str, float|int]): - if "power" in data: - power = data["power"] - elif "pulsePower" in data: - power = data["pulsePower"] - - if "band" in data: - if isinstance(data["band"], int): - bands = [data["band"],] - else: - bands = data["band"] - else: - bands = [] - - if ("receiver" in data): - receiver:dict[str, float|dict] = data["receiver"] - rcs = receiver.get("rcs", None) - ranges = {} - for k, v in receiver.items(): - if not k.startswith("range") and k != "rangeMax": - continue - ranges[k] = v - rangeMax = receiver["rangeMax"] - else: - rcs = data.get("rcs", None) - ranges = {} - for k, v in data.items(): - if not k.startswith("range") and k != "rangeMax": - continue - ranges[k] = v - rangeMax = data["rangeMax"] - - if "antenna" in data: - if "sideLobesSensitivity" in data["antenna"]: - antenna = Sensor.Antenna( - data["antenna"]["angleHalfSens"], - data["antenna"]["sideLobesSensitivity"] - ) - elif "azimuth" in data["antenna"]: - antenna = { - "azimuth": Sensor.Antenna( - data["antenna"]["azimuth"]["angleHalfSens"], - data["antenna"]["azimuth"]["sideLobesSensitivity"] - ), - "elevation": Sensor.Antenna( - data["antenna"]["elevation"]["angleHalfSens"], - data["antenna"]["elevation"]["sideLobesSensitivity"] - ), - } - - return cls( - _type, - data.get("sideLobesAttenuation"), - power, - data.get("pulseWidth"), - bands, - rcs, - ranges, - rangeMax, - [], - antenna, - data.get("visibilityType") - ) - def to_json(self): - obj = asdict(self) - for key, value in obj.items(): - if isinstance(value, Sensor.Antenna): - obj[key] = value.to_json() - elif isinstance(value, dict): - for antenna, entry in value.items(): - if not isinstance(entry, Sensor.Antenna): - continue - obj[key][antenna] = entry.to_json() - - return obj - @dataclass(frozen=True, slots=True) - class _illuminationTransmitter: - power: float - antenna: Sensor.Antenna - - def to_json(self): - obj = asdict(self) - for key, value in obj.items(): - if isinstance(value, Sensor.Antenna): - obj[key] = value.to_json() - - return obj - @dataclass(frozen=True, slots=True) - class _signalEntry: - @dataclass(frozen=True, slots=True) - class _distance: - presents: bool - minValue: float - maxValue: float - width: float | None - - @classmethod - def from_json(cls, data:dict[str, Any]|None) -> Sensor._signalEntry._distance | None: - if data is None: - return - return cls( - data["presents"], - data["minValue"], - data["maxValue"], - data.get("width") - ) - def to_json(self): - return asdict(self) - @dataclass(frozen=True, slots=True) - class _dopplerSpeed: - presents: bool - minValue: float - maxValue: float - signalWidthMin: float # Yes i had to make a new dataclass for a single value - width: float - - @classmethod - def from_json(cls, data:dict[str, Any]|None) -> Sensor._signalEntry._dopplerSpeed | None: - if data is None: - return - if not data["presents"]: - return - - return cls( - data["presents"], - data["minValue"], - data["maxValue"], - data["signalWidthMin"], - data["width"] - ) - def to_json(self): - return asdict(self) - type: str - groundClutter: bool - aircraftAsTarget: bool - IFF: bool - targetId: bool - mainBeamNotchWidth: float - mainBeamNotchMaxElevation: float - distance: _distance | None - dopplerSpeed: _dopplerSpeed | None - extras: dict[str, Any] - - @classmethod - def from_json(cls, _type:str, data:dict[str, Any]): - return cls( - _type, - data.get("groundClutter", True), - data.get("aircraftAsTarget", True), - data.get("friendFoeId", False), - data.get("targetId", False), - data.get("mainBeamNotchWidth"), - data.get("mainBeamNotchMaxElevation"), - cls._distance.from_json(data.get("distance")), - cls._dopplerSpeed.from_json(data.get("dopplerSpeed")), - {k:v for k, v in data.items() if k not in ["groundClutter", "aircraftAsTarget", "friendFoeId", "targetId", "mainBeamNotchWidth", "mainBeamNotchMaxElevation", "distance", "dopplerSpeed"]} - ) - - def to_json(self): - obj = asdict(self) - for key, value in obj.items(): - if isinstance(value, (self._distance, self._dopplerSpeed)): - obj[key] = asdict(value) - return obj - @dataclass(frozen=True, slots=True) - class _scanPattern: - name: str - scanPatternSet: str - type: str - azimuthLimits: _limit - elevationLimits: _limit - rollStabLimit: float - pitchStabLimit: float - period: float - width: float - barHeight: float - barsCount: int - rowMajor: bool - - @classmethod - def from_data(cls, name: str, data:dict[str, Any], scanPatternSet:str): - return cls( - name, - scanPatternSet, - data.get("type"), - _limit.from_list(data.get("azimuthLimits")), - _limit.from_list(data.get("elevationLimits")), - data.get("rollStabLimit"), - data.get("pitchStabLimit"), - data.get("period"), - data.get("width"), - data.get("barHeight"), - data.get("barsCount"), - data.get("rowMajor") - ) - - def to_json(self): - obj = asdict(self) - for key, value in obj.items(): - if isinstance(value, _limit): - obj[key] = value.to_json() - - return obj - @dataclass(frozen=True, slots=True) - class _targetTypeId: - name: str - targetType: list[str] - - @classmethod - def from_json(cls, data:dict[str, Any]): - return cls( - data.get("name"), - data.get("targetType") - ) - def to_json(self): - return asdict(self) - @dataclass(frozen=True, slots=True) - class _vehicleTypeId: - name: str - propulsion: dict[str, str|int] - - @classmethod - def from_json(cls, data:dict[str, Any]): - return cls ( - data.get("name"), - data.get("targetPropulsion") - ) - - def to_json(self): - return asdict(self) - - type:str - name:str - displayName: str - maxTargets:int - transivers: tuple[_transiversEntry] - illuminationTransmitter: _illuminationTransmitter | None - signals: tuple[_signalEntry] - signals_track:bool | None - scopeRangeSets: dict[str, tuple[float]] - scanPatterns: tuple[_scanPattern] - targetTypeId: tuple[_targetTypeId] - vehicleTypeId: tuple[_vehicleTypeId] - sizeRanges: dict[str, _limit] - - @classmethod - async def from_id(cls, sensor:str): - for path in vehicle_data_loc.SENSOR_DATA.rglob(f"{sensor}.blkx"): - return await cls.from_path(path) - _logger.error(f"Could not find sensor '{sensor}'") - return None - @classmethod - async def from_path(cls, sensor: Path): - if not sensor.exists(): - raise LookupError(f"Sensor file not found at {sensor}") - if sensor in _sensor_data_cache: - data = _sensor_data_cache[sensor] - else: - loop = get_running_loop() - data = await loop.run_in_executor(None, lambda: loads(sensor.read_text())) - _sensor_data_cache[sensor] = data - name = ".".join(sensor.name.split(".")[:-1]) - maxTargets = data.get("weaponTargetsMax", -1) - - transivers = [] - for k, v in data.get("transivers", {}).items(): - transivers.append(cls._transiversEntry.from_json(k, v)) - - _ = data.get("illuminationTransmitter", {}) - if _: - illuminationTransmitter = cls._illuminationTransmitter( - _["power"], - cls.Antenna( - _["antenna"]["angleHalfSens"], - _["antenna"]["sideLobesSensitivity"] - ) - ) - else: - illuminationTransmitter = None - - signals = [] - for k, v in data.get("signals", {}).items(): - if k.lower() == "track": - track = v - continue - signals.append(cls._signalEntry.from_json(k, v)) - - scopeRangeSets = {} - for k, v in data.get("scopeRangeSets", {}).items(): - scopeRangeSets[k] = [i for i in v] - - tmp = {} - for k, v in data.get("scanPatternSets", {}).items(): - tmp[k] = [i for i in v.values()] - scanPatterns = [] - for k, v in data.get("scanPatterns", {}).items(): - patternSet = next((i for i, j in tmp.items() if k in j), None) - scanPatterns.append(cls._scanPattern.from_data(k, v, patternSet)) - - sizeRanges = {} - vehicleTypeId = [] - targetTypeId = [] - for v in data.get("targetTypeId", []): - name:str = v.get("name").removeprefix("hud/") - if (_:=v.get("sizeRange", [])): - sizeRanges[name] = _limit.from_list(_) - elif name in ["helicopter", "single prop", "multi prop", "single jet", "multi jet", "rocket"]: - vehicleTypeId.append(cls._vehicleTypeId.from_json(v)) - else: - targetTypeId.append(cls._targetTypeId.from_json(v)) - - return cls( - data["type"], - name, - data.get("name"), - maxTargets, - tuple(transivers), - illuminationTransmitter, - tuple(signals), - track, - scopeRangeSets, - tuple(scanPatterns), - tuple(targetTypeId), - tuple(vehicleTypeId), - sizeRanges - ) - - def to_json(self): - obj = asdict(self) - for key, value in obj.items(): - if isinstance(value, self._illuminationTransmitter): - obj[key] = value.to_json() - elif isinstance(value, tuple): - new = [] - for item in value: - if isinstance(item, (self._transiversEntry, self._scanPattern, self._targetTypeId, self._targetTypeId, self._vehicleTypeId)): - new.append(item.to_json()) - else: - # Just in case - new.append(item) - obj[key] = tuple(new) - elif isinstance(value, dict): - for k, v in value.items(): - if isinstance(v, _limit): - obj[key][k] = v.to_json() - - return obj - -@dataclass(slots=True) -class Weapon: - @dataclass(frozen=True, slots=True) - class _ammo: - name: str = None - type: str = None - caliber: float = 0.0 - mass: float = 0.0 - speed: float = 0.0 - max_distance: float = 0.0 - explosive_type: str | None = None - explosive_mass: float | None = 0.0 - - @classmethod - def from_json(cls, data:dict[str, Any]) -> Weapon._ammo | None: - if not data: - return - return cls( - getMultipleKeys(data, "bombName", "bulletName"), - getMultipleKeys(data, "bombType", "bulletType"), - data.get("caliber"), - _[0] if isinstance(_:=data.get("mass"), list) else _, - getMultipleKeys(data, "maxSpeedInWater", "speed", "maxSpeed"), - getMultipleKeys(data, "distToLive", "maxDistance"), - data.get("explosiveType"), - data.get("explosiveMass") - ) - - name: str = None - type: str = None - ammo: tuple[_ammo] = tuple() - - @classmethod - async def from_id(cls, weapon:str): - for i in ["drop_tank","rocketguns","containers","bombguns","equipment"]: - weapon = weapon.removeprefix(i+"_") - for path in vehicle_data_loc.WEAPON_DATA.rglob(f"{weapon}.blkx"): - return await cls.from_path(path) - _logger.error(f"Could not find weapon '{weapon}'") - return None - - @classmethod - async def from_path(cls, weapon:Path): - - self = cls() - - if not weapon.exists(): - raise LookupError(f"Weapon file not found at {weapon}") - - if weapon in _weapon_data_cache: - weapon_blk = _weapon_data_cache[weapon] - else: - loop = get_running_loop() - weapon_blk = await loop.run_in_executor(None, lambda: loads(weapon.read_text())) - _weapon_data_cache[weapon] = weapon_blk - - self.name = ".".join(weapon.name.split(".")[:-1]) - if (self.name == "dummy_weapon"): - return - - weapon_type = weapon_blk.get("weaponType") - - lowercase_keys = [i.lower() for i in weapon_blk.keys()] - - is_rocket: bool = weapon_blk.get(ROCKET_NAME) or ROCKET_TYPE in lowercase_keys or weapon_blk.get(ROCKET_TYPE) - is_cannon: bool = weapon_blk.get(CANNON_NAME) or CANNON_TYPE in lowercase_keys or weapon_blk.get(CANNON_TYPE) or weapon_type == -1 or weapon_type == 1 or weapon_type == 3 - is_torpedo: bool = weapon_blk.get(TORPEDO_NAME) or TORPEDO_TYPE in lowercase_keys or weapon_blk.get(TORPEDO_TYPE) or weapon_type == 1 - is_bomb: bool = weapon_blk.get(BOMB_NAME) or BOMB_TYPE in lowercase_keys or weapon_blk.get(BOMB_TYPE) - is_booster: bool = weapon_blk.get(BOOSTER_NAME) or BOOSTER_TYPE in lowercase_keys or weapon_blk.get(BOOSTER_TYPE) - is_container: bool = weapon_blk.get(CONTAINER_NAME) or CONTAINER_TYPE in lowercase_keys or weapon_blk.get(CONTAINER_TYPE) - is_extfueltank: bool = weapon_blk.get(EXTFUELTANK_NAME) or EXTFUELTANK_TYPE in lowercase_keys or weapon_blk.get(EXTFUELTANK_TYPE) - - valid = weapon_type is not None or is_rocket or is_torpedo or is_cannon or is_bomb or is_booster or is_container or is_extfueltank - if not valid: - _logger.error(f"Weapon {self.name}'s type is missing\n\n{weapon}\n\tType: {weapon_type}") - return - - if is_cannon: - self._get_ammo("bullet", weapon_blk) - self.type = CANNON_NAME - elif is_rocket: - self._get_ammo("rocket", weapon_blk) - self.type = ROCKET_NAME - elif is_torpedo: - self._get_ammo("torpedo", weapon_blk) - self.type = TORPEDO_NAME - elif is_bomb: - self._get_ammo("bomb", weapon_blk) - self.type = BOMB_NAME - elif is_booster: - self._get_ammo("payload", weapon_blk) - self.type = BOOSTER_NAME - elif is_container: - self.type = CONTAINER_NAME - return await self.from_path(referenceToPath(weapon_blk["blk"])) - elif is_extfueltank: - self._get_ammo("payload", weapon_blk) - self.type = EXTFUELTANK_NAME - - return self - - def _get_ammo(self, key:str, data:dict[str, Any]): - ammo_list = [] - for k in data.keys(): - raw_ammo = None - key_value = data.get(k) - - lowercase_keys = [i.lower() for i in data.keys()] - - if isinstance(key_value, dict) or isinstance(key_value, list) and k.lower() == key: - raw_ammo = key_value - elif isinstance(key_value, dict) and key in lowercase_keys: - raw_ammo = key_value.get(key) - - if not raw_ammo: - continue - - raw_ammo = raw_ammo if isinstance(raw_ammo, list) else [raw_ammo,] - - for ammos in raw_ammo: - if "bullet" in ammos and isinstance(ammos["bullet"], list): - for ammo in ammos["bullet"]: - _ammo = self._ammo.from_json(ammo) - ammo_list.append(_ammo) - else: - _ammo = self._ammo.from_json(ammos) - ammo_list.append(_ammo) - self.ammo = tuple(ammo_list) - - def to_json(self): - return { - "weapon": self.name, - "type": self.type, - "ammo": [asdict(i) for i in self.ammo] - } - -class Vehicle: - version: Version - identifier: str - type: str - subtypes: list[str] - operator: str - tags: list[str] - vehicle_stats: dict[str, float] - release_date:datetime - sensors: list[str] - - @dataclass(frozen=True, slots=True) - class _weapon: - """A shorter, less computationally intensive weapon class. Holds less data""" - id: str - totalMass: int - totalCount: int - damage: int|None - weaponmask: int - reqModification: str|None = None - usedForCustomSlot: bool = False - guidance: str|None = None - - @classmethod - def from_json(cls, id:str, data:dict[str, Any]): - guidance = getMultipleKeys(data, "aamGuidanceType", "atgmVisibilityType", "guidedBombVisibilityType") - if guidance == "default": - if "aamGuidanceType" in data: - guidance = "infraRed" - elif "atgmVisibilityType" in data: - guidance = "laser" - elif "guidedBombVisibilityType" in data: - raise NotImplementedError("Didn't implement default for this one yet") - guidance = "" - return cls( - id, - getMultipleKeys(data, "totalGuidedBombMass", "totalBombRocketMass"), - getMultipleKeys(data, "totalBombCount"), - data.get("weaponDamage"), - data.get("weaponmask"), - data.get("reqModification"), - data.get("isWeaponForCustomSlot", False), - guidance - ) - def to_json(self): - return asdict(self) - - @dataclass(frozen=True, slots=True) - class _defaultPreset: - id: str - totalDamage: int - mass: int|None - ammoCount: int|None - hasCountermeasures: bool - mass_per_sec: int - weaponmask: int - weapons: dict[str, dict[str, Vehicle._weapon|int]] - - @classmethod - def from_json(cls, key:str, data:dict[str, Any], full_weapon_data:dict[str, dict[str, Any]]): - if any(key.startswith(i) for i in ["rocketguns", "containers", "bombguns", "equipment", "drop_tank", "custom_presets"]): - raise RuntimeError(f"Invalid key for default preset: {key}") - weapons = {} - for k,v in data.get("sum_weapons", {}).items(): - weapons[k] = { - "weapon": Vehicle._weapon.from_json(k, full_weapon_data[k]), - "count": v - } - - return cls( - key, - data.get("weaponDamage"), - getMultipleKeys(data, "totalGuidedBombMass", "totalBombRocketMass"), - getMultipleKeys(data, "totalBombCount"), - data.get("hasCountermeasures", False), - data.get("mass_per_sec", 0), - data.get("weaponmask"), - weapons - ) - def to_json(self): - obj = asdict(self) - for id, data in self.weapons.items(): - for key, value in data.items(): - if isinstance(value, Vehicle._weapon): - obj["weapons"][id][key] = value.to_json() - - return obj - default_presets: tuple[_defaultPreset] | None = None - - @dataclass(frozen=True, slots=True) - class _pylonData: - index: int - weapons: tuple[dict[str, Vehicle._weapon|int|dict[str, int]]] - - @classmethod - def from_json(cls, data:dict[str, int|dict[str, int]], all_data:dict[str, Any]): - index = data.get("index") - if (index is None): - raise LookupError("No index value for pylon") - - weapons = [] - for k, v in data.items(): - if k == "index": - continue - entry = {} - entry[k] = {} - for key, value in v.items(): - if key == "DependentWeaponPreset": - entry[k]["dependsOn"] = {} - for name, idx in value.items(): - entry[k]["dependsOn"][name] = idx - elif key == "BannedWeaponPreset": - entry[k]["bannedPreset"] = {} - for name, idx in value.items(): - entry[k]["bannedPreset"][name] = idx - else: - entry[k][key] = Vehicle._weapon.from_json(value, all_data[key]) - weapons.append(entry) - return cls(index, tuple(weapons)) - def to_json(self): - new_weapons = [] - for idx, weapon in enumerate(self.weapons): - new_weapons.append({}) - for k, v in weapon.items(): - if k == "dependsOn": - new_weapons[idx][k]["dependsOn"] = v - elif k == "bannedPreset": - new_weapons[idx][k]["bannedPreset"] = v - elif isinstance(v, Vehicle._weapon): - new_weapons[idx][k] = v.to_json() - else: - new_weapons[idx][k] = v - - return { - "index": self.index, - "weapons": tuple(new_weapons) - } - pylon_configurations: tuple[_pylonData] - - @dataclass(frozen=True, slots=True) - class _computer: - gun_ccip: bool - turret_ccip: bool - bombs_ccip: bool - rocket_ccip: bool - gun_ccrp: bool - turret_ccrp: bool - bombs_ccrp: bool - rocket_ccrp: bool - laser_designator: bool - poi_designator: bool - poi_memory: bool - aiming_point_memory: bool - gyro_sight: bool - - def to_json(self): - return asdict(self) - computer:_computer - - @dataclass(frozen=True, slots=True) - class _nightvision: - @dataclass(frozen=True, slots=True) - class entry: - resolution: tuple[int, int] - generation: str - noise: float - index: int - ghosting: float | None = None - lightMult: float | None = None - sightThermal: entry|None - sightTgtPodThermal: entry|None - gunnerIr: entry|None - pilotIr: entry|None - - def to_json(self): - obj = asdict(self) - for key, value in obj.items(): - if isinstance(value, self.entry): - obj[key] = asdict(value) - return obj - night_vision: _nightvision - - @dataclass(frozen=True, slots=True) - class _preset: - name: str = None - weapons: tuple[Weapon] = () - - def to_json(self): - _ = asdict(self) - _["weapons"] = tuple([i.to_json() for i in self.weapons]) - return _ - - @dataclass(frozen=True, slots=True) - class _modification: - id: str - prevModification: str | None - reqModification: str | None - tier: int | None - effects: dict[str, float] - modClass: str | None - extras: dict[str, Any] - @classmethod - def from_json(cls, mod_id:str, data:dict[str, Any]): - extras = {k:v for k, v in data.items() if k not in ["prevModification","reqModification","tier","effects","modClass"]} - return cls( - mod_id, - data.get("prevModification"), - data.get("reqModification"), - data.get("tier"), - data.get("effects", {}), - data.get("modClass"), - extras - ) - def to_json(self): - return asdict(self) - modifications:tuple[_modification] - - @dataclass(frozen=True, slots=True) - class _wpcost: - @dataclass(frozen=True, slots=True) - class _GamemodesSplit: - arcade: float - realistic: float - simulator: float|None = None - realistic_ground: float|None = None - simulator_ground: float|None = None - @classmethod - def from_json(cls, data:dict[str, Any], base:str): - return cls( - float(data[f"{base}Arcade"]), - float(data[f"{base}Historical"]), - float(data[f"{base}Simulation"]) if f"{base}Simulation" in data else None, - float(data[f"{base}TankHistorical"]) if f"{base}TankHistorical" in data else None, - float(data[f"{base}TankSimulation"]) if f"{base}TankSimulation" in data else None - ) - price: int - requiredRP: int - trainCost: int - expertCost: int - aceCostGE: int - aceCostRP: int - repairTimeHrs: _GamemodesSplit - repairTimeHrsNoCrew: _GamemodesSplit - repairCost: _GamemodesSplit - repairCostPerMin: _GamemodesSplit - repairCostFullUpgraded: _GamemodesSplit | None - battleTimeAward: _GamemodesSplit - avgAward: _GamemodesSplit - rewardMultiplier: _GamemodesSplit - RpMultiplier: float - battleTime: _GamemodesSplit - rank: int - battleRating: _GamemodesSplit - country: str - unitClass: str - speed: float | None - maxAmmo: int | None - maxFlightTimeMinutes: int | None - requiredUnit: str | None - crewCount: int | None - givesNationBonus: bool - has_customizable_weapons:bool - turretSpeed: tuple[int, int] | None - hideUnlessOwned: bool - - @classmethod - def from_json(cls, data:dict[str, Any]): - return cls( - data["value"], - data.get("reqExp", 0), - data["trainCost"], - data["train2Cost"], - data["train3Cost_gold"], - data["train3Cost_exp"], - cls._GamemodesSplit.from_json(data, "repairTimeHrs"), - cls._GamemodesSplit.from_json(data, "repairTimeHrsNoCrew"), - cls._GamemodesSplit.from_json(data, "repairCost"), - cls._GamemodesSplit.from_json(data, "repairCostPerMin"), - cls._GamemodesSplit.from_json(data, "repairCostFullUpgraded") if "repairCostFullUpgradedArcade" in data else None, - cls._GamemodesSplit.from_json(data, "battleTimeAward"), - cls._GamemodesSplit.from_json(data, "avgAward"), - cls._GamemodesSplit.from_json(data, "rewardMul"), - data["expMul"], - cls._GamemodesSplit.from_json(data, "battleTime"), - data["rank"], - cls._GamemodesSplit.from_json(data, "economicRank"), - Vehicle.convert_country(data["country"]), - data["unitClass"], - data.get("speed"), - data.get("maxAmmo"), - data.get("maxFlightTimeMinutes"), - data.get("reqAir"), - data.get("crewTotalCount"), - data.get("doesItGiveNationBonus", False), - data.get("hasWeaponSlots", False), - tuple(_) if (_:=data.get("turretSpeed")) is not None else None, - data.get("showOnlyWhenBought", False) - ) - - def to_json(self): - obj = asdict(self) - - for key, value in obj.items(): - if isinstance(value, self._GamemodesSplit): - obj[key] = asdict(value) - - return obj - economy: _wpcost - - @dataclass(frozen=True, slots=True) - class Localization: - language: str - short: str - long: str - - def to_json(self): - return {self.language: { - "short": self.short, - "long": self.long - }} - - localizations: tuple[Localization] - statcard_image: Path - techtree_image: Path - - def __init__( - self, - vehicle_paths:VehiclePaths, - data:dict[str, Any] - ): - self.identifier = vehicle_paths.vehicle_id - self.version = VERSION - - self.sensors = [] - self.tags = [] - self.subtypes = [] - self.modifications = [] - - self._parse_economy() - self._parse_unittags() - self._parse_data(data) - self._parse_localization() - - self.statcard_image = vehicle_paths.images.statcard - self.techtree_image = vehicle_paths.images.techtree - - @classmethod - async def from_id(cls, vehicle_id:str): - await update_gamefiles() - paths = get_vehicle_paths(vehicle_id) - if paths == None: - raise LookupError(f"Could not find vehicle '{vehicle_id}'") - loop = get_running_loop() - data:dict[str, Any] = await loop.run_in_executor(None, lambda: loads(paths.vehicleData.read_text())) - return cls(paths, data) - - @staticmethod - def convert_country(country_code:str) -> str: - return country_code.removeprefix("country_") - - async def get_sensors(self) -> tuple[Sensor]: - sensors = [] - for sensor in self.sensors: - sensors.append(await Sensor.from_id(sensor)) - return tuple(sensors) - - async def get_weapons(self) -> dict[str, dict[str, Weapon]]: - weapons = { - "default": {}, - "custom": {} - } - for preset in self.default_presets: - for weapon in preset.weapons: - if weapon in weapons["default"]: - continue - weapons["default"][weapon] = await Weapon.from_id(weapon) - for pylon in self.pylon_configurations: - for preset in pylon.weapons: - for loadout in preset.values(): - for name in loadout: - if name in ["dependsOn", "BannedPreset"]: - continue - weapons["custom"][name] = await Weapon.from_id(name) - - return weapons - - def _parse_localization(self): - localizations = [] - - long_line = UNIT_LOC.loc[f"{self.identifier}_shop"] - short_line = UNIT_LOC.loc[f"{self.identifier}_0"] - languages = LOC_META["text_translation"]["lang"] - for lang in languages: - localizations.append(self.Localization( - lang, - short_line.get(f"<{lang}>"), - long_line.get(f"<{lang}>") - )) - - self.localizations = tuple(localizations) - - def _parse_unittags(self): - vehicleDataEntry:dict[str, str|dict] = VEHICLE_DATA.get(self.identifier) - if (vehicleDataEntry is None): - return - self.vehicle_stats = vehicleDataEntry.get("Shop") - tags:dict[str, bool] = vehicleDataEntry["tags"] - - self.type = vehicleDataEntry["type"] - for tag in tags: - if tag.startswith("country_") or tag == self.type: - continue - elif tag.startswith("type_"): - self.subtypes.append(tag.removeprefix("type_")) - else: - self.tags.append(tag) - - release = vehicleDataEntry.get("releaseDate", "1970-01-01 00:00:00") - if release == '': - release = "1970-01-01 00:00:00" - self.release_date = datetime.fromisoformat(release) - - if ("operatorCountry" in vehicleDataEntry): - if isinstance(vehicleDataEntry["operatorCountry"], list): - self.operator = [self.convert_country(i) for i in vehicleDataEntry["operatorCountry"]] - else: - self.operator = self.convert_country(vehicleDataEntry["operatorCountry"]) - else: - self.operator = self.economy.country or None - - def _parse_economy(self): - self.economy = self._wpcost.from_json(WPCOST[self.identifier]) - - weaponry = WPCOST[self.identifier]["weapons"] - def_presets = [] - pylons = [] - for k, v in weaponry.items(): - if (k.startswith(self.identifier)): # Default presets - def_presets.append(self._defaultPreset.from_json(k, v, weaponry)) - elif (k == "custom_presets"): # Custom Presets - if isinstance(v["slot"], dict): - pylons.append(self._pylonData.from_json(v["slot"], weaponry)) - else: - for pylon in v["slot"]: - pylons.append(self._pylonData.from_json(pylon, weaponry)) - self.default_presets = tuple(def_presets) - self.pylon_configurations = tuple(pylons) - #endregion - - def _parse_data(self, data: dict): - self.computer = self._computer( - gun_ccip = data.get("haveCCIPForGun", False), - turret_ccip = data.get("haveCCIPForTurret", False), - bombs_ccip = data.get("haveCCIPForBombs", False), - rocket_ccip = data.get("haveCCIPForRocket", False), - gun_ccrp = data.get("haveCCRPForGun", False), - turret_ccrp = data.get("haveCCRPForTurret", False), - bombs_ccrp = data.get("haveCCRPForBombs", False), - rocket_ccrp = data.get("haveCCRPForRocket", False), - laser_designator = data.get("laserDesignator", False), - poi_designator = data.get("havePointOfInterestDesignator", False), - poi_memory = data.get("hasPointOfInterestMemory", False), - aiming_point_memory = data.get("hasAimingPointsMemory", False), - gyro_sight = data.get("gyroSight", False) - ) - - #region NVDs - tmp:dict[str, list[dict[str, Any]]] = data.get("nightVision", {}) - for k, v in tmp.items(): - if "ir" in k.lower(): - tmp[k]["generation"] = IR_VISION_GENERATIONS.get(tuple(v["resolution"]), "Unknown") - elif "thermal" in k.lower(): - tmp[k]["generation"] = THERMAL_VISION_GENERATIONS.get(tuple(v["resolution"]), "Unknown") - elif "nightvisiondmpart" in k.lower(): - pass - else: - raise KeyError(f"Type of night vision '{k}' not found") - - self.night_vision = self._nightvision( - self._nightvision.entry( - tuple(tmp["sightThermal"]["resolution"]), - tmp["sightThermal"]["generation"], - tmp["sightThermal"]["noiseFactor"], - tmp["sightThermal"].get("index", -1) - ) if tmp.get("sightThermal") is not None else None, - self._nightvision.entry( - tuple(tmp["sightTPodThermal"]["resolution"]), - tmp["sightTPodThermal"]["generation"], - tmp["sightTPodThermal"]["noiseFactor"], - tmp["sightTPodThermal"].get("index", -1) - ) if tmp.get("sightTPodThermal") is not None else None, - self._nightvision.entry( - tuple(tmp["gunnerIr"]["resolution"]), - tmp["gunnerIr"]["generation"], - tmp["gunnerIr"]["noiseFactor"], - -1, - tmp["gunnerIr"]["ghosting"], - tmp["gunnerIr"]["lightMult"] - ) if tmp.get("gunnerIr") is not None else None, - self._nightvision.entry( - tuple(tmp["pilotIr"]["resolution"]), - tmp["pilotIr"]["generation"], - tmp["pilotIr"]["noiseFactor"], - -1, - tmp["pilotIr"]["ghosting"], - tmp["pilotIr"]["lightMult"] - ) if tmp.get("pilotIr") is not None else None - ) - #endregion - - #region Sensors - sensorsData = data.get("sensors", {"sensor":[]}) - if not isinstance(sensorsData, dict): - raise RuntimeError("Sensors entry not a dict") - if "sensor" in sensorsData: - if isinstance(sensorsData["sensor"], dict): - blkname = sensorsData["sensor"].get("blk") - if blkname is not None: - self.sensors.append(referenceToPath(blkname).name.removesuffix(".blkx")) - else: - for sensor in sensorsData["sensor"]: - blkname:str = sensor.get("blk") - if blkname is None: - continue - self.sensors.append(referenceToPath(blkname).name.removesuffix(".blkx")) - elif "fireDirecting" in sensorsData: - pass # TODO: Navy stuff, no data retrieved currently - #endregion - - self.modifications = tuple([self._modification.from_json(k, v) for k,v in data.get("modifications", {}).items()]) - pass - - def to_json(self): - langs = {} - for loc in self.localizations: - langs.update(loc.to_json()) - obj = { - "id": self.identifier, - "data_version": self.version, - "economy": self.economy.to_json(), - "modifications": [i.to_json() for i in self.modifications], - "nightvision": self.night_vision.to_json(), - "computers": self.computer.to_json(), - "release_date": self.release_date, - "type": self.type, - "subtypes": self.subtypes, - "operator": self.operator, - "tags": self.tags, - "stats": self.vehicle_stats, - "default_presets": tuple([i.to_json() for i in self.default_presets]) if self.default_presets else None, - "pylon_configurations": tuple([i.to_json() for i in self.pylon_configurations]) if self.pylon_configurations else None, - "localizations": langs, - "sensors": self.sensors - } - return obj - -class UpdateAvailableError(Exception): - """An exception class for when a git update is available""" - def __init__(self, *args): - super().__init__(*args) - -async def getAllVehicleIDs() -> tuple[str]: - await update_gamefiles() - return [k for k in WPCOST.keys() if k != "economicRankMax"] -async def processVehicles(*vehicle_ids:str) -> tuple[Vehicle]: - await update_gamefiles() - start_time = perf_counter() - vehicle_entries = [] - for id in vehicle_ids: - if id not in WPCOST: - _logger.error(f"Invalid vehicle ID: '{id}'") - continue - try: - vehicle_entries.append(await Vehicle.from_id(id)) - except LookupError: - _logger.exception(f"Could not parse vehicle {id}") - end_time = perf_counter() - _logger.debug(f"Vehicle parsing took {round(end_time-start_time, 2)} seconds") - return tuple(vehicle_entries) - -if __name__ == '__main__': - from logging import DEBUG, basicConfig - from asyncio import new_event_loop - basicConfig( - level=DEBUG, - format="%(asctime)s:%(name)-30s:%(funcName)-15s:%(lineno)-3d:%(levelname)-7s:%(message)s" - ) - loop = new_event_loop() - start_time = perf_counter() - #result = loop.run_until_complete(processVehicles(*loop.run_until_complete(getAllVehicleIDs()))) - #result = loop.run_until_complete(processVehicles("saab_jas39e", "saab_j21a_2", "tiger_uht", "germ_leopard_2k", "ussr_battlecruiser_izmail", "it_gabbiano_class")) - result = loop.run_until_complete(processVehicles("saab_jas39e")) - end_time = perf_counter() - _logger.debug(f"Fetching took {end_time-start_time} seconds to parse {len(result)} entries") - - start_time = perf_counter() - results = [i.to_json() for i in result] - end_time = perf_counter() - _logger.debug(f"JSON conversion took {end_time-start_time} seconds to convert {len(result)} entries") - - pass diff --git a/compose.yml b/compose.yml index b11c9574..6064e908 100644 --- a/compose.yml +++ b/compose.yml @@ -5,8 +5,6 @@ services: - .env environment: DEBUG_MODE: "0" - # Trust X-Forwarded-For from the Cloudflare tunnel so logs show the real client IP - FORWARDED_ALLOW_IPS: "*" user: "${UID:-1000}:${GID:-1001}" volumes: - "./data:/data" diff --git a/dev_tools/decompress.py b/dev_tools/decompress.py index a3498cde..fb447d52 100644 --- a/dev_tools/decompress.py +++ b/dev_tools/decompress.py @@ -3,13 +3,14 @@ import struct import sys + def read_input_bytes(input_file): - with open(input_file, 'rb') as f: + with open(input_file, "rb") as f: raw_data = f.read() - stripped = b''.join(raw_data.split()) + stripped = b"".join(raw_data.split()) try: - decoded = bytes.fromhex(stripped.decode('ascii')) + decoded = bytes.fromhex(stripped.decode("ascii")) except (ValueError, UnicodeDecodeError): return raw_data @@ -27,17 +28,17 @@ def decompress_lz4(data, force=False): return None candidates = [] - if data[:1] == b'\x4c': + if data[:1] == b"\x4c": if len(data) < 5: print("[-] LZ4 marker found, but the file is too short to contain a size header.") return None # First byte is the compression marker. The next 4 bytes are the expected size. - candidates.append(("marker+size", struct.unpack('>I', data[1:5])[0], data[5:])) + candidates.append(("marker+size", struct.unpack(">I", data[1:5])[0], data[5:])) elif force: # Forced LZ4 handles files without the 4C marker by treating the first 4 bytes # as the expected decompressed size. - candidates.append(("size-header", struct.unpack('>I', data[:4])[0], data[4:])) + candidates.append(("size-header", struct.unpack(">I", data[:4])[0], data[4:])) else: return None @@ -51,7 +52,7 @@ def decompress_lz4(data, force=False): return None def decompress_bzip(data, force=False): - offset = data.find(b'BZh') if force else data[:20].find(b'BZh') + offset = data.find(b"BZh") if force else data[:20].find(b"BZh") if offset == -1: if not force: return None @@ -75,7 +76,7 @@ def decompress_file(input_file, output_file, force=None): print("[*] Forcing bzip decompression") decompressed = decompress_bzip(all_data, force=True) else: - if b'BZh' in all_data[:20]: + if b"BZh" in all_data[:20]: decompressed = decompress_bzip(all_data) if decompressed is None: decompressed = decompress_lz4(all_data, force=True) @@ -83,7 +84,7 @@ def decompress_file(input_file, output_file, force=None): if decompressed is None: return False - with open(output_file, 'wb') as f_out: + with open(output_file, "wb") as f_out: f_out.write(decompressed) print(f"[+] Success! File saved to {output_file}") diff --git a/gaijin_api_endpoints.md b/gaijin_api_endpoints.md index 3af11648..51edee2d 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/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..e1e95da0 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,55 @@ +[project] +name="ThunderAPI" +description="Translation layer for Gaijin Entertainment's servers" +version = "1.0.0" +requires-python = ">= 3.14" +authors = [ + {name = "Maho Yoshino", email="mahoyoshino@proton.me"} +] +readme = "README.md" +license = "Apache-2.0" + +[project.urls] +Homepage = "https://thunderapi.mahoyoshino.hu" +Repository = "https://github.com/Order-Of-The-Birb/ThunderAPI.git" +Issues = "https://github.com/Order-Of-The-Birb/ThunderAPI/issues" + +[dependency-groups] +dev = [ + "pytest", + "pytest-asyncio", + "ruff", + "httpx" +] + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["src"] +asyncio_mode = "auto" + +[tool.ruff] +target-version = "py314" +line-length = 120 + +[tool.ruff.lint] +select = [ + "D211", + "E4", + "E7", + "E9", + "F", + "I", + "B", + "FAST002", + "PIE790", + "PYI009", + "PYI042", + "Q000", + "W2", + "UP018", + "UP039", + "UP045", + "RUF036", + "TRY002", + "TRY004" +] diff --git a/requirements.txt b/requirements.txt index 28b7e173..02b5a68b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,16 +3,16 @@ packaging # API Backend slowapi -fastapi==0.136.1 +fastapi==0.162.0 uvicorn apscheduler python-multipart PyGithub -bs4 # Data processing lz4 bs4 +lxml pandas pydantic[email] cryptography diff --git a/app/api/__init__.py b/src/api/__init__.py similarity index 67% rename from app/api/__init__.py rename to src/api/__init__.py index 5f6270f0..a3abc4b9 100644 --- a/app/api/__init__.py +++ b/src/api/__init__.py @@ -1,11 +1,12 @@ from fastapi import APIRouter, status -from api.v1 import router as v1Router + from api.root import router as rootRouter +from api.v1 import router as v1Router router = APIRouter( - prefix="", - tags=[], - responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}} + prefix = "", + tags = [], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} ) router.include_router(v1Router) router.include_router(rootRouter) diff --git a/src/api/root.py b/src/api/root.py new file mode 100644 index 00000000..606439f4 --- /dev/null +++ b/src/api/root.py @@ -0,0 +1,24 @@ +from fastapi import APIRouter, status +from fastapi.responses import RedirectResponse + +router = APIRouter( + prefix = "", + tags = [], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +@router.get( + "/privacy", + description = "Redirects to the privacy policy", + status_code = status.HTTP_301_MOVED_PERMANENTLY +) +def privacy_policy(): + return RedirectResponse("https://github.com/Order-Of-The-Birb/ThunderAPI/README.md#privacy-policy", status.HTTP_301_MOVED_PERMANENTLY) + +@router.get( + "/github", + summary = "Redirects to the github source code", + status_code = status.HTTP_301_MOVED_PERMANENTLY +) +async def github_redirect(): + return RedirectResponse("https://github.com/Order-Of-The-Birb/ThunderAPI", status.HTTP_301_MOVED_PERMANENTLY) diff --git a/app/api/shared.py b/src/api/shared.py similarity index 74% rename from app/api/shared.py rename to src/api/shared.py index cec29ab5..662195ba 100644 --- a/app/api/shared.py +++ b/src/api/shared.py @@ -2,5 +2,5 @@ from slowapi.util import get_remote_address as _gra limiter = _slowapiLimiter( - key_func= lambda request: _gra(request) + key_func = lambda request: _gra(request) ) diff --git a/src/api/v1/__init__.py b/src/api/v1/__init__.py new file mode 100644 index 00000000..1c79bce9 --- /dev/null +++ b/src/api/v1/__init__.py @@ -0,0 +1,20 @@ +from fastapi import APIRouter + +from .auth import router as authRouter +from .clans import router as clanRouter +from .general import router as generalRouter +from .marketplace import router as tradeRouter +from .replays import router as replayRouter +from .units import router as unitRouter +from .users import router as userRouter + +router = APIRouter( + prefix = "/v1" +) +router.include_router(authRouter) +router.include_router(clanRouter) +router.include_router(generalRouter) +router.include_router(tradeRouter) +router.include_router(replayRouter) +router.include_router(unitRouter) +router.include_router(userRouter) diff --git a/src/api/v1/auth/__init__.py b/src/api/v1/auth/__init__.py new file mode 100644 index 00000000..a06f755a --- /dev/null +++ b/src/api/v1/auth/__init__.py @@ -0,0 +1,95 @@ +from os import getenv + +from fastapi import APIRouter, Form, HTTPException, Request, status +from fastapi.responses import JSONResponse +from pydantic import EmailStr +from typing_extensions import Annotated + +from api.shared import limiter +from api.v1.models import GenericEmptyResponse +from api.v1.shared import TokenBearer +from utils import users_auth +from utils.helper import dtToTimestamp + +from .models import Login, LoginToken + +router = APIRouter( + tags = ["authentication"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +@router.post( + "/login", + summary = "Get a token to use in other endpoints", + description = "You can use this token for the endpoints. If given user has 2FA enabled, they must provide the 2FA code along with their credentials through either `Gaijin pass` or the `/v1/answer-2fa` endpoint. If you generated a token that hasn't expired yet, the endpoint will just overwrite the previous token.", + responses = { + status.HTTP_200_OK: {"model": Login.LoginResponse}, + status.HTTP_206_PARTIAL_CONTENT: {"description": "The account has 2FA enabled. Go through the 2FA process to log in."}, + status.HTTP_408_REQUEST_TIMEOUT: {"description": "Account has Two Factor Authentication, and authentication timed out"}, + status.HTTP_429_TOO_MANY_REQUESTS: {"description": "Rate limit exceeded. Please wait a bit before trying again."}, + }, + response_model=Login.LoginResponse +) +@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) +async def login_post( + request: Request, + email: Annotated[EmailStr, Form()], + password: Annotated[str, Form(min_length = 6, max_length = 64, json_schema_extra = {"format": "password"})] +): + token, uidHint = await users_auth.login(email, password) + + return Login.LoginResponse(token = token, user_id = uidHint) + +@router.post( + "/refresh-token", + summary = "Refresh your token so it stays alive for longer. This is essentially a 'No op', just to keep the token active.", + description = "If you are cached it will refresh the token. The game generally refreshes the token every 30 minutes. Returns an UNIX timestamp of the new token expiry", + responses = { + status.HTTP_200_OK: {"model": LoginToken.LoginTokenResponse, "description": "Token refreshed successfully"}, + status.HTTP_401_UNAUTHORIZED: {"model": LoginToken.LoginFailResponse, "description": "Invalid token provided. The token is either expired or invalid."}, + status.HTTP_429_TOO_MANY_REQUESTS: {"description": "Rate limit exceeded. Please wait a bit before trying again."} + }, + response_model=LoginToken.LoginTokenResponse +) +@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) +async def login_token( + request: Request, + user: TokenBearer +): + await user.entry.refresh() + return { + "expires": dtToTimestamp(user.entry.expires), + "status": "OK" + } + +@router.post( + "/answer-2fa", + summary = "Provide 2FA code to finish login in case of a 2FA account without Gaijin Pass", + responses={ + status.HTTP_200_OK: {"model": Login.LoginResponse, "description": "Successful 2FA Authentication"} + }, + response_model=Login.LoginResponse +) +@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) +async def answer_2fa( + request: Request, + 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[str, Form(title = "The 2FA code")] +): + token, uidHint = await users_auth.login(email, password, code = code) + return Login.LoginResponse(token = token, user_id = uidHint) + +@router.delete( + "/remove", + summary = "Removes your login entry from our system", + response_model=GenericEmptyResponse +) +@limiter.limit(getenv("LOGIN_RATE_LIMIT", "5/minute")) +async def remove_login( + request: Request, + user: TokenBearer +): + if (await users_auth.remove_entry(user.entry)): + return JSONResponse({"success": True}) + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An error occurred during login deletion") diff --git a/src/api/v1/auth/models.py b/src/api/v1/auth/models.py new file mode 100644 index 00000000..1c214866 --- /dev/null +++ b/src/api/v1/auth/models.py @@ -0,0 +1,17 @@ +from typing import Literal + +from pydantic import BaseModel, Field + + +class Login: # /v1/login endpoint + class LoginResponse(BaseModel): + status: Literal["OK"] = "OK" + token: str + user_id: int +class LoginToken: # /v1/login-token endpoint + class LoginTokenResponse(BaseModel): + expires: int = Field(description = "UNIX timestamp of the new token expiry") + status: Literal["OK"] = "OK" + class LoginFailResponse(BaseModel): + status: Literal["FAIL"] = "FAIL" + detail: str diff --git a/src/api/v1/clans/__init__.py b/src/api/v1/clans/__init__.py new file mode 100644 index 00000000..423ca984 --- /dev/null +++ b/src/api/v1/clans/__init__.py @@ -0,0 +1,359 @@ +from datetime import UTC, datetime, timedelta +from os import getenv + +from fastapi import APIRouter, Form, HTTPException, Path, Query, status +from fastapi import Request as faRequest +from typing_extensions import Annotated + +from api.shared import limiter +from api.v1.clans.backend import ( + SQB_BRACKET_TIMES, + current_sqb_br, + get_sqb_brackets, + getClan, + getLeaderboard, + getLogs, + searchClan, +) +from api.v1.models import GenericEmptyResponse +from api.v1.shared import OptionalAuth, ServerBearer, TokenBearer +from utils.connection import Request + +from .models import ( + ApplicantModel, + ClanLeaderboardModel, + ClanModel, + ClanSearchResultModel, + CurrentSQBBracket, + LogsModel, + Roles, + RolesDisplay, + SQBTimeBracket, +) + +squadronId = Annotated[int, Path(title = "The squadron's ID", gt = 0)] +gaijinUserId = Annotated[int, Path(title = "The user's ID", gt = 0)] + +router = APIRouter( + prefix = "/clans", + tags = ["clans"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +@router.post( + "/apply/{clanId}", + summary = "Sends an application to the squadron, if allowed", + responses = { + status.HTTP_409_CONFLICT: {"description": "User is already in a squadron"} + }, + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def send_application( + request: faRequest, + user: TokenBearer, + clanId: squadronId, + comment: Annotated[str, Query(description = "The message sent with the application. Doesn't appear ingame, only through this API, so if the squadron isn't using an API, they won't see it")] = "" +): + response = await Request.send_template( + user, + "clan_membership_request", + remove_keys = set(["cancelRequest"]), + _id = clanId, + comments = comment + ) + return {"success": response.get("clanTag") is not None} + +@router.post( + "/cancelApply", + summary = "Cancels the current squadron application", + responses = { + status.HTTP_409_CONFLICT: {"description": "User is already accepted into the squadron. Use the `leave` endpoint instead"} + }, + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def unsend_application( + request: faRequest, + user: TokenBearer, + comment: str = "" +): + response = await Request.send_template( + user, + "clan_membership_request", + remove_keys = set(["_id"]), + comments = comment, + cancelRequest = True + ) + return {"success": response.get("clanTag") is None} + +@router.post( + "/leave", + summary = "Leaves the current squadron", + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def leave_squadron( + request: faRequest, + user: TokenBearer +): + response = await Request.send_template( + user, + "clan_leave" + ) + return {"success": response.get("clanTag") is None} + +@router.get( + "/applicants/{clanId}", + summary = "Gets the currently applying members", + response_model=list[ApplicantModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_applicants( + request: faRequest, + user: ServerBearer, + clanId: squadronId +): + clanData = await getClan(user, clanId) + applicants = clanData.get("applicants") + if applicants is None: + return [] + return applicants +@router.post( + "/accept/{userId}", + responses = { + status.HTTP_200_OK: { + "model": GenericEmptyResponse, + "description": "Successfully accepted the applicant", + }, + status.HTTP_403_FORBIDDEN: { + "description": "You do not have permission to accept applicants" + }, + status.HTTP_404_NOT_FOUND: { + "description": "The given user is not an applicant" + } + }, + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def accept_applicant( + request: faRequest, + user: TokenBearer, + userId: gaijinUserId, + role:RolesDisplay = RolesDisplay.PRIVATE +): + squadronId = await user.entry.getSquadronId() + if squadronId is None: + raise HTTPException(403, "User is not part of a squadron") + data = await Request.send_template( + user, + "clan_accept_membership_request", + userId = userId, + _id = squadronId, + role = Roles[role.name.upper()].value + ) + return data + +@router.post( + "/reject/{userId}", + responses = { + status.HTTP_200_OK: {"model": GenericEmptyResponse, "description":"Successfully rejected user"}, + status.HTTP_404_NOT_FOUND: {"description":"Applicant could not be found"}, + status.HTTP_403_FORBIDDEN: {"description":"You do not have permission to reject applicants"} + }, + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def reject_applicant( + request: faRequest, + user: TokenBearer, + userId: gaijinUserId, + message: Annotated[str, Query(title = "Message to include alongside rejection")] = "", +): + squadronId = await user.entry.getSquadronId() + if squadronId is None: + raise HTTPException(403, "User is not part of a squadron") + data = await Request.send_template( + user, + "clan_reject_membership_request", + userId = userId, + _id = squadronId, + comments = message + ) + return data + +@router.post( + "/role/{userId}", + summary = "Set a member's role", + description = "Requires `Deputy` or `Commander` level in squadron", + responses = { + status.HTTP_200_OK: {"model": GenericEmptyResponse}, + status.HTTP_403_FORBIDDEN: {"description": "You do not have the required permissions"} + }, + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def change_role( + request: faRequest, + user: TokenBearer, + userId: gaijinUserId, + role: Annotated[RolesDisplay, Query(title = "The role to assign")], +): + role = Roles[role.name] + data = await Request.send_template( + user, + "clan_change_member_role", + userid = userId, + role = role.value + ) + return data + +@router.post( + "/kick/{userId}", + summary = "Kicks the given user", + description = "Requires either `Officer`, `Deputy` or `Commander` rank to remove someone else", + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def kick_member( + request: faRequest, + user: TokenBearer, + userId: gaijinUserId, + reason: Annotated[str, Form(title = "The reason for kicking")] = "", +): + data = await Request.send_template( + user, + "clan_dismiss_member", + userid = userId, + comments = reason + ) + return data + +@router.get( + "/logs/{clanId}", + summary = "Gets the squadron logs", + response_model=LogsModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_clan_logs( + request: faRequest, + user: OptionalAuth, + clanId: squadronId, + limit: Annotated[int, Query(title = "The max ammount to get at once", gt = 0, le = 50)] = 10, + fromEntry: Annotated[str, Query(title = "The last call's 'lastLog' value to begin searching from")] = None, +): + return await getLogs(user, clanId, limit, fromEntry) + +@router.get( + "/search", + summary = "Search for squadron", + response_model=list[ClanSearchResultModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_clan_search( + request: faRequest, + user: ServerBearer, + clanName: Annotated[str, Query(title = "Squadron name to look up")] = None, + clanTag: Annotated[str, Query(title = "Squadron tag to look up")] = None, + limit: Annotated[int, Query(title = "Amount of squadrons to return", gt = 0, lt = 50)] = 10, + page: Annotated[int, Query(title = "The page to display. Count starts from 0", ge = 0)] = 0, +): + return await searchClan(user, clanName = clanName, clanTag = clanTag, limit = limit, page = page) + +@router.get( + "/leaderboard", + summary = "Gets the leaderboard of squadrons.", + response_model=list[ClanLeaderboardModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_clan_leaderboard( + request: faRequest, + user: ServerBearer, + limit: Annotated[int, Query(title = "The max amount to get at once", gt = 0, le = 50)] = 20, + page: Annotated[int, Query(title = "The page to look up. Starts from 0.", ge = 0)] = 0, +): + return await getLeaderboard(user, limit, page) + +@router.get( + "/leaderboard/{clanId}", + summary = "Gets the leaderboard position of a given squadron.", + responses = { + 404: {"description": "Clan not found"} + }, + response_model=ClanLeaderboardModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_clan_leaderboard_position( + request: faRequest, + user: ServerBearer, + clanId: Annotated[int, Path(title = "The squadron's ID")], +): + r = await getLeaderboard(user, clanId = clanId) + + if r is None or len(r) < 1: + raise HTTPException(404, "Clan not found") + + return r[0] + +@router.get( + "/sqb", + summary = "Returns the current season's SQB/SRB battle rating brackets", + description = "Data is obtained from the forum post, if this data is outdated here, it is probably outdated there", + response_model=tuple[SQBTimeBracket, ...] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_brackets( + request: faRequest +): + return await get_sqb_brackets() + +@router.get( + "/sqb/current", + summary = "Returns the current SQB/SRB bracket, and if one is open, also returns it's start and end time. If currently there is no open timebracket, it returns the next bracket's start and end", + description = "Data is obtained from the forum post, if this data is outdated here, it is probably outdated there", + response_model=CurrentSQBBracket +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_current_bracket( + request: faRequest +): + bracket = await current_sqb_br() + + rn = datetime.now(UTC) + date = max(rn.date(), bracket["start"].date()) + last_date = bracket["end"].date() + + while date <= last_date: + for start, end in SQB_BRACKET_TIMES: + start_dt = datetime.combine(date, start, UTC) + end_dt = datetime.combine(date, end, UTC) + if start_dt <= rn <= end_dt: + return { + "bracket": bracket, + "start": start_dt, + "end": end_dt + } + if start_dt > rn: + return { + "bracket": bracket, + "start": start_dt, + "end": end_dt + } + date += timedelta(days = 1) + + return { + "bracket": bracket + } + +@router.get( + "/{clanId}", + summary = "Gets data about the given squadron", + response_model=ClanModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "clans") +async def get_clan( + request: faRequest, + user: ServerBearer, + clanId: Annotated[int, Path(title = "The squadron's ID")], +): + return await getClan(user, clanId) diff --git a/app/api/v1/backends/clans.py b/src/api/v1/clans/backend.py similarity index 64% rename from app/api/v1/backends/clans.py rename to src/api/v1/clans/backend.py index 23c0855d..cff2f1ac 100644 --- a/app/api/v1/backends/clans.py +++ b/src/api/v1/clans/backend.py @@ -1,17 +1,20 @@ -from asyncio import Lock +import asyncio +from datetime import UTC, datetime, time from logging import getLogger as _gL -from fastapi import HTTPException, status +from re import IGNORECASE +from re import search as re_search from typing import Any -from datetime import datetime, UTC, time + from bs4 import BeautifulSoup -from re import search as re_search, IGNORECASE +from fastapi import HTTPException, status -from utils.connection import Request +import utils.connection.network as Network from utils.auth import LoginEntry +from utils.connection import Request from utils.geo import lookup_city, lookup_utc_offset -from utils.helper import Keymod -from api.v1.models.clans import ClanModel, Roles, Platforms, Actions, ClanLeaderboardModel, ClanSearchResultModel -import utils.connection.network as Network +from utils.helper import dictUtil + +from .models import Actions, ClanLeaderboardModel, ClanModel, ClanSearchResultModel, Platforms, Roles _logger = _gL(__name__) @@ -19,12 +22,12 @@ async def getLeaderboard(user: LoginEntry, limit: int = 20, page: int = 0, clanI response = await Request.from_template( user, "clan_get_leaderboard", - count=limit, - start=limit*page + count = limit, + start = limit*page ) if clanId is None: - response.headers.pop("clanId") + response.headers.pop("clanId", None) else: response.replace("count", 1) response.replace("start", 0) @@ -97,12 +100,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: @@ -131,14 +134,14 @@ async def getLogs(user: LoginEntry, clanId: int, limit: int = 10, fromEntry: str } async def searchClan(user: LoginEntry, clanName: str | None = None, clanTag: str | None = None, limit: int = 10, page:int = 0) -> list[ClanSearchResultModel]: + if clanName is None and clanTag is None: + raise HTTPException(status.HTTP_400_BAD_REQUEST, "You must provide either a clanName or clanTag") response = await Request.from_template( user, "clan_find_by_prefix", - count=limit, - start=limit*page + count = limit, + start = limit*page ) - if clanName is None and clanTag is None: - raise HTTPException(status.HTTP_400_BAD_REQUEST, "You must provide either a clanName or clanTag") if clanName: response.headers["namePrefix"] = clanName else: @@ -147,6 +150,7 @@ async def searchClan(user: LoginEntry, clanName: str | None = None, clanTag: str response.headers["tagPrefix"] = clanTag else: del response.headers["tagPrefix"] + response = await response.send() if isinstance(response["clan"], dict): response["clan"] = [response["clan"],] @@ -156,7 +160,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"] @@ -168,48 +172,63 @@ async def getClan(user: LoginEntry, clanId: int) -> ClanModel: data = await Request.send_template( user, "clan_get", - clanId=clanId + clanId = clanId ) 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.KeyMod("_id", new_name = "id"), + dictUtil.KeyRem( + "transactions", + "namel", + "regionl", + "tagl", + "currentTagRegalia", + "interlockid", + "type" + ), ) - data = Keymod.run_all(data, SANITIZE) + data = await dictUtil.run_all(data, SANITIZE) return data SQB_BRACKET_TIMES = ( ( - time(hour=1, minute=0, tzinfo=UTC), - time(hour=7, minute=0, tzinfo=UTC) + time(hour = 1, minute = 0, tzinfo = UTC), + time(hour = 7, minute = 0, tzinfo = UTC) ), ( - time(hour=14, minute=0, tzinfo=UTC), - time(hour=22, minute=0, tzinfo=UTC) + time(hour = 14, minute = 0, tzinfo = UTC), + time(hour = 22, minute = 0, tzinfo = UTC) ) ) SQB_BRACKET_CACHE: tuple[dict[str, datetime|float]] | None = None -SQB_BRACKET_CACHE_LOCK = Lock() +SQB_BRACKET_CACHE_LOCK = asyncio.Lock() 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" - }) 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) + async with Network.get( + "https://forum.warthunder.com/t/season-schedule-for-squadron-battles/4446", + Network.ReturnType.TEXT, + headers = { + "User-Agent": "Thunderapi/1.0" + } + ) as resp: + document = BeautifulSoup(resp, "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() @@ -217,8 +236,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: @@ -251,11 +270,22 @@ 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") -def sanitizeMembers(members:dict|list): +async def next_sqb_bracket() -> dict[str, datetime|float]: + weeks = await get_sqb_brackets() + rn = datetime.now(UTC) + for week in weeks: + if week["start"] > rn: + return week + raise HTTPException(status.HTTP_404_NOT_FOUND, "Could not find next bracket data") + +async def sanitizeMembers(members:dict|list): if members is None: return [] @@ -263,53 +293,56 @@ 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") + }, default = Platforms.PC.value), + 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] = 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 [] if isinstance(applicants, dict): applicants = [applicants,] - def _ip_to_geo(x: str) -> dict[str, Any] | None: - geo = lookup_city(x) - if geo is None: - return - - return { - "offset": lookup_utc_offset(geo.location.time_zone), - "city": geo.city.name, - "country": geo.country.iso_code - } + async def _ip_to_geo(x: str) -> dict[str, Any] | None: + try: + geo = await asyncio.to_thread(lookup_city, x) + if geo is None: + return None + + return { + "offset": await asyncio.to_thread(lookup_utc_offset, geo.location.time_zone), + "city": geo.city.name, + "country": geo.country.iso_code + } + except Exception: + return 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 = _ip_to_geo) ) for i, applicant in enumerate(applicants): - applicants[i] = Keymod.run_all(applicant, SANITIZATION) + applicants[i] = await dictUtil.run_all(applicant, SANITIZATION) return applicants diff --git a/app/api/v1/models/clans.py b/src/api/v1/clans/models.py similarity index 83% rename from app/api/v1/models/clans.py rename to src/api/v1/clans/models.py index 575b50a4..33529077 100644 --- a/app/api/v1/models/clans.py +++ b/src/api/v1/clans/models.py @@ -1,8 +1,10 @@ +from datetime import datetime from enum import Enum, IntEnum -from pydantic import BaseModel, Field from typing import Literal -from datetime import datetime -from ..backends.shared import IpString, IntString + +from pydantic import BaseModel, ConfigDict, Field + +from api.v1.shared import IntString PLATFORM_NAMES = Literal["PC", "PSN_TRANSFER_PC", "PSN", "XBOX_TRANSFER_PC", "XBOX"] class Actions(Enum): @@ -34,7 +36,7 @@ class Platforms(Enum): XBOX = 12 class ApplicantModel(BaseModel): - uid: int + uid: IntString nickname: str timestamp: int comment: str @@ -42,7 +44,7 @@ class GeolocationDataModel(BaseModel): offset: float country: str city: str - geo:GeolocationDataModel = Field(default=None) + geo:GeolocationDataModel = Field(default = None) class MemberModel(BaseModel): class enumModel(BaseModel): @@ -62,22 +64,22 @@ class LogsModel(BaseModel): logs: list[ClanLogs] class ClanLogs(BaseModel): class _userEntry(BaseModel): - _id: int + id: int nickname: str class _action(BaseModel): value: int detail: str class _roleChange(BaseModel): - old: str | None = Field(default=None, description="Previous role. Only present for role-change log entries.") - new: str | None = Field(default=None, description="New role. Only present for role-change log entries.") + old: str | None = Field(default = None, description = "Previous role. Only present for role-change log entries.") + new: str | None = Field(default = None, description = "New role. Only present for role-change log entries.") timestamp: int - affected: _userEntry | None = Field(default=None, exclude_if=lambda x: x is None) + affected: _userEntry | None = Field(default = None, exclude_if = lambda x: x is None) action: _action - admin: _userEntry | None = Field(default=None, exclude_if=lambda x: x is None) - roleChange: _roleChange | None = Field(default=None, exclude_if=lambda x: x is None) + admin: _userEntry | None = Field(default = None, exclude_if = lambda x: x is None) + roleChange: _roleChange | None = Field(default = None, exclude_if = lambda x: x is None) class ClanLeaderboardModel(BaseModel): class ClanStatsModel(BaseModel): @@ -144,7 +146,7 @@ class astatModel(BaseModel): activity: int clan_activity_by_periods: int pos: int | None = None - _id: int | None = None + id: IntString | None = None autoaccept: bool | None = None cdate: int | None = None changed_by_uid: int | None = None @@ -162,10 +164,9 @@ class astatModel(BaseModel): membership_req: dict | None = None astat: astatModel | None = None clanRewardRatingPerUser_60: dict | None = None - applicants: list[ApplicantModel] | None = Field(default=None, exclude_if=lambda x: x is None) + applicants: list[ApplicantModel] | None = Field(default = None, exclude_if = lambda x: x is None) - class Config: - extra = "allow" + model_config = ConfigDict(extra = "allow") class ClanSearchResultModel(BaseModel): id: int diff --git a/src/api/v1/general/__init__.py b/src/api/v1/general/__init__.py new file mode 100644 index 00000000..ec5581cf --- /dev/null +++ b/src/api/v1/general/__init__.py @@ -0,0 +1,43 @@ +from os import getenv +from typing import Literal + +from fastapi import APIRouter, Query, Request, WebSocket, status +from typing_extensions import Annotated + +from api.shared import limiter +from api.v1.shared import IpString +from utils import newsManager +from utils.news import NewsEntry + +from .backend import getLatestGameVer + +router = APIRouter( + tags = ["general"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +@router.get("/latestGameVersion", summary = "Get latest game version", response_model=IpString) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "general") +async def get_latest_game_ver( + request: Request, + branch: Annotated[Literal["dev", "dev-stable"], Query(title = "The game version to get")] = None, +): + return await getLatestGameVer(branch) + +@router.get( + "/news", + summary = "Gets the latest news from gaijin", + description = "Puts the pinned news first (Current update changelog + latest big news). There is additionally a `/v1/news_ws` websocket, that doesn't require any authentication, and provides the news through there. This websocket is the single exception to the 'token auth everywhere' rule. Websocket returns the same format for an entry like this endpoint", + response_model=list[NewsEntry] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "general") +async def get_news(request: Request): + return await newsManager.fetch() + +@router.websocket( + "/news_ws", + name = "News stream" +) +async def news_ws(websocket: WebSocket): + async for _msg in newsManager.websocket_mgr.connect(websocket): + pass # Ignore all messages diff --git a/src/api/v1/general/backend.py b/src/api/v1/general/backend.py new file mode 100644 index 00000000..b6889e5b --- /dev/null +++ b/src/api/v1/general/backend.py @@ -0,0 +1,13 @@ +from typing import Literal + +import utils.connection.network as Network + + +async def getLatestGameVer(branch: Literal["dev", "dev-stable"]|None): + if branch is None: + branch = "" + async with Network.get( + f"https://yupmaster.gaijinent.com/yuitem/get_version.php?proj=warthunder&tag={branch}", + Network.ReturnType.TEXT + ) as response: + return response diff --git a/src/api/v1/marketplace/__init__.py b/src/api/v1/marketplace/__init__.py new file mode 100644 index 00000000..21f97867 --- /dev/null +++ b/src/api/v1/marketplace/__init__.py @@ -0,0 +1,271 @@ +from decimal import Decimal +from os import getenv + +from fastapi import APIRouter, HTTPException, Path, Query, status +from fastapi import Request as faRequest +from typing_extensions import Annotated + +from api.shared import limiter +from api.v1.models import GenericEmptyResponse +from api.v1.shared import ServerBearer, TokenBearer +from utils.connection import Request + +from .backend import User +from .models import Models + +router = APIRouter( + prefix = "/market", + tags = ["marketplace"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +@router.post( + "/orders/{orderId}/cancel", + summary = "Cancels an order", + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def cancel_order( + request: faRequest, user: TokenBearer, + orderId: Annotated[int, Path(description = "The order ID")] +): + orders = await User(user).orders() + if orderId not in orders: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Order ID not found") + + result = await orders[orderId].cancel() + return {"success": result} + +@router.get( + "/orders/{orderId}", + summary = "Gets information about an order", + response_model=Models.OrderModel +) +@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 User(user).orders() + if orderId not in orders: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Order ID not found") + return orders[orderId].to_json() + +@router.get( + "/orders", + summary = "Gets the currently active orders", + responses = { + status.HTTP_200_OK: {"model": list[Models.OrderModel]} + }, + response_model=list[Models.OrderModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def get_orders( + request: faRequest, user: TokenBearer, + orderType: Annotated[User.Order.Type | None, Query()] = None +): + return [order.to_json() for order in (await User(user).orders(orderType)).values()] + +@router.get( + "/inventory", + summary = "Gets the account's inventory contents", + response_model=list[Models.InventoryItemModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def getInventory( + request: faRequest, user: TokenBearer +): + inv = await User(user).inventory() + return [ + i.to_json() + for i in inv.values() + ] + +@router.get( + "/balance", + summary = "Gets the account's balance", + response_model=Models.BalanceModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def get_balance( + request: faRequest, user: TokenBearer +): + return {"balance": await User(user).balance()} + +@router.get( + "/search", + summary = "Searches the marketplace for a given item", + responses = { + status.HTTP_200_OK: {"model": list[Models.ItemModel]} + }, + response_model=list[Models.ItemModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def searchItem( + request: faRequest, user: ServerBearer, + name: Annotated[str, Query(title = "The item to search for. Leave empty to search for ALL units")] = "", + 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 User(user).MarketItem.search(user, name, count, page) + return [await i.to_json() for i in data.values()] + +@router.get( + "/{itemHash}/history", + summary = "Retrieves marketplace history data about the given item", + response_model=Models.OrderHistoryModel +) +@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")], +): + pairData = await Request.send_template( + user, + "cln_get_pair_stat", + market_name = itemHash + ) + if "response" in pairData: + pairData = pairData["response"] + else: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") + + ret_data = { + "short":[], + "whole":[] + } + for i in pairData["1h"]: + ret_data["short"].append({ + "timestamp": i[0], + "price": i[1]/10000, + "transactions_count": i[2] + }) + for i in pairData["1d"]: + ret_data["whole"].append({ + "timestamp": i[0], + "price": i[1]/10000, + "transactions_count": i[2] + }) + return ret_data + +@router.get( + "/{itemHash}/orders", + summary = "Retrieves marketplace data about the given item", + response_model=Models.OrdersModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def get_item_orders( + request: faRequest, user: ServerBearer, + itemHash: Annotated[str, Path(title = "The item to look up")], +): + books_brief = await Request.send_template( + user, + "cln_books_brief", + market_name = itemHash + ) + if "response" in books_brief: + books_brief = books_brief["response"] + else: + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "An unexpected error occurred") + + ret_data = {} + ret_data["buy_orders"] = books_brief["depth"]["BUY"] + ret_data["sell_orders"] = books_brief["depth"]["SELL"] + ret_data["buy_prices"] = [{"price":i[0]/10000,"amount":i[1]} for i in books_brief["BUY"]] + ret_data["sell_prices"] = [{"price":i[0]/10000,"amount":i[1]} for i in books_brief["SELL"]] + return ret_data + +@router.get( + "/{itemHash}/view", + summary = "Views the item ingame", + response_model=GenericEmptyResponse +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def view_item( + request: faRequest, user: TokenBearer, + itemHash: Annotated[str, Path(title = "The item's hash to view")], +): + 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, + "market_view_item1", + params = { + "appId": "1067", + "assetClass": [ + { + "name": hashData[0]["name"], + "value": hashData[0]["value"] + } + ] + } + ) + await Request.send_template( + user, + "market_view_item2" + ) + return {"success": 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"} + }, + response_model=list[Models.SellModel] +) +@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[Decimal, Query(description = "The price in GJN to sell for (Includes gaijin's fee, not the value you get)", ge = 0.1, le = 2000, decimal_places=2)], + 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 +): + return await User(user).sell(item_hash = itemHash, price = price, count = count, anonymous = anonymous) + +@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"} + }, + response_model=GenericEmptyResponse +) +@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[Decimal, Query(description = "The price in GJN to buy for", ge = 0.1, le = 2000, decimal_places=2)], + count: Annotated[int, Query(description = "The amount to buy", gt = 0)] = 1, + anonymous: Annotated[bool, Query(description = "Appear as an anonymous buyer")] = False +): + return await User(user).buy(item_hash = itemHash, price = price, count = count, anonymous = anonymous) + +@router.get( + "/{itemHash}", + summary = "Gets metadata about the given item", + response_model=Models.ItemModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "trade") +async def get_item( + request: faRequest, user: ServerBearer, + itemHash: Annotated[str, Path(title = "The item to look up")], +): + item = await User.MarketItem.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/marketplace/backend.py b/src/api/v1/marketplace/backend.py new file mode 100644 index 00000000..cdff39a1 --- /dev/null +++ b/src/api/v1/marketplace/backend.py @@ -0,0 +1,409 @@ +import asyncio +from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime +from decimal import Decimal +from enum import StrEnum +from random import randint +from typing import Any, TypedDict + +from fastapi import HTTPException, status + +import utils.connection.network as Network +from api.v1.shared import IntString +from utils.auth import LoginEntry +from utils.connection import Request +from utils.helper import dictUtil, dtToTimestampMs + + +class User: + login: LoginEntry + def __init__(self, login: LoginEntry): + self.login = login + + @dataclass(frozen = True, slots = True) + class Order: + class Type(StrEnum): + BUY = "buy" + SELL = "sell" + LOGIN: LoginEntry + market_hash: str + id: int + type: Type + pairId: int + 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 = cls.Type[obj["type"]], + pairId = int(obj["pairId"]), + price = int(obj["localPrice"])/10000, + timestamp = datetime.fromtimestamp(obj["time"], UTC), + amount = int(obj["amount"]) + ) + + 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.") + + def to_json(self): + return { + "market_hash": self.market_hash, + "id": self.id, + "type": self.type, + "price": self.price, + "timestamp": self.timestamp, + "amount": self.amount + } + + @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 + icon_url_large: str + hash: str + name: str + display_name:str + tags: list[dict[str, str|int]] + type: str + marketable: bool + name_color: str + class_name: str + class_value: int + ids:list[int] + contextid: int + @classmethod + def from_json(cls, data:dict[str, Any], user: LoginEntry, itemData: dict[str, Any], context: int): + assetData: dict[str, Any] = data["result"]["asset"] + classData: dict[str, Any] = itemData["class"][0] + + return cls( + LOGIN = user, + commodity = assetData.get("commodity") or False, + 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 + ) + + async def sell(self, price: Decimal | float, count: int, anonymous: bool = False) -> tuple[SellData]: + agree_stamp = dtToTimestampMs(datetime.now(UTC)) + if isinstance(price, Decimal): + price = int(price*100)/100 + + price = int(round(price*10000, -2)) + seller_should_get = int(round(price*0.85, -2)) + + soldItems = [] + sold = 0 + if len(self.ids) < count: + 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)[:count]: + 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 = price, + seller_should_get = seller_should_get, + agree_stamp = agree_stamp, + privateMode = anonymous, + contextid = self.contextid + ) + success = resp.get("response", {}).get("success", False) + if success: + self.ids.remove(id) + sold += 1 + soldItems.append({ + "item": str(id), + "success": success, + "price": price/10000, + "seller_gets": seller_should_get/10000 + }) + + return tuple(soldItems) + + def to_json(self): + return { + "commodity": self.commodity, + "description": self.description, + "icon_url": self.icon_url, + "icon_url_large": self.icon_url_large, + "hash": self.hash, + "name": self.name, + "display_name": self.display_name, + "tags": self.tags, + "type": self.type, + "marketable": self.marketable, + "name_color": self.name_color, + "count": len(self.ids), + } + + @dataclass(slots = True) + class MarketItem: + 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: + raise RuntimeError(f"Somehow item {data["hash_name"]}'s tag '{tag}' has more than 1 separator") + 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") or 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") or False, + icon = assetData.get("icon_url_large", assetData.get("icon_url", None)), + 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", [])), 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"], + 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) -> dict[str, User.MarketItem]: + 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[item["hash_name"]] = User.MarketItem.from_dict(item) + return items + + @staticmethod + async def get(user: LoginEntry, itemHash: str) -> User.MarketItem: + 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 User.MarketItem.from_assetdata(resp, books_brief, hashData) + + async def orders(self, orderType: Order.Type | None = None) -> dict[int, "Order"]: + data = await Request.send_template(self.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"]: + if orderType is None or orderType == self.Order.Type[entry["type"]]: + orders[int(entry["id"])] = User.Order.from_dict(entry, self.login) + return orders + + async def balance(self) -> float: + data = await Request.send_template( + self.login, + "GetBalance" + ) + if data.get("status") == "OK": + return data["balance"]/10000 + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to get balance") + + async def inventory(self) -> dict[tuple[str, Any, int], InventoryItem]: + items:dict[tuple[str, Any, int], User.InventoryItem] = {} + async with Network.operation() as session: + contexts = await Request.send_template( + self.login, + "GetContexts", + session = session + ) + 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( + self.login, + "GetContextContents", + session = session, + contextid = context["id"] + ) + if "result" not in ctx_data: + continue + for item in ctx_data["result"]["assets"]: + item_data = await Request.send_template( + self.login, + "GetAssetClassInfo", + session = session, + class_name0 = item["class"][0]["name"], + class_value0 = item["class"][0]["value"] + ) + if "result" not in item_data: + continue + key = (item["class"][0]["name"], item["class"][0]["value"], int(context["id"])) + if key in items: + items[key].ids.append(int(item["id"])) + else: + items[key] = self.InventoryItem.from_json(item_data, self.login, item, int(context["id"])) + return items + + async def sell(self, item_hash: str, price: Decimal | float, count: int = 1, anonymous: bool = False) -> tuple[InventoryItem.SellData, ...]: + matching = [item for item in (await self.inventory()).values() if item.hash == item_hash] + if not matching: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Item not found in inventory") + + total = sum(len(item.ids) for item in matching) + if total < count: + raise HTTPException(status.HTTP_400_BAD_REQUEST, f"Requested selling {count} items, but user only has {total} items in their inventory") + + sold = [] + remaining = count + for item in matching: + if remaining <= 0: + break + take = min(len(item.ids), remaining) + sold.extend(await item.sell(price = price, count = take, anonymous = anonymous)) + remaining -= take + + return tuple(sold) + + async def buy(self, item_hash: str, price: float, count: int = 1, anonymous: bool = False): + agree_stamp = dtToTimestampMs(datetime.now(UTC)) + resp = await Request.send_template( + self.login, + "cln_market_buy", + transactid = randint(10**6, 10**15), + reqstamp = dtToTimestampMs(datetime.now(UTC)), + market_name = item_hash, + 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") + + async def get_asset_class(self, hash:str) -> list[dict[str, str|IntString]]: + return await Request.send_template( + self.login, + "cln_market_get_asset_class", + name = hash + ) diff --git a/src/api/v1/marketplace/models.py b/src/api/v1/marketplace/models.py new file mode 100644 index 00000000..ea56f472 --- /dev/null +++ b/src/api/v1/marketplace/models.py @@ -0,0 +1,91 @@ +from datetime import datetime + +from pydantic import BaseModel, Field + +from api.v1.shared import IntString + + +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 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 + count: int + + 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] + + class BalanceModel(BaseModel): + balance: float diff --git a/src/api/v1/models.py b/src/api/v1/models.py new file mode 100644 index 00000000..1df5b0e9 --- /dev/null +++ b/src/api/v1/models.py @@ -0,0 +1,7 @@ + +from pydantic import BaseModel + + +class GenericEmptyResponse(BaseModel): + """Basic `{"success":true}` response""" + success: bool diff --git a/src/api/v1/replays/__init__.py b/src/api/v1/replays/__init__.py new file mode 100644 index 00000000..7310674d --- /dev/null +++ b/src/api/v1/replays/__init__.py @@ -0,0 +1,155 @@ +from os import getenv + +from fastapi import APIRouter, Path, Query, status +from fastapi import Request as faRequest +from typing_extensions import Annotated + +from api.shared import limiter +from api.v1.shared import TokenBearer +from utils.replayParser import Replay + +from .backend import ReplayMode, ReplayTechType, ReplayType, search_replay +from .models import DataModel, MatchModel, ReplayNotFoundModel, ResultsModel + +router = APIRouter( + prefix = "/replay", + tags = ["replays"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +""" +@router.get( + "/search", + summary = "Searches for replays based on given parameters", + responses = { + status.HTTP_200_OK: {"model": SearchModel}, + status.HTTP_403_FORBIDDEN: {"description": "The token has no associated `identity_sid` value associated, required for replay lookup. Get one from `/v1/get-sid`"}, + } +) +""" # FIXME: Temporarily removed due to issues with identity_sid generation +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") +async def search_replays( + request: faRequest, + user: TokenBearer, + uid: Annotated[ + int, + Query(title = "The UID of the user to search replays for") + ] = None, + nickname: Annotated[ + str, + Query(title = "The nickname of the user to search replays for") + ] = None, + gameType: Annotated[ + ReplayType, + Query( + title = "The type of game to search replays for", + description = "If not provided, will search for random battles", + min_length = 1 + ) + ] = ReplayType.RANDOM_BATTLE, + techType: Annotated[ + ReplayTechType, + Query( + title = "The type of tech to search replays for", + description = "If not provided, will search for all tech types", + min_length = 1 + ) + ] = ReplayTechType.ALL, + mode: Annotated[ + set[ReplayMode] | None, + Query( + title = "The game modes to filter by", + description = "If not provided, will search for all game modes", + ) + ] = None, + limit: Annotated[ + int, + Query( + title = "The maximum number of replays to return", + description = "Must be between 1 and 100", + ge = 1, + le = 100 + ) + ] = 25, + page: Annotated[ + int, + Query( + title = "The page of results to return", + description = "Must be 0 or greater", + ge = 0 + ) + ] = 0, +): + return await search_replay(user, uid, nickname, gameType, techType, mode, limit, page) + +@router.get( + "/{replayId}", + summary = "Gets data from a specified replay", + responses = { + status.HTTP_200_OK: {"model": DataModel}, + 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"} + }, + response_model = DataModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") +async def get_replay( + request: faRequest, + 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) + +@router.get( + "/{replayId}/teams", + 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"}, + status.HTTP_425_TOO_EARLY: {"description": "Replay probably hasn't ended yet, since it isn't properly parseable yet"} + }, + response_model = ResultsModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") +async def get_replay_teams( + request: faRequest, + 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": MatchModel}, + 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"} + }, + response_model = MatchModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "replays") +async def get_replay_match( + request: faRequest, + 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/app/api/v1/backends/replay.py b/src/api/v1/replays/backend.py similarity index 96% rename from app/api/v1/backends/replay.py rename to src/api/v1/replays/backend.py index 178d567f..0fdca618 100644 --- a/app/api/v1/backends/replay.py +++ b/src/api/v1/replays/backend.py @@ -1,7 +1,10 @@ +from enum import Enum, StrEnum + from fastapi import HTTPException, status -from enum import StrEnum, Enum + from utils.auth import LoginEntry + class ReplayType(StrEnum): RANDOM_BATTLE = "randomBattle" SQUADRON_TOURNAMENT = "squadron_tournament" diff --git a/src/api/v1/replays/models.py b/src/api/v1/replays/models.py new file mode 100644 index 00000000..9f2bc4c8 --- /dev/null +++ b/src/api/v1/replays/models.py @@ -0,0 +1,135 @@ +from typing import Literal + +from pydantic import BaseModel, Field + +from api.v1.shared import IntString, IpString + + +class SearchModel(BaseModel): + class ReplayEntry(BaseModel): + class PlayerEntry(BaseModel): + userId: IntString + name: str + fakeName: str + sessionId: str + sessionIdHex: str + policy: int + title: str + missionName: str + missionDescription: str + tournamentName: str + startTime: int + endTime: int + totalViews: int + statisticGroup: str + url: str + version: int + teamNames: None + gameVersion: IpString + clanBattle: bool + isCompleted: bool + isNewbies: bool + gameType: str + gameMode: str + players: dict[Literal["team_1", "team_2"], list[PlayerEntry]] + + class PaginationModel(BaseModel): + nextNum: int + first_page: int + items: list[int] + sumPages: int + offset: int + limit: int + items: list[ReplayEntry] + count: int + total_count: int + pagination: PaginationModel + partsCount: int + visible: int + id: 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 | None = Field( + default = None, + exclude_if = lambda x: x is None, + description = "Maximum battle rating of the user's lineup", + examples = [6.7, 8.0, 9.7] + ) + clanTag: str | None = Field( + default = None, + exclude_if = lambda x: x is None, + description = "Clan tag of the user, if applicable. Includes border", + examples = ["┾PECK┿"] + ) + nickname: str + autosquad: bool = Field(description = "Whether the user was assigned into a squad automatically") + squadId: int | None = Field( + default = None, + exclude_if = lambda x: x is None, + 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 + + spectators: dict[IntString, UserModel] + team1: dict[IntString, UserModel] + team2: dict[IntString, 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"]) + 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"]) + battleType: str +class DataModel(BaseModel): + status: Literal["OK"] = "OK" + + matchId: IntString + 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/shared.py b/src/api/v1/shared.py new file mode 100644 index 00000000..95ddf2df --- /dev/null +++ b/src/api/v1/shared.py @@ -0,0 +1,97 @@ +from datetime import UTC, datetime + +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from pydantic import Field, StringConstraints +from typing_extensions import Annotated + +import utils +from utils import users_auth +from utils.auth import LoginEntry + +security = HTTPBearer(description = "Get the token from `POST /v1/login`") +optional_security = HTTPBearer(auto_error = False) + +class Authentication: + @staticmethod + async def _track_usage(user: LoginEntry): + # move the existing flush/counter block here + flush = False + async with users_auth._auth_used_lock: + cache = users_auth._auth_used_cache.setdefault(user.entry.hashed, {"cnt": 0}) + cache["cnt"] += 1 + cache["used"] = datetime.now(UTC) + if cache["cnt"] >= 10: + user.entry.requests_count += cache["cnt"] + user.entry.last_used = cache["used"] + cache["cnt"] = 0 + flush = True + if flush: + await user.entry._write_values() + + @staticmethod + async def get_auth(credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]): + user = await users_auth.get(credentials.credentials) + if not user: + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "User not found") + user = user.getEntry() + await Authentication._track_usage(user) + return user + + @staticmethod + async def get_server_auth( + credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(optional_security)] = None + ) -> LoginEntry: + if utils.server_auth is None: + if credentials is None: + raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Server account unavailable, you must log in with an account") + return await Authentication.get_auth(credentials) + + entry = utils.server_auth.getLogin() + if entry is None: + if credentials is None: + raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Server account unavailable, you must log in with an account") + return await Authentication.get_auth(credentials) + return entry + + @staticmethod + async def get_optional_auth( + credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(optional_security)] + ) -> LoginEntry: + if credentials is not None: + user = await users_auth.get(credentials.credentials) + if user is not None: + user = user.getEntry() + await Authentication._track_usage(user) + return user + raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token") + return await Authentication.get_server_auth(credentials) + + +TokenBearer = Annotated[LoginEntry, Depends(Authentication.get_auth) ] +ServerBearer = Annotated[LoginEntry, Depends(Authentication.get_server_auth) ] +OptionalAuth = Annotated[LoginEntry, Depends(Authentication.get_optional_auth) ] + +IntString = Annotated[ + str, + StringConstraints(pattern = r"^\d+$"), + Field( + description = "Integer value represented as a string to avoid precision loss when JSON clients (JavaScript/IEEE-754) parse large 64-bit integers above 2^53 − 1.", + coerce_numbers_to_str = True, + examples = ["10016", "652677", "62762477"] + ), +] +FloatString = Annotated[ + str, + StringConstraints(pattern = r"^\d+(?:\.\d+)?$"), + Field( + description = "Floating point value represented as a string to avoid precision loss when JSON clients (JavaScript/IEEE-754) parse decimal values as binary floating point (IEEE-754 doubles).", + coerce_numbers_to_str = True, + examples = ["0.005", "1.0", "4.3"] + ), +] +IpString = Annotated[ + str, + StringConstraints(pattern = r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"), + Field(description = "IP address represented as a string", examples = ["0.0.0.0", "192.168.0.1", "127.0.0.1"]) +] diff --git a/src/api/v1/units/__init__.py b/src/api/v1/units/__init__.py new file mode 100644 index 00000000..785d2a46 --- /dev/null +++ b/src/api/v1/units/__init__.py @@ -0,0 +1,72 @@ +import asyncio +from enum import StrEnum +from os import getenv + +from fastapi import APIRouter, HTTPException, Path, Query, status +from fastapi import Request as faRequest +from typing_extensions import Annotated + +from api.shared import limiter +from utils.vehicleParser import shared +from utils.vehicleParser.localization import Languages + +from .models import LocalizationModel + +router = APIRouter( + tags = ["units"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}}, + prefix = "/units" +) + +class LanguagesCompat(StrEnum): + en = "en" + fr = "fr" + it = "it" + de = "de" + es = "es" + ru = "ru" + pl = "pl" + cs = "cs" + tr = "tr" + zh = "zh" + ja = "ja" + pt = "pt" + uk = "uk" + sr = "sr" + hu = "hu" + kr = "kr" + be = "be" + ro = "ro" + zh_tw = "zh_tw" + zh_cn = "zh_cn" + vi = "vi" + +@router.get( + "/{unit}/localization", + response_model=LocalizationModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "units") +async def localize_unit( + request: faRequest, + unit: Annotated[str, Path(description = "The internal hash of the vehicle")], + language: Annotated[LanguagesCompat, Query(description = "The language to get the localization for (e.g. en, de, fr)")] = LanguagesCompat.en +): + if not shared.UNIT_LOC: + asyncio.create_task(shared.update_gamefiles()) + raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Vehicle localizations not loaded. Please try again later") + if unit not in shared.UNIT_LOC: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Vehicle not found") + lang = Languages[language.value] + unit_loc = shared.UNIT_LOC[unit] + + short = unit_loc.get("short", {}) + shop = unit_loc.get("shop", {}) + if (lang.value not in short or lang.value not in shop) or (short[lang.value] is None or shop[lang.value] is None): + raise HTTPException(status.HTTP_404_NOT_FOUND, "Localization not found for vehicle") + return_dict = { + "short": unit_loc["short"][lang.value], + "long": unit_loc["shop"][lang.value] + } + if return_dict["short"] is None or return_dict["long"] is None: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Localization not found for vehicle") + return return_dict diff --git a/src/api/v1/units/models.py b/src/api/v1/units/models.py new file mode 100644 index 00000000..6b226179 --- /dev/null +++ b/src/api/v1/units/models.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel + + +class LocalizationModel(BaseModel): + short: str + long: str diff --git a/src/api/v1/users/__init__.py b/src/api/v1/users/__init__.py new file mode 100644 index 00000000..402b4881 --- /dev/null +++ b/src/api/v1/users/__init__.py @@ -0,0 +1,133 @@ +from os import getenv + +from fastapi import APIRouter, Path, Query, status +from fastapi import Request as faRequest +from typing_extensions import Annotated + +from api.shared import limiter +from api.v1.shared import ServerBearer, TokenBearer +from utils.connection import Request +from utils.helper import dictUtil + +from .backend import get_self, get_terse, get_user +from .models import SIMPLE_COUNTRIES, GamemodesEnum, TerseReturnModel, getUserDirect + +router = APIRouter( + prefix = "/users", + tags = ["users"], + responses = {status.HTTP_404_NOT_FOUND: {"description": "Not found"}} +) + +@router.get( + "/terse", + summary = "Get several users by ID", + response_model=dict[str, TerseReturnModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +async def get_users_terse_info( + request: faRequest, + user: ServerBearer, + id: Annotated[list[int], Query( + title = "The ID of the users to get information about", + description = "Provide multiple IDs to get information about multiple users at once", + min_length = 1, + max_length = 50) + ], +): + """Get terse information about users by their IDs.""" + return await get_terse(user, *id) + +@router.get( + "/search/{nick}", + summary = "Get users by name", + responses = {}, + response_model=dict[str, TerseReturnModel] +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +async def get_users_search( + request: faRequest, + user: ServerBearer, + nick: Annotated[str, Path(title = "The nickname to search for")], + limit: Annotated[int, Query(title = "How many users to retrieve", ge = 2, le = 50)] = 10, +): + response = await Request.send_template( + user, + "find_users_by_nick_prefix", + nick = nick, + maxCount = limit + ) + + return await get_terse(user, *list(response.keys())) + +@router.get( + "/self", + summary = "Get metadata about the logged in user", + responses = { + 200: {"model": getUserDirect.metaModel} + }, + response_model = getUserDirect.metaModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +async def get_self_meta( + request: faRequest, + user: TokenBearer +): + return await get_self(user) + +@router.get( + "/{userid}/meta", + summary = "Gets metadata about a user", + response_model=getUserDirect.metaModel +) +@limiter.shared_limit(getenv("REGULAR_RATE_LIMIT", "30/minute"), "users") +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)], +): + data = await get_user(user, userid) + SANITIZE = ( + dictUtil.KeyRem("summary", "statistics", "countries"), + ) + return await dictUtil.run_all(data, SANITIZE) + +@router.get( + "/{userid}/stats", + summary = "Gets per-vehicle statistics about a user", + response_model=dict[str, getUserDirect.statisticsModel.unitStatModel] +) +@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)], + mode: Annotated[GamemodesEnum, Query(title="The gamemode to query the data for")] +): + return (await get_user(user, userid))["statistics"].get(mode, {}) + +@router.get( + "/{userid}/countries", + summary = "Gets country data about a user", + response_model=dict[SIMPLE_COUNTRIES, getUserDirect.countriesModel] +) +@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)], +): + return (await get_user(user, userid))["countries"] + + +@router.get( + "/{userid}/summary", + summary = "Gets a summary of a user's statistics per-difficulty and per-vehicle type", + response_model=getUserDirect.summaryModel +) +@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)], +): + return (await get_user(user, userid))["summary"] diff --git a/src/api/v1/users/backend.py b/src/api/v1/users/backend.py new file mode 100644 index 00000000..d5340ab0 --- /dev/null +++ b/src/api/v1/users/backend.py @@ -0,0 +1,123 @@ +from datetime import UTC, datetime + +from utils.auth import LoginEntry +from utils.connection import Request +from utils.helper import dictUtil + +from .models import PlayerRank, TerseReturnModel + + +async def get_terse(user:LoginEntry, *userIds:int|str) -> dict[str, TerseReturnModel]: + data = await Request.send_template( + user, + "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 dict(data): + data[k] = await dictUtil.run_all(data.pop(k), SANITIZE) + + return data + +async def get_self(user:LoginEntry): + userData = await get_user(user, user.uidHint) + + return await dictUtil.KeyRem("summary", "statistics", "countries").run(userData) + +async def get_user(user:LoginEntry, userid: int): + data = await Request.send_template( + user, + "get_public_userstat", + userId = userid + ) + SANITIZE = ( + dictUtil.KeyMod("userid", new_name = "id", convert = lambda x: int(x)), + dictUtil.KeyMod("userstat", new_name = "statistics"), + 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", + "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"]: + 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 + + 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["rank"] = { + "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"] = 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] = await dictUtil.run_all(v_data, VEHICLE_SANITIZE) + data["userstat"][mode] = m_data + data["userstat"] = await dictUtil.KeyMod("simulation", new_name = "simulator").run(data["userstat"]) + for mode in data["summary"]: + data["summary"][mode] = await dictUtil.KeyMod("hardcore", new_name = "simulator").run(data["summary"][mode]) + + data = await dictUtil.run_all(data, SANITIZE) + + return data + diff --git a/src/api/v1/users/models.py b/src/api/v1/users/models.py new file mode 100644 index 00000000..4fc11466 --- /dev/null +++ b/src/api/v1/users/models.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +from bisect import bisect_right +from datetime import date, datetime +from enum import Enum, StrEnum +from typing import Literal + +from pydantic import BaseModel, Field + +COUNTRIES = Literal[ + "country_usa", + "country_germany", + "country_ussr", + "country_britain", + "country_japan", + "country_china", + "country_italy", + "country_france", + "country_sweden", + "country_israel" +] +SIMPLE_COUNTRIES = Literal[ + "usa", + "germany", + "ussr", + "britain", + "japan", + "china", + "italy", + "france", + "sweden", + "israel" +] +GAMEMODES = Literal[ + "arcade", + "realistic", + "simulator" +] +class GamemodesEnum(StrEnum): + arcade = "arcade" + realistic = "historical" + simulator = "simulator" + +SPECIFIC_GAMEMODES = Literal[ + "air_arcade", + "air_realistic", + "air_simulation", + "tank_arcade", + "tank_realistic", + "tank_simulation", + "test_ship_arcade", + "test_ship_realistic", + "helicopter_arcade" +] +VEHICLE_TYPES = Literal[ + "fighter", + "bomber", + "assault", + "tank", + "heavy_tank", + "tank_destroyer", + "SPAA", + "ship", + "torpedo_boat", + "gun_boat", + "torpedo_gun_boat", + "submarine_chaser", + "destroyer", + "naval_ferry_barge", + "helicopter", + "cruiser", + "human" +] + +class getUserDirect: + class summaryModel(BaseModel): + class summaryGameModeModel(BaseModel): + class vehicleModel(BaseModel): + timePlayed: int + air_kills: int + ground_kills: int + naval_kills: int + respawns: int + missionsComplete: int + victories: int + fighter:vehicleModel + bomber: vehicleModel + assault: vehicleModel + tank: vehicleModel + heavy_tank: vehicleModel + tank_destroyer: vehicleModel + SPAA: vehicleModel + ship: vehicleModel + torpedo_boat: vehicleModel + gun_boat: vehicleModel + torpedo_gun_boat: vehicleModel + submarine_chaser: vehicleModel + destroyer: vehicleModel + naval_ferry_barge: vehicleModel + helicopter: vehicleModel + cruiser: vehicleModel + human: vehicleModel + single_played: dict[GAMEMODES, summaryGameModeModel] + pvp_played: dict[GAMEMODES, summaryGameModeModel] + skirmish_played: dict[GAMEMODES, summaryGameModeModel] + campaign_played: dict[GAMEMODES, summaryGameModeModel] + dynamic_played: dict[GAMEMODES, summaryGameModeModel] + builder_played: dict[GAMEMODES, summaryGameModeModel] + other_played: dict[GAMEMODES, summaryGameModeModel] + + 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 + + arcade: dict[str, unitStatModel] = {} + historical: dict[str, unitStatModel] = {} + simulator: dict[str, unitStatModel] = {} + + class countriesModel(BaseModel): + class maxRanksModel(BaseModel): + 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 + current_lineup: tuple[str, ...] = tuple() + units: tuple[str, ...] = tuple() + + 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 + rank: _playerLevelModel + clan: _clanDataModel | None = Field(default = None, exclude_if = lambda x: x is None) + numEliteUnits: int + penaltyStatus: str + #summary: _summaryModel + #statistics: _statisticsModel + #countries: dict[SIMPLE_COUNTRIES, _countriesModel] + +class TerseReturnModel(BaseModel): + clanName: str = Field(default = None, description = "Name of the clan the user is in, if applicable", examples = ["Order Of The Birb", ""], exclude_if = lambda x: x is None) + clanTag: str = Field(default = None, 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┿"], exclude_if = lambda x: x is None) + username: str + +USER_RANK: tuple[int] = ( + 0, 500, 1800, 5000, 11600, 23500, 42700, 71700, 113200, 170100, + 245600, 322600, 401400, 482100, 564600, 648900, 735000, 822900, 912700, 1004300, + 1097700, 1192900, 1290000, 1388900, 1489600, 1592100, 1696500, 1802700, 1910700, 2020500, + 2132200, 2245700, 2361000, 2478100, 2597100, 2717900, 2840500, 2964900, 3091200, 3219300, + 3349200, 3480900, 3614500, 3749900, 3887100, 4026100, 4167000, 4309700, 4454200, 4600500, + 4748700, 4898700, 5050500, 5204100, 5359600, 5516900, 5676000, 5836900, 5999600, 6164200, + 6330600, 6498800, 6668800, 6840700, 7014400, 7189900, 7367200, 7546400, 7727400, 7910200, + 8094800, 8281300, 8469600, 8659700, 8851600, 9045400, 9241000, 9438400, 9637600, 9838700, + 10041600, 10246300, 10452800, 10661200, 10871400, 11083400, 11297200, 11512900, 11730400, 11949700, + 12170800, 12393800, 12618600, 12845200, 13073600, 13303900, 13536000, 13769900, 14005600, 14243100, + 14482500 +) + +class PlayerRank(Enum): + ROOKIE = 0, 11, "Rookie" + LIEUTENANT = 12, 23, "Lieutenant" + CAPTAIN = 24, 35, "Captain" + MAJOR = 36, 47, "Major" + COLONEL = 48, 59, "Colonel" + COMMANDER = 60, 71, "Commander" + COMMODORE = 72, 83, "Commodore" + GENERAL = 84, 99, "General" + MARSHAL = 100, 100, "Marshal" + + def __new__(cls, rank_from: int, rank_to: int, label: str): + obj = object.__new__(cls) + obj._value_ = rank_from # `.value` == rank_from + obj.rank_from = rank_from + obj.rank_to = rank_to + obj.label = label + return obj + + @classmethod + def from_level(cls, level: int) -> "PlayerRank": + if level < 0: + level = 0 + for rank in cls: + if rank.rank_from <= level <= rank.rank_to: + return rank + raise ValueError(f"No rank for level {level}") + + @staticmethod + def get_level(exp: int) -> int: + """Map raw account XP to the numeric player level (0–100).""" + if exp < 0: + exp = 0 + return bisect_right(USER_RANK, exp) - 1 diff --git a/app/config.py b/src/config.py similarity index 78% rename from app/config.py rename to src/config.py index 27b6cf7d..64cd4625 100644 --- a/app/config.py +++ b/src/config.py @@ -1,11 +1,22 @@ from os import getenv from pathlib import Path - __DEBUG_MODE:bool = int(getenv("DEBUG_MODE", "0")) == 1 DATA_DIR = Path("/data/") if not __DEBUG_MODE else Path(__file__).parent.parent / "data" TOOL_DIR = Path("/opt/tools/") if not __DEBUG_MODE else Path(__file__).parent.parent / "tools" +FORWARDED_ALLOW_IPS = getenv("FORWARDED_ALLOW_IPS") or None +CONTACT_NAME = getenv("CONTACT_NAME") +CONTACT_URL = getenv("CONTACT_URL") or None +CONTACT_EMAIL = getenv("CONTACT_EMAIL") or None + +CONTACT = { + "name": CONTACT_NAME +} +if CONTACT_URL: + CONTACT["url"] = CONTACT_URL +if CONTACT_EMAIL: + CONTACT["email"] = CONTACT_EMAIL class _usersDB: DB = DATA_DIR / "users.db" @@ -15,7 +26,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/app/main.py b/src/main.py similarity index 62% rename from app/main.py rename to src/main.py index 063fedbb..eeac534b 100644 --- a/app/main.py +++ b/src/main.py @@ -1,31 +1,35 @@ -import logging, asyncio - -logger = logging.getLogger() - +import asyncio +import logging +from contextlib import asynccontextmanager +from dataclasses import asdict, dataclass +from json import loads from logging.handlers import TimedRotatingFileHandler +from os import getenv, path + from fastapi import FastAPI, status -from fastapi.openapi.utils import get_openapi from fastapi.openapi.docs import get_swagger_ui_html -from fastapi.responses import JSONResponse, HTMLResponse +from fastapi.openapi.utils import get_openapi +from fastapi.responses import HTMLResponse, JSONResponse +from fastapi.routing import APIRoute, APIWebSocketRoute, _IncludedRouter +from slowapi.errors import RateLimitExceeded from slowapi.middleware import SlowAPIMiddleware from slowapi.util import get_remote_address -from slowapi.errors import RateLimitExceeded from uvicorn import run as uvicorn_run -from os import getenv, path -from contextlib import asynccontextmanager -from dataclasses import dataclass, asdict -from json import loads -from utils import users_auth, newsManager -from utils.auth import scheduler, ServerAuth -import utils.connection.network as Network import utils -from utils.geo import update_db -from utils.connection import _populate_serverlist -from utils.connection.blk_utils import Decompress +import utils.cache as Cache +import utils.connection.network as Network from api import router from api.shared import limiter -from config import SWAGGER_CSS, SWAGGER_JS, DEFAULT_NETWORK_CFG, LOGS_DIR, HOST, PORT +from config import CONTACT, DEFAULT_NETWORK_CFG, FORWARDED_ALLOW_IPS, HOST, LOGS_DIR, PORT, SWAGGER_CSS, SWAGGER_JS +from utils import newsManager, users_auth +from utils.auth import ServerAuth, scheduler +from utils.connection import _populate_serverlist +from utils.connection.blk_utils import Decompress +from utils.geo import update_db +from utils.vehicleParser import shared as vpShared + +logger = logging.getLogger() logging.getLogger("aiosqlite").setLevel(logging.WARNING) logging.getLogger("asyncio").setLevel(logging.WARNING) @@ -72,41 +76,49 @@ async def lifespan(app: FastAPI): #region Gaijin servers config init content = {} - try: - async with Network.get("https://public-configs-warthunder-gcore.cdn.gaijin.net/production/network.blk", timeout=5) as _resp: - temp = await Network.handle_response(_resp, False) - content = Decompress(temp)["production"] - except Exception: - logger.warning("Failed to fetch server from first server, trying secondary server") + async with Network.operation() as session: try: - async with Network.get("https://public-configs.warthunder.com/production/network.blk", timeout=5) as _resp: - temp = await Network.handle_response(_resp, False) - content = Decompress(temp)["production"] + async with Network.get( + "https://public-configs-warthunder-gcore.cdn.gaijin.net/production/network.blk", + Network.ReturnType.BIN, + timeout = 5, + session = session + ) as _resp: + content = Decompress(_resp)["production"] except Exception: - pass + logger.warning("Failed to fetch server from first server, trying secondary server") + try: + async with Network.get( + "https://public-configs.warthunder.com/production/network.blk", + Network.ReturnType.BIN, + timeout = 5, + session = session + ) as _resp: + content = Decompress(_resp)["production"] + except Exception: + pass if not content: - logger.warning(f"Failed to fetch server list, using default server list") + logger.warning("Failed to fetch server list, using default server list") content = loads(DEFAULT_NETWORK_CFG.read_text()) _populate_serverlist(content) del content #endregion + try: + await vpShared.update_gamefiles() + except Exception: + logger.exception("An error occurred when trying to update the vehicle files") + + Cache.LONG_RUNNING = ( + asyncio.create_task(newsManager.mainloop()), + asyncio.create_task(update_db()) + ) - newsManager.task = asyncio.create_task(newsManager.mainloop()) - geolocation_task = 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() @@ -115,20 +127,18 @@ async def lifespan(app: FastAPI): debug = int(getenv("DEBUG_MODE", "0")) == 1 app = FastAPI( - title="ThunderAPI", - description="API to retrieve War Thunder data.", - version="1.0.0", - openapi_tags=tags_metadata, - lifespan=lifespan, - redoc_url=None, - docs_url=None, - responses={ + title = "ThunderAPI", + description = "API to retrieve War Thunder data.", + version = "1.0.0", + openapi_tags = tags_metadata, + lifespan = lifespan, + redoc_url = None, + docs_url = None, + responses = { status.HTTP_401_UNAUTHORIZED: {"description": "User token was not found, user is not authenticated or login expired"} }, - contact={ - "discord": "https://discord.gg/wsn9Wcqqym", - }, - debug=debug + contact = CONTACT, + debug = debug ) #region Rate Limiter @@ -137,32 +147,16 @@ async def lifespan(app: FastAPI): RateLimitExceeded, lambda request, exc: ( logging.warning(f"Rate limit exceeded for {get_remote_address(request)}"), - JSONResponse({"detail": "Rate limit exceeded"}, status_code=status.HTTP_429_TOO_MANY_REQUESTS) + JSONResponse({"detail": "Rate limit exceeded"}, status_code = status.HTTP_429_TOO_MANY_REQUESTS) )[1] ) #endregion -class CloudflareClientIPMiddleware: - """Rewrite the client address from Cloudflare's CF-Connecting-IP header.""" - - def __init__(self, app): - self.app = app - - async def __call__(self, scope, receive, send): - if scope["type"] in ("http", "websocket"): - for name, value in scope.get("headers", []): - if name == b"cf-connecting-ip": - client = scope.get("client") - scope["client"] = (value.decode("latin1").strip(), client[1] if client else 0) - break - await self.app(scope, receive, send) - app.include_router(router) app.add_middleware(SlowAPIMiddleware) -app.add_middleware(CloudflareClientIPMiddleware) #region Modify OpenAPI schema -@dataclass(slots=True) +@dataclass(slots = True) class WebSocketInfo: tags: list[str] summary: str @@ -182,25 +176,34 @@ def custom_openapi(): return app.openapi_schema openapi_schema = get_openapi( - title=app.title, - version=app.version, - description=app.description, - routes=app.routes, - tags=app.openapi_tags, + title = app.title, + version = app.version, + description = app.description, + routes = app.routes, + tags = app.openapi_tags, + contact = app.contact ) - for path in openapi_schema["paths"].values(): - for method in path.values(): + for ep_path in openapi_schema["paths"].values(): + for method in ep_path.values(): method["responses"].pop("422", None) - for route in app.routes: - ws_data = websockets.get(route.path) - if ws_data is None: - continue - - openapi_schema["paths"].setdefault(route.path, {}) - openapi_schema["paths"][route.path]["x-websocket"] = ws_data.to_json() + def handle_routes(route: _IncludedRouter|APIRoute|APIWebSocketRoute, path: str = ""): + if isinstance(route, _IncludedRouter): + for r in route.original_router.routes: + handle_routes(r, path+route.original_router.prefix) + return + if isinstance(route, APIWebSocketRoute): + ws_path = path+route.path + ws_data = websockets.get(ws_path) + if ws_data is None: + logger.warning(f"Route {ws_path} doesn't have any configuration, it will not show up in Swagger UI") + return + openapi_schema["paths"].setdefault(ws_path, {}) + openapi_schema["paths"][ws_path]["x-websocket"] = ws_data.to_json() + for route in app.routes: + handle_routes(route) app.openapi_schema = openapi_schema return app.openapi_schema @@ -209,17 +212,17 @@ def custom_openapi(): #region Modify Documentation page swagger_docs = None -@app.get("/docs", include_in_schema=False) -@app.get("/", include_in_schema=False) +@app.get("/docs", include_in_schema = False) +@app.get("/", include_in_schema = False) def custom_swagger_ui(): global swagger_docs if swagger_docs: return HTMLResponse(swagger_docs) page = get_swagger_ui_html( - openapi_url=app.openapi_url, - title=f"{app.title} - Swagger UI", - swagger_ui_parameters={"defaultModelsExpandDepth": -1}, + openapi_url = app.openapi_url, + title = f"{app.title} - Swagger UI", + swagger_ui_parameters = {"defaultModelsExpandDepth": -1}, ) html = page.body.decode("utf-8") @@ -237,7 +240,7 @@ def custom_swagger_ui(): def main(): # region Logging - LOGS_DIR.mkdir(mode=0o755, exist_ok=True, parents=True) + LOGS_DIR.mkdir(mode = 0o755, exist_ok = True, parents = True) #region Handler and Formatter def log_namer(default_name:str): @@ -245,9 +248,9 @@ def log_namer(default_name:str): filename = path.basename(default_name) _, _, date = filename.rpartition(".") return path.join(dirname, f"{date}.log") - handler = TimedRotatingFileHandler(LOGS_DIR / "latest.log", when="midnight", interval=1, utc=True, backupCount=5) + handler = TimedRotatingFileHandler(LOGS_DIR / "latest.log", when = "midnight", interval = 1, utc = True, backupCount = 5) handler.suffix = "%Y-%m-%d" - formatter = logging.Formatter(f"%(asctime)s:%(name)-30s:%(funcName)-15s:%(lineno)-3d:%(levelname)-7s:%(message)s", datefmt="%Y-%m-%d %H:%M:%S") + formatter = logging.Formatter("%(asctime)s:%(name)-30s:%(funcName)-15s:%(lineno)-3d:%(levelname)-7s:%(message)s", datefmt = "%Y-%m-%d %H:%M:%S") handler.setFormatter(formatter) handler.namer = log_namer logger.addHandler(handler) @@ -289,11 +292,11 @@ def log_namer(default_name:str): # endregion try: - uvicorn_run(app, host=HOST, port=PORT) + uvicorn_run(app, host = HOST, port = PORT, forwarded_allow_ips = FORWARDED_ALLOW_IPS) except Exception: logger.exception("An uncaught error occurred during runtime") finally: logger.info("Shutting down") -if __name__ == '__main__': +if __name__ == "__main__": main() 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 58% rename from app/swagger_ui_modify.js rename to src/swagger_ui_modify.js index 6b5774f5..bbe70044 100644 --- a/app/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