Move SinusBotService to backend

This commit is contained in:
2020-05-30 19:32:12 +02:00
parent 32ce290a13
commit 5925872ac8
8 changed files with 129 additions and 59 deletions

View File

@@ -1,12 +1,22 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { TableEntry } from "./models/TableEntry";
import { SinusBotService } from "./services/sinusbot.service";
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
constructor(
private readonly appService: AppService,
private readonly sinusBotService: SinusBotService
) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get()
async getStats(): Promise<TableEntry[]> {
return await this.sinusBotService.fetchStats();
}
}

View File

@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { SinusBotService } from "./services/sinusbot.service";
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
providers: [AppService, SinusBotService],
})
export class AppModule {}

View File

@@ -0,0 +1,4 @@
export interface TableEntry {
name: string;
onlineTime: string;
}

View File

@@ -0,0 +1,5 @@
export interface TunakillLogin {
username: string;
password: string;
botId: string;
}

View File

@@ -0,0 +1,5 @@
export interface TunakillUser {
name: string;
time: number;
uid: string;
}

View File

@@ -0,0 +1,101 @@
import { TableEntry } from "../models/TableEntry";
import { TunakillUser } from "../models/TunakillUser";
import { Injectable } from "@nestjs/common";
import {TunakillLogin} from "../models/TunakillLogin";
@Injectable()
export class SinusBotService {
private host = process.env.HOST
private botId = process.env.SINUSBOT_BOTID;
private tunaKillURL = `${this.host}/api/v1/bot/i/${this.botId}/event/tunakill_rank_all_user`;
private loginURL = `${this.host}/api/v1/bot/login`;
private credentials = {
username: process.env.SINUSBOT_USER,
password: process.env.SINUSBOT_PASSWORD
}
private bearer: string;
public async fetchStats(): Promise<TableEntry[] | undefined> {
if (this.bearer === null) {
this.bearer = await this.login().catch(error => error.message);
}
return await fetch(this.tunaKillURL)
.then(res => res.json())
.then(data => this.consumeTunakillResponse(data));
}
/**
* Returns bearer token if login was successful
*/
private async login(): Promise<string> {
const body: TunakillLogin = {
botId: this.botId,
username: this.credentials.password,
password: this.credentials.username,
}
return await fetch(this.loginURL, this.requestConfig(JSON.stringify(body)))
.then(res => {
if (res.ok && res.body !== null) {
return res.json();
} else {
throw new Error('Response is invalid.');
}
})
.then(data => {
if (data.token !== null) {
return data.token;
} else {
throw new Error('Token in response does not exist.');
}
});
}
requestConfig = (body?: string, bearerToken?: string): RequestInit => {
return {
method: 'POST',
body: body,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'HumeniusTSRankingBackend/0.0.1',
'Authorization': `Bearer ${bearerToken}`
}
};
}
private consumeTunakillResponse(data: any): TableEntry[] | undefined {
if (!(data !== null || data[0] !== null || data[0].data !== null)) {
return undefined;
}
const response = data[0].data;
if (!(response.length > 0)) {
return undefined;
}
return response
.map((user: TunakillUser) => {
if (user.name === "Server Query Admin") { return null; }
return {
name: user.name,
rawTime: user.time,
onlineTime: new Date(user.time * 1000)
.toISOString()
.substr(11, 8)
};
})
.sort((a: any, b: any) => {
if (a.rawTime < b.rawTime) {
return -1;
}
if (a.rawTime > b.rawTime) {
return 1;
}
return 0;
});
}
}