2018-06-28 17:11:04 +02:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
import { Router } from '@angular/router';
|
|
|
|
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
|
|
|
|
|
2018-07-12 14:11:31 +02:00
|
|
|
/**
|
|
|
|
* Service that handles WebSocket connections.
|
|
|
|
*
|
|
|
|
* Creates or returns already created WebSockets.
|
|
|
|
*/
|
2018-06-28 17:11:04 +02:00
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class WebsocketService {
|
2018-07-12 14:11:31 +02:00
|
|
|
/**
|
|
|
|
* Constructor that handles the router
|
|
|
|
* @param router the URL Router
|
|
|
|
*/
|
2018-06-28 17:11:04 +02:00
|
|
|
constructor(private router: Router) {}
|
|
|
|
|
2018-07-12 14:11:31 +02:00
|
|
|
/**
|
|
|
|
* Observable subject that might be `any` for simplicity, `MessageEvent` or something appropriate
|
|
|
|
*/
|
2018-06-28 17:11:04 +02:00
|
|
|
private subject: WebSocketSubject<any>;
|
|
|
|
|
2018-07-12 14:11:31 +02:00
|
|
|
/**
|
|
|
|
* Creates a new WebSocket connection as WebSocketSubject
|
|
|
|
*
|
|
|
|
* Can return old Subjects to prevent multiple WebSocket connections.
|
|
|
|
*/
|
2018-06-28 17:11:04 +02:00
|
|
|
public connect(): WebSocketSubject<any> {
|
2018-07-12 14:11:31 +02:00
|
|
|
const socketProtocol = this.getWebSocketProtocol();
|
2018-06-28 17:11:04 +02:00
|
|
|
const socketPath = this.getWebSocketPath();
|
|
|
|
const socketServer = window.location.hostname + ':' + window.location.port;
|
|
|
|
if (!this.subject) {
|
|
|
|
this.subject = webSocket(socketProtocol + socketServer + socketPath);
|
|
|
|
}
|
|
|
|
return this.subject;
|
|
|
|
}
|
|
|
|
|
2018-07-12 14:11:31 +02:00
|
|
|
/**
|
|
|
|
* Delegates to socket-path for either the side or projector websocket.
|
|
|
|
*/
|
2018-06-28 17:11:04 +02:00
|
|
|
private getWebSocketPath(): string {
|
|
|
|
//currentRoute does not end with '/'
|
|
|
|
const currentRoute = this.router.url;
|
|
|
|
if (currentRoute.includes('/projector') || currentRoute.includes('/real-projector')) {
|
|
|
|
return '/ws/projector';
|
|
|
|
} else {
|
|
|
|
return '/ws/site/';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-12 14:11:31 +02:00
|
|
|
/**
|
|
|
|
* returns the desired websocket protocol
|
|
|
|
*
|
|
|
|
* TODO: HTTPS is not yet tested
|
|
|
|
*/
|
|
|
|
private getWebSocketProtocol(): string {
|
2018-06-28 17:11:04 +02:00
|
|
|
if (location.protocol === 'https') {
|
|
|
|
return 'wss://';
|
|
|
|
} else {
|
|
|
|
return 'ws://';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|