mirror of
https://git.leinelab.org/Mal/metasocket-cordova.git
synced 2026-03-20 14:22:26 +01:00
Approvement of reconnection.
This commit is contained in:
@@ -2,7 +2,7 @@ import {Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Token} from './token';
|
||||
import {Host} from './host';
|
||||
import {Setting} from './setting';
|
||||
import {ChatMessage} from './chat.message';
|
||||
import {ChatTokenResponse} from './chat.token';
|
||||
|
||||
@@ -25,19 +25,26 @@ export class ApiService {
|
||||
}
|
||||
|
||||
getAuthToken(username: string, password: string): Observable<Token> {
|
||||
return this.client.post<Token>(Host.URL + '/token', {username, password});
|
||||
return this.client.post<Token>(Setting.URL + '/token', {username, password});
|
||||
}
|
||||
|
||||
getChatToken(authToken: string): Observable<ChatTokenResponse> {
|
||||
return this.client.get<ChatTokenResponse>(
|
||||
Host.URL + '/session/chat',
|
||||
Setting.URL + '/session/chat',
|
||||
{headers: {Authorization: 'Bearer ' + authToken}}
|
||||
);
|
||||
}
|
||||
|
||||
getChatHistory(token: string, offset: number, limit: number): Observable<ChatMessage[]> {
|
||||
return this.client.get<ChatMessage[]>(
|
||||
Host.URL + '/session/chat/history?limit=' + limit + '&offset=' + offset,
|
||||
Setting.URL + '/session/chat/history?limit=' + limit + '&offset=' + offset + (Setting.DEBUG ? '&debug=true' : ''),
|
||||
{headers: {Authorization: 'Bearer ' + token}}
|
||||
);
|
||||
}
|
||||
|
||||
getChatMessagesMissed(token: string, lastMessageId: number): Observable<ChatMessage[]> {
|
||||
return this.client.get<ChatMessage[]>(
|
||||
Setting.URL + '/session/chat/history/missed?lastMessageId=' + lastMessageId,
|
||||
{headers: {Authorization: 'Bearer ' + token}}
|
||||
);
|
||||
}
|
||||
@@ -45,7 +52,7 @@ export class ApiService {
|
||||
deleteAuthToken(token: string): Observable<string>
|
||||
{
|
||||
return this.client.delete<string>(
|
||||
Host.URL + '/token/' + token,
|
||||
Setting.URL + '/token/' + token,
|
||||
{headers: {Authorization: 'Bearer ' + token}}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<ion-app>
|
||||
<app-chat></app-chat>
|
||||
<app-chat *ngIf="getToken() !== null"></app-chat>
|
||||
<app-login *ngIf="getToken() === null"></app-login>
|
||||
</ion-app>
|
||||
|
||||
@@ -14,14 +14,14 @@ import {LoginComponent} from './login/login.component';
|
||||
import {TopbarComponent} from './topbar/topbar.component';
|
||||
import {LocalNotifications} from '@ionic-native/local-notifications/ngx';
|
||||
import {BackgroundMode} from '@ionic-native/background-mode/ngx';
|
||||
import {ForegroundService} from '@ionic-native/foreground-service/ngx';
|
||||
import {AppMinimize} from '@ionic-native/app-minimize/ngx';
|
||||
|
||||
@NgModule({
|
||||
declarations: [AppComponent, ChatComponent, LoginComponent, TopbarComponent],
|
||||
entryComponents: [],
|
||||
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, FormsModule, HttpClientModule],
|
||||
providers: [
|
||||
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, LocalNotifications, BackgroundMode, ForegroundService
|
||||
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, LocalNotifications, BackgroundMode, AppMinimize
|
||||
],
|
||||
bootstrap: [AppComponent],
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export interface ChatMessage
|
||||
{
|
||||
id: number;
|
||||
userId: number;
|
||||
username: string;
|
||||
message: string;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<div id="chat">
|
||||
<app-topbar></app-topbar>
|
||||
<div #errorMessage id="error-message">Konnte keine Verbindung herstellen!</div>
|
||||
|
||||
<div #chatPostArea id="chat-post-area" (scroll)="onScroll()">
|
||||
<div *ngFor="let message of messages" class="chat-post" [class.chat-own-post]="userId === message.userId">
|
||||
<img class="chat-avatar" src="{{url}}/user/{{message.userId}}/avatar?token={{userToken}}">
|
||||
@@ -12,6 +13,6 @@
|
||||
</div>
|
||||
|
||||
<div id="chat-type-area">
|
||||
<textarea [(ngModel)]="chatText" id="chat-textarea" (keydown)="onTextInput($event)" autofocus></textarea>
|
||||
<textarea [(ngModel)]="chatText" id="chat-textarea" (keydown)="onTextInput($event)" autofocus maxlength="2000"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import {Plugins, AppState} from '@capacitor/core';
|
||||
import {AfterViewChecked, AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
|
||||
import {ChatMessage} from '../chat.message';
|
||||
import {Host} from '../host';
|
||||
import {Setting} from '../setting';
|
||||
import {ApiService} from '../api.service';
|
||||
import {WebsocketListener} from '../websocket.listener';
|
||||
import {WebsocketService} from '../websocket.service';
|
||||
import {LocalNotifications} from '@ionic-native/local-notifications/ngx';
|
||||
import {BackgroundMode} from '@ionic-native/background-mode/ngx';
|
||||
import {ForegroundService} from '@ionic-native/foreground-service/ngx';
|
||||
import {AppComponent} from '../app.component';
|
||||
import {Platform} from '@ionic/angular';
|
||||
|
||||
const {App} = Plugins;
|
||||
|
||||
@@ -23,6 +24,7 @@ export class ChatComponent implements OnInit, AfterViewInit, AfterViewChecked, W
|
||||
url: string;
|
||||
|
||||
@ViewChild('chatPostArea') chatPostArea: ElementRef;
|
||||
@ViewChild('errorMessage') errorMessage: ElementRef;
|
||||
chatText: string;
|
||||
|
||||
private oldScrollHeight = 0;
|
||||
@@ -30,17 +32,18 @@ export class ChatComponent implements OnInit, AfterViewInit, AfterViewChecked, W
|
||||
private messageLimit = 10;
|
||||
private hasBeenReloaded = false;
|
||||
private hasFocus = true;
|
||||
private isReconnection = false;
|
||||
|
||||
public constructor(
|
||||
private apiService: ApiService,
|
||||
private websocketService: WebsocketService,
|
||||
private localNotifications: LocalNotifications,
|
||||
private backgroundMode: BackgroundMode,
|
||||
private foregroundService: ForegroundService
|
||||
private platform: Platform
|
||||
) {
|
||||
this.userToken = this.apiService.getFromStorage('token');
|
||||
this.userId = Number(this.apiService.getFromStorage('userId'));
|
||||
this.url = Host.URL;
|
||||
this.url = Setting.URL;
|
||||
this.websocketService.setListener(this);
|
||||
this.websocketService.initializeSocket(this.apiService.getFromStorage('chatToken'));
|
||||
this.backgroundMode.disableBatteryOptimizations();
|
||||
@@ -74,19 +77,34 @@ export class ChatComponent implements OnInit, AfterViewInit, AfterViewChecked, W
|
||||
|
||||
this.localNotifications.requestPermission();
|
||||
|
||||
this.foregroundService.start('METAsocket', 'The chat for WowApp', 'ic_stat_notification_icon_enabled');
|
||||
|
||||
this.apiService.getChatHistory(this.userToken, this.messageOffset, this.messageLimit).subscribe(
|
||||
(response) => {
|
||||
this.messages = response;
|
||||
this.messageOffset += this.messageLimit;
|
||||
}
|
||||
);
|
||||
this.apiService.getChatHistory(this.userToken, this.messageOffset, this.messageLimit).toPromise()
|
||||
.then(
|
||||
(response) => {
|
||||
response.forEach(
|
||||
(message: ChatMessage) => {
|
||||
this.messages.push(message);
|
||||
this.messageOffset++;
|
||||
}
|
||||
);
|
||||
}
|
||||
).catch(
|
||||
(error) => {
|
||||
window.alert('Fehler ' + error.status + ': Verbindung zur Web-API gescheitert!');
|
||||
}
|
||||
);
|
||||
|
||||
App.addListener('appStateChange', (state: AppState) => {
|
||||
this.hasFocus = state.isActive;
|
||||
});
|
||||
|
||||
this.platform.backButton.subscribe(
|
||||
() => {
|
||||
if (window.confirm('Möchtest du wirklich ausloggen?')) {
|
||||
this.onLogout();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
setInterval(
|
||||
() => {
|
||||
this.websocketService.sendKeepAliveMessage();
|
||||
@@ -129,6 +147,12 @@ export class ChatComponent implements OnInit, AfterViewInit, AfterViewChecked, W
|
||||
}
|
||||
}
|
||||
|
||||
onLogout() {
|
||||
this.apiService.storeData('token', null);
|
||||
|
||||
AppComponent.token = null;
|
||||
}
|
||||
|
||||
onChatMessage(message: ChatMessage): void {
|
||||
this.messages.push(message);
|
||||
this.messageOffset++;
|
||||
@@ -140,6 +164,40 @@ export class ChatComponent implements OnInit, AfterViewInit, AfterViewChecked, W
|
||||
this.triggerNotification(message);
|
||||
}
|
||||
|
||||
onConnection(): void
|
||||
{
|
||||
this.errorMessage.nativeElement.style.display = 'none';
|
||||
|
||||
this.apiService.getChatMessagesMissed(this.userToken, this.messages[this.messages.length - 1].id).toPromise()
|
||||
.then(
|
||||
(messagesMissed) => {
|
||||
if (messagesMissed.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.messages.concat(messagesMissed);
|
||||
this.messageOffset += messagesMissed.length;
|
||||
}
|
||||
).catch(
|
||||
(error) => {
|
||||
console.log('Failed to load messages missed after reconnect!', error);
|
||||
}
|
||||
);
|
||||
|
||||
this.isReconnection = true;
|
||||
}
|
||||
|
||||
onReconnect(): void
|
||||
{
|
||||
this.isReconnection = true;
|
||||
}
|
||||
|
||||
onError(message: string): void
|
||||
{
|
||||
this.errorMessage.nativeElement.style.display = 'block';
|
||||
this.errorMessage.nativeElement.innerText = message;
|
||||
}
|
||||
|
||||
triggerNotification(message: ChatMessage): void
|
||||
{
|
||||
this.localNotifications.schedule(
|
||||
@@ -150,13 +208,24 @@ export class ChatComponent implements OnInit, AfterViewInit, AfterViewChecked, W
|
||||
priority: 2,
|
||||
lockscreen: true,
|
||||
autoClear: true,
|
||||
icon: Host.URL + '/user/' + message.userId + '/avatar?token=' + this.userToken,
|
||||
icon: Setting.URL + '/user/' + message.userId + '/avatar?token=' + this.userToken,
|
||||
smallIcon: 'ic_stat_notification_icon_enabled',
|
||||
led: {color: '#ff00ff', on: 500, off: 500},
|
||||
led: '#ff00ff',
|
||||
trigger: { at: new Date(new Date().getTime() + 1000) },
|
||||
sound: 'file://assets/audio/murloc.wav',
|
||||
vibrate: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private hasChatMessage(message: ChatMessage): boolean
|
||||
{
|
||||
for (const messageStored of this.messages) {
|
||||
if (messageStored.id === message.id) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
export class Host
|
||||
{
|
||||
public static readonly URL: string = 'https://sabolli.de/wow/api/v1';
|
||||
public static readonly WEBSOCKET: string = 'wss://sabolli.de/metasocket';
|
||||
}
|
||||
@@ -6,12 +6,12 @@
|
||||
<form>
|
||||
<label>
|
||||
Username
|
||||
<input name="username" [(ngModel)] = "username">
|
||||
<input name="username" [(ngModel)] = "username" required>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
Password
|
||||
<input type="password" name="password" [(ngModel)] = "password">
|
||||
<input type="password" name="password" [(ngModel)] = "password" required>
|
||||
</label>
|
||||
|
||||
<input type="submit" (click)="login($event)" value="Anmelden">
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { ApiService } from '../api.service';
|
||||
import {Platform} from '@ionic/angular';
|
||||
import {AppMinimize} from '@ionic-native/app-minimize/ngx';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
@@ -11,9 +13,15 @@ export class LoginComponent implements OnInit {
|
||||
password = '';
|
||||
error: string = null;
|
||||
|
||||
constructor(private apiService: ApiService) { }
|
||||
constructor(private apiService: ApiService, private platform: Platform, private appMinimize: AppMinimize) { }
|
||||
|
||||
ngOnInit(): void {}
|
||||
ngOnInit(): void {
|
||||
this.platform.backButton.subscribe(
|
||||
(t) => {
|
||||
this.appMinimize.minimize();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
login(event): void
|
||||
{
|
||||
|
||||
6
src/app/setting.ts
Normal file
6
src/app/setting.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export class Setting
|
||||
{
|
||||
public static readonly DEBUG: boolean = false;
|
||||
public static readonly URL: string = 'https://sabolli.de/wow/api/v1';
|
||||
public static readonly WEBSOCKET: string = Setting.DEBUG ? 'wss://sabolli.de/metasocket-debug' : 'wss://sabolli.de/metasocket';
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export interface SocketReceivedMessage {
|
||||
export interface SocketReceivedChatMessage {
|
||||
type: number;
|
||||
id: number;
|
||||
userId: number;
|
||||
message: string;
|
||||
datetime: string;
|
||||
@@ -3,4 +3,12 @@ import {ChatMessage} from './chat.message';
|
||||
export interface WebsocketListener
|
||||
{
|
||||
onChatMessage(message: ChatMessage): void;
|
||||
|
||||
onLogout(): void;
|
||||
|
||||
onConnection(): void;
|
||||
|
||||
onReconnect(): void;
|
||||
|
||||
onError(message: string): void;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Host} from './host';
|
||||
import {Setting} from './setting';
|
||||
import {ChatMessage} from './chat.message';
|
||||
import {SocketRegistrationMessage} from './socket.registration.message';
|
||||
import {SocketReceivedMessage} from './socket.received.message';
|
||||
import {SocketReceivedChatMessage} from './socketReceivedChatMessage';
|
||||
import {WebsocketListener} from './websocket.listener';
|
||||
import {SocketSendMessage} from './socket.send.message';
|
||||
import {SocketKeepaliveMessage} from './socket.keepalive.message';
|
||||
@@ -11,28 +11,21 @@ import {SocketKeepaliveMessage} from './socket.keepalive.message';
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class WebsocketService {
|
||||
private socket: WebSocket = new WebSocket(Host.WEBSOCKET);
|
||||
private socket: WebSocket = new WebSocket(Setting.WEBSOCKET);
|
||||
private userList: Map<number, string> = new Map<number, string>();
|
||||
private listener: WebsocketListener;
|
||||
private chatToken: string;
|
||||
private isReconnectDesired = true;
|
||||
private lastReconnectAttempts: Date[] = [];
|
||||
|
||||
initializeSocket(chatToken: string): void {
|
||||
this.chatToken = chatToken;
|
||||
|
||||
this.socket = new WebSocket(Host.WEBSOCKET);
|
||||
this.socket.addEventListener('open', () => {
|
||||
this.authorize();
|
||||
});
|
||||
this.socket.addEventListener('message', (transmission: MessageEvent) => {
|
||||
this.handleIncomingTransmission(transmission);
|
||||
});
|
||||
this.socket.addEventListener(
|
||||
'close',
|
||||
() => {
|
||||
this.initializeSocket(this.chatToken);
|
||||
this.authorize();
|
||||
}
|
||||
);
|
||||
this.socket = new WebSocket(Setting.WEBSOCKET);
|
||||
this.socket.addEventListener('open', () => {this.authorize(); this.listener.onConnection(); });
|
||||
this.socket.addEventListener('message', (transmission: MessageEvent) => {this.onMessage(transmission); });
|
||||
this.socket.addEventListener('close', () => {this.onClose(); });
|
||||
this.socket.addEventListener('error', () => {this.onError(); });
|
||||
}
|
||||
|
||||
setListener(listener: WebsocketListener): void {
|
||||
@@ -48,6 +41,10 @@ export class WebsocketService {
|
||||
}
|
||||
|
||||
sendKeepAliveMessage(): void {
|
||||
if (this.socket === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const socketMessage: SocketKeepaliveMessage = {
|
||||
type: Response.KEEP_ALIVE
|
||||
};
|
||||
@@ -60,14 +57,15 @@ export class WebsocketService {
|
||||
this.socket.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
private handleIncomingTransmission(transmission: MessageEvent): void {
|
||||
private onMessage(transmission: MessageEvent): void {
|
||||
const response = JSON.parse(transmission.data);
|
||||
|
||||
switch (response.type) {
|
||||
case Response.CHAT_MESSAGE:
|
||||
const messageReceived: SocketReceivedMessage = response;
|
||||
const messageReceived: SocketReceivedChatMessage = response;
|
||||
|
||||
const message: ChatMessage = {
|
||||
id: messageReceived.id,
|
||||
userId: messageReceived.userId,
|
||||
username: this.userList.get(messageReceived.userId),
|
||||
datetime: messageReceived.datetime,
|
||||
@@ -94,6 +92,59 @@ export class WebsocketService {
|
||||
throw new Error('Unknown message type: ' + response.type);
|
||||
}
|
||||
}
|
||||
|
||||
private reconnect(): void
|
||||
{
|
||||
this.initializeSocket(this.chatToken);
|
||||
this.authorize();
|
||||
this.listener.onReconnect();
|
||||
}
|
||||
|
||||
private needsAuthorizationForFurtherReconnectAttempts(): boolean {
|
||||
if (this.lastReconnectAttempts.length < 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = new Date().getTime();
|
||||
let recentAttempts = 0;
|
||||
|
||||
for (const attempt of this.lastReconnectAttempts) {
|
||||
if (now - attempt.getTime() < 20000) {
|
||||
recentAttempts++;
|
||||
}
|
||||
}
|
||||
|
||||
return recentAttempts >= 3;
|
||||
}
|
||||
|
||||
private onError(): void {
|
||||
if (this.needsAuthorizationForFurtherReconnectAttempts()) {
|
||||
this.lastReconnectAttempts = [];
|
||||
this.isReconnectDesired = false;
|
||||
|
||||
setTimeout(
|
||||
() => {
|
||||
this.isReconnectDesired = true;
|
||||
this.onClose();
|
||||
}, 10000
|
||||
);
|
||||
}
|
||||
|
||||
if (this.isReconnectDesired) {
|
||||
this.lastReconnectAttempts.push(new Date());
|
||||
}
|
||||
|
||||
this.listener.onError('Die Verbindung konnte nicht hergestellt werden!');
|
||||
}
|
||||
|
||||
private onClose(): void
|
||||
{
|
||||
this.listener.onError('Verbindung unterbrochen!');
|
||||
|
||||
if (this.isReconnectDesired) {
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Response {
|
||||
|
||||
Reference in New Issue
Block a user