Skip to content

Commit

Permalink
chore: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
flx-sta committed Oct 4, 2024
1 parent ab6a191 commit 0e3e128
Show file tree
Hide file tree
Showing 38 changed files with 588 additions and 513 deletions.
17 changes: 17 additions & 0 deletions src/@types/PokerogueAccountApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { UserInfo } from "#app/account";

export interface AccountInfoResponse extends UserInfo {}

export interface AccountLoginRequest {
username: string;
password: string;
}

export interface AccountLoginResponse {
token: string;
}

export interface AccountRegisterRequest {
username: string;
password: string;
}
File renamed without changes.
File renamed without changes.
10 changes: 10 additions & 0 deletions src/@types/PokerogueDailyApi.ts
Original file line number Diff line number Diff line change
@@ -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;
}
File renamed without changes.
39 changes: 39 additions & 0 deletions src/@types/PokerogueSessionSavedataApi.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 20 additions & 0 deletions src/@types/PokerogueSystemSavedataApi.ts
Original file line number Diff line number Diff line change
@@ -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;
}
9 changes: 0 additions & 9 deletions src/@types/pokerogue-api.ts

This file was deleted.

11 changes: 4 additions & 7 deletions src/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,14 @@ export function updateUserInfo(): Promise<[boolean, integer]> {
});
return resolve([ true, 200 ]);
}
pokerogueApi.getAccountInfo().then((accountInfoOrStatus) => {
if (typeof accountInfoOrStatus === "number") {
resolve([ false, accountInfoOrStatus ]);
pokerogueApi.account.getInfo().then(([accountInfo, status]) => {
if (!accountInfo) {
resolve([ false, status ]);
return;
} else {
loggedInUser = accountInfoOrStatus;
loggedInUser = accountInfo;
resolve([ true, 200 ]);
}
}).catch(err => {
console.error(err);
resolve([ false, 500 ]);
});
});
}
4 changes: 2 additions & 2 deletions src/data/daily-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ export interface DailyRunConfig {

export function fetchDailyRunSeed(): Promise<string | null> {
return new Promise<string | null>((resolve, reject) => {
pokerogueApi.getDailySeed().then(dailySeed => {
pokerogueApi.daily.getSeed().then(dailySeed => {
resolve(dailySeed);
}).catch(err => reject(err)); // TODO: does this ever reject with the api class?
});
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/phases/game-over-phase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ export class GameOverPhase extends BattlePhase {
If Offline, execute offlineNewClear(), a localStorage implementation of newClear daily run checks */
if (this.victory) {
if (!Utils.isLocal || Utils.isLocalServerConnected) {
pokerogueApi.newclearSession(this.scene.sessionSlotId, clientSessionId)
.then((isNewClear) => doGameOver(!!isNewClear));
pokerogueApi.savedata.session.newclear({ slot: this.scene.sessionSlotId, clientSessionId })
.then((success) => doGameOver(!!success));
} else {
this.scene.gameData.offlineNewClear(this.scene).then(result => {
doGameOver(result);
Expand Down
17 changes: 16 additions & 1 deletion src/plugins/api/api.ts → src/plugins/api/api-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getCookie } from "#app/utils";

type DataType = "json" | "form-urlencoded";

export abstract class Api {
export abstract class ApiBase {
//#region Fields

protected readonly base: string;
Expand Down Expand Up @@ -71,4 +71,19 @@ export abstract class Api {

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);
}
}
4 changes: 0 additions & 4 deletions src/plugins/api/models/AccountInfo.ts

This file was deleted.

10 changes: 0 additions & 10 deletions src/plugins/api/models/AccountLogin.ts

This file was deleted.

4 changes: 0 additions & 4 deletions src/plugins/api/models/AccountRegister.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/plugins/api/models/BaseApiResponse.ts

This file was deleted.

3 changes: 0 additions & 3 deletions src/plugins/api/models/ClientSession.ts

This file was deleted.

4 changes: 0 additions & 4 deletions src/plugins/api/models/ErrorResponse.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/plugins/api/models/UpdateSessionSavedata.ts

This file was deleted.

5 changes: 0 additions & 5 deletions src/plugins/api/models/UpdateSystemSavedata.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/plugins/api/models/VerifySavedata.ts

This file was deleted.

101 changes: 101 additions & 0 deletions src/plugins/api/pokerogue-account-api.ts
Original file line number Diff line number Diff line change
@@ -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.error("Log out failed!", err);
}

removeCookie(SESSION_ID_COOKIE_NAME); // we are always clearing the cookie.
}
}
15 changes: 7 additions & 8 deletions src/plugins/api/pokerogue-admin-api.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { Api } from "#app/plugins/api/api";
import type { LinkAccountToDiscordIdRequest } from "#app/plugins/api/models/LinkAccountToDiscordId";
import type { LinkAccountToDiscordIdRequest } from "#app/@types/PokerogueAdminApi";
import { ApiBase } from "#app/plugins/api/api-base";

export class PokerogueAdminApi extends Api {
export class PokerogueAdminApi extends ApiBase {
/**
* Links an account to a discord id.
* @param linkData The {@linkcode LinkAccountToDiscordIdRequest} to send
* @param params The {@linkcode LinkAccountToDiscordIdRequest} to send
* @returns `true` if successful, `false` if not
*/
public async linkAccountToDiscordId(linkData: LinkAccountToDiscordIdRequest) {
public async linkAccountToDiscord(params: LinkAccountToDiscordIdRequest) {
try {
const linkArr = Object.entries(linkData).map(([key, value]) => [key, String(value)]);
const params = new URLSearchParams(linkArr);
const response = await this.doPost("/admin/account/discord-link", params, "form-urlencoded");
const urlSearchParams = this.toUrlSearchParams(params);
const response = await this.doPost("/admin/account/discord-link", urlSearchParams, "form-urlencoded");

if (response.ok) {
return true;
Expand Down
Loading

0 comments on commit 0e3e128

Please sign in to comment.