<commit_before>import BaseStore from './base-store';
import SocketConstants from '../constants/socket-constants';
import AppDispatcher from '../dispatcher/app-dispatcher';

class SocketStore extends BaseStore {
  constructor() {
    super()
    this.registerActions(() => this._actionsHandler.bind(this));
    this.ws = new WebSocket('ws://localhost:4652');
    this.ws.onmessage = this._message.bind(this);
    this.ws.onopen = this._open.bind(this);
    this.ws.onclose = this._close.bind(this);
    this.isConnected = false;
    this.isRoomReady = false;
    this.userName = "";
    this.roomName = "";
  }

  addSocketListener(name, callback) {
    this.on(name, callback);
  }

  removeSocketListener(name, callback) {
    this.removeListener(name, callback);
  }

  _actionsHandler(action) {
    switch (action.actionType) {
      case SocketConstants.SOCKET_ADD_USER_TO_ROOM:
        if (action.data && action.data.userName && action.data.roomName) {
          this._addUserToRoom(action.data.userName, action.data.roomName);
        }
        break;

      case SocketConstants.SOCKET_JOIN_USER_TO_ROOM:
        if (action.data && action.data.userName && action.data.roomName) {
          this._joinUserToRoom(action.data.userName, action.data.roomName);
        }

      case SocketConstants.SOCKET_SEND_TEXT_MESSAGE:
        if (action.data &&
            action.data.userName &&
            action.data.roomName &&
            action.data.chatText
        ) {
          this._sendTextMessage(action.data);
        }
        break;

      default:
          console.log('unknown socket action');
    }
  }

  _message(e) {
    try {
      let payload = JSON.parse(e.data);
      if (payload.name === 'chat message') {
        this.emit(SocketConstants.SOCKET_RECEIVE_TEXT_MESSAGE, {
          from: payload.data.user,
          text: payload.data.text,
        });
      }
    }
    catch (err) {
      this.emit(SocketConstants.SOCKET_ERROR, err)
    }
  }

  _open() {
    console.log('Socket open');
    this.isConnected = true;
    this.emit(SocketConstants.SOCKET_CONNECT);
  }

  _close() {
    console.log('Socket close');
    this.isConnected = false;
    this.emit(SocketConstants.SOCKET_DISCONNECT);
  }

  _addUserToRoom(userName, roomName) {
    let message = {
      name: 'room add',
      data: {
        user: userName,
        room: roomName,
      }
    };
    try {
      this.ws.send(JSON.stringify(message));
      this.userName = userName;
      this.roomName = roomName;
      this.isConnected = true;
      this.isRoomReady = true;
      localStorage.setItem('userName', userName);
      localStorage.setItem('roomName', roomName);
      this.emit(SocketConstants.SOCKET_ROOM_READY);
    }
    catch(err) {
      console.log(err);
    }
  }<commit_msg>Added websocket reconnect code to be triggered on connection loss.<commit_after>import BaseStore from './base-store';
import SocketConstants from '../constants/socket-constants';
import AppDispatcher from '../dispatcher/app-dispatcher';

class SocketStore extends BaseStore {
  constructor() {
    super()
    this.registerActions(() => this._actionsHandler.bind(this));
    this._createWebSocket();
    this.reconnectAttempts = 0;
    this.userName = "";
    this.roomName = "";
  }

  addSocketListener(name, callback) {
    this.on(name, callback);
  }

  removeSocketListener(name, callback) {
    this.removeListener(name, callback);
  }

  _createWebSocket() {
    this.ws = new WebSocket('ws://localhost:4652');
    this.ws.onmessage = this._message.bind(this);
    this.ws.onopen = this._open.bind(this);
    this.ws.onclose = this._close.bind(this);
    this.isConnected = false;
    this.isRoomReady = false;
  }

  _actionsHandler(action) {
    switch (action.actionType) {
      case SocketConstants.SOCKET_ADD_USER_TO_ROOM:
        if (action.data && action.data.userName && action.data.roomName) {
          this._addUserToRoom(action.data.userName, action.data.roomName);
        }
        break;

      case SocketConstants.SOCKET_JOIN_USER_TO_ROOM:
        if (action.data && action.data.userName && action.data.roomName) {
          this._joinUserToRoom(action.data.userName, action.data.roomName);
        }

      case SocketConstants.SOCKET_SEND_TEXT_MESSAGE:
        if (action.data &&
            action.data.userName &&
            action.data.roomName &&
            action.data.chatText
        ) {
          this._sendTextMessage(action.data);
        }
        break;

      default:
          console.log('unknown socket action');
    }
  }

  _message(e) {
    try {
      let payload = JSON.parse(e.data);
      if (payload.name === 'chat message') {
        this.emit(SocketConstants.SOCKET_RECEIVE_TEXT_MESSAGE, {
          from: payload.data.user,
          text: payload.data.text,
        });
      }
    }
    catch (err) {
      this.emit(SocketConstants.SOCKET_ERROR, err)
    }
  }

  _open() {
    console.log('Socket open');
    this.reconnectAttempts = 1;
    this.isConnected = true;
    this.emit(SocketConstants.SOCKET_CONNECT);
  }

  _close() {
    console.log('Socket close');
    this.isConnected = false;
    this.emit(SocketConstants.SOCKET_DISCONNECT);

    let interval = this._getReconnectInterval(this.reconnectAttempts);

    console.log('Will reconnect in ' + interval / 1000 + ' seconds...');

    setTimeout(() => {
      this.reconnectAttempts++;
      this._createWebSocket();
    }, interval);
  }

  _getReconnectInterval(interval) {
    return Math.min(15, (Math.pow(2, interval) - 1)) * 1000;
  }

  _addUserToRoom(userName, roomName) {
    let message = {
      name: 'room add',
      data: {
        user: userName,
        room: roomName,
      }
    };
    try {
      this.ws.send(JSON.stringify(message));
      this.userName = userName;
      this.roomName = roomName;
      this.isConnected = true;
      this.isRoomReady = true;
      localStorage.setItem('userName', userName);
      localStorage.setItem('roomName', roomName);
      this.emit(SocketConstants.SOCKET_ROOM_READY);
    }
    catch(err) {
      console.log(err);
    }
  }
{'fraction_non_alphanumeric': 0.12854566322347927, 'fraction_numerical': 0.003607148712903755, 'mean_word_length': 2.5840188014101058, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1434598', 'n_tokens_mistral': 1953, 'n_tokens_neox': 1913, 'n_words': 305}