blob: 0944d019a324c1fffb8db2e06378cbb210b3b6bf [file] [log] [blame]
Maleke6c3c722018-10-16 16:44:41 +03001/*
2* Copyright © 2018 European Support Limited
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http: //www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
talig8e9c0652017-12-20 14:30:43 +020016
17import store from 'sdc-app/AppStore.js';
18import Configuration from 'sdc-app/config/Configuration.js';
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020019import { actionTypes } from 'sdc-app/onboarding/userNotifications/UserNotificationsConstants.js';
Maleke6c3c722018-10-16 16:44:41 +030020import WorkerUtil from 'nfvo-utils/WorkerUtil';
talig8e9c0652017-12-20 14:30:43 +020021
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020022export const websocketUrl =
Maleke6c3c722018-10-16 16:44:41 +030023 Configuration.get('websocketProtocol') +
24 '://' +
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020025 window.location.hostname +
26 ':' +
27 Configuration.get('websocketPort') +
28 '/' +
29 Configuration.get('websocketPath');
talig8e9c0652017-12-20 14:30:43 +020030
31/***
32 * Websocket is treated like a singleton. only need one for the application.
33 */
Maleke6c3c722018-10-16 16:44:41 +030034let websocket;
35const workerUtil = new WorkerUtil();
talig8e9c0652017-12-20 14:30:43 +020036export default {
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020037 open(url, { lastScanned }) {
38 if (
39 websocket === undefined ||
40 websocket.readyState === websocket.CLOSED
41 ) {
42 websocket = new WebSocket(
43 `${url}?LAST_DELIVERED_EVENT_ID=${lastScanned}`
44 );
45 websocket.onmessage = event =>
46 store.dispatch({
47 type: actionTypes.NOTIFICATION,
48 data: JSON.parse(event.data)
49 });
50 websocket.onclose = event => {
51 if (event.code && event.code === 1001) {
52 // - Idle Timeout
53 const { lastScanned } = store.getState().notifications;
54 console.log('Reconnecting to Websocket');
55 this.open(websocketUrl, { lastScanned });
56 }
57 };
Maleke6c3c722018-10-16 16:44:41 +030058 websocket.onerror = () => {
59 workerUtil.open();
60 };
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020061 }
62 },
talig8e9c0652017-12-20 14:30:43 +020063
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020064 close() {
65 if (websocket !== undefined) {
66 websocket.close();
67 }
Maleke6c3c722018-10-16 16:44:41 +030068
69 workerUtil.close();
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020070 }
talig8e9c0652017-12-20 14:30:43 +020071};