Skip to content

Commit

Permalink
Complete #513
Browse files Browse the repository at this point in the history
Also allow to clear all the game data when cache panic
  • Loading branch information
KevinGuancheDarias committed Feb 17, 2024
1 parent a64b352 commit 139f77b
Show file tree
Hide file tree
Showing 18 changed files with 179 additions and 16 deletions.
11 changes: 10 additions & 1 deletion business/database/migrations/v0.11.0.sql
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,13 @@ CREATE TABLE `suspicions`
) ENGINE = InnoDB;

ALTER TABLE upgrades
ADD `order_number` smallint unsigned DEFAULT NULL COMMENT 'The upgrade order' AFTER id;
ADD `order_number` smallint unsigned DEFAULT NULL COMMENT 'The upgrade order' AFTER id;

CREATE TABLE track_browser
(
id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL,
method VARCHAR(8) NOT NULL,
json_content TEXT NOT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id)
) ENGINE = InnoDB
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.kevinguanchedarias.owgejava.entity;

import jakarta.persistence.*;
import lombok.*;

import java.time.Instant;

@Data
@Entity
@Table
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class TrackBrowser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@EqualsAndHashCode.Include
private Long id;

String method;
String jsonContent;

Instant createdAt;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kevinguanchedarias.owgejava.repository;

import com.kevinguanchedarias.owgejava.entity.TrackBrowser;
import org.springframework.data.jpa.repository.JpaRepository;

