Repository navigation
Cleanup returns - #7
Conversation
This better fits the whole project's scope, and it is a more standardized name
Now it is less monolithic in design, with separate classes for different actions
Removed the part, which stores the latest IDs in an external JSON file This code used to be part of [PECK Bot](https://github.com/Order-Of-The-Birb/peck-bot), however the API doesn't require any persistent check for already-sent data Added forum parsing Implemented parralel fetching to speed it up Restructured the code
Got tired of writing caches manually
Also added new functionality while i was at it
Now websockets get hidden properly
This bugfix allowed us to raise the FastAPI version from 0.136.1 to 0.162.0
more to come in the future
Automatic linting and pytest running should now work in theory
Ruff one didnt work because i was stupid
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
|
fucking clanker... anyway @Maho-Yoshino review the requests bruh and correct the code so we can ship this |
MrMindBlow
left a comment
There was a problem hiding this comment.
Please address the startup and manual login failures before merging 32870f1. Repeated HTTP 429s can prevent the API from starting, and /v1/answer-2fa cannot complete an active manual challenge. I also confirmed that a 0.57 GJN buy order still produces 5699 backend units. The eight inline comments cover these issues and the remaining inventory, localization, routing, parser, and CI findings.
Ruff and pytest passed on GitHub. I verified the price calculation locally and traced the other findings in source. Live Gaijin behavior remains unverified.
MrMindBlow
left a comment
There was a problem hiding this comment.
Correct the buy price calculation and the email login procedure before merge. I checked the price calculation for commit e12337ba. A buy order for 0.57 GJN sends 5699 units. The correct value is 5700. The email login procedure can discard a valid code while it waits for a device response.
The ten line comments give the findings and the requested changes. Ruff and Pytest passed on GitHub. I reviewed the source code and checked the price calculation locally. I did not test the API with a Gaijin account.
MrMindBlow
left a comment
There was a problem hiding this comment.
The 0.57 GJN buy order now converts to 5700 backend units, and the replay download has a single GET retry loop. I’m requesting changes because the email 2FA completion path needs a credential check and cancelling a server-account Gaijin Pass challenge can leave startup waiting indefinitely. The inline comments also cover upstream rate limits, trusted proxies, and vehicle-data refresh.
I reviewed f7808f35 in source. Both GitHub checks passed. I did not exercise the live Gaijin endpoints.
MrMindBlow
left a comment
There was a problem hiding this comment.
The pending-login password check and trusted-proxy changes address the earlier findings. Two authentication issues still block approval. A user who follows the Gaijin Pass prompt can start a second challenge after approving the first, and an upstream 429 during token refresh can abort application startup when stored accounts are refreshed. The inline comments identify the affected paths and the changes needed.
Ruff and Pytest passed on GitHub. I traced the authentication and inventory flows in source and checked the news examples against the public War Thunder site. I did not exercise account-backed Gaijin endpoints.
| } | ||
| ) as r: | ||
| content = await Network.handle_response(r) | ||
| content = await Network.handle_response(r, Network.ReturnType.JSON) |
There was a problem hiding this comment.
Handle upstream rate limits during token refresh. Entry.refresh() still uses session.post() directly. On a 429, handle_response() raises ClientResponseError, so /v1/refresh-token returns 500. The same exception escapes the startup call to users_auth._refresh() if any stored account hits that limit. Return 429 to an explicit refresh caller and let the background pass defer that account and continue with the others.
| await wait_for(e.login.wait(), timeout=60) | ||
| except TimeoutError: | ||
| raise HTTPException(status.HTTP_408_REQUEST_TIMEOUT, "2FA timed out") | ||
| await wait_for(e.login.wait(), timeout = 60) |
There was a problem hiding this comment.
Deliver a failed 2FA exchange to the waiting request. If the final Network.post() fails after an email code has been submitted, the background task exits before entry.login.set() or cleanup. /answer-2fa waits the full 60 seconds and reports a timeout, and subsequent attempts find the same failed challenge. Propagate the task’s terminal error to the verified caller and clear that challenge so a fresh login can proceed.
| try: | ||
| async with Network.get(f"https://auth.gaijinent.com/api/auth/requestTwoStep?requestId={data['requestId']}&userId={data['userId']}", timeout = 60, session = session) as r: | ||
| data = r | ||
| except (HTTPException, ClientResponseError) as e: |
There was a problem hiding this comment.
Retry a disconnected Gaijin Pass poll. gaijin_api_endpoints.md records that Gaijin can close an unanswered requestTwoStep connection. A socket disconnect or the 60-second timeout falls through to except Exception, which removes the challenge on the first attempt. Include ServerDisconnectedError and TimeoutError in the bounded recovery path so it can obtain a fresh request ID.
| await entry.provided.wait() | ||
| data = await login(self.__EMAIL, self.__PASS) | ||
| await entry.await_task | ||
| data = entry.login_data |
There was a problem hiding this comment.
Validate the server account’s 2FA result before reading tokens. A rejected code can complete entry.await_task normally with status="2STEPERROR", as the wrong_code.json fixture shows. Reading data["jwt"] then raises KeyError during startup and hides Gaijin’s reason. Apply the same status checks used by the user-login path before reading the token fields.
| # TODO: Implement. Due to the nature of the 2FA system, it is hard to implement | ||
| token, uidHint = await users_auth.login(email, password) | ||
|
|
||
| return JSONResponse({ |
There was a problem hiding this comment.
Return the user ID type declared by /answer-2fa. The successful 2FA fixture supplies user_id as a string, and UserAuth.login passes it through unchanged. Returning JSONResponse bypasses FastAPI’s LoginResponse validation, so clients receive a JSON string where the schema promises an integer. Return the response model or a plain dict and let FastAPI serialize it. The same applies to /login.
|
|
||
| return cls( | ||
| LOGIN = user, | ||
| commodity = assetData.get("commodity"), |
There was a problem hiding this comment.
Give inventory items a valid default for commodity. When GetAssetClassInfo omits this flag, .get("commodity") produces None. The new inventory response model requires a bool, so a single such asset makes the entire inventory request fail validation. Use the same False default that MarketItem.from_assetdata already uses for this payload.
| async def fetchForumIDs(self) -> tuple[int, ...]: | ||
| """Gets the latest "planned battle rating changes" post's ID""" | ||
| async with Network.get( | ||
| "https://forum.warthunder.com/tag/br-changes", |
There was a problem hiding this comment.
Order forum announcements by publication date. The tag page sorts by activity. It currently puts an October 2025 topic above the October 2026 planned changes because the older discussion received a later reply. fetchForum() picks the first eligible row, and the WebSocket poll can announce an old topic again when a reply moves it above the saved ID. Request descending creation order before selecting the first topic or advancing the cursor. Forum listing · Original announcement
| def from_json(cls, data:dict[str, Any]): | ||
| tags = set(data.get("tags", [])) | ||
| title:str = data["title"] | ||
| for tag in re.finditer(r"\[([A-z ]+)\]", title, re.IGNORECASE): |
There was a problem hiding this comment.
Parse adjacent title tags individually. The ASCII range A-z includes both square brackets. For [Video] [Development], this pattern captures Video] [Development as a single tag and sends that malformed value to feed consumers. Use a character class that excludes the brackets, such as [A-Za-z ], so each prefix produces its own tag. War Thunder title using both tags
* Fix two-factor login, token refresh, inventory, and news handling * Fix token refresh, 2FA retries, and marketplace and forum responses
Adds a few rudimentary tests using
pytest(will get expanded upon in the future)Clears up a lot of the endpoints' return formats, removes unusable/worthless return data, returns a lot less (good for both bandwidth and memory)
Adds automated tests using GitHub Actions, including automatic linting using
ruffand runningpytestUpgraded
fastapifrom0.136.1to0.162.0(and upgraded the corresponding code that prevented this beforehand)Reordered some marketplace endpoints
Cleaned up marketplace backend code
Added endpoints for viewing marketplace orders and cancelling them
Improved upon the
dictUtil(previouslyKeyMod) system, which is now asyncMoved the app from
app/tosrc/to better fit the code, as this is no appAdded forum posts lookup for
planned battle rating changesposts, which is now included in the news endpointsAdded a caching module which is to be used in the future (currently used by the replays and news modules)
Fixed
/v1/clans/sqb/currentthrowing an error when it wasn't called during an open bracketAdded documentation to the
cln_get_user_open_ordersactionChanged the network manager code to also parse the contents
Changed some middleware configs, hopefully I didn't break the cloudflare integration