aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/odlux/framework/src/services/notificationService.ts
blob: 76132f8433dac8af23b3a2640e07e4309d933c01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import * as X2JS from 'x2js';

const socketUrl = [location.protocol === 'https:' ? 'wss://' : 'ws://', 'admin', ':', 'admin', '@', location.hostname, ':', location.port, '/websocket'].join('');
const subscriptions: { [scope: string]: SubscriptionCallback[] } = { };

export interface IFormatedMessage {
  notifType: string | null;
  time: string;
}

export type SubscriptionCallback<TMessage extends IFormatedMessage = IFormatedMessage> = (msg: TMessage) => void;

function formatData(event: MessageEvent) : IFormatedMessage | undefined {

  var x2js = new X2JS();
  var jsonObj: { [key: string]: IFormatedMessage } = x2js.xml2js(event.data);
  if (jsonObj && typeof (jsonObj) === 'object') {

    const notifType = Object.keys(jsonObj)[0];
    const formated = jsonObj[notifType];
    formated.notifType = notifType ;
    formated.time = new Date().toISOString();
    return formated;
  }
  return undefined;

}

export function subscribe<TMessage extends IFormatedMessage = IFormatedMessage>(scope: string | string[], callback: SubscriptionCallback<TMessage>): Promise<boolean> {
  return socketReady.then((notificationSocket) => {
    const scopes = scope instanceof Array ? scope : [scope];

    // send all new scopes to subscribe
    const newScopesToSubscribe: string[] = scopes.reduce((acc: string[], cur: string) => {
      const currentCallbacks = subscriptions[cur];
      if (currentCallbacks) {
        if (!currentCallbacks.some(c => c === callback)) {
          currentCallbacks.push(callback);
        }
      } else {
        subscriptions[cur] = [callback];
        acc.push(cur);
      }
      return acc;
    }, []);

    if (newScopesToSubscribe.length === 0) {
      return true;
    }

    // send a subscription to all active scopes
    const scopesToSubscribe = Object.keys(subscriptions);
    if (notificationSocket.readyState === notificationSocket.OPEN) {
      const data = {
        'data': 'scopes',
        'scopes': scopesToSubscribe
      };
      notificationSocket.send(JSON.stringify(data));
      return true;
    }
    return false;
  });
}

export function unsubscribe<TMessage extends IFormatedMessage = IFormatedMessage>(scope: string | string[], callback: SubscriptionCallback<TMessage>): Promise<boolean> {
  return socketReady.then((notificationSocket) => {
    const scopes = scope instanceof Array ? scope : [scope];
    scopes.forEach(s => {
      const callbacks = subscriptions[s];
      const index = callbacks && callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
      if (callbacks.length === 0) {
        subscriptions[s] === undefined;
      }
    });

    // send a subscription to all active scopes
    const scopesToSubscribe = Object.keys(subscriptions);
    if (notificationSocket.readyState === notificationSocket.OPEN) {
      const data = {
        'data': 'scopes',
        'scopes': scopesToSubscribe
      };
      notificationSocket.send(JSON.stringify(data));
      return true;
    }
    return false;
  });
}

const connect = (): Promise<WebSocket> => {
  return new Promise((resolve, reject) => {
    const notificationSocket = new WebSocket(socketUrl);

    notificationSocket.onmessage = (event) => {
      // process received event
      if (typeof event.data === 'string') {
        const formated = formatData(event);
        if (formated && formated.notifType) {
          const callbacks = subscriptions[formated.notifType];
          if (callbacks) {
            callbacks.forEach(cb => {
              // ensure all callbacks will be called
              try {
                return cb(formated);
              } catch (reason) {
                console.error(reason);
              }
            });
          }
        }
      }
    };

    notificationSocket.onerror = function (error) {
      console.log("Socket error: " + error);
      reject("Socket error: " + error);
    };

    notificationSocket.onopen = function (event) {
      console.log("Socket connection opened.");
      resolve(notificationSocket);
    };

    notificationSocket.onclose = function (event) {
      socketReady = connect();
    };
  });
}

let socketReady = connect();