public interface TrackBrowserRepository extends JpaRepository<TrackBrowser, Long> {
}
2 changes: 2 additions & 0 deletions game-frontend/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ v0.11.5 (latest)
* __Fix:__ [In the unit info dialog, the attackable types is not working in Neon theme #526](https://github.com/KevinGuancheDarias/owge/issues/526)
* __Fix:__ Potential fix to error caused by fixing #541, also stabilize handling of duplicated units
* __Fix:__ [Selected planet is not preserved after f5 #542](https://github.com/KevinGuancheDarias/owge/issues/542)
* __Improvement:__ [Add browser tracking to be able to detect frontend bugs #513](https://github.com/KevinGuancheDarias/owge/issues/513)
* __Improvement:__ Allow to clear all the game data when cache panic

v0.11.4 (2024-02-08 05:39)
==================
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {ObsService} from './services/obs.service';
import {SecurePlanetEntryPipePipe} from './pipes/secure-entry.pipe';
import {PlanetDisplayNamePipe} from './pipes/planet-display-name.pipe';
import {SecureItemDirective} from './directives/secure-item.directive';
import {ErrorLoggingService} from '../../../owge-universe/src/lib/services/error-logging.service';

/**
* Has the shared features between modules, such as loading image
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class SessionService extends AbstractWebsocketApplicationHandler implemen
return sessionStorage.getItem(SessionService.LOCAL_STORAGE_TOKEN_PARAM);
}

public logout(): any {
public logout(): void {
this._clearSessionData();
this._redirectIfNotLoggedIn();
this._logoutEmitter.emit();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ export class PlanetService extends AbstractWebsocketApplicationHandler {
}

private handleLogin(): void {
console.log('pene');
this.loginService.onLogin.subscribe(() =>
this.findMyPlanets().pipe(take(1)).subscribe(planets =>
this.defineSelectedPlanet(planets.find(planet => planet.home))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {Injectable} from '@angular/core';
import {UniverseGameService} from './universe-game.service';
import {stringify} from 'flatted';

@Injectable({
providedIn: 'root'
})
export class ErrorLoggingService {
private readonly originalWarn = console.warn.bind(console);

constructor(private universeGameService: UniverseGameService) {
window.onerror = (msg, url, lineNo, columnNo, error) => {
console.log('ups',msg,lineNo, error);
};
['warn','error'].forEach(level => this.intercept(level));
}

private intercept(method: string): void {
// eslint-disable-next-line no-console
const original = console[method].bind(console);
// eslint-disable-next-line no-console
console[method] = (...args) => {
// eslint-disable-next-line no-console
this.doReport(method, args).then(() => console.debug('Logged data ',method, args));
original(...args);
};
}

private async doReport(method: string, args: unknown[]): Promise<void> {
try {
const content = stringify(args);
if(content.length > 100) {
await this.universeGameService.requestWithAutorizationToContext(
'game', 'post', `track-browser/${method}`, content
).toPromise();
} else {
this.originalWarn('Not logging due to insufficient information',content);
}
}catch (e) {
this.originalWarn('unable to track browser',e );
}
}
}
1 change: 1 addition & 0 deletions game-frontend/modules/owge-universe/src/public-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export * from './lib/pojos/resource-requirements.pojo';
export * from './lib/services/abstract-crud.service';
export * from './lib/services/active-time-special.service';
export * from './lib/services/active-time-special-rule-finder.service';
export * from './lib/services/error-logging.service';
export * from './lib/services/image-store.service';
export * from './lib/services/mission.service';
export * from './lib/services/resource-manager.service';
Expand Down
21 changes: 17 additions & 4 deletions game-frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions game-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"startWithNightlyBackend": "npm run createVersionFile && ng serve --proxy-config nightly.proxy.conf.json",
"start": "npm run createVersionFile && npm run compileChangelog && ng serve",
"startAdmin": "ng serve game-admin",
"ngServeDocker": "npm run createVersionFile && npm run compileChangelog && ng serve --host 0.0.0.0 --disable-host-check",
"ngServeDockerAdmin": "ng serve game-admin --host 0.0.0.0 --disable-host-check",
"ngServeDocker": "npm run createVersionFile && npm run compileChangelog && ng serve --host 0.0.0.0 --disable-host-check --live-reload false",
"ngServeDockerAdmin": "ng serve game-admin --host 0.0.0.0 --disable-host-check --live-reload false",
"build": "npm run createVersionFile && npm run compileChangelog && ng build --prod",
"buildDevLike": "npm run createVersionFile && npm run compileChangelog && ng build",
"buildAdmin": "npm run createVersionFile && npm run compileChangelog && ng build game-admin --prod",
Expand Down Expand Up @@ -44,6 +44,7 @@
"bootstrap": "^4.4.1",
"core-js": "^2.4.1",
"dexie": "^3.0.1",
"flatted": "^3.2.9",
"karma-spec-reporter": "0.0.26",
"lodash-es": "^4.17.15",
"ng2-logger": "^3.0.11",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
<!-- Forces an scroll to be available on mobile devices-->
</div>
<div *ngIf="isPanic" class="panic-wrapper">
<button class="btn btn-block" (click)="clickReload()">{{ 'APP.BTN_RELOAD' | translate }}</button>
<button class="btn btn-block btn-clear-data" (click)="clearData()">{{ 'APP.BTN_CLEAR_DATA' | translate }}</button>
<button class="btn btn-block btn-reload" (click)="clickReload()">{{ 'APP.BTN_RELOAD' | translate }}</button>
</div>
</div>
<div *ngIf="isInGame" class="is-connected" [ngClass]="panicClass || connectedClass"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@
button {
width: 90vw;
margin: 0 auto;
margin-top: calc(50vh - 10px);
}
button.btn-clear-data {
margin-top: calc(50vh - 60px);
}
button.btn-reload {
margin-top: 30px;
}
}

Expand Down
19 changes: 16 additions & 3 deletions game-frontend/projects/game-frontend/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Component, OnInit } from '@angular/core';

import { LoadingService, ToastrService } from '@owge/core';
import {LoadingService, SessionService, ToastrService} from '@owge/core';

import { state, style, trigger, transition, animate } from '@angular/animations';
import { WebsocketService, UniverseGameService } from '@owge/universe';
Expand Down Expand Up @@ -62,9 +62,10 @@ export class AppComponent implements OnInit {
public constructor(
private _universeGameService: UniverseGameService,
private _loadingService: LoadingService,
private websocketService: WebsocketService,
private sessionService: SessionService,
swUpdate: SwUpdate,
toastrService: ToastrService,
websocketService: WebsocketService,
twitchService: TwitchService
) {
websocketService.isConnected.subscribe(val => {
Expand Down Expand Up @@ -106,7 +107,7 @@ export class AppComponent implements OnInit {
}

public clickReload() {
// window.location.reload();
window.location.reload();
}

public onDisplayTwitch(val: TwitchState): void {
Expand All @@ -118,6 +119,18 @@ export class AppComponent implements OnInit {
}
}

async clearData() {
this.websocketService.close();
// TODO: When updating to typescript 5.4 this should be supported so no need to ts-ignore:
// https://github.com/microsoft/TypeScript/commit/9ebe11c2d375bfb1c8fad10d705ffae09583c522
// @ts-ignore
const dbs: any[] = await window.indexedDB.databases();
dbs.forEach(db => window.indexedDB.deleteDatabase(db.name));
sessionStorage.clear();
this.sessionService.logout();
setTimeout(() => window.location.reload(), 1000);
}

private _loadPlayer(val: TwitchState) {
this.twitchPlayer = new Twitch.Player(AppComponent._TWITCH_DIV, {
width: '100%',
Expand Down
5 changes: 3 additions & 2 deletions game-frontend/projects/game-frontend/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from '@owge/core';
import { OwgeGalaxyModule, PlanetListService, PlanetService } from '@owge/galaxy';
import {
OwgeUniverseModule, SystemMessageService, TimeSpecialService, UniverseGameService,
ErrorLoggingService, OwgeUniverseModule, SystemMessageService, TimeSpecialService, UniverseGameService,
UserStorage, WebsocketService, WsEventCacheService
} from '@owge/universe';
import { OwgeWidgetsModule } from '@owge/widgets';
Expand Down Expand Up @@ -220,7 +220,8 @@ export class AppModule {
private _userStorage: UserStorage<User>,
private _universeGameService: UniverseGameService,
private _wsEventCacheService: WsEventCacheService,
private themeService: ThemeService
private themeService: ThemeService,
private errorLoggingService: ErrorLoggingService
) {
ServiceLocator.injector = this._injector;
themeService.useUserDefinedOrDefault();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"NOT_CONNECTED": "Not connected, you can continue browsing, but can't run actions",
"SYNC_ERROR": "Sync error, please check your Internet is stable, maybe your game account is broken, contact admin",
"NOT_CONNECTED_CLICK_ERROR": "You don't have Internet, or server is down, you can't run this action",
"BTN_CLEAR_DATA": "Clear the game data",
"BTN_RELOAD": "Reload the game page",
"LOGIN": {
"PLACEHOLDER_EMAIL": "Email or username",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"NOT_CONNECTED": "Desconectado, puedes seguir viendo cosas, pero no se ejecutarán acciones",
"SYNC_ERROR": "Error de sincronización, quizá tu Internet es débil, o tu cuenta esté rota, si tu Internet funciona, contacta con un administrador",
"NOT_CONNECTED_CLICK_ERROR": "No tienes Internet, o el servidor está caído, no puedes ejecutar esta acción",
"BTN_CLEAR_DATA": "Limpiar datos del juego (cerrará sesión)",
"BTN_RELOAD": "Recargar la página del juego",
"LOGIN": {
"PLACEHOLDER_EMAIL": "Email o usuario",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.kevinguanchedarias.owgejava.rest.game;

import com.kevinguanchedarias.owgejava.entity.TrackBrowser;
import com.kevinguanchedarias.owgejava.repository.TrackBrowserRepository;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.ApplicationScope;

import java.time.Instant;

@RestController
@RequestMapping("game/track-browser")
@ApplicationScope
@AllArgsConstructor
public class TrackBrowserRestService {
private final TrackBrowserRepository trackBrowserRepository;

@PostMapping("warn")
public void warn(@RequestBody String body) {
doTrack("warn", body);
}

@PostMapping("error")
public void error(@RequestBody String body) {
doTrack("error", body);
}

private void doTrack(String method, String content) {
trackBrowserRepository.save(
TrackBrowser.builder()
.method(method)
.jsonContent(content)
.createdAt(Instant.now())
.build()
);
}
}

0 comments on commit 139f77b

Please sign in to comment.