mirror of
https://github.com/pagefaultgames/pokerogue.git
synced 2024-11-25 08:16:04 +00:00
Merge branch 'beta' into linger-arena-trap-fix
This commit is contained in:
commit
610dbc32bf
2
global.d.ts
vendored
2
global.d.ts
vendored
@ -10,5 +10,5 @@ declare global {
|
||||
*
|
||||
* To set up your own server in a test see `game_data.test.ts`
|
||||
*/
|
||||
var i18nServer: SetupServerApi;
|
||||
var server: SetupServerApi;
|
||||
}
|
||||
|
17
src/@types/PokerogueAccountApi.ts
Normal file
17
src/@types/PokerogueAccountApi.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import type { UserInfo } from "#app/@types/UserInfo";
|
||||
|
||||
export interface AccountInfoResponse extends UserInfo {}
|
||||
|
||||
export interface AccountLoginRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AccountLoginResponse {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface AccountRegisterRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
31
src/@types/PokerogueAdminApi.ts
Normal file
31
src/@types/PokerogueAdminApi.ts
Normal file
@ -0,0 +1,31 @@
|
||||
export interface LinkAccountToDiscordIdRequest {
|
||||
username: string;
|
||||
discordId: string;
|
||||
}
|
||||
|
||||
export interface UnlinkAccountFromDiscordIdRequest {
|
||||
username: string;
|
||||
discordId: string;
|
||||
}
|
||||
|
||||
export interface LinkAccountToGoogledIdRequest {
|
||||
username: string;
|
||||
googleId: string;
|
||||
}
|
||||
|
||||
export interface UnlinkAccountFromGoogledIdRequest {
|
||||
username: string;
|
||||
googleId: string;
|
||||
}
|
||||
|
||||
export interface SearchAccountRequest {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface SearchAccountResponse {
|
||||
username: string;
|
||||
discordId: string;
|
||||
googleId: string;
|
||||
lastLoggedIn: string;
|
||||
registered: string;
|
||||
}
|
4
src/@types/PokerogueApi.ts
Normal file
4
src/@types/PokerogueApi.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export interface TitleStatsResponse {
|
||||
playerCount: number;
|
||||
battleCount: number;
|
||||
}
|
10
src/@types/PokerogueDailyApi.ts
Normal file
10
src/@types/PokerogueDailyApi.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import type { ScoreboardCategory } from "#app/ui/daily-run-scoreboard";
|
||||
|
||||
export interface GetDailyRankingsRequest {
|
||||
category: ScoreboardCategory;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export interface GetDailyRankingsPageCountRequest {
|
||||
category: ScoreboardCategory;
|
||||
}
|
8
src/@types/PokerogueSavedataApi.ts
Normal file
8
src/@types/PokerogueSavedataApi.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import type { SessionSaveData, SystemSaveData } from "#app/system/game-data";
|
||||
|
||||
export interface UpdateAllSavedataRequest {
|
||||
system: SystemSaveData;
|
||||
session: SessionSaveData;
|
||||
sessionSlotId: number;
|
||||
clientSessionId: string;
|
||||
}
|
39
src/@types/PokerogueSessionSavedataApi.ts
Normal file
39
src/@types/PokerogueSessionSavedataApi.ts
Normal file
@ -0,0 +1,39 @@
|
||||
export class UpdateSessionSavedataRequest {
|
||||
slot: number;
|
||||
trainerId: number;
|
||||
secretId: number;
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
/** This is **NOT** similar to {@linkcode ClearSessionSavedataRequest} */
|
||||
export interface NewClearSessionSavedataRequest {
|
||||
slot: number;
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
export interface GetSessionSavedataRequest {
|
||||
slot: number;
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
export interface DeleteSessionSavedataRequest {
|
||||
slot: number;
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
/** This is **NOT** similar to {@linkcode NewClearSessionSavedataRequest} */
|
||||
export interface ClearSessionSavedataRequest {
|
||||
slot: number;
|
||||
trainerId: number;
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pokerogue API response for path: `/savedata/session/clear`
|
||||
*/
|
||||
export interface ClearSessionSavedataResponse {
|
||||
/** Contains the error message if any occured */
|
||||
error?: string;
|
||||
/** Is `true` if the request was successfully processed */
|
||||
success?: boolean;
|
||||
}
|
20
src/@types/PokerogueSystemSavedataApi.ts
Normal file
20
src/@types/PokerogueSystemSavedataApi.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import type { SystemSaveData } from "#app/system/game-data";
|
||||
|
||||
export interface GetSystemSavedataRequest {
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
export class UpdateSystemSavedataRequest {
|
||||
clientSessionId: string;
|
||||
trainerId?: number;
|
||||
secretId?: number;
|
||||
}
|
||||
|
||||
export interface VerifySystemSavedataRequest {
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
export interface VerifySystemSavedataResponse {
|
||||
valid: boolean;
|
||||
systemData: SystemSaveData;
|
||||
}
|
7
src/@types/UserInfo.ts
Normal file
7
src/@types/UserInfo.ts
Normal file
@ -0,0 +1,7 @@
|
||||
export interface UserInfo {
|
||||
username: string;
|
||||
lastSessionSlot: number;
|
||||
discordId: string;
|
||||
googleId: string;
|
||||
hasAdminRole: boolean;
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
/**
|
||||
* Pokerogue API response for path: `/savedata/session/clear`
|
||||
*/
|
||||
export interface PokerogueApiClearSessionData {
|
||||
/** Contains the error message if any occured */
|
||||
error?: string;
|
||||
/** Is `true` if the request was successfully processed */
|
||||
success?: boolean;
|
||||
}
|
@ -1,14 +1,8 @@
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import type { UserInfo } from "#app/@types/UserInfo";
|
||||
import { bypassLogin } from "./battle-scene";
|
||||
import * as Utils from "./utils";
|
||||
|
||||
export interface UserInfo {
|
||||
username: string;
|
||||
lastSessionSlot: integer;
|
||||
discordId: string;
|
||||
googleId: string;
|
||||
hasAdminRole: boolean;
|
||||
}
|
||||
|
||||
export let loggedInUser: UserInfo | null = null;
|
||||
// This is a random string that is used to identify the client session - unique per session (tab or window) so that the game will only save on the one that the server is expecting
|
||||
export const clientSessionId = Utils.randomString(32);
|
||||
@ -43,18 +37,14 @@ export function updateUserInfo(): Promise<[boolean, integer]> {
|
||||
});
|
||||
return resolve([ true, 200 ]);
|
||||
}
|
||||
Utils.apiFetch("account/info", true).then(response => {
|
||||
if (!response.ok) {
|
||||
resolve([ false, response.status ]);
|
||||
pokerogueApi.account.getInfo().then(([ accountInfo, status ]) => {
|
||||
if (!accountInfo) {
|
||||
resolve([ false, status ]);
|
||||
return;
|
||||
} else {
|
||||
loggedInUser = accountInfo;
|
||||
resolve([ true, 200 ]);
|
||||
}
|
||||
return response.json();
|
||||
}).then(jsonResponse => {
|
||||
loggedInUser = jsonResponse;
|
||||
resolve([ true, 200 ]);
|
||||
}).catch(err => {
|
||||
console.error(err);
|
||||
resolve([ false, 500 ]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
@ -3,3 +3,9 @@ export const PLAYER_PARTY_MAX_SIZE: number = 6;
|
||||
|
||||
/** Whether to use seasonal splash messages in general */
|
||||
export const USE_SEASONAL_SPLASH_MESSAGES: boolean = false;
|
||||
|
||||
/** Name of the session ID cookie */
|
||||
export const SESSION_ID_COOKIE_NAME: string = "pokerogue_sessionId";
|
||||
|
||||
/** Max value for an integer attribute in {@linkcode SystemSaveData} */
|
||||
export const MAX_INT_ATTR_VALUE = 0x80000000;
|
||||
|
@ -6,6 +6,7 @@ import { Starter } from "#app/ui/starter-select-ui-handler";
|
||||
import * as Utils from "#app/utils";
|
||||
import PokemonSpecies, { PokemonSpeciesForm, getPokemonSpecies, getPokemonSpeciesForm } from "#app/data/pokemon-species";
|
||||
import { speciesStarterCosts } from "#app/data/balance/starters";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
export interface DailyRunConfig {
|
||||
seed: integer;
|
||||
@ -14,14 +15,9 @@ export interface DailyRunConfig {
|
||||
|
||||
export function fetchDailyRunSeed(): Promise<string | null> {
|
||||
return new Promise<string | null>((resolve, reject) => {
|
||||
Utils.apiFetch("daily/seed").then(response => {
|
||||
if (!response.ok) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
return response.text();
|
||||
}).then(seed => resolve(seed ?? null))
|
||||
.catch(err => reject(err));
|
||||
pokerogueApi.daily.getSeed().then(dailySeed => {
|
||||
resolve(dailySeed);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -23,6 +23,7 @@ import * as Utils from "#app/utils";
|
||||
import { PlayerGender } from "#enums/player-gender";
|
||||
import { TrainerType } from "#enums/trainer-type";
|
||||
import i18next from "i18next";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
export class GameOverPhase extends BattlePhase {
|
||||
private victory: boolean;
|
||||
@ -176,10 +177,9 @@ export class GameOverPhase extends BattlePhase {
|
||||
If Online, execute apiFetch as intended
|
||||
If Offline, execute offlineNewClear(), a localStorage implementation of newClear daily run checks */
|
||||
if (this.victory) {
|
||||
if (!Utils.isLocal) {
|
||||
Utils.apiFetch(`savedata/session/newclear?slot=${this.scene.sessionSlotId}&clientSessionId=${clientSessionId}`, true)
|
||||
.then(response => response.json())
|
||||
.then(newClear => doGameOver(newClear));
|
||||
if (!Utils.isLocal || Utils.isLocalServerConnected) {
|
||||
pokerogueApi.savedata.session.newclear({ slot: this.scene.sessionSlotId, clientSessionId })
|
||||
.then((success) => doGameOver(!!success));
|
||||
} else {
|
||||
this.scene.gameData.offlineNewClear(this.scene).then(result => {
|
||||
doGameOver(result);
|
||||
|
@ -243,7 +243,7 @@ export class TitlePhase extends Phase {
|
||||
};
|
||||
|
||||
// If Online, calls seed fetch from db to generate daily run. If Offline, generates a daily run based on current date.
|
||||
if (!Utils.isLocal) {
|
||||
if (!Utils.isLocal || Utils.isLocalServerConnected) {
|
||||
fetchDailyRunSeed().then(seed => {
|
||||
if (seed) {
|
||||
generateDaily(seed);
|
||||
|
91
src/plugins/api/api-base.ts
Normal file
91
src/plugins/api/api-base.ts
Normal file
@ -0,0 +1,91 @@
|
||||
import { SESSION_ID_COOKIE_NAME } from "#app/constants";
|
||||
import { getCookie } from "#app/utils";
|
||||
|
||||
type DataType = "json" | "form-urlencoded";
|
||||
|
||||
export abstract class ApiBase {
|
||||
//#region Fields
|
||||
|
||||
public readonly ERR_GENERIC: string = "There was an error";
|
||||
|
||||
protected readonly base: string;
|
||||
|
||||
//#region Public
|
||||
|
||||
constructor(base: string) {
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
//#region Protected
|
||||
|
||||
/**
|
||||
* Send a GET request.
|
||||
* @param path The path to send the request to.
|
||||
*/
|
||||
protected async doGet(path: string) {
|
||||
return this.doFetch(path, { method: "GET" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a POST request.
|
||||
* @param path THe path to send the request to.
|
||||
* @param bodyData The body-data to send.
|
||||
* @param dataType The data-type of the {@linkcode bodyData}.
|
||||
*/
|
||||
protected async doPost<D = undefined>(path: string, bodyData?: D, dataType: DataType = "json") {
|
||||
let body: string | undefined = undefined;
|
||||
const headers: HeadersInit = {};
|
||||
|
||||
if (bodyData) {
|
||||
if (dataType === "json") {
|
||||
body = typeof bodyData === "string" ? bodyData : JSON.stringify(bodyData);
|
||||
headers["Content-Type"] = "application/json";
|
||||
} else if (dataType === "form-urlencoded") {
|
||||
if (bodyData instanceof Object) {
|
||||
body = this.toUrlSearchParams(bodyData).toString();
|
||||
} else {
|
||||
console.warn("Could not add body data to form-urlencoded!", bodyData);
|
||||
}
|
||||
headers["Content-Type"] = "application/x-www-form-urlencoded";
|
||||
} else {
|
||||
console.warn(`Unsupported data type: ${dataType}`);
|
||||
body = String(bodyData);
|
||||
headers["Content-Type"] = "text/plain";
|
||||
}
|
||||
}
|
||||
|
||||
return await this.doFetch(path, { method: "POST", body, headers });
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic request helper.
|
||||
* @param path The path to send the request to.
|
||||
* @param config The request {@linkcode RequestInit | Configuration}.
|
||||
*/
|
||||
protected async doFetch(path: string, config: RequestInit): Promise<Response> {
|
||||
config.headers = {
|
||||
...config.headers,
|
||||
Authorization: getCookie(SESSION_ID_COOKIE_NAME),
|
||||
"Content-Type": config.headers?.["Content-Type"] ?? "application/json",
|
||||
};
|
||||
|
||||
console.log(`Sending ${config.method ?? "GET"} request to: `, this.base + path, config);
|
||||
|
||||
return await fetch(this.base + path, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to transform data to {@linkcode URLSearchParams}
|
||||
* Any key with a value of `undefined` will be ignored.
|
||||
* Any key with a value of `null` will be included.
|
||||
* @param data the data to transform to {@linkcode URLSearchParams}
|
||||
* @returns a {@linkcode URLSearchParams} representaton of {@linkcode data}
|
||||
*/
|
||||
protected toUrlSearchParams<D extends Record<string, any>>(data: D) {
|
||||
const arr = Object.entries(data)
|
||||
.map(([ key, value ]) => (value !== undefined ? [ key, String(value) ] : [ key, "" ]))
|
||||
.filter(([ , value ]) => value !== "");
|
||||
|
||||
return new URLSearchParams(arr);
|
||||
}
|
||||
}
|
101
src/plugins/api/pokerogue-account-api.ts
Normal file
101
src/plugins/api/pokerogue-account-api.ts
Normal file
@ -0,0 +1,101 @@
|
||||
import type {
|
||||
AccountInfoResponse,
|
||||
AccountLoginRequest,
|
||||
AccountLoginResponse,
|
||||
AccountRegisterRequest,
|
||||
} from "#app/@types/PokerogueAccountApi";
|
||||
import { SESSION_ID_COOKIE_NAME } from "#app/constants";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
import { removeCookie, setCookie } from "#app/utils";
|
||||
|
||||
/**
|
||||
* A wrapper for PokéRogue account API requests.
|
||||
*/
|
||||
export class PokerogueAccountApi extends ApiBase {
|
||||
//#region Public
|
||||
|
||||
/**
|
||||
* Request the {@linkcode AccountInfoResponse | UserInfo} of the logged in user.
|
||||
* The user is identified by the {@linkcode SESSION_ID_COOKIE_NAME | session cookie}.
|
||||
*/
|
||||
public async getInfo(): Promise<[data: AccountInfoResponse | null, status: number]> {
|
||||
try {
|
||||
const response = await this.doGet("/account/info");
|
||||
|
||||
if (response.ok) {
|
||||
const resData = (await response.json()) as AccountInfoResponse;
|
||||
return [ resData, response.status ];
|
||||
} else {
|
||||
console.warn("Could not get account info!", response.status, response.statusText);
|
||||
return [ null, response.status ];
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not get account info!", err);
|
||||
return [ null, 500 ];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new account.
|
||||
* @param registerData The {@linkcode AccountRegisterRequest} to send
|
||||
* @returns An error message if something went wrong
|
||||
*/
|
||||
public async register(registerData: AccountRegisterRequest) {
|
||||
try {
|
||||
const response = await this.doPost("/account/register", registerData, "form-urlencoded");
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
} else {
|
||||
return response.text();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Register failed!", err);
|
||||
}
|
||||
|
||||
return "Unknown error!";
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a login request.
|
||||
* Sets the session cookie on success.
|
||||
* @param loginData The {@linkcode AccountLoginRequest} to send
|
||||
* @returns An error message if something went wrong
|
||||
*/
|
||||
public async login(loginData: AccountLoginRequest) {
|
||||
try {
|
||||
const response = await this.doPost("/account/login", loginData, "form-urlencoded");
|
||||
|
||||
if (response.ok) {
|
||||
const loginResponse = (await response.json()) as AccountLoginResponse;
|
||||
setCookie(SESSION_ID_COOKIE_NAME, loginResponse.token);
|
||||
return null;
|
||||
} else {
|
||||
console.warn("Login failed!", response.status, response.statusText);
|
||||
return response.text();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Login failed!", err);
|
||||
}
|
||||
|
||||
return "Unknown error!";
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a logout request.
|
||||
* **Always** (no matter if failed or not) removes the session cookie.
|
||||
*/
|
||||
public async logout() {
|
||||
try {
|
||||
const response = await this.doGet("/account/logout");
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status}: ${response.statusText}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Log out failed!", err);
|
||||
}
|
||||
|
||||
removeCookie(SESSION_ID_COOKIE_NAME); // we are always clearing the cookie.
|
||||
}
|
||||
}
|
140
src/plugins/api/pokerogue-admin-api.ts
Normal file
140
src/plugins/api/pokerogue-admin-api.ts
Normal file
@ -0,0 +1,140 @@
|
||||
import type {
|
||||
LinkAccountToDiscordIdRequest,
|
||||
LinkAccountToGoogledIdRequest,
|
||||
SearchAccountRequest,
|
||||
SearchAccountResponse,
|
||||
UnlinkAccountFromDiscordIdRequest,
|
||||
UnlinkAccountFromGoogledIdRequest,
|
||||
} from "#app/@types/PokerogueAdminApi";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
|
||||
export class PokerogueAdminApi extends ApiBase {
|
||||
public readonly ERR_USERNAME_NOT_FOUND: string = "Username not found!";
|
||||
|
||||
/**
|
||||
* Links an account to a discord id.
|
||||
* @param params The {@linkcode LinkAccountToDiscordIdRequest} to send
|
||||
* @returns `null` if successful, error message if not
|
||||
*/
|
||||
public async linkAccountToDiscord(params: LinkAccountToDiscordIdRequest) {
|
||||
try {
|
||||
const response = await this.doPost("/admin/account/discordLink", params, "form-urlencoded");
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
} else {
|
||||
console.warn("Could not link account with discord!", response.status, response.statusText);
|
||||
|
||||
if (response.status === 404) {
|
||||
return this.ERR_USERNAME_NOT_FOUND;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not link account with discord!", err);
|
||||
}
|
||||
|
||||
return this.ERR_GENERIC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlinks an account from a discord id.
|
||||
* @param params The {@linkcode UnlinkAccountFromDiscordIdRequest} to send
|
||||
* @returns `null` if successful, error message if not
|
||||
*/
|
||||
public async unlinkAccountFromDiscord(params: UnlinkAccountFromDiscordIdRequest) {
|
||||
try {
|
||||
const response = await this.doPost("/admin/account/discordUnlink", params, "form-urlencoded");
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
} else {
|
||||
console.warn("Could not unlink account from discord!", response.status, response.statusText);
|
||||
|
||||
if (response.status === 404) {
|
||||
return this.ERR_USERNAME_NOT_FOUND;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not unlink account from discord!", err);
|
||||
}
|
||||
|
||||
return this.ERR_GENERIC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Links an account to a google id.
|
||||
* @param params The {@linkcode LinkAccountToGoogledIdRequest} to send
|
||||
* @returns `null` if successful, error message if not
|
||||
*/
|
||||
public async linkAccountToGoogleId(params: LinkAccountToGoogledIdRequest) {
|
||||
try {
|
||||
const response = await this.doPost("/admin/account/googleLink", params, "form-urlencoded");
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
} else {
|
||||
console.warn("Could not link account with google!", response.status, response.statusText);
|
||||
|
||||
if (response.status === 404) {
|
||||
return this.ERR_USERNAME_NOT_FOUND;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not link account with google!", err);
|
||||
}
|
||||
|
||||
return this.ERR_GENERIC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlinks an account from a google id.
|
||||
* @param params The {@linkcode UnlinkAccountFromGoogledIdRequest} to send
|
||||
* @returns `null` if successful, error message if not
|
||||
*/
|
||||
public async unlinkAccountFromGoogleId(params: UnlinkAccountFromGoogledIdRequest) {
|
||||
try {
|
||||
const response = await this.doPost("/admin/account/googleUnlink", params, "form-urlencoded");
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
} else {
|
||||
console.warn("Could not unlink account from google!", response.status, response.statusText);
|
||||
|
||||
if (response.status === 404) {
|
||||
return this.ERR_USERNAME_NOT_FOUND;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not unlink account from google!", err);
|
||||
}
|
||||
|
||||
return this.ERR_GENERIC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search an account.
|
||||
* @param params The {@linkcode SearchAccountRequest} to send
|
||||
* @returns an array of {@linkcode SearchAccountResponse} and error. Both can be `undefined`
|
||||
*/
|
||||
public async searchAccount(params: SearchAccountRequest): Promise<[data?: SearchAccountResponse, error?: string]> {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/admin/account/adminSearch?${urlSearchParams}`);
|
||||
|
||||
if (response.ok) {
|
||||
const resData: SearchAccountResponse = await response.json();
|
||||
return [ resData, undefined ];
|
||||
} else {
|
||||
console.warn("Could not find account!", response.status, response.statusText);
|
||||
|
||||
if (response.status === 404) {
|
||||
return [ undefined, this.ERR_USERNAME_NOT_FOUND ];
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not find account!", err);
|
||||
}
|
||||
|
||||
return [ undefined, this.ERR_GENERIC ];
|
||||
}
|
||||
}
|
83
src/plugins/api/pokerogue-api.ts
Normal file
83
src/plugins/api/pokerogue-api.ts
Normal file
@ -0,0 +1,83 @@
|
||||
import type { TitleStatsResponse } from "#app/@types/PokerogueApi";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
import { PokerogueAccountApi } from "#app/plugins/api/pokerogue-account-api";
|
||||
import { PokerogueAdminApi } from "#app/plugins/api/pokerogue-admin-api";
|
||||
import { PokerogueDailyApi } from "#app/plugins/api/pokerogue-daily-api";
|
||||
import { PokerogueSavedataApi } from "#app/plugins/api/pokerogue-savedata-api";
|
||||
|
||||
/**
|
||||
* A wrapper for PokéRogue API requests.
|
||||
*/
|
||||
export class PokerogueApi extends ApiBase {
|
||||
//#region Fields∏
|
||||
|
||||
public readonly account: PokerogueAccountApi;
|
||||
public readonly daily: PokerogueDailyApi;
|
||||
public readonly admin: PokerogueAdminApi;
|
||||
public readonly savedata: PokerogueSavedataApi;
|
||||
|
||||
//#region Public
|
||||
|
||||
constructor(base: string) {
|
||||
super(base);
|
||||
this.account = new PokerogueAccountApi(base);
|
||||
this.daily = new PokerogueDailyApi(base);
|
||||
this.admin = new PokerogueAdminApi(base);
|
||||
this.savedata = new PokerogueSavedataApi(base);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request game title-stats.
|
||||
*/
|
||||
public async getGameTitleStats() {
|
||||
try {
|
||||
const response = await this.doGet("/game/titlestats");
|
||||
return (await response.json()) as TitleStatsResponse;
|
||||
} catch (err) {
|
||||
console.warn("Could not get game title stats!", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlink the currently logged in user from Discord.
|
||||
* @returns `true` if unlinking was successful, `false` if not
|
||||
*/
|
||||
public async unlinkDiscord() {
|
||||
try {
|
||||
const response = await this.doPost("/auth/discord/logout");
|
||||
if (response.ok) {
|
||||
return true;
|
||||
} else {
|
||||
console.warn(`Discord unlink failed (${response.status}: ${response.statusText})`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not unlink Discord!", err);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlink the currently logged in user from Google.
|
||||
* @returns `true` if unlinking was successful, `false` if not
|
||||
*/
|
||||
public async unlinkGoogle() {
|
||||
try {
|
||||
const response = await this.doPost("/auth/google/logout");
|
||||
if (response.ok) {
|
||||
return true;
|
||||
} else {
|
||||
console.warn(`Google unlink failed (${response.status}: ${response.statusText})`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not unlink Google!", err);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
}
|
||||
|
||||
export const pokerogueApi = new PokerogueApi(import.meta.env.VITE_SERVER_URL ?? "http://localhost:8001");
|
57
src/plugins/api/pokerogue-daily-api.ts
Normal file
57
src/plugins/api/pokerogue-daily-api.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import type { GetDailyRankingsPageCountRequest, GetDailyRankingsRequest } from "#app/@types/PokerogueDailyApi";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
import type { RankingEntry } from "#app/ui/daily-run-scoreboard";
|
||||
|
||||
/**
|
||||
* A wrapper for daily-run PokéRogue API requests.
|
||||
*/
|
||||
export class PokerogueDailyApi extends ApiBase {
|
||||
//#region Public
|
||||
|
||||
/**
|
||||
* Request the daily-run seed.
|
||||
* @returns The active daily-run seed as `string`.
|
||||
*/
|
||||
public async getSeed() {
|
||||
try {
|
||||
const response = await this.doGet("/daily/seed");
|
||||
return response.text();
|
||||
} catch (err) {
|
||||
console.warn("Could not get daily-run seed!", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the daily rankings for a {@linkcode ScoreboardCategory}.
|
||||
* @param params The {@linkcode GetDailyRankingsRequest} to send
|
||||
*/
|
||||
public async getRankings(params: GetDailyRankingsRequest) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/daily/rankings?${urlSearchParams}`);
|
||||
|
||||
return (await response.json()) as RankingEntry[];
|
||||
} catch (err) {
|
||||
console.warn("Could not get daily rankings!", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the page count of the daily rankings for a {@linkcode ScoreboardCategory}.
|
||||
* @param params The {@linkcode GetDailyRankingsPageCountRequest} to send.
|
||||
*/
|
||||
public async getRankingsPageCount(params: GetDailyRankingsPageCountRequest) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/daily/rankingpagecount?${urlSearchParams}`);
|
||||
const json = await response.json();
|
||||
|
||||
return Number(json);
|
||||
} catch (err) {
|
||||
console.warn("Could not get daily rankings page count!", err);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
41
src/plugins/api/pokerogue-savedata-api.ts
Normal file
41
src/plugins/api/pokerogue-savedata-api.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import type { UpdateAllSavedataRequest } from "#app/@types/PokerogueSavedataApi";
|
||||
import { MAX_INT_ATTR_VALUE } from "#app/constants";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
import { PokerogueSessionSavedataApi } from "#app/plugins/api/pokerogue-session-savedata-api";
|
||||
import { PokerogueSystemSavedataApi } from "#app/plugins/api/pokerogue-system-savedata-api";
|
||||
|
||||
/**
|
||||
* A wrapper for PokéRogue savedata API requests.
|
||||
*/
|
||||
export class PokerogueSavedataApi extends ApiBase {
|
||||
//#region Fields
|
||||
|
||||
public readonly system: PokerogueSystemSavedataApi;
|
||||
public readonly session: PokerogueSessionSavedataApi;
|
||||
|
||||
//#region Public
|
||||
|
||||
constructor(base: string) {
|
||||
super(base);
|
||||
this.system = new PokerogueSystemSavedataApi(base);
|
||||
this.session = new PokerogueSessionSavedataApi(base);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update all savedata
|
||||
* @param bodyData The {@linkcode UpdateAllSavedataRequest | request data} to send
|
||||
* @returns An error message if something went wrong
|
||||
*/
|
||||
public async updateAll(bodyData: UpdateAllSavedataRequest) {
|
||||
try {
|
||||
const rawBodyData = JSON.stringify(bodyData, (_k: any, v: any) =>
|
||||
typeof v === "bigint" ? (v <= MAX_INT_ATTR_VALUE ? Number(v) : v.toString()) : v
|
||||
);
|
||||
const response = await this.doPost("/savedata/updateall", rawBodyData);
|
||||
return await response.text();
|
||||
} catch (err) {
|
||||
console.warn("Could not update all savedata!", err);
|
||||
return "Unknown error";
|
||||
}
|
||||
}
|
||||
}
|
115
src/plugins/api/pokerogue-session-savedata-api.ts
Normal file
115
src/plugins/api/pokerogue-session-savedata-api.ts
Normal file
@ -0,0 +1,115 @@
|
||||
import type {
|
||||
ClearSessionSavedataRequest,
|
||||
ClearSessionSavedataResponse,
|
||||
DeleteSessionSavedataRequest,
|
||||
GetSessionSavedataRequest,
|
||||
NewClearSessionSavedataRequest,
|
||||
UpdateSessionSavedataRequest,
|
||||
} from "#app/@types/PokerogueSessionSavedataApi";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
import type { SessionSaveData } from "#app/system/game-data";
|
||||
|
||||
/**
|
||||
* A wrapper for PokéRogue session savedata API requests.
|
||||
*/
|
||||
export class PokerogueSessionSavedataApi extends ApiBase {
|
||||
//#region Public
|
||||
|
||||
/**
|
||||
* Mark a session as cleared aka "newclear".\
|
||||
* *This is **NOT** the same as {@linkcode clear | clear()}.*
|
||||
* @param params The {@linkcode NewClearSessionSavedataRequest} to send
|
||||
* @returns The raw savedata as `string`.
|
||||
*/
|
||||
public async newclear(params: NewClearSessionSavedataRequest) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/savedata/session/newclear?${urlSearchParams}`);
|
||||
const json = await response.json();
|
||||
|
||||
return Boolean(json);
|
||||
} catch (err) {
|
||||
console.warn("Could not newclear session!", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a session savedata.
|
||||
* @param params The {@linkcode GetSessionSavedataRequest} to send
|
||||
* @returns The session as `string`
|
||||
*/
|
||||
public async get(params: GetSessionSavedataRequest) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/savedata/session/get?${urlSearchParams}`);
|
||||
|
||||
return await response.text();
|
||||
} catch (err) {
|
||||
console.warn("Could not get session savedata!", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a session savedata.
|
||||
* @param params The {@linkcode UpdateSessionSavedataRequest} to send
|
||||
* @param rawSavedata The raw savedata (as `string`)
|
||||
* @returns An error message if something went wrong
|
||||
*/
|
||||
public async update(params: UpdateSessionSavedataRequest, rawSavedata: string) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doPost(`/savedata/session/update?${urlSearchParams}`, rawSavedata);
|
||||
|
||||
return await response.text();
|
||||
} catch (err) {
|
||||
console.warn("Could not update session savedata!", err);
|
||||
}
|
||||
|
||||
return "Unknown Error!";
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a session savedata slot.
|
||||
* @param params The {@linkcode DeleteSessionSavedataRequest} to send
|
||||
* @returns An error message if something went wrong
|
||||
*/
|
||||
public async delete(params: DeleteSessionSavedataRequest) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/savedata/session/delete?${urlSearchParams}`);
|
||||
|
||||
if (response.ok) {
|
||||
return null;
|
||||
} else {
|
||||
return await response.text();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not delete session savedata!", err);
|
||||
return "Unknown error";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the session savedata of the given slot.\
|
||||
* *This is **NOT** the same as {@linkcode newclear | newclear()}.*
|
||||
* @param params The {@linkcode ClearSessionSavedataRequest} to send
|
||||
* @param sessionData The {@linkcode SessionSaveData} object
|
||||
*/
|
||||
public async clear(params: ClearSessionSavedataRequest, sessionData: SessionSaveData) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doPost(`/savedata/session/clear?${urlSearchParams}`, sessionData);
|
||||
|
||||
return (await response.json()) as ClearSessionSavedataResponse;
|
||||
} catch (err) {
|
||||
console.warn("Could not clear session savedata!", err);
|
||||
}
|
||||
|
||||
return {
|
||||
error: "Unknown error",
|
||||
success: false,
|
||||
} as ClearSessionSavedataResponse;
|
||||
}
|
||||
}
|
77
src/plugins/api/pokerogue-system-savedata-api.ts
Normal file
77
src/plugins/api/pokerogue-system-savedata-api.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import type {
|
||||
GetSystemSavedataRequest,
|
||||
UpdateSystemSavedataRequest,
|
||||
VerifySystemSavedataRequest,
|
||||
VerifySystemSavedataResponse,
|
||||
} from "#app/@types/PokerogueSystemSavedataApi";
|
||||
import { ApiBase } from "#app/plugins/api/api-base";
|
||||
|
||||
/**
|
||||
* A wrapper for PokéRogue system savedata API requests.
|
||||
*/
|
||||
export class PokerogueSystemSavedataApi extends ApiBase {
|
||||
//#region Public
|
||||
|
||||
/**
|
||||
* Get a system savedata.
|
||||
* @param params The {@linkcode GetSystemSavedataRequest} to send
|
||||
* @returns The system savedata as `string` or `null` on error
|
||||
*/
|
||||
public async get(params: GetSystemSavedataRequest) {
|
||||
try {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/savedata/system/get?${urlSearchParams}`);
|
||||
const rawSavedata = await response.text();
|
||||
|
||||
return rawSavedata;
|
||||
} catch (err) {
|
||||
console.warn("Could not get system savedata!", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if the session is valid.
|
||||
* If not the {@linkcode SystemSaveData} is returned.
|
||||
* @param params The {@linkcode VerifySystemSavedataRequest} to send
|
||||
* @returns A {@linkcode SystemSaveData} if **NOT** valid, otherwise `null`.
|
||||
*
|
||||
* TODO: add handling for errors
|
||||
*/
|
||||
public async verify(params: VerifySystemSavedataRequest) {
|
||||
const urlSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doGet(`/savedata/system/verify?${urlSearchParams}`);
|
||||
|
||||
if (response.ok) {
|
||||
const verifySavedata = (await response.json()) as VerifySystemSavedataResponse;
|
||||
|
||||
if (!verifySavedata.valid) {
|
||||
console.warn("Invalid system savedata!");
|
||||
return verifySavedata.systemData;
|
||||
}
|
||||
} else {
|
||||
console.warn("System savedata verification failed!", response.status, response.statusText);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a system savedata.
|
||||
* @param params The {@linkcode UpdateSystemSavedataRequest} to send
|
||||
* @param rawSystemData The raw {@linkcode SystemSaveData}
|
||||
* @returns An error message if something went wrong
|
||||
*/
|
||||
public async update(params: UpdateSystemSavedataRequest, rawSystemData: string) {
|
||||
try {
|
||||
const urSearchParams = this.toUrlSearchParams(params);
|
||||
const response = await this.doPost(`/savedata/system/update?${urSearchParams}`, rawSystemData);
|
||||
|
||||
return await response.text();
|
||||
} catch (err) {
|
||||
console.warn("Could not update system savedata!", err);
|
||||
}
|
||||
|
||||
return "Unknown Error";
|
||||
}
|
||||
}
|
@ -48,7 +48,7 @@ import { RUN_HISTORY_LIMIT } from "#app/ui/run-history-ui-handler";
|
||||
import { applySessionVersionMigration, applySystemVersionMigration, applySettingsVersionMigration } from "./version_migration/version_converter";
|
||||
import { MysteryEncounterSaveData } from "#app/data/mystery-encounters/mystery-encounter-save-data";
|
||||
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
|
||||
import { PokerogueApiClearSessionData } from "#app/@types/pokerogue-api";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import { ArenaTrapTag } from "#app/data/arena-tag";
|
||||
|
||||
export const defaultStarterSpecies: Species[] = [
|
||||
@ -397,8 +397,7 @@ export class GameData {
|
||||
localStorage.setItem(`data_${loggedInUser?.username}`, encrypt(systemData, bypassLogin));
|
||||
|
||||
if (!bypassLogin) {
|
||||
Utils.apiPost(`savedata/system/update?clientSessionId=${clientSessionId}`, systemData, undefined, true)
|
||||
.then(response => response.text())
|
||||
pokerogueApi.savedata.system.update({ clientSessionId }, systemData)
|
||||
.then(error => {
|
||||
this.scene.ui.savingIcon.hide();
|
||||
if (error) {
|
||||
@ -428,23 +427,22 @@ export class GameData {
|
||||
}
|
||||
|
||||
if (!bypassLogin) {
|
||||
Utils.apiFetch(`savedata/system/get?clientSessionId=${clientSessionId}`, true)
|
||||
.then(response => response.text())
|
||||
.then(response => {
|
||||
if (!response.length || response[0] !== "{") {
|
||||
if (response.startsWith("sql: no rows in result set")) {
|
||||
pokerogueApi.savedata.system.get({ clientSessionId })
|
||||
.then(saveDataOrErr => {
|
||||
if (!saveDataOrErr || saveDataOrErr.length === 0 || saveDataOrErr[0] !== "{") {
|
||||
if (saveDataOrErr?.startsWith("sql: no rows in result set")) {
|
||||
this.scene.queueMessage("Save data could not be found. If this is a new account, you can safely ignore this message.", null, true);
|
||||
return resolve(true);
|
||||
} else if (response.indexOf("Too many connections") > -1) {
|
||||
} else if (saveDataOrErr?.includes("Too many connections")) {
|
||||
this.scene.queueMessage("Too many people are trying to connect and the server is overloaded. Please try again later.", null, true);
|
||||
return resolve(false);
|
||||
}
|
||||
console.error(response);
|
||||
console.error(saveDataOrErr);
|
||||
return resolve(false);
|
||||
}
|
||||
|
||||
const cachedSystem = localStorage.getItem(`data_${loggedInUser?.username}`);
|
||||
this.initSystem(response, cachedSystem ? AES.decrypt(cachedSystem, saveKey).toString(enc.Utf8) : undefined).then(resolve);
|
||||
this.initSystem(saveDataOrErr, cachedSystem ? AES.decrypt(cachedSystem, saveKey).toString(enc.Utf8) : undefined).then(resolve);
|
||||
});
|
||||
} else {
|
||||
this.initSystem(decrypt(localStorage.getItem(`data_${loggedInUser?.username}`)!, bypassLogin)).then(resolve); // TODO: is this bang correct?
|
||||
@ -580,6 +578,7 @@ export class GameData {
|
||||
if (!Utils.isLocal) {
|
||||
/**
|
||||
* Networking Code DO NOT DELETE!
|
||||
* Note: Might have to be migrated to `pokerogue-api.ts`
|
||||
*
|
||||
const response = await Utils.apiFetch("savedata/runHistory", true);
|
||||
const data = await response.json();
|
||||
@ -660,6 +659,7 @@ export class GameData {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
NOTE: should be adopted to `pokerogue-api.ts`
|
||||
*/
|
||||
return true;
|
||||
}
|
||||
@ -704,12 +704,11 @@ export class GameData {
|
||||
return true;
|
||||
}
|
||||
|
||||
const response = await Utils.apiFetch(`savedata/system/verify?clientSessionId=${clientSessionId}`, true)
|
||||
.then(response => response.json());
|
||||
const systemData = await pokerogueApi.savedata.system.verify({ clientSessionId });
|
||||
|
||||
if (!response.valid) {
|
||||
if (systemData) {
|
||||
this.scene.clearPhaseQueue();
|
||||
this.scene.unshiftPhase(new ReloadSessionPhase(this.scene, JSON.stringify(response.systemData)));
|
||||
this.scene.unshiftPhase(new ReloadSessionPhase(this.scene, JSON.stringify(systemData)));
|
||||
this.clearLocalData();
|
||||
return false;
|
||||
}
|
||||
@ -984,10 +983,9 @@ export class GameData {
|
||||
};
|
||||
|
||||
if (!bypassLogin && !localStorage.getItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`)) {
|
||||
Utils.apiFetch(`savedata/session/get?slot=${slotId}&clientSessionId=${clientSessionId}`, true)
|
||||
.then(response => response.text())
|
||||
pokerogueApi.savedata.session.get({ slot: slotId, clientSessionId })
|
||||
.then(async response => {
|
||||
if (!response.length || response[0] !== "{") {
|
||||
if (!response || response?.length === 0 || response?.[0] !== "{") {
|
||||
console.error(response);
|
||||
return resolve(null);
|
||||
}
|
||||
@ -1149,14 +1147,7 @@ export class GameData {
|
||||
if (success !== null && !success) {
|
||||
return resolve(false);
|
||||
}
|
||||
Utils.apiFetch(`savedata/session/delete?slot=${slotId}&clientSessionId=${clientSessionId}`, true).then(response => {
|
||||
if (response.ok) {
|
||||
loggedInUser!.lastSessionSlot = -1; // TODO: is the bang correct?
|
||||
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
||||
resolve(true);
|
||||
}
|
||||
return response.text();
|
||||
}).then(error => {
|
||||
pokerogueApi.savedata.session.delete({ slot: slotId, clientSessionId }).then(error => {
|
||||
if (error) {
|
||||
if (error.startsWith("session out of date")) {
|
||||
this.scene.clearPhaseQueue();
|
||||
@ -1164,8 +1155,15 @@ export class GameData {
|
||||
}
|
||||
console.error(error);
|
||||
resolve(false);
|
||||
} else {
|
||||
if (loggedInUser) {
|
||||
loggedInUser.lastSessionSlot = -1;
|
||||
}
|
||||
|
||||
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
||||
resolve(true);
|
||||
|
||||
}
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1215,17 +1213,15 @@ export class GameData {
|
||||
result = [ true, true ];
|
||||
} else {
|
||||
const sessionData = this.getSessionSaveData(scene);
|
||||
const response = await Utils.apiPost(`savedata/session/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`, JSON.stringify(sessionData), undefined, true);
|
||||
const { trainerId } = this;
|
||||
const jsonResponse = await pokerogueApi.savedata.session.clear({ slot: slotId, trainerId, clientSessionId }, sessionData);
|
||||
|
||||
if (response.ok) {
|
||||
loggedInUser!.lastSessionSlot = -1; // TODO: is the bang correct?
|
||||
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
||||
}
|
||||
|
||||
const jsonResponse: PokerogueApiClearSessionData = await response.json();
|
||||
|
||||
if (!jsonResponse.error) {
|
||||
result = [ true, jsonResponse.success ?? false ];
|
||||
if (!jsonResponse?.error) {
|
||||
result = [ true, jsonResponse?.success ?? false ];
|
||||
if (loggedInUser) {
|
||||
loggedInUser!.lastSessionSlot = -1;
|
||||
}
|
||||
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
||||
} else {
|
||||
if (jsonResponse && jsonResponse.error?.startsWith("session out of date")) {
|
||||
this.scene.clearPhaseQueue();
|
||||
@ -1342,8 +1338,7 @@ export class GameData {
|
||||
console.debug("Session data saved");
|
||||
|
||||
if (!bypassLogin && sync) {
|
||||
Utils.apiPost("savedata/updateall", JSON.stringify(request, (k: any, v: any) => typeof v === "bigint" ? v <= maxIntAttrValue ? Number(v) : v.toString() : v), undefined, true)
|
||||
.then(response => response.text())
|
||||
pokerogueApi.savedata.updateAll(request)
|
||||
.then(error => {
|
||||
if (sync) {
|
||||
this.scene.lastSavePlayTime = 0;
|
||||
@ -1387,18 +1382,24 @@ export class GameData {
|
||||
link.remove();
|
||||
};
|
||||
if (!bypassLogin && dataType < GameDataType.SETTINGS) {
|
||||
Utils.apiFetch(`savedata/${dataType === GameDataType.SYSTEM ? "system" : "session"}/get?clientSessionId=${clientSessionId}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ""}`, true)
|
||||
.then(response => response.text())
|
||||
.then(response => {
|
||||
if (!response.length || response[0] !== "{") {
|
||||
console.error(response);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
let promise: Promise<string | null> = Promise.resolve(null);
|
||||
|
||||
handleData(response);
|
||||
resolve(true);
|
||||
});
|
||||
if (dataType === GameDataType.SYSTEM) {
|
||||
promise = pokerogueApi.savedata.system.get({ clientSessionId });
|
||||
} else if (dataType === GameDataType.SESSION) {
|
||||
promise = pokerogueApi.savedata.session.get({ slot: slotId, clientSessionId });
|
||||
}
|
||||
|
||||
promise.then(response => {
|
||||
if (!response?.length || response[0] !== "{") {
|
||||
console.error(response);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
handleData(response);
|
||||
resolve(true);
|
||||
});
|
||||
} else {
|
||||
const data = localStorage.getItem(dataKey);
|
||||
if (data) {
|
||||
@ -1477,14 +1478,14 @@ export class GameData {
|
||||
if (!success[0]) {
|
||||
return displayError(`Could not contact the server. Your ${dataName} data could not be imported.`);
|
||||
}
|
||||
let url: string;
|
||||
const { trainerId, secretId } = this;
|
||||
let updatePromise: Promise<string | null>;
|
||||
if (dataType === GameDataType.SESSION) {
|
||||
url = `savedata/session/update?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`;
|
||||
updatePromise = pokerogueApi.savedata.session.update({ slot: slotId, trainerId, secretId, clientSessionId }, dataStr);
|
||||
} else {
|
||||
url = `savedata/system/update?trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`;
|
||||
updatePromise = pokerogueApi.savedata.system.update({ trainerId, secretId, clientSessionId }, dataStr);
|
||||
}
|
||||
Utils.apiPost(url, dataStr, undefined, true)
|
||||
.then(response => response.text())
|
||||
updatePromise
|
||||
.then(error => {
|
||||
if (error) {
|
||||
console.error(error);
|
||||
|
@ -1,7 +1,7 @@
|
||||
import * as battleScene from "#app/battle-scene";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { initLoggedInUser, loggedInUser, updateUserInfo } from "../account";
|
||||
import * as utils from "../utils";
|
||||
|
||||
describe("account", () => {
|
||||
describe("initLoggedInUser", () => {
|
||||
@ -27,17 +27,16 @@ describe("account", () => {
|
||||
|
||||
it("should fetch user info from the API if bypassLogin is false", async () => {
|
||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
||||
vi.spyOn(utils, "apiFetch").mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
username: "test",
|
||||
lastSessionSlot: 99,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
}
|
||||
)
|
||||
);
|
||||
vi.spyOn(pokerogueApi.account, "getInfo").mockResolvedValue([
|
||||
{
|
||||
username: "test",
|
||||
lastSessionSlot: 99,
|
||||
discordId: "",
|
||||
googleId: "",
|
||||
hasAdminRole: false,
|
||||
},
|
||||
200,
|
||||
]);
|
||||
|
||||
const [ success, status ] = await updateUserInfo();
|
||||
|
||||
@ -49,9 +48,7 @@ describe("account", () => {
|
||||
|
||||
it("should handle resolved API errors", async () => {
|
||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
||||
vi.spyOn(utils, "apiFetch").mockResolvedValue(
|
||||
new Response(null, { status: 401 })
|
||||
);
|
||||
vi.spyOn(pokerogueApi.account, "getInfo").mockResolvedValue([ null, 401 ]);
|
||||
|
||||
const [ success, status ] = await updateUserInfo();
|
||||
|
||||
@ -59,16 +56,14 @@ describe("account", () => {
|
||||
expect(status).toBe(401);
|
||||
});
|
||||
|
||||
it("should handle rejected API errors", async () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, "error");
|
||||
it("should handle 500 API errors", async () => {
|
||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
||||
vi.spyOn(utils, "apiFetch").mockRejectedValue(new Error("Api failed!"));
|
||||
vi.spyOn(pokerogueApi.account, "getInfo").mockResolvedValue([ null, 500 ]);
|
||||
|
||||
const [ success, status ] = await updateUserInfo();
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(status).toBe(500);
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -1,11 +1,12 @@
|
||||
import { MapModifier } from "#app/modifier/modifier";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import GameManager from "./utils/gameManager";
|
||||
import { Moves } from "#app/enums/moves";
|
||||
import { Biome } from "#app/enums/biome";
|
||||
import { Mode } from "#app/ui/ui";
|
||||
import { Moves } from "#app/enums/moves";
|
||||
import { MapModifier } from "#app/modifier/modifier";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import ModifierSelectUiHandler from "#app/ui/modifier-select-ui-handler";
|
||||
import { Species } from "#enums/species";
|
||||
import { Mode } from "#app/ui/ui";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import GameManager from "#app/test/utils/gameManager";
|
||||
|
||||
//const TIMEOUT = 20 * 1000;
|
||||
|
||||
@ -21,6 +22,7 @@ describe("Daily Mode", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
game = new GameManager(phaserGame);
|
||||
vi.spyOn(pokerogueApi.daily, "getSeed").mockResolvedValue("test-seed");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@ -32,7 +34,7 @@ describe("Daily Mode", () => {
|
||||
|
||||
const party = game.scene.getPlayerParty();
|
||||
expect(party).toHaveLength(3);
|
||||
party.forEach(pkm => {
|
||||
party.forEach((pkm) => {
|
||||
expect(pkm.level).toBe(20);
|
||||
expect(pkm.moveset.length).toBeGreaterThan(0);
|
||||
});
|
||||
@ -63,6 +65,7 @@ describe("Shop modifications", async () => {
|
||||
game.modifiers
|
||||
.addCheck("EVIOLITE")
|
||||
.addCheck("MINI_BLACK_HOLE");
|
||||
vi.spyOn(pokerogueApi.daily, "getSeed").mockResolvedValue("test-seed");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { apiFetch } from "#app/utils";
|
||||
// import { apiFetch } from "#app/utils";
|
||||
import GameManager from "#test/utils/gameManager";
|
||||
import { waitUntil } from "#test/utils/gameManagerUtils";
|
||||
import Phaser from "phaser";
|
||||
@ -35,18 +35,18 @@ describe("Test misc", () => {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("test apifetch mock async", async () => {
|
||||
const spy = vi.fn();
|
||||
await apiFetch("https://localhost:8080/account/info").then(response => {
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.ok).toBe(true);
|
||||
return response.json();
|
||||
}).then(data => {
|
||||
spy(); // Call the spy function
|
||||
expect(data).toEqual({ "username": "greenlamp", "lastSessionSlot": 0 });
|
||||
});
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
// it.skip("test apifetch mock async", async () => {
|
||||
// const spy = vi.fn();
|
||||
// await apiFetch("https://localhost:8080/account/info").then(response => {
|
||||
// expect(response.status).toBe(200);
|
||||
// expect(response.ok).toBe(true);
|
||||
// return response.json();
|
||||
// }).then(data => {
|
||||
// spy(); // Call the spy function
|
||||
// expect(data).toEqual({ "username": "greenlamp", "lastSessionSlot": 0 });
|
||||
// });
|
||||
// expect(spy).toHaveBeenCalled();
|
||||
// });
|
||||
|
||||
it("test fetch mock sync", async () => {
|
||||
const response = await fetch("https://localhost:8080/account/info");
|
||||
|
157
src/test/plugins/api/pokerogue-account-api.test.ts
Normal file
157
src/test/plugins/api/pokerogue-account-api.test.ts
Normal file
@ -0,0 +1,157 @@
|
||||
import type { AccountInfoResponse } from "#app/@types/PokerogueAccountApi";
|
||||
import { SESSION_ID_COOKIE_NAME } from "#app/constants";
|
||||
import { PokerogueAccountApi } from "#app/plugins/api/pokerogue-account-api";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import * as Utils from "#app/utils";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const accountApi = new PokerogueAccountApi(apiBase);
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue Account API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Get Info", () => {
|
||||
it("should return account-info & 200 on SUCCESS", async () => {
|
||||
const expectedAccountInfo: AccountInfoResponse = {
|
||||
username: "test",
|
||||
lastSessionSlot: -1,
|
||||
discordId: "23235353543535",
|
||||
googleId: "1ed1d1d11d1d1d1d1d1",
|
||||
hasAdminRole: false,
|
||||
};
|
||||
server.use(http.get(`${apiBase}/account/info`, () => HttpResponse.json(expectedAccountInfo)));
|
||||
|
||||
const [ accountInfo, status ] = await accountApi.getInfo();
|
||||
|
||||
expect(accountInfo).toEqual(expectedAccountInfo);
|
||||
expect(status).toBe(200);
|
||||
});
|
||||
|
||||
it("should return null + status-code anad report a warning on FAILURE", async () => {
|
||||
server.use(http.get(`${apiBase}/account/info`, () => new HttpResponse("", { status: 401 })));
|
||||
|
||||
const [ accountInfo, status ] = await accountApi.getInfo();
|
||||
|
||||
expect(accountInfo).toBeNull();
|
||||
expect(status).toBe(401);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get account info!", 401, "Unauthorized");
|
||||
});
|
||||
|
||||
it("should return null + 500 anad report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/account/info`, () => HttpResponse.error()));
|
||||
|
||||
const [ accountInfo, status ] = await accountApi.getInfo();
|
||||
|
||||
expect(accountInfo).toBeNull();
|
||||
expect(status).toBe(500);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get account info!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Register", () => {
|
||||
const registerParams = { username: "test", password: "test" };
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/account/register`, () => HttpResponse.text()));
|
||||
|
||||
const error = await accountApi.register(registerParams);
|
||||
|
||||
expect(error).toBeNull();
|
||||
});
|
||||
|
||||
it("should return error message on FAILURE", async () => {
|
||||
server.use(
|
||||
http.post(`${apiBase}/account/register`, () => new HttpResponse("Username is already taken", { status: 400 }))
|
||||
);
|
||||
|
||||
const error = await accountApi.register(registerParams);
|
||||
|
||||
expect(error).toBe("Username is already taken");
|
||||
});
|
||||
|
||||
it("should return \"Unknown error\" and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/account/register`, () => HttpResponse.error()));
|
||||
|
||||
const error = await accountApi.register(registerParams);
|
||||
|
||||
expect(error).toBe("Unknown error!");
|
||||
expect(console.warn).toHaveBeenCalledWith("Register failed!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Login", () => {
|
||||
const loginParams = { username: "test", password: "test" };
|
||||
|
||||
it("should return null and set the cookie on SUCCESS", async () => {
|
||||
vi.spyOn(Utils, "setCookie");
|
||||
server.use(http.post(`${apiBase}/account/login`, () => HttpResponse.json({ token: "abctest" })));
|
||||
|
||||
const error = await accountApi.login(loginParams);
|
||||
|
||||
expect(error).toBeNull();
|
||||
expect(Utils.setCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME, "abctest");
|
||||
});
|
||||
|
||||
it("should return error message and report a warning on FAILURE", async () => {
|
||||
server.use(
|
||||
http.post(`${apiBase}/account/login`, () => new HttpResponse("Password is incorrect", { status: 401 }))
|
||||
);
|
||||
|
||||
const error = await accountApi.login(loginParams);
|
||||
|
||||
expect(error).toBe("Password is incorrect");
|
||||
expect(console.warn).toHaveBeenCalledWith("Login failed!", 401, "Unauthorized");
|
||||
});
|
||||
|
||||
it("should return \"Unknown error\" and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/account/login`, () => HttpResponse.error()));
|
||||
|
||||
const error = await accountApi.login(loginParams);
|
||||
|
||||
expect(error).toBe("Unknown error!");
|
||||
expect(console.warn).toHaveBeenCalledWith("Login failed!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Logout", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(Utils, "removeCookie");
|
||||
});
|
||||
|
||||
it("should remove cookie on success", async () => {
|
||||
vi.spyOn(Utils, "setCookie");
|
||||
server.use(http.get(`${apiBase}/account/logout`, () => new HttpResponse("", { status: 200 })));
|
||||
|
||||
await accountApi.logout();
|
||||
|
||||
expect(Utils.removeCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME);
|
||||
});
|
||||
|
||||
it("should report a warning on and remove cookie on FAILURE", async () => {
|
||||
server.use(http.get(`${apiBase}/account/logout`, () => new HttpResponse("", { status: 401 })));
|
||||
|
||||
await accountApi.logout();
|
||||
|
||||
expect(Utils.removeCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME);
|
||||
expect(console.warn).toHaveBeenCalledWith("Log out failed!", expect.any(Error));
|
||||
});
|
||||
|
||||
it("should report a warning on and remove cookie on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/account/logout`, () => HttpResponse.error()));
|
||||
|
||||
await accountApi.logout();
|
||||
|
||||
expect(Utils.removeCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME);
|
||||
expect(console.warn).toHaveBeenCalledWith("Log out failed!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
232
src/test/plugins/api/pokerogue-admin-api.test.ts
Normal file
232
src/test/plugins/api/pokerogue-admin-api.test.ts
Normal file
@ -0,0 +1,232 @@
|
||||
import type {
|
||||
LinkAccountToDiscordIdRequest,
|
||||
LinkAccountToGoogledIdRequest,
|
||||
SearchAccountRequest,
|
||||
SearchAccountResponse,
|
||||
UnlinkAccountFromDiscordIdRequest,
|
||||
UnlinkAccountFromGoogledIdRequest,
|
||||
} from "#app/@types/PokerogueAdminApi";
|
||||
import { PokerogueAdminApi } from "#app/plugins/api/pokerogue-admin-api";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const adminApi = new PokerogueAdminApi(apiBase);
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue Admin API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Link Account to Discord", () => {
|
||||
const params: LinkAccountToDiscordIdRequest = { username: "test", discordId: "test-12575756" };
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => HttpResponse.json(true)));
|
||||
|
||||
const success = await adminApi.linkAccountToDiscord(params);
|
||||
|
||||
expect(success).toBeNull();
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => new HttpResponse("", { status: 400 })));
|
||||
|
||||
const success = await adminApi.linkAccountToDiscord(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not link account with discord!", 400, "Bad Request");
|
||||
});
|
||||
|
||||
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => new HttpResponse("", { status: 404 })));
|
||||
|
||||
const success = await adminApi.linkAccountToDiscord(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not link account with discord!", 404, "Not Found");
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => HttpResponse.error()));
|
||||
|
||||
const success = await adminApi.linkAccountToDiscord(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not link account with discord!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Unlink Account from Discord", () => {
|
||||
const params: UnlinkAccountFromDiscordIdRequest = { username: "test", discordId: "test-12575756" };
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => HttpResponse.json(true)));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||
|
||||
expect(success).toBeNull();
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => new HttpResponse("", { status: 400 })));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from discord!", 400, "Bad Request");
|
||||
});
|
||||
|
||||
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => new HttpResponse("", { status: 404 })));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from discord!", 404, "Not Found");
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => HttpResponse.error()));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from discord!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Link Account to Google", () => {
|
||||
const params: LinkAccountToGoogledIdRequest = { username: "test", googleId: "test-12575756" };
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => HttpResponse.json(true)));
|
||||
|
||||
const success = await adminApi.linkAccountToGoogleId(params);
|
||||
|
||||
expect(success).toBeNull();
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => new HttpResponse("", { status: 400 })));
|
||||
|
||||
const success = await adminApi.linkAccountToGoogleId(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not link account with google!", 400, "Bad Request");
|
||||
});
|
||||
|
||||
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => new HttpResponse("", { status: 404 })));
|
||||
|
||||
const success = await adminApi.linkAccountToGoogleId(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not link account with google!", 404, "Not Found");
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => HttpResponse.error()));
|
||||
|
||||
const success = await adminApi.linkAccountToGoogleId(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not link account with google!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Unlink Account from Google", () => {
|
||||
const params: UnlinkAccountFromGoogledIdRequest = { username: "test", googleId: "test-12575756" };
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => HttpResponse.json(true)));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||
|
||||
expect(success).toBeNull();
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => new HttpResponse("", { status: 400 })));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from google!", 400, "Bad Request");
|
||||
});
|
||||
|
||||
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => new HttpResponse("", { status: 404 })));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from google!", 404, "Not Found");
|
||||
});
|
||||
|
||||
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => HttpResponse.error()));
|
||||
|
||||
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||
|
||||
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from google!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Search Account", () => {
|
||||
const params: SearchAccountRequest = { username: "test" };
|
||||
|
||||
it("should return [data, undefined] on SUCCESS", async () => {
|
||||
const responseData: SearchAccountResponse = {
|
||||
username: "test",
|
||||
discordId: "discord-test-123",
|
||||
googleId: "google-test-123",
|
||||
lastLoggedIn: "2022-01-01",
|
||||
registered: "2022-01-01",
|
||||
};
|
||||
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => HttpResponse.json(responseData)));
|
||||
|
||||
const [ data, err ] = await adminApi.searchAccount(params);
|
||||
|
||||
expect(data).toStrictEqual(responseData);
|
||||
expect(err).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return [undefined, ERR_GENERIC] and report a warning on on FAILURE", async () => {
|
||||
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => new HttpResponse("", { status: 400 })));
|
||||
|
||||
const [ data, err ] = await adminApi.searchAccount(params);
|
||||
|
||||
expect(data).toBeUndefined();
|
||||
expect(err).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not find account!", 400, "Bad Request");
|
||||
});
|
||||
|
||||
it("should return [undefined, ERR_USERNAME_NOT_FOUND] and report a warning on on 404", async () => {
|
||||
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => new HttpResponse("", { status: 404 })));
|
||||
|
||||
const [ data, err ] = await adminApi.searchAccount(params);
|
||||
|
||||
expect(data).toBeUndefined();
|
||||
expect(err).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not find account!", 404, "Not Found");
|
||||
});
|
||||
|
||||
it("should return [undefined, ERR_GENERIC] and report a warning on on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => HttpResponse.error()));
|
||||
|
||||
const [ data, err ] = await adminApi.searchAccount(params);
|
||||
|
||||
expect(data).toBeUndefined();
|
||||
expect(err).toBe(adminApi.ERR_GENERIC);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not find account!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
97
src/test/plugins/api/pokerogue-api.test.ts
Normal file
97
src/test/plugins/api/pokerogue-api.test.ts
Normal file
@ -0,0 +1,97 @@
|
||||
import type { TitleStatsResponse } from "#app/@types/PokerogueApi";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Game Title Stats", () => {
|
||||
const expectedTitleStats: TitleStatsResponse = {
|
||||
playerCount: 9999999,
|
||||
battleCount: 9999999,
|
||||
};
|
||||
|
||||
it("should return the stats on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/game/titlestats`, () => HttpResponse.json(expectedTitleStats)));
|
||||
|
||||
const titleStats = await pokerogueApi.getGameTitleStats();
|
||||
|
||||
expect(titleStats).toEqual(expectedTitleStats);
|
||||
});
|
||||
|
||||
it("should return null and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/game/titlestats`, () => HttpResponse.error()));
|
||||
const titleStats = await pokerogueApi.getGameTitleStats();
|
||||
|
||||
expect(titleStats).toBeNull();
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get game title stats!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Unlink Discord", () => {
|
||||
it("should return true on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/auth/discord/logout`, () => new HttpResponse("", { status: 200 })));
|
||||
|
||||
const success = await pokerogueApi.unlinkDiscord();
|
||||
|
||||
expect(success).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false and report a warning on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/auth/discord/logout`, () => new HttpResponse("", { status: 401 })));
|
||||
|
||||
const success = await pokerogueApi.unlinkDiscord();
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(console.warn).toHaveBeenCalledWith("Discord unlink failed (401: Unauthorized)");
|
||||
});
|
||||
|
||||
it("should return false and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/auth/discord/logout`, () => HttpResponse.error()));
|
||||
|
||||
const success = await pokerogueApi.unlinkDiscord();
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink Discord!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Unlink Google", () => {
|
||||
it("should return true on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/auth/google/logout`, () => new HttpResponse("", { status: 200 })));
|
||||
|
||||
const success = await pokerogueApi.unlinkGoogle();
|
||||
|
||||
expect(success).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false and report a warning on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/auth/google/logout`, () => new HttpResponse("", { status: 401 })));
|
||||
|
||||
const success = await pokerogueApi.unlinkGoogle();
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(console.warn).toHaveBeenCalledWith("Google unlink failed (401: Unauthorized)");
|
||||
});
|
||||
|
||||
it("should return false and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/auth/google/logout`, () => HttpResponse.error()));
|
||||
|
||||
const success = await pokerogueApi.unlinkGoogle();
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not unlink Google!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
89
src/test/plugins/api/pokerogue-daily-api.test.ts
Normal file
89
src/test/plugins/api/pokerogue-daily-api.test.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import type { GetDailyRankingsPageCountRequest, GetDailyRankingsRequest } from "#app/@types/PokerogueDailyApi";
|
||||
import { PokerogueDailyApi } from "#app/plugins/api/pokerogue-daily-api";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import { ScoreboardCategory, type RankingEntry } from "#app/ui/daily-run-scoreboard";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const dailyApi = new PokerogueDailyApi(apiBase);
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue Daily API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Get Seed", () => {
|
||||
it("should return seed string on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/daily/seed`, () => HttpResponse.text("this-is-a-test-seed")));
|
||||
|
||||
const seed = await dailyApi.getSeed();
|
||||
|
||||
expect(seed).toBe("this-is-a-test-seed");
|
||||
});
|
||||
|
||||
it("should return null and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/daily/seed`, () => HttpResponse.error()));
|
||||
|
||||
const seed = await dailyApi.getSeed();
|
||||
|
||||
expect(seed).toBeNull();
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get daily-run seed!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Get Rankings", () => {
|
||||
const params: GetDailyRankingsRequest = {
|
||||
category: ScoreboardCategory.DAILY,
|
||||
};
|
||||
|
||||
it("should return ranking entries on SUCCESS", async () => {
|
||||
const expectedRankings: RankingEntry[] = [
|
||||
{ rank: 1, score: 999, username: "Player 1", wave: 200 },
|
||||
{ rank: 2, score: 10, username: "Player 2", wave: 1 },
|
||||
];
|
||||
server.use(http.get(`${apiBase}/daily/rankings`, () => HttpResponse.json(expectedRankings)));
|
||||
|
||||
const rankings = await dailyApi.getRankings(params);
|
||||
|
||||
expect(rankings).toStrictEqual(expectedRankings);
|
||||
});
|
||||
|
||||
it("should return null and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/daily/rankings`, () => HttpResponse.error()));
|
||||
|
||||
const rankings = await dailyApi.getRankings(params);
|
||||
|
||||
expect(rankings).toBeNull();
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get daily rankings!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Get Rankings Page Count", () => {
|
||||
const params: GetDailyRankingsPageCountRequest = {
|
||||
category: ScoreboardCategory.DAILY,
|
||||
};
|
||||
|
||||
it("should return a number on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/daily/rankingpagecount`, () => HttpResponse.json(5)));
|
||||
|
||||
const pageCount = await dailyApi.getRankingsPageCount(params);
|
||||
|
||||
expect(pageCount).toBe(5);
|
||||
});
|
||||
|
||||
it("should return 1 and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/daily/rankingpagecount`, () => HttpResponse.error()));
|
||||
|
||||
const pageCount = await dailyApi.getRankingsPageCount(params);
|
||||
|
||||
expect(pageCount).toBe(1);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get daily rankings page count!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
46
src/test/plugins/api/pokerogue-savedata-api.test.ts
Normal file
46
src/test/plugins/api/pokerogue-savedata-api.test.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import type { UpdateAllSavedataRequest } from "#app/@types/PokerogueSavedataApi";
|
||||
import { PokerogueSavedataApi } from "#app/plugins/api/pokerogue-savedata-api";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const savedataApi = new PokerogueSavedataApi(apiBase);
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue Savedata API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Update All", () => {
|
||||
it("should return an empty string on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/updateall`, () => HttpResponse.text(null)));
|
||||
|
||||
const error = await savedataApi.updateAll({} as UpdateAllSavedataRequest);
|
||||
|
||||
expect(error).toBe("");
|
||||
});
|
||||
|
||||
it("should return an error message on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/updateall`, () => HttpResponse.text("Failed to update all!")));
|
||||
|
||||
const error = await savedataApi.updateAll({} as UpdateAllSavedataRequest);
|
||||
|
||||
expect(error).toBe("Failed to update all!");
|
||||
});
|
||||
|
||||
it("should return 'Unknown error' and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/updateall`, () => HttpResponse.error()));
|
||||
|
||||
const error = await savedataApi.updateAll({} as UpdateAllSavedataRequest);
|
||||
|
||||
expect(error).toBe("Unknown error");
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not update all savedata!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
199
src/test/plugins/api/pokerogue-session-savedata-api.test.ts
Normal file
199
src/test/plugins/api/pokerogue-session-savedata-api.test.ts
Normal file
@ -0,0 +1,199 @@
|
||||
import type {
|
||||
ClearSessionSavedataRequest,
|
||||
ClearSessionSavedataResponse,
|
||||
DeleteSessionSavedataRequest,
|
||||
GetSessionSavedataRequest,
|
||||
NewClearSessionSavedataRequest,
|
||||
UpdateSessionSavedataRequest,
|
||||
} from "#app/@types/PokerogueSessionSavedataApi";
|
||||
import { PokerogueSessionSavedataApi } from "#app/plugins/api/pokerogue-session-savedata-api";
|
||||
import type { SessionSaveData } from "#app/system/game-data";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const sessionSavedataApi = new PokerogueSessionSavedataApi(apiBase);
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue Session Savedata API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Newclear", () => {
|
||||
const params: NewClearSessionSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
slot: 3,
|
||||
};
|
||||
|
||||
it("should return true on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/newclear`, () => HttpResponse.json(true)));
|
||||
|
||||
const success = await sessionSavedataApi.newclear(params);
|
||||
|
||||
expect(success).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false on FAILURE", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/newclear`, () => HttpResponse.json(false)));
|
||||
|
||||
const success = await sessionSavedataApi.newclear(params);
|
||||
|
||||
expect(success).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/newclear`, () => HttpResponse.error()));
|
||||
|
||||
const success = await sessionSavedataApi.newclear(params);
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not newclear session!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Get ", () => {
|
||||
const params: GetSessionSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
slot: 3,
|
||||
};
|
||||
|
||||
it("should return session-savedata string on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/get`, () => HttpResponse.text("TEST SESSION SAVEDATA")));
|
||||
|
||||
const savedata = await sessionSavedataApi.get(params);
|
||||
|
||||
expect(savedata).toBe("TEST SESSION SAVEDATA");
|
||||
});
|
||||
|
||||
it("should return null and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/get`, () => HttpResponse.error()));
|
||||
|
||||
const savedata = await sessionSavedataApi.get(params);
|
||||
|
||||
expect(savedata).toBeNull();
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get session savedata!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Update", () => {
|
||||
const params: UpdateSessionSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
slot: 3,
|
||||
secretId: 9876543321,
|
||||
trainerId: 123456789,
|
||||
};
|
||||
|
||||
it("should return an empty string on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/session/update`, () => HttpResponse.text(null)));
|
||||
|
||||
const error = await sessionSavedataApi.update(params, "UPDATED SESSION SAVEDATA");
|
||||
|
||||
expect(error).toBe("");
|
||||
});
|
||||
|
||||
it("should return an error string on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/session/update`, () => HttpResponse.text("Failed to update!")));
|
||||
|
||||
const error = await sessionSavedataApi.update(params, "UPDATED SESSION SAVEDATA");
|
||||
|
||||
expect(error).toBe("Failed to update!");
|
||||
});
|
||||
|
||||
it("should return 'Unknown Error!' and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/session/update`, () => HttpResponse.error()));
|
||||
|
||||
const error = await sessionSavedataApi.update(params, "UPDATED SESSION SAVEDATA");
|
||||
|
||||
expect(error).toBe("Unknown Error!");
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not update session savedata!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delete", () => {
|
||||
const params: DeleteSessionSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
slot: 3,
|
||||
};
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/delete`, () => HttpResponse.text(null)));
|
||||
|
||||
const error = await sessionSavedataApi.delete(params);
|
||||
|
||||
expect(error).toBeNull();
|
||||
});
|
||||
|
||||
it("should return an error string on FAILURE", async () => {
|
||||
server.use(
|
||||
http.get(`${apiBase}/savedata/session/delete`, () => new HttpResponse("Failed to delete!", { status: 400 }))
|
||||
);
|
||||
|
||||
const error = await sessionSavedataApi.delete(params);
|
||||
|
||||
expect(error).toBe("Failed to delete!");
|
||||
});
|
||||
|
||||
it("should return 'Unknown error' and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/session/delete`, () => HttpResponse.error()));
|
||||
|
||||
const error = await sessionSavedataApi.delete(params);
|
||||
|
||||
expect(error).toBe("Unknown error");
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not delete session savedata!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Clear", () => {
|
||||
const params: ClearSessionSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
slot: 3,
|
||||
trainerId: 123456789,
|
||||
};
|
||||
|
||||
it("should return sucess=true on SUCCESS", async () => {
|
||||
server.use(
|
||||
http.post(`${apiBase}/savedata/session/clear`, () =>
|
||||
HttpResponse.json<ClearSessionSavedataResponse>({
|
||||
success: true,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const { success, error } = await sessionSavedataApi.clear(params, {} as SessionSaveData);
|
||||
|
||||
expect(success).toBe(true);
|
||||
expect(error).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return sucess=false & an error string on FAILURE", async () => {
|
||||
server.use(
|
||||
http.post(`${apiBase}/savedata/session/clear`, () =>
|
||||
HttpResponse.json<ClearSessionSavedataResponse>({
|
||||
success: false,
|
||||
error: "Failed to clear!",
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const { success, error } = await sessionSavedataApi.clear(params, {} as SessionSaveData);
|
||||
|
||||
expect(error).toBe("Failed to clear!");
|
||||
expect(success).toBe(false);
|
||||
});
|
||||
|
||||
it("should return success=false & error='Unknown error' and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.error()));
|
||||
|
||||
const { success, error } = await sessionSavedataApi.clear(params, {} as SessionSaveData);
|
||||
|
||||
expect(error).toBe("Unknown error");
|
||||
expect(success).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
122
src/test/plugins/api/pokerogue-system-savedata-api.test.ts
Normal file
122
src/test/plugins/api/pokerogue-system-savedata-api.test.ts
Normal file
@ -0,0 +1,122 @@
|
||||
import type {
|
||||
GetSystemSavedataRequest,
|
||||
UpdateSystemSavedataRequest,
|
||||
VerifySystemSavedataRequest,
|
||||
VerifySystemSavedataResponse,
|
||||
} from "#app/@types/PokerogueSystemSavedataApi";
|
||||
import { PokerogueSystemSavedataApi } from "#app/plugins/api/pokerogue-system-savedata-api";
|
||||
import type { SystemSaveData } from "#app/system/game-data";
|
||||
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiBase = getApiBaseUrl();
|
||||
const systemSavedataApi = new PokerogueSystemSavedataApi(getApiBaseUrl());
|
||||
const { server } = global;
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe("Pokerogue System Savedata API", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn");
|
||||
});
|
||||
|
||||
describe("Get", () => {
|
||||
const params: GetSystemSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
};
|
||||
|
||||
it("should return system-savedata string on SUCCESS", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/system/get`, () => HttpResponse.text("TEST SYSTEM SAVEDATA")));
|
||||
|
||||
const savedata = await systemSavedataApi.get(params);
|
||||
|
||||
expect(savedata).toBe("TEST SYSTEM SAVEDATA");
|
||||
});
|
||||
|
||||
it("should return null and report a warning on ERROR", async () => {
|
||||
server.use(http.get(`${apiBase}/savedata/system/get`, () => HttpResponse.error()));
|
||||
|
||||
const savedata = await systemSavedataApi.get(params);
|
||||
|
||||
expect(savedata).toBeNull();
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not get system savedata!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Verify", () => {
|
||||
const params: VerifySystemSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
};
|
||||
|
||||
it("should return null on SUCCESS", async () => {
|
||||
server.use(
|
||||
http.get(`${apiBase}/savedata/system/verify`, () =>
|
||||
HttpResponse.json<VerifySystemSavedataResponse>({
|
||||
systemData: {
|
||||
trainerId: 123456789,
|
||||
} as SystemSaveData,
|
||||
valid: true,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const savedata = await systemSavedataApi.verify(params);
|
||||
|
||||
expect(savedata).toBeNull();
|
||||
});
|
||||
|
||||
it("should return system-savedata and report a warning on FAILURE", async () => {
|
||||
server.use(
|
||||
http.get(`${apiBase}/savedata/system/verify`, () =>
|
||||
HttpResponse.json<VerifySystemSavedataResponse>({
|
||||
systemData: {
|
||||
trainerId: 123456789,
|
||||
} as SystemSaveData,
|
||||
valid: false,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const savedata = await systemSavedataApi.verify(params);
|
||||
|
||||
expect(savedata?.trainerId).toBe(123456789);
|
||||
expect(console.warn).toHaveBeenCalledWith("Invalid system savedata!");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Update", () => {
|
||||
const params: UpdateSystemSavedataRequest = {
|
||||
clientSessionId: "test-session-id",
|
||||
secretId: 9876543321,
|
||||
trainerId: 123456789,
|
||||
};
|
||||
|
||||
it("should return an empty string on SUCCESS", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/system/update`, () => HttpResponse.text(null)));
|
||||
|
||||
const error = await systemSavedataApi.update(params, "UPDATED SYSTEM SAVEDATA");
|
||||
|
||||
expect(error).toBe("");
|
||||
});
|
||||
|
||||
it("should return an error string on FAILURE", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/system/update`, () => HttpResponse.text("Failed to update!")));
|
||||
|
||||
const error = await systemSavedataApi.update(params, "UPDATED SYSTEM SAVEDATA");
|
||||
|
||||
expect(error).toBe("Failed to update!");
|
||||
});
|
||||
|
||||
it("should return 'Unknown Error' and report a warning on ERROR", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/system/update`, () => HttpResponse.error()));
|
||||
|
||||
const error = await systemSavedataApi.update(params, "UPDATED SYSTEM SAVEDATA");
|
||||
|
||||
expect(error).toBe("Unknown Error");
|
||||
expect(console.warn).toHaveBeenCalledWith("Could not update system savedata!", expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
@ -1,4 +1,5 @@
|
||||
import { GameModes } from "#app/game-mode";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import OptionSelectUiHandler from "#app/ui/settings/option-select-ui-handler";
|
||||
import { Mode } from "#app/ui/ui";
|
||||
import { Biome } from "#enums/biome";
|
||||
@ -7,7 +8,7 @@ import { Moves } from "#enums/moves";
|
||||
import { Species } from "#enums/species";
|
||||
import GameManager from "#test/utils/gameManager";
|
||||
import { MockClock } from "#test/utils/mocks/mockClock";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
describe("Reload", () => {
|
||||
let phaserGame: Phaser.Game;
|
||||
@ -25,6 +26,8 @@ describe("Reload", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
game = new GameManager(phaserGame);
|
||||
vi.spyOn(pokerogueApi, "getGameTitleStats").mockResolvedValue({ battleCount: -1, playerCount: -1 });
|
||||
vi.spyOn(pokerogueApi.daily, "getSeed").mockResolvedValue("test-seed");
|
||||
});
|
||||
|
||||
it("should not have RNG inconsistencies in a Classic run", async () => {
|
||||
@ -110,8 +113,7 @@ describe("Reload", () => {
|
||||
}, 20000);
|
||||
|
||||
it("should not have RNG inconsistencies at a Daily run double battle", async () => {
|
||||
game.override
|
||||
.battleType("double");
|
||||
game.override.battleType("double");
|
||||
await game.dailyMode.startBattle();
|
||||
|
||||
const preReloadRngState = Phaser.Math.RND.state();
|
||||
@ -124,9 +126,7 @@ describe("Reload", () => {
|
||||
}, 20000);
|
||||
|
||||
it("should not have RNG inconsistencies at a Daily run Gym Leader fight", async () => {
|
||||
game.override
|
||||
.battleType("single")
|
||||
.startingWave(40);
|
||||
game.override.battleType("single").startingWave(40);
|
||||
await game.dailyMode.startBattle();
|
||||
|
||||
const preReloadRngState = Phaser.Math.RND.state();
|
||||
@ -139,9 +139,7 @@ describe("Reload", () => {
|
||||
}, 20000);
|
||||
|
||||
it("should not have RNG inconsistencies at a Daily run regular trainer fight", async () => {
|
||||
game.override
|
||||
.battleType("single")
|
||||
.startingWave(45);
|
||||
game.override.battleType("single").startingWave(45);
|
||||
await game.dailyMode.startBattle();
|
||||
|
||||
const preReloadRngState = Phaser.Math.RND.state();
|
||||
@ -154,9 +152,7 @@ describe("Reload", () => {
|
||||
}, 20000);
|
||||
|
||||
it("should not have RNG inconsistencies at a Daily run wave 50 Boss fight", async () => {
|
||||
game.override
|
||||
.battleType("single")
|
||||
.startingWave(50);
|
||||
game.override.battleType("single").startingWave(50);
|
||||
await game.runToFinalBossEncounter([ Species.BULBASAUR ], GameModes.DAILY);
|
||||
|
||||
const preReloadRngState = Phaser.Math.RND.state();
|
||||
|
@ -1,36 +1,23 @@
|
||||
import * as BattleScene from "#app/battle-scene";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import { SessionSaveData } from "#app/system/game-data";
|
||||
import { Abilities } from "#enums/abilities";
|
||||
import { Moves } from "#enums/moves";
|
||||
import GameManager from "#test/utils/gameManager";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import Phaser from "phaser";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as account from "../../account";
|
||||
|
||||
const apiBase = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8001";
|
||||
|
||||
/** We need a custom server. For some reasons I can't extend the listeners of {@linkcode global.i18nServer} with {@linkcode global.i18nServer.use} */
|
||||
const server = setupServer();
|
||||
|
||||
describe("System - Game Data", () => {
|
||||
let phaserGame: Phaser.Game;
|
||||
let game: GameManager;
|
||||
|
||||
beforeAll(() => {
|
||||
global.i18nServer.close();
|
||||
server.listen();
|
||||
phaserGame = new Phaser.Game({
|
||||
type: Phaser.HEADLESS,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server.close();
|
||||
global.i18nServer.listen();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
game = new GameManager(phaserGame);
|
||||
game.override
|
||||
@ -41,7 +28,6 @@ describe("System - Game Data", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
game.phaseInterceptor.restoreOg();
|
||||
});
|
||||
|
||||
@ -61,7 +47,7 @@ describe("System - Game Data", () => {
|
||||
});
|
||||
|
||||
it("should return [true, true] if successful", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.json({ success: true })));
|
||||
vi.spyOn(pokerogueApi.savedata.session, "clear").mockResolvedValue({ success: true });
|
||||
|
||||
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
||||
|
||||
@ -70,7 +56,7 @@ describe("System - Game Data", () => {
|
||||
});
|
||||
|
||||
it("should return [true, false] if not successful", async () => {
|
||||
server.use(http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.json({ success: false })));
|
||||
vi.spyOn(pokerogueApi.savedata.session, "clear").mockResolvedValue({ success: false });
|
||||
|
||||
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
||||
|
||||
@ -79,9 +65,7 @@ describe("System - Game Data", () => {
|
||||
});
|
||||
|
||||
it("should return [false, false] session is out of date", async () => {
|
||||
server.use(
|
||||
http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.json({ error: "session out of date" }))
|
||||
);
|
||||
vi.spyOn(pokerogueApi.savedata.session, "clear").mockResolvedValue({ error: "session out of date" });
|
||||
|
||||
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
||||
|
||||
|
@ -79,7 +79,7 @@ export default class GameWrapper {
|
||||
|
||||
constructor(phaserGame: Phaser.Game, bypassLogin: boolean) {
|
||||
Phaser.Math.RND.sow([ 'test' ]);
|
||||
vi.spyOn(Utils, "apiFetch", "get").mockReturnValue(fetch);
|
||||
// vi.spyOn(Utils, "apiFetch", "get").mockReturnValue(fetch);
|
||||
if (bypassLogin) {
|
||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(true);
|
||||
}
|
||||
|
@ -21,3 +21,11 @@ export function mockI18next() {
|
||||
export function arrayOfRange(start: integer, end: integer) {
|
||||
return Array.from({ length: end - start }, (_v, k) => k + start);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility to get the API base URL from the environment variable (or the default/fallback).
|
||||
* @returns the API base URL
|
||||
*/
|
||||
export function getApiBaseUrl() {
|
||||
return import.meta.env.VITE_SERVER_URL ?? "http://localhost:8001";
|
||||
}
|
||||
|
@ -38,7 +38,7 @@ vi.mock("i18next", async (importOriginal) => {
|
||||
const { setupServer } = await import("msw/node");
|
||||
const { http, HttpResponse } = await import("msw");
|
||||
|
||||
global.i18nServer = setupServer(
|
||||
global.server = setupServer(
|
||||
http.get("/locales/en/*", async (req) => {
|
||||
const filename = req.params[0];
|
||||
|
||||
@ -50,9 +50,12 @@ vi.mock("i18next", async (importOriginal) => {
|
||||
console.log(`Failed to load locale ${filename}!`, err);
|
||||
return HttpResponse.json({});
|
||||
}
|
||||
})
|
||||
}),
|
||||
http.get("https://fonts.googleapis.com/*", () => {
|
||||
return HttpResponse.text("");
|
||||
}),
|
||||
);
|
||||
global.i18nServer.listen({ onUnhandledRequest: "error" });
|
||||
global.server.listen({ onUnhandledRequest: "error" });
|
||||
console.log("i18n MSW server listening!");
|
||||
|
||||
return await importOriginal();
|
||||
@ -83,6 +86,6 @@ beforeAll(() => {
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
global.i18nServer.close();
|
||||
global.server.close();
|
||||
console.log("Closing i18n MSW server!");
|
||||
});
|
||||
|
@ -1,10 +1,14 @@
|
||||
import BattleScene from "#app/battle-scene";
|
||||
import { ModalConfig } from "./modal-ui-handler";
|
||||
import { Mode } from "./ui";
|
||||
import * as Utils from "../utils";
|
||||
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
||||
import { Button } from "#app/enums/buttons";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
import { formatText } from "#app/utils";
|
||||
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
||||
import { ModalConfig } from "./modal-ui-handler";
|
||||
import { TextStyle } from "./text";
|
||||
import { Mode } from "./ui";
|
||||
|
||||
type AdminUiHandlerService = "discord" | "google";
|
||||
type AdminUiHandlerServiceMode = "Link" | "Unlink";
|
||||
|
||||
export default class AdminUiHandler extends FormModalUiHandler {
|
||||
|
||||
@ -17,17 +21,15 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
||||
private readonly httpUserNotFoundErrorCode: number = 404;
|
||||
private readonly ERR_REQUIRED_FIELD = (field: string) => {
|
||||
if (field === "username") {
|
||||
return `${Utils.formatText(field)} is required`;
|
||||
return `${formatText(field)} is required`;
|
||||
} else {
|
||||
return `${Utils.formatText(field)} Id is required`;
|
||||
return `${formatText(field)} Id is required`;
|
||||
}
|
||||
};
|
||||
// returns a string saying whether a username has been successfully linked/unlinked to discord/google
|
||||
private readonly SUCCESS_SERVICE_MODE = (service: string, mode: string) => {
|
||||
return `Username and ${service} successfully ${mode.toLowerCase()}ed`;
|
||||
};
|
||||
private readonly ERR_USERNAME_NOT_FOUND: string = "Username not found!";
|
||||
private readonly ERR_GENERIC_ERROR: string = "There was an error";
|
||||
|
||||
constructor(scene: BattleScene, mode: Mode | null = null) {
|
||||
super(scene, mode);
|
||||
@ -148,7 +150,6 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
||||
} else if (this.adminMode === AdminMode.ADMIN) {
|
||||
this.updateAdminPanelInfo(adminSearchResult, AdminMode.SEARCH);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
@ -196,7 +197,7 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
||||
this.scene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error
|
||||
return this.showMessage(validFields.errorMessage ?? "", adminResult, true);
|
||||
}
|
||||
this.adminLinkUnlink(this.convertInputsToAdmin(), service, mode).then(response => { // attempts to link/unlink depending on the service
|
||||
this.adminLinkUnlink(this.convertInputsToAdmin(), service as AdminUiHandlerService, mode).then(response => { // attempts to link/unlink depending on the service
|
||||
if (response.error) {
|
||||
this.scene.ui.setMode(Mode.LOADING, { buttonActions: []});
|
||||
return this.showMessage(response.errorType, adminResult, true); // fail
|
||||
@ -276,12 +277,11 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
||||
|
||||
private async adminSearch(adminSearchResult: AdminSearchInfo) {
|
||||
try {
|
||||
const adminInfo = await Utils.apiFetch(`admin/account/adminSearch?username=${encodeURIComponent(adminSearchResult.username)}`, true);
|
||||
if (!adminInfo.ok) { // error - if adminInfo.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
||||
return { adminSearchResult: adminSearchResult, error: true, errorType: adminInfo.status === this.httpUserNotFoundErrorCode ? this.ERR_USERNAME_NOT_FOUND : this.ERR_GENERIC_ERROR };
|
||||
const [ adminInfo, errorType ] = await pokerogueApi.admin.searchAccount({ username: adminSearchResult.username });
|
||||
if (errorType || !adminInfo) { // error - if adminInfo.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
||||
return { adminSearchResult: adminSearchResult, error: true, errorType };
|
||||
} else { // success
|
||||
const adminInfoJson: AdminSearchInfo = await adminInfo.json();
|
||||
return { adminSearchResult: adminInfoJson, error: false };
|
||||
return { adminSearchResult: adminInfo, error: false };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@ -289,12 +289,47 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private async adminLinkUnlink(adminSearchResult: AdminSearchInfo, service: string, mode: string) {
|
||||
private async adminLinkUnlink(adminSearchResult: AdminSearchInfo, service: AdminUiHandlerService, mode: AdminUiHandlerServiceMode) {
|
||||
try {
|
||||
const response = await Utils.apiPost(`admin/account/${service}${mode}`, `username=${encodeURIComponent(adminSearchResult.username)}&${service}Id=${encodeURIComponent(service === "discord" ? adminSearchResult.discordId : adminSearchResult.googleId)}`, "application/x-www-form-urlencoded", true);
|
||||
if (!response.ok) { // error - if response.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
||||
return { adminSearchResult: adminSearchResult, error: true, errorType: response.status === this.httpUserNotFoundErrorCode ? this.ERR_USERNAME_NOT_FOUND : this.ERR_GENERIC_ERROR };
|
||||
} else { // success!
|
||||
let errorType: string | null = null;
|
||||
|
||||
if (service === "discord") {
|
||||
if (mode === "Link") {
|
||||
errorType = await pokerogueApi.admin.linkAccountToDiscord({
|
||||
discordId: adminSearchResult.discordId,
|
||||
username: adminSearchResult.username,
|
||||
});
|
||||
} else if (mode === "Unlink") {
|
||||
errorType = await pokerogueApi.admin.unlinkAccountFromDiscord({
|
||||
discordId: adminSearchResult.discordId,
|
||||
username: adminSearchResult.username,
|
||||
});
|
||||
} else {
|
||||
console.warn("Unknown mode", mode, "for service", service);
|
||||
}
|
||||
} else if (service === "google") {
|
||||
if (mode === "Link") {
|
||||
errorType = await pokerogueApi.admin.linkAccountToGoogleId({
|
||||
googleId: adminSearchResult.googleId,
|
||||
username: adminSearchResult.username,
|
||||
});
|
||||
} else if (mode === "Unlink") {
|
||||
errorType = await pokerogueApi.admin.unlinkAccountFromGoogleId({
|
||||
googleId: adminSearchResult.googleId,
|
||||
username: adminSearchResult.username,
|
||||
});
|
||||
} else {
|
||||
console.warn("Unknown mode", mode, "for service", service);
|
||||
}
|
||||
} else {
|
||||
console.warn("Unknown service", service);
|
||||
}
|
||||
|
||||
if (errorType) {
|
||||
// error - if response.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
||||
return { adminSearchResult: adminSearchResult, error: true, errorType };
|
||||
} else {
|
||||
// success!
|
||||
return { adminSearchResult: adminSearchResult, error: false };
|
||||
}
|
||||
} catch (err) {
|
||||
|
@ -3,8 +3,9 @@ import BattleScene from "../battle-scene";
|
||||
import * as Utils from "../utils";
|
||||
import { TextStyle, addTextObject } from "./text";
|
||||
import { WindowVariant, addWindow } from "./ui-theme";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
interface RankingEntry {
|
||||
export interface RankingEntry {
|
||||
rank: integer,
|
||||
username: string,
|
||||
score: integer,
|
||||
@ -12,7 +13,7 @@ interface RankingEntry {
|
||||
}
|
||||
|
||||
// Don't forget to update translations when adding a new category
|
||||
enum ScoreboardCategory {
|
||||
export enum ScoreboardCategory {
|
||||
DAILY,
|
||||
WEEKLY
|
||||
}
|
||||
@ -191,18 +192,17 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container {
|
||||
}
|
||||
|
||||
Utils.executeIf(category !== this.category || this.pageCount === undefined,
|
||||
() => Utils.apiFetch(`daily/rankingpagecount?category=${category}`).then(response => response.json()).then(count => this.pageCount = count)
|
||||
() => pokerogueApi.daily.getRankingsPageCount({ category }).then(count => this.pageCount = count)
|
||||
).then(() => {
|
||||
Utils.apiFetch(`daily/rankings?category=${category}&page=${page}`)
|
||||
.then(response => response.json())
|
||||
.then(jsonResponse => {
|
||||
pokerogueApi.daily.getRankings({ category, page })
|
||||
.then(rankings => {
|
||||
this.page = page;
|
||||
this.category = category;
|
||||
this.titleLabel.setText(`${i18next.t(`menu:${ScoreboardCategory[category].toLowerCase()}Rankings`)}`);
|
||||
this.pageNumberLabel.setText(page.toString());
|
||||
if (jsonResponse) {
|
||||
if (rankings) {
|
||||
this.loadingLabel.setVisible(false);
|
||||
this.updateRankings(jsonResponse);
|
||||
this.updateRankings(rankings);
|
||||
} else {
|
||||
this.loadingLabel.setText(i18next.t("menu:noRankings"));
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ import BattleScene from "#app/battle-scene";
|
||||
import { addTextObject, TextStyle } from "./text";
|
||||
import { addWindow } from "./ui-theme";
|
||||
import { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
interface BuildInteractableImageOpts {
|
||||
scale?: number;
|
||||
@ -135,21 +136,16 @@ export default class LoginFormUiHandler extends FormModalUiHandler {
|
||||
if (!this.inputs[0].text) {
|
||||
return onFail(i18next.t("menu:emptyUsername"));
|
||||
}
|
||||
Utils.apiPost("account/login", `username=${encodeURIComponent(this.inputs[0].text)}&password=${encodeURIComponent(this.inputs[1].text)}`, "application/x-www-form-urlencoded")
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(response => {
|
||||
if (response.hasOwnProperty("token")) {
|
||||
Utils.setCookie(Utils.sessionIdKey, response.token);
|
||||
originalLoginAction && originalLoginAction();
|
||||
} else {
|
||||
onFail(response);
|
||||
}
|
||||
});
|
||||
|
||||
const [ usernameInput, passwordInput ] = this.inputs;
|
||||
|
||||
pokerogueApi.account.login({ username: usernameInput.text, password: passwordInput.text }).then(error => {
|
||||
if (!error) {
|
||||
originalLoginAction && originalLoginAction();
|
||||
} else {
|
||||
onFail(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return true;
|
||||
|
@ -14,6 +14,7 @@ import BgmBar from "#app/ui/bgm-bar";
|
||||
import AwaitableUiHandler from "./awaitable-ui-handler";
|
||||
import { SelectModifierPhase } from "#app/phases/select-modifier-phase";
|
||||
import { AdminMode, getAdminModeName } from "./admin-ui-handler";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
enum MenuOptions {
|
||||
GAME_SETTINGS,
|
||||
@ -539,10 +540,7 @@ export default class MenuUiHandler extends MessageUiHandler {
|
||||
window.open(discordUrl, "_self");
|
||||
return true;
|
||||
} else {
|
||||
Utils.apiPost("/auth/discord/logout", undefined, undefined, true).then(res => {
|
||||
if (!res.ok) {
|
||||
console.error(`Unlink failed (${res.status}: ${res.statusText})`);
|
||||
}
|
||||
pokerogueApi.unlinkDiscord().then(_isSuccess => {
|
||||
updateUserInfo().then(() => this.scene.reset(true, true));
|
||||
});
|
||||
return true;
|
||||
@ -560,10 +558,7 @@ export default class MenuUiHandler extends MessageUiHandler {
|
||||
window.open(googleUrl, "_self");
|
||||
return true;
|
||||
} else {
|
||||
Utils.apiPost("/auth/google/logout", undefined, undefined, true).then(res => {
|
||||
if (!res.ok) {
|
||||
console.error(`Unlink failed (${res.status}: ${res.statusText})`);
|
||||
}
|
||||
pokerogueApi.unlinkGoogle().then(_isSuccess => {
|
||||
updateUserInfo().then(() => this.scene.reset(true, true));
|
||||
});
|
||||
return true;
|
||||
@ -612,11 +607,7 @@ export default class MenuUiHandler extends MessageUiHandler {
|
||||
success = true;
|
||||
const doLogout = () => {
|
||||
ui.setMode(Mode.LOADING, {
|
||||
buttonActions: [], fadeOut: () => Utils.apiFetch("account/logout", true).then(res => {
|
||||
if (!res.ok) {
|
||||
console.error(`Log out failed (${res.status}: ${res.statusText})`);
|
||||
}
|
||||
Utils.removeCookie(Utils.sessionIdKey);
|
||||
buttonActions: [], fadeOut: () => pokerogueApi.account.logout().then(() => {
|
||||
updateUserInfo().then(() => this.scene.reset(true, true));
|
||||
})
|
||||
});
|
||||
|
@ -1,9 +1,9 @@
|
||||
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
||||
import { ModalConfig } from "./modal-ui-handler";
|
||||
import * as Utils from "../utils";
|
||||
import { Mode } from "./ui";
|
||||
import { TextStyle, addTextObject } from "./text";
|
||||
import i18next from "i18next";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
|
||||
interface LanguageSetting {
|
||||
@ -110,27 +110,20 @@ export default class RegistrationFormUiHandler extends FormModalUiHandler {
|
||||
if (this.inputs[1].text !== this.inputs[2].text) {
|
||||
return onFail(i18next.t("menu:passwordNotMatchingConfirmPassword"));
|
||||
}
|
||||
Utils.apiPost("account/register", `username=${encodeURIComponent(this.inputs[0].text)}&password=${encodeURIComponent(this.inputs[1].text)}`, "application/x-www-form-urlencoded")
|
||||
.then(response => response.text())
|
||||
.then(response => {
|
||||
if (!response) {
|
||||
Utils.apiPost("account/login", `username=${encodeURIComponent(this.inputs[0].text)}&password=${encodeURIComponent(this.inputs[1].text)}`, "application/x-www-form-urlencoded")
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(response => {
|
||||
if (response.hasOwnProperty("token")) {
|
||||
Utils.setCookie(Utils.sessionIdKey, response.token);
|
||||
const [ usernameInput, passwordInput ] = this.inputs;
|
||||
pokerogueApi.account.register({ username: usernameInput.text, password: passwordInput.text })
|
||||
.then(registerError => {
|
||||
if (!registerError) {
|
||||
pokerogueApi.account.login({ username: usernameInput.text, password: passwordInput.text })
|
||||
.then(loginError => {
|
||||
if (!loginError) {
|
||||
originalRegistrationAction && originalRegistrationAction();
|
||||
} else {
|
||||
onFail(response);
|
||||
onFail(loginError);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
onFail(response);
|
||||
onFail(registerError);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
@ -7,6 +7,7 @@ import { getSplashMessages } from "../data/splash-messages";
|
||||
import i18next from "i18next";
|
||||
import { TimedEventDisplay } from "#app/timed-event-manager";
|
||||
import { version } from "../../package.json";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
export default class TitleUiHandler extends OptionSelectUiHandler {
|
||||
/** If the stats can not be retrieved, use this fallback value */
|
||||
@ -78,12 +79,13 @@ export default class TitleUiHandler extends OptionSelectUiHandler {
|
||||
}
|
||||
|
||||
updateTitleStats(): void {
|
||||
Utils.apiFetch("game/titlestats")
|
||||
.then(request => request.json())
|
||||
pokerogueApi.getGameTitleStats()
|
||||
.then(stats => {
|
||||
this.playerCountLabel.setText(`${stats.playerCount} ${i18next.t("menu:playersOnline")}`);
|
||||
if (this.splashMessage === "splashMessages:battlesWon") {
|
||||
this.splashMessageText.setText(i18next.t(this.splashMessage, { count: stats.battleCount }));
|
||||
if (stats) {
|
||||
this.playerCountLabel.setText(`${stats.playerCount} ${i18next.t("menu:playersOnline")}`);
|
||||
if (this.splashMessage === "splashMessages:battlesWon") {
|
||||
this.splashMessageText.setText(i18next.t(this.splashMessage, { count: stats.battleCount }));
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
|
52
src/utils.ts
52
src/utils.ts
@ -1,6 +1,7 @@
|
||||
import { MoneyFormat } from "#enums/money-format";
|
||||
import { Moves } from "#enums/moves";
|
||||
import i18next from "i18next";
|
||||
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||
|
||||
export type nil = null | undefined;
|
||||
|
||||
@ -258,9 +259,16 @@ export const isLocal = (
|
||||
/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(window.location.hostname)) &&
|
||||
window.location.port !== "") || window.location.hostname === "";
|
||||
|
||||
/**
|
||||
* @deprecated Refer to [pokerogue-api.ts](./plugins/api/pokerogue-api.ts) instead
|
||||
*/
|
||||
export const localServerUrl = import.meta.env.VITE_SERVER_URL ?? `http://${window.location.hostname}:${window.location.port + 1}`;
|
||||
|
||||
// Set the server URL based on whether it's local or not
|
||||
/**
|
||||
* Set the server URL based on whether it's local or not
|
||||
*
|
||||
* @deprecated Refer to [pokerogue-api.ts](./plugins/api/pokerogue-api.ts) instead
|
||||
*/
|
||||
export const apiUrl = localServerUrl ?? "https://api.pokerogue.net";
|
||||
// used to disable api calls when isLocal is true and a server is not found
|
||||
export let isLocalServerConnected = true;
|
||||
@ -307,48 +315,14 @@ export function getCookie(cName: string): string {
|
||||
* with a GET request to verify if a server is running,
|
||||
* sets isLocalServerConnected based on results
|
||||
*/
|
||||
export function localPing() {
|
||||
export async function localPing() {
|
||||
if (isLocal) {
|
||||
apiFetch("game/titlestats")
|
||||
.then(resolved => isLocalServerConnected = true,
|
||||
rejected => isLocalServerConnected = false
|
||||
);
|
||||
const titleStats = await pokerogueApi.getGameTitleStats();
|
||||
isLocalServerConnected = !!titleStats;
|
||||
console.log("isLocalServerConnected:", isLocalServerConnected);
|
||||
}
|
||||
}
|
||||
|
||||
export function apiFetch(path: string, authed: boolean = false): Promise<Response> {
|
||||
return (isLocal && isLocalServerConnected) || !isLocal ? new Promise((resolve, reject) => {
|
||||
const request = {};
|
||||
if (authed) {
|
||||
const sId = getCookie(sessionIdKey);
|
||||
if (sId) {
|
||||
request["headers"] = { "Authorization": sId };
|
||||
}
|
||||
}
|
||||
fetch(`${apiUrl}/${path}`, request)
|
||||
.then(response => resolve(response))
|
||||
.catch(err => reject(err));
|
||||
}) : new Promise(() => {});
|
||||
}
|
||||
|
||||
export function apiPost(path: string, data?: any, contentType: string = "application/json", authed: boolean = false): Promise<Response> {
|
||||
return (isLocal && isLocalServerConnected) || !isLocal ? new Promise((resolve, reject) => {
|
||||
const headers = {
|
||||
"Accept": contentType,
|
||||
"Content-Type": contentType,
|
||||
};
|
||||
if (authed) {
|
||||
const sId = getCookie(sessionIdKey);
|
||||
if (sId) {
|
||||
headers["Authorization"] = sId;
|
||||
}
|
||||
}
|
||||
fetch(`${apiUrl}/${path}`, { method: "POST", headers: headers, body: data })
|
||||
.then(response => resolve(response))
|
||||
.catch(err => reject(err));
|
||||
}) : new Promise(() => {});
|
||||
}
|
||||
|
||||
/** Alias for the constructor of a class */
|
||||
export type Constructor<T> = new(...args: unknown[]) => T;
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user