fc37ddc6cd89e82be004f7ff6deecf0d13425f3f
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIServerUtils.ts
1 import type { IncomingMessage } from 'http';
2
3 import { Protocol, ProtocolVersion } from '../../types/UIProtocol';
4 import logger from '../../utils/Logger';
5 import Utils from '../../utils/Utils';
6
7 export class UIServerUtils {
8 private constructor() {
9 // This is intentional
10 }
11
12 public static handleProtocols = (
13 protocols: Set<string>,
14 // eslint-disable-next-line @typescript-eslint/no-unused-vars
15 request: IncomingMessage
16 ): string | false => {
17 let protocol: Protocol;
18 let version: ProtocolVersion;
19 if (protocols.size === 0) {
20 return false;
21 }
22 for (const fullProtocol of protocols) {
23 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === true) {
24 return fullProtocol;
25 }
26 }
27 logger.error(
28 `${Utils.logPrefix(
29 ' UI WebSocket Server |'
30 )} Unsupported protocol: ${protocol} or protocol version: ${version}`
31 );
32 return false;
33 };
34
35 public static isProtocolAndVersionSupported = (protocolStr: string): boolean => {
36 const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr);
37 return (
38 Object.values(Protocol).includes(protocol) === true &&
39 Object.values(ProtocolVersion).includes(version) === true
40 );
41 };
42
43 public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
44 const protocolIndex = protocolStr.indexOf(Protocol.UI);
45 const protocol = protocolStr.substring(
46 protocolIndex,
47 protocolIndex + Protocol.UI.length
48 ) as Protocol;
49 const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
50 return [protocol, version];
51 };
52
53 public static isLoopback(address: string): boolean {
54 const isLoopbackRegExp = new RegExp(
55 // eslint-disable-next-line no-useless-escape
56 /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
57 'i'
58 );
59 return isLoopbackRegExp.test(address);
60 }
61 }