ATG: Cleanup connector statuses initialization
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / UIServiceUtils.ts
... / ...
CommitLineData
1import type { IncomingMessage } from 'http';
2
3import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
4import logger from '../../../utils/Logger';
5import Utils from '../../../utils/Utils';
6
7export 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) === true &&
40 Object.values(ProtocolVersion).includes(version) === true;
41
42 public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
43 const protocolIndex = protocolStr.indexOf(Protocol.UI);
44 const protocol = protocolStr.substring(
45 protocolIndex,
46 protocolIndex + Protocol.UI.length
47 ) as Protocol;
48 const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
49 return [protocol, version];
50 };
51
52 public static isLoopback(address: string): boolean {
53 const isLoopbackRegExp = new RegExp(
54 // eslint-disable-next-line no-useless-escape
55 /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
56 'i'
57 );
58 return isLoopbackRegExp.test(address);
59 }
60}