Queue.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. let Users = require('../database').Repositories.Users;
  2. let io = require('./sockets.js');
  3. const debug = (d) => {
  4. console.log(d);
  5. }
  6. class Queue {
  7. constructor(namespace) {
  8. this.matches= [];
  9. this._namespace_name = namespace;
  10. this.namespace = io;
  11. }
  12. getName() { return this._namespace_name; }
  13. createMatch(Match) { // sockets
  14. this.matches.push(match); // create Garbage collector
  15. }
  16. queue(socket) {
  17. // add socket to this queue
  18. debug("Joining queue : " + this._namespace_name);
  19. socket.join(this._namespace_name + 'queue');
  20. this._matchmaking();
  21. }
  22. _matchmaking() {
  23. return this.namespace.in(this._namespace_name + 'queue').clients((err, clients) => {
  24. this.namespace.emit(this._namespace_name + 'Size', clients.length);
  25. return this._checkClients(err, clients);
  26. });
  27. }
  28. _checkClients(err, clients) {
  29. if(err) throw err;
  30. if(clients.length < 2) return false;
  31. let client1 = clients[0];
  32. let client2 = clients[1];
  33. let socket1 = this.namespace.sockets.connected[client1];
  34. let socket2 = this.namespace.sockets.connected[client2];
  35. let token1 = socket1.request._query['token'];
  36. let token2 = socket2.request._query['token'];
  37. let channel = 'DQ' + client1 + client2 + this._namespace_name;
  38. // abstract joinGame depending on type
  39. // to be overriden
  40. let matchInfo = this.joinGame(token1, token2, channel);
  41. // save User info to DB
  42. this._saveUser(token1, matchInfo.playerOneState).then(() => this._saveUser(token2, matchInfo.playerTwoState))
  43. .then (() => this._match(socket1, socket2, channel, matchInfo))
  44. .catch(this._breakMatch);
  45. }
  46. _saveUser(token, currentGame) {
  47. return Users.getUser(token).then((user) => {
  48. user.currentGame = currentGame;
  49. Users.save(user);
  50. });
  51. }
  52. _breakMatch(err) {
  53. console.log(err);
  54. return ;
  55. }
  56. _match(s1, s2, channel, matchInfo) {
  57. // Check queue to make matchmaking
  58. s1.leave(this._namespace_name + 'queue');
  59. s2.leave(this._namespace_name + 'queue');
  60. s1.emit('joinGame', { personal: matchInfo.playerOneState, setup: matchInfo.setup});
  61. s2.emit('joinGame', { personal: matchInfo.playerTwoState, setup: matchInfo.setup});
  62. // finish my job!
  63. if(this.onMatchFound) this.onMatchFound(s1,s2,channel, matchInfo);
  64. }
  65. joinGame(token1, token2, channel) {
  66. return { channel };
  67. }
  68. _updateLobby() {
  69. this.namespace.in(this._namespace_name + 'queue').clients((err, clients) => {
  70. this.namespace.emit(this._namespace_name + 'Size', clients.length);
  71. });
  72. }
  73. }
  74. module.exports = Queue;