aboutsummaryrefslogtreecommitdiff
path: root/utils/ident.js
blob: 187132fb8d031b30a26bcb64625663ae3efa058c (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
// A portable script to find the sender when the server websocket opens (by cursor movement)

const vec = require('../utils/vec');

module.exports = function identify(sock, initOnce, init, deinit){
  // `sock` should be Socket instance.
  // initOnce and init should be functions that act like they describe; initOnce runs once per program execution and init whenever the socket turns back on

  sock.on('open', ()=>{
    // "Pings" the server with a cursor location which is detected and saved by identity()
    let coords = [Math.floor(Math.random()*100000+16), Math.floor(Math.random()*1000000+16)];
    sock.cursor(coords);
    sock.on('cursor', detect);
    function detect(pos, send){
      if (vec.equals(pos[0],coords)){
        sock.off('cursor', detect);
        identity(send);
      }
    }
  });

  sock.on('close', deinit);

  // Calls initOnce and init on successful identification.
  let initialized = false;
  function identity(send){
    if (! initialized){
      initialized = true;
      initOnce();
    }
    init(send);
  }
}