All files / src PieSocket.js

60.6% Statements 40/66
68.57% Branches 24/35
50% Functions 7/14
60.6% Lines 40/66

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                  5x   5x 5x 5x       3x 3x         3x 3x   3x 1x 1x   2x 2x                                     2x   2x 2x 2x             2x 1x 1x 1x 1x     1x       1x                                                                         14x 3x     11x       12x 12x 12x     12x 1x 11x 3x 3x 2x         12x 1x       12x   12x      
import Channel from './Channel.js';
import Logger from './Logger.js';
import Portal from './Portal.js';
import InvalidAuthException from './InvalidAuthException.js';
import defaultOptions from './misc/DefaultOptions.js';
import {v4 as uuidv4} from 'uuid';
 
export default class PieSocket {
  constructor(options) {
    options = options || {};
 
    this.options = {...defaultOptions, ...options};
    this.connections = {};
    this.logger = new Logger(this.options);
  }
 
  async subscribe(channelId, roomOptions={}) {
    return new Promise(async (resolve, reject) => {
      Iif (roomOptions.video || roomOptions.audio || roomOptions.portal) {
        // Force config when video is required
        this.options.notifySelf = true;
      }
 
      const uuid = uuidv4();
      const endpoint = await this.getEndpoint(channelId, uuid);
 
      if (this.connections[channelId]) {
        this.logger.log('Returning existing channel', channelId);
        resolve(this.connections[channelId]);
      } else {
        this.logger.log('Creating new channel', channelId);
        const channel = new Channel(endpoint, {
          channelId: channelId,
          onSocketConnected: () => {
            channel.uuid = uuid;
            if (roomOptions.video || roomOptions.audio || roomOptions.portal) {
              channel.portal = new Portal(channel, {
                ...this.options,
                ...roomOptions,
              }); ``;
            }
            this.connections[channelId] = channel;
            resolve(channel);
          },
          onSocketError: () => {
            reject('Failed to make websocket connection');
          },
          ...this.options,
        });
 
        Eif (typeof WebSocket == 'undefined') {
          // Resolves the promise in case WebSocket is not defined
          channel.uuid = uuid;
          this.connections[channelId] = channel;
          resolve(channel);
        }
      }
    });
  }
 
  unsubscribe(channelId) {
    if (this.connections[channelId]) {
      this.connections[channelId].shouldReconnect = false;
      this.connections[channelId].connection.close();
      delete this.connections[channelId];
      return true;
    }
 
    return false;
  }
 
  getConnections() {
    return this.connections;
  }
 
  async getAuthToken(channel) {
    return new Promise((resolve, reject)=>{
      const data = new FormData();
      data.append('channel_name', channel);
 
      const xhr = new XMLHttpRequest();
      xhr.withCredentials = true;
 
      xhr.addEventListener('readystatechange', function() {
        if (this.readyState === 4) {
          try {
            const response = JSON.parse(this.responseText);
            resolve(response);
          } catch (e) {
            reject(new InvalidAuthException('Could not fetch auth token', 'AuthEndpointResponseError'));
          }
        }
      });
      xhr.addEventListener('error', ()=>{
        reject(new InvalidAuthException('Could not fetch auth token', 'AuthEndpointError'));
      });
 
      xhr.open('POST', this.options.authEndpoint);
 
      const headers = Object.keys(this.options.authHeaders);
      headers.forEach((header) => {
        xhr.setRequestHeader(header, this.options.authHeaders[header]);
      });
 
      xhr.send(data);
    });
  }
 
  isGuarded(channel) {
    if (this.options.forceAuth) {
      return true;
    }
 
    return (''+channel).startsWith('private-');
  }
 
  async getEndpoint(channelId, uuid) {
    const clusterDomain = this.options.clusterDomain == null ? `${this.options.clusterId}.piesocket.com` : this.options.clusterDomain;
    const protocol = this.options.ssl ? 'wss' : 'ws';
    let endpoint = `${protocol}://${clusterDomain}/v${this.options.version}/${channelId}?api_key=${this.options.apiKey}&notify_self=${this.options.notifySelf}&source=jssdk&v=5.2.0&presence=${this.options.presence}`;
 
    // Set auth
    if (this.options.jwt) {
      endpoint = endpoint+'&jwt='+this.options.jwt;
    } else if (this.isGuarded(channelId)) {
      const auth = await this.getAuthToken(channelId);
      if (auth.auth) {
        endpoint = endpoint + '&jwt='+auth.auth;
      }
    }
 
    // Set user identity
    if (this.options.userId) {
      endpoint = endpoint + '&user='+this.options.userId;
    }
 
    // Add uuid
    endpoint = endpoint+'&uuid='+uuid;
 
    return endpoint;
  }
}