UI Protocol: add boot notification command support
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / UIServiceUtils.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 UIServiceUtils {
8 private constructor() {
9 // This is intentional
10 }
11
12 public static handleProtocols = (
13 protocols: Set<string>,
14 request: IncomingMessage
15 ): string | false => {
16 let protocol: Protocol;
17 let version: ProtocolVersion;
18 if (protocols.size === 0) {
19 return false;
20 }
21 for (const fullProtocol of protocols) {
22 [protocol, version] = UIServiceUtils.getProtocolAndVersion(fullProtocol);
23 if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === 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 = (
36 protocol: Protocol,
37 version: ProtocolVersion
38 ): boolean =>
39 Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version);
40
41 public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
42 const protocolIndex = protocolStr.indexOf(Protocol.UI);
43 const protocol = protocolStr.substring(
44 protocolIndex,
45 protocolIndex + Protocol.UI.length
46 ) as Protocol;
47 const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
48 return [protocol, version];
49 };
50
51 public static isLoopback(address: string): boolean {
52 const isLoopbackRegExp = new RegExp(
53 // eslint-disable-next-line no-useless-escape
54 /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
55 'i'
56 );
57 return isLoopbackRegExp.test(address);
58 }
59 }