All files / src Channel.js

77.06% Statements 84/109
54.43% Branches 43/79
84.21% Functions 16/19
77.77% Lines 84/108

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236            5x 5x 5x 5x 5x 5x 5x   5x 1x     4x       5x 5x 5x 5x 5x                                     7x 7x 7x 7x 7x   7x 2x     7x 2x     7x         12x         3x         1x       3x     3x                 2x 1x     2x 2x   1x 1x               1x   1x 1x           2x       2x 2x   1x 1x             1x   1x 1x           1x   1x 1x 1x         1x 1x   1x 1x     1x 1x               1x 1x         1x   1x   1x         1x   1x   1x   1x   1x   1x   1x           1x 1x     1x       1x 1x     1x     1x 1x         1x 1x     1x 1x         2x     2x 2x      
import Logger from './Logger.js';
import Blockchain from './Blockchain.js';
import Socket from './misc/WebSocket.js';
 
export default class Channel {
  constructor(endpoint, identity, init=true) {
    this.events = {};
    this.listeners = {};
    this.members = [];
    this.portal = null;
    this.uuid = null;
    this.onSocketConnected = () => {};
    this.onSocketError = () => {};
 
    if (!init) {
      return;
    }
 
    this.init(endpoint, identity);
  }
 
  init(endpoint, identity) {
    this.endpoint = endpoint;
    this.identity = identity;
    this.connection = this.connect();
    this.shouldReconnect = false;
    this.logger = new Logger(identity);
  }
 
  getMemberByUUID(uuid) {
    let member = null;
    for (let i = 0; i < this.members.length; i++) {
      if (this.members[i].uuid == uuid) {
        member = this.members[i];
        break;
      }
    }
    return member;
  }
 
  getCurrentMember() {
    return this.getMemberByUUID(this.uuid);
  }
 
  connect() {
    const connection = new Socket(this.endpoint);
    connection.onmessage = this.onMessage.bind(this);
    connection.onopen = this.onOpen.bind(this);
    connection.onerror = this.onError.bind(this);
    connection.onclose = this.onClose.bind(this);
 
    if (this.identity.onSocketConnected) {
      this.onSocketConnected = this.identity.onSocketConnected;
    }
 
    if (this.identity.onSocketError) {
      this.onSocketError = this.identity.onSocketError;
    }
 
    return connection;
  }
 
  on(event, callback) {
    // Register lifecycle callbacks
    this.events[event] = callback;
  }
 
  listen(event, callback) {
    // Register user defined callbacks
    this.listeners[event] = callback;
  }
 
 
  send(data) {
    return this.connection.send(data);
  }
 
  async publish(event, data, meta) {
    Iif (meta && meta.blockchain) {
      return await this.sendOnBlockchain(event, data, meta);
    }
    return this.connection.send(JSON.stringify({
      event: event,
      data: data,
      meta: meta,
    }));
  }
 
 
  async sendOnBlockchain(event, data, meta) {
    if (!this.blockchain) {
      this.blockchain = new Blockchain(this.identity);
    }
 
    try {
      const receipt = await this.blockchain.send(data);
 
      Eif (this.events['blockchain-hash']) {
        this.events['blockchain-hash'].bind(this)({
          event: event,
          data: data,
          meta: meta,
          transactionHash: receipt.hash,
        });
      }
 
      return this.connection.send(JSON.stringify({'event': event, 'data': data, 'meta': {...meta, 'transaction_id': receipt.id, 'transaction_hash': receipt.hash}}));
    } catch (e) {
      Eif (this.events['blockchain-error']) {
        this.events['blockchain-error'].bind(this)(e);
      }
    };
  }
 
  async confirmOnBlockchain(event, transactionHash) {
    Iif (!this.blockchain) {
      this.blockchain = new Blockchain(this.identity);
    }
 
    try {
      const hash = await this.blockchain.confirm(transactionHash);
 
      Eif (this.events['blockchain-hash']) {
        this.events['blockchain-hash'].bind(this)({
          event: event,
          confirmationHash: transactionHash,
          transactionHash: hash,
        });
      }
 
      return this.connection.send(JSON.stringify({'event': event, 'data': transactionHash, 'meta': {'transaction_id': 1, 'transaction_hash': hash}}));
    } catch (e) {
      Eif (this.events['blockchain-error']) {
        this.events['blockchain-error'].bind(this)(e);
      }
    }
  }
 
  onMessage(e) {
    this.logger.log('Channel message:', e);
 
    try {
      const message = JSON.parse(e.data);
      Iif (message.error && message.error.length) {
        this.shouldReconnect = false;
      }
 
      // Fire event listeners
      Eif (message.event) {
        this.handleMemberHandshake(message);
 
        Eif (this.listeners[message.event]) {
          this.listeners[message.event].bind(this)(message.data, message.meta);
        }
 
        Eif (this.listeners['*']) {
          this.listeners['*'].bind(this)(message.event, message.data, message.meta);
        }
      }
    } catch (jsonException) {
      console.error(jsonException);
    }
 
    // Fire lifecycle callback
    Eif (this.events['message']) {
      this.events['message'].bind(this)(e);
    }
  }
 
  handleMemberHandshake(message) {
    Iif (message.event == 'system:member_list') {
      this.members = message.data.members;
    } else Iif (message.event == 'system:member_joined') {
      this.members = message.data.members;
    } else Iif (message.event == 'system:member_left') {
      this.members = message.data.members;
      if (this.portal) {
        this.portal.removeParticipant(message.data.member.uuid);
      }
    } else Iif (message.event == 'system:portal_broadcaster' && message.data.from != this.uuid) {
      this.portal.requestOfferFromPeer(message.data);
    } else Iif (message.event == 'system:stopped_screen' && message.data.from != this.uuid) {
      this.portal.onRemoteScreenStopped(message.data.from, message.data.streamId);
    } else Iif (message.event == 'system:portal_watcher' && message.data.from != this.uuid) {
      this.portal.shareVideo(message.data);
    } else Iif (message.event == 'system:video_request' && message.data.from != this.uuid) {
      this.portal.shareVideo(message.data);
    } else Iif (message.event == 'system:portal_candidate' && message.data.to == this.uuid) {
      this.portal.addIceCandidate(message.data);
    } else Iif (message.event == 'system:video_offer' && message.data.to == this.uuid) {
      this.portal.createAnswer(message.data);
    } else Iif (message.event == 'system:video_answer' && message.data.to == this.uuid) {
      this.portal.handleAnswer(message.data);
    }
  }
 
  onOpen(e) {
    this.logger.log('Channel connected:', e);
    this.shouldReconnect = true;
 
    // System init callback
    this.onSocketConnected(e);
  }
 
  onError(e) {
    this.logger.error('Channel error:', e);
    this.connection.close();
 
    // System init error callback
    this.onSocketError(e);
 
    // User defined callback
    Eif (this.events['error']) {
      this.events['error'].bind(this)(e);
    }
  }
 
  onClose(e) {
    this.logger.warn('Channel closed:', e);
    this.reconnect();
 
    // User defined callback
    Eif (this.events['close']) {
      this.events['close'].bind(this)(e);
    }
  }
 
  reconnect() {
    Iif (!this.shouldReconnect) {
      return;
    }
    this.logger.log('Reconnecting');
    this.connection = this.connect();
  }
}