summaryrefslogtreecommitdiff
path: root/WebInterface/NodeJSServer/src/modules/server-client.js
blob: ea37e1e4cda6919b6ddad59dff65e2df3f8e3d4f (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
import * as signalR from '@aspnet/signalr';
import ServerListing from './ui/server-listing.js';

/**
 * Class for communication to server
 */
export default class ServerClient {
  /**
   * Creates new connection
   * @param {string} url URL of server running signalR
   * @param {string} serverListingId HTML ID of server-listing element,
   *    to populate with available games
   * @param {boolean} [debug=false] Enable debug output?
   */
  constructor(url, serverListingId, debug = false) {
    const connectionBuilder = new signalR.HubConnectionBuilder()
        .withUrl(url);

    if (debug) {
      connectionBuilder.configureLogging(signalR.LogLevel.Debug);
    } else {
      connectionBuilder.configureLogging(signalR.LogLevel.Error);
    }

    this.connection = connectionBuilder.build();
    this.connection.start()
        .then(() => this.loadServers()) // Load games list, once connected
        .catch((err) => console.error(err.toString()));

    // Initialize refreshing (blocks new refreshes if true)
    this.refreshing = false;

    this.serverListing = new ServerListing(serverListingId);

    this.messageHandling();
  }

  /**
   * Requests list of avalable games on the server
   */
  loadServers() {
    if (this.refreshing) return; // If already refreshing, no new request

    this.connection.on('ListGroups', (groups) => {
      // Populate server listing
      this.serverListing.flushElements();
      this.serverListing.addElements(groups);
      this.connection.off('ListGroups');

      this.refreshing = false;
    });

    this.connection.invoke('GetGroups')
        .catch((err) => {
          this.refreshing = false;
          console.error(err.toString());
        });
    this.refreshing = true;
  }

  /**
   * Sends a game creating request to the server
   * @param {string} name Name of the new game
   * @param {string} password Password
   */
  createServer(name, password) {
    // TODO: Create
  }

  /**
   * Sends a login request
   * @param {string} group Group name to join
   * @param {string} password Password to send as SHA-256 Base64 String
   * @param {string} username Display name to use
   * @param {ServerClient~loginCallback} callback Callback function to use
   */
  sendLogin(group, password, username, callback) {
    this.connection.on('LoginResponse', (result) => {
      callback(result);
      this.connection.off('LoginResponse');
    });
    this.connection.invoke('Login', group, username, password);
  }

  /**
   * Registers message handling
   */
  messageHandling() {
    this.connection.on('ReceiveMessage', (user, message) => {
      let msg = message.replace(/&/g, '&')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;');
      let encodedMsg = user + ' sagt:  ' + msg;
      console.log(encodedMsg); // TODO: REMOVE, JUST FOR DEBUGGING
    });
  }
}

/**
 * Callback to call with response to login request
 * @callback ServerClient~loginCallback
 * @param {number} result 0: Success, 1: PasswordError, 2:UsernameTaken
 *    , 3:Unknown Error
 */