All files / server/lobby persist.js

50.74% Statements 138/272
50.96% Branches 53/104
35.21% Functions 25/71
53.75% Lines 129/240

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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 4492x       2x 2x 2x 2x 2x   2x 2x       2x                     2x 2x 2x 2x 2x       2x                                                                                                                                                                                                                                 32x 62x 32x 32x 32x 32x 32x 32x 82x   48x   34x         82x                         82x 82x 82x 82x 82x 82x 82x     82x 82x 82x   32x 32x 32x 24x 24x 24x 48x 48x   24x 8x                         32x   32x                           2x 2x 2x     2x         2x               2x 2x 2x 2x 2x 2x       6x 6x 6x 6x 6x 6x   6x       2x       2x 2x 2x 2x                     2x       2x 2x 2x 4x 4x 4x                       2x           2x 2x 2x 2x 2x 2x 2x 2x       12x 12x 12x 12x 10x 10x 20x 8x     10x   10x 10x 10x 10x     10x 10x 10x 10x 10x 6x 4x   2x     4x 4x 2x 2x   2x 2x             10x 8x     10x                                                 4x                                                                 2x   2x 2x               2x 2x 2x 1x 1x   2x   2x    
const optionDefinitions = [
  { name: 'use_redis_mock', type: Boolean },
  { name: 'use_redis_server', type: Boolean }
]
const commandline = require('command-line-args')
const deepmerge = require('deepmerge')
const randomWords = require('random-words')
const RedisSessions = require('redis-sessions')
const argv = commandline(optionDefinitions, { partial: true, argv: process.argv })
 
const PapanUtils = require('../../common/utils.js')
const PapanServerUtils = require('../common/utils.js')
 
class PersistClient {
  constructor ({ rs, client, redis }) {
    const execIntercept = object => new Proxy(object, {
      get: (target, prop, receiver) => {
        if (prop !== 'exec') return (...args) => execIntercept(object[prop](...args))
        return () => new Promise((resolve, reject) => {
          object.exec((err, result) => {
            if (err) reject(err)
            resolve(result)
          })
        })
      }
    })
    this._redis = redis
    this._rs = rs
    this._client = client
    this._promised = PapanServerUtils.promisifyClass(client)
    this._promised.multi = () => execIntercept(client.multi())
  }
 
  close () {
    this._client.quit()
  }
 
  createSession (userId) {
    return new Promise((resolve, reject) => {
      this._rs.create({
        app: 'papan',
        id: userId,
        ip: '1'
      }, (err, resp) => {
        if (err) reject(err)
        resolve(resp.token)
      })
    })
  }
 
  getIdFromSession (session) {
    return new Promise((resolve, reject) => {
      this._rs.get({
        app: 'papan',
        token: session
      }, (err, resp) => {
        if (err) reject(err)
        if (!resp.id) reject(Error('Empty session'))
        resolve(resp.id)
      })
    })
  }
 
  getSessionData (session) {
    return new Promise((resolve, reject) => {
      this._rs.get({
        app: 'papan',
        token: session
      }, (err, resp) => {
        if (err) reject(err)
        if (!resp.id) reject(Error('Empty session'))
        resolve(resp.d)
      })
    })
  }
 
  setSessionData (session, data) {
    return new Promise((resolve, reject) => {
      this._rs.set({
        app: 'papan',
        token: session,
        d: data
      }, (err, resp) => {
        if (err) reject(err)
        if (!resp.id) reject(Error('Empty session'))
        resolve(resp.d)
      })
    })
  }
 
  userSubscribe (userId, callback) {
    const subscriber = this._redis.createClient()
    const key = 'usersub:' + userId
    subscriber.subscribe(key)
    subscriber.on('message', (channel, message) => {
      if (channel === key) {
        callback(PapanUtils.JSON.parse(message))
      }
    })
 
    const ret = {
      subscriber: subscriber,
      close: () => subscriber.unsubscribe(key)
    }
    return ret
  }
 
  sendUserMessage (userId, message) {
    this._client.publish('usersub:' + userId, PapanUtils.JSON.stringify(message))
  }
 
  registerGameServer (id, games) {
    let request = this._promised.multi().sadd('gameservers', id)
    games.forEach(infoHash => {
      request = request.sadd('game:' + infoHash, id)
    })
    return request.exec()
  }
 
  gameServerSubscribe (id, callback) {
    const subscriber = this._redis.createClient()
    const key = 'gamesub:' + id
    subscriber.subscribe(key)
    subscriber.on('message', (channel, message) => {
      if (channel === key) {
        callback(PapanUtils.JSON.parse(message))
      }
    })
 
    return {
      subscriber: subscriber,
      close: () => subscriber.unsubscribe(key)
    }
  }
 
  sendGameMessage (id, message) {
    this._client.publish('gamesub:' + id, PapanUtils.JSON.stringify(message))
  }
 
  async getJoinedLobbies (data) {
    const { id } = data
    let results = await this._promised.smembers('user:' + id + ':lobbies')
    if (!results) results = []
    return Promise.all(results.map(id => this.getLobbyInfo({ id: id })))
  }
 
  async getLobbyInfo (data) {
    const { id } = data
    const members = (await this._promised.smembers('lobbymembers:' + id)).map(id => ({ id: id }))
    const info = await this._promised.hgetall('lobbyinfo:' + id)
    const gameId = await this._promised.get('lobbyinfo:' + id + ':gameid')
    Iif (!info || !info.owner) throw Error('Lobby doesn\'t exist')
    const playersInfoTree = {}
    const teaminfo = await this._promised.hgetall('lobbyinfo:' + id + ':gameteaminfo:' + gameId)
    const convertValue = (key, value) => {
      switch (key) {
        case 'order':
          return parseInt(value)
        case 'user':
          return { id: value }
        default:
          return value
      }
    }
    Object.keys(teaminfo || {}).filter(subKey => subKey.match(/^playerinfo:.*team:/)).sort().forEach(team => {
      const matches = team.match(/^playerinfo:(.*):?team:(.*):(.*)$/)
      const components = matches[1].split(':')
      const id = matches[2]
      const key = matches[3]
      let parent = playersInfoTree
      components.filter(id => id.length !== 0).forEach(id => {
        parent = parent.teams[id]
      })
      if (!parent.teams) parent.teams = {}
      if (!parent.teams[id]) parent.teams[id] = {}
      parent.teams[id][key] = convertValue(key, teaminfo[team])
    })
    Object.keys(teaminfo || {}).filter(subkey => subkey.match(/^playerinfo:.*slot:/)).forEach(slot => {
      const matches = slot.match(/^playerinfo:(.*):?slot:(.*):(.*)$/)
      const components = matches[1].split(':')
      const id = matches[2]
      const key = matches[3]
      let parent = playersInfoTree
      components.filter(id => id.length !== 0).forEach(id => {
        parent = parent.teams[id]
      })
      if (!parent.slots) parent.slots = {}
      if (!parent.slots[id]) parent.slots[id] = {}
      parent.slots[id][key] = convertValue(key, teaminfo[slot])
    })
    const convertTree = tree => {
      const ret = {}
      if (tree.slots) {
        ret.slots = {}
        ret.slots.slot = []
        Object.keys(tree.slots).forEach(id => {
          tree.slots[id].id = id
          ret.slots.slot.push(tree.slots[id])
        })
        ret.slots.slot.sort((a, b) => a.order - b.order)
      } else Iif (tree.teams) {
        ret.teams = {}
        ret.teams.team = []
        Object.keys(tree.teams).forEach(id => {
          const subTree = convertTree(tree.teams[id])
          delete tree.teams[id].teams
          delete tree.teams[id].slots
          tree.teams[id].playersInfo = subTree
          ret.teams.team.push(tree.teams[id])
        })
        ret.teams.team.sort((a, b) => a.order - b.order)
      }
 
      return ret
    }
    return {
      id: id,
      owner: {
        id: info.owner
      },
      members: members,
      name: info.name,
      public: info.public === 'true',
      playersInfo: convertTree(playersInfoTree),
      gameInfo: info.gameInfo ? PapanUtils.JSON.parse(info.gameInfo) : info.gameInfo
    }
  }
 
  async createLobby (data) {
    const { userId } = data
    const id = await PapanServerUtils.generateToken({ prefix: 'LBBY' })
    Iif ((await this._promised.hsetnx('lobbyinfo:' + id, 'owner', userId)) === 0) {
      return this.createLobby(data)
    }
    await Promise.all([
      this._promised.set('lobbyinfo:' + id + ':gameid', 0),
      this._promised.sadd('lobbymembers:' + id, userId),
      this._promised.sadd('user:' + userId + ':lobbies', id)
    ])
    return this.setLobbyName({
      id: id,
      userId: userId,
      name: randomWords({ exactly: 4, join: ' ' })
    })
  }
 
  async joinLobby (data) {
    const { userId, id } = data
    const owner = await this._promised.hget('lobbyinfo:' + id, 'owner')
    Iif (owner === null) throw Error('Lobby doesn\'t exist')
    await this._promised.sadd('lobbymembers:' + id, userId)
    await this._promised.sadd('user:' + userId + ':lobbies', id)
    return this.getLobbyInfo({ id: id })
  }
 
  async _setLobbyField (data) {
    const { id, userId, field } = data
    const key = 'lobbyinfo:' + id
    const owner = await this._promised.hget(key, 'owner')
    Iif (owner === null) throw Error('Lobby doesn\'t exist')
    Eif (userId === owner) {
      await this._promised.hset(key, field, data[field])
    }
    return this.getLobbyInfo({ id: id })
  }
 
  setLobbyName (data) {
    return this._setLobbyField(deepmerge(data, { field: 'name' }))
  }
 
  async setLobbyPublic (data) {
    const info = await this._setLobbyField(deepmerge(data, { field: 'public' }))
    Eif (data.public) {
      await this._promised.sadd('publiclobbies', data.id)
      this._client.publish('publiclobbies', PapanUtils.JSON.stringify({
        id: data.id,
        status: 'ADDED'
      }))
    } else {
      await this._promised.srem('publiclobbies', data.id)
      this._client.publish('publiclobbies', PapanUtils.JSON.stringify({
        id: data.id,
        status: 'REMOVED'
      }))
    }
    return info
  }
 
  async setLobbyGame ({ userId, id, gameInfo }) {
    const createMinimumSlots = async (gameTeamKey, multi, playersInfo, owner = '') => {
      Eif (playersInfo.info === 'players') {
        for (let i = 0; i < playersInfo.players.min; i++) {
          const slotId = await PapanServerUtils.generateToken({ prefix: 'SLOT' })
          const subKey = 'playerinfo:' + owner + 'slot:' + slotId + ':order'
          multi.hset(gameTeamKey, subKey, i)
        }
      } else {
        for (let i = 0; i < playersInfo.teams.cardMin; i++) {
          const teamId = await PapanServerUtils.generateToken({ prefix: 'TEAM' })
          const subKey = 'playerinfo:' + owner + 'team:' + teamId
          multi.hset(gameTeamKey, subKey + ':order', i)
          multi.hset(gameTeamKey, subKey + ':name', playersInfo.teams.name)
          await createMinimumSlots(multi, playersInfo.teams.playersInfo, teamId + ':')
        }
      }
    }
    const info = await this._setLobbyField({
      userId: userId,
      id: id,
      gameInfo: PapanUtils.JSON.stringify(gameInfo),
      field: 'gameInfo'
    })
    Iif (info.owner.id !== userId) return info
    const newGameId = await this._promised.incrby('lobbyinfo:' + id + ':gameid', 1)
    const oldGameId = newGameId - 1
    const multi = this._client.multi()
    multi.del('lobbyinfo:' + id + ':gameteaminfo:' + oldGameId)
    await createMinimumSlots('lobbyinfo:' + id + ':gameteaminfo:' + newGameId, multi, gameInfo.json.playersInfo)
    await multi.exec()
    return this.getLobbyInfo({ id: id })
  }
 
  async assignSlot (data) {
    const { lobbyId, userId, senderId } = data
    const info = await this.getLobbyInfo({ id: lobbyId })
    const owner = info.owner.id
    if (userId) {
      let found = false
      info.members.forEach(user => {
        if (user.id === userId) {
          found = true
        }
      })
      if (!found) return info
    }
    this._client.watch('lobbyinfo:' + lobbyId + ':gameid')
    const gameId = await this._promised.get('lobbyinfo:' + lobbyId + ':gameid')
    const buildSlotId = data => {
      Eif (data.slotId) return 'slot:' + data.slotId
      return (data.id ? (data.id + ':') : '') + buildSlotId(data.team)
    }
    const slotId = 'playerinfo:' + buildSlotId(data)
    const multi = this._client.multi()
    let discarded = false
    const gameKey = 'lobbyinfo:' + lobbyId + ':gameteaminfo:' + gameId
    if (owner === senderId) {
      if (userId) {
        multi.hset(gameKey, slotId + ':user', userId)
      } else {
        multi.hdel(gameKey, slotId + ':user')
      }
    } else {
      const currentPlayer = await this._promised.hget(gameKey, slotId + ':user')
      if ((currentPlayer && currentPlayer !== senderId) || (userId && userId !== senderId)) {
        multi.discard()
        discarded = true
      } else {
        Eif (userId) {
          multi.hsetnx(gameKey, slotId + ':user', userId)
        } else {
          multi.hdel(gameKey, slotId + ':user')
        }
      }
    }
 
    if (!discarded) {
      await multi.exec()
    }
 
    return this.getLobbyInfo({ id: lobbyId })
  }
 
  lobbySubscribe (id, callback) {
    const subscriber = this._redis.createClient()
    const key = 'lobbysub:' + id
    subscriber.subscribe(key)
    subscriber.on('message', (channel, message) => {
      if (channel === key) {
        callback(PapanUtils.JSON.parse(message))
      }
    })
 
    const ret = {
      subscriber: subscriber,
      close: () => subscriber.unsubscribe(key)
    }
    return ret
  }
 
  lobbySendMessage (id, message) {
    this._client.publish('lobbysub:' + id, PapanUtils.JSON.stringify(message))
  }
 
  getPublicLobbies () {
    return this._promised.smembers('publiclobbies')
  }
 
  lobbyListSubscribe (callback) {
    const subscriber = this._redis.createClient()
    const key = 'publiclobbies'
    subscriber.subscribe(key)
    subscriber.on('message', (channel, message) => {
      const data = PapanUtils.JSON.parse(message)
      if (data.status === 0) {
        this.getLobbyInfo({ id: data.id })
          .then(info => {
            data.lobby = info
            callback(data)
          })
      } else {
        data.lobby = { id: data.id }
        callback(data)
      }
    })
 
    const ret = {
      subscriber: subscriber,
      close: () => subscriber.unsubscribe(key)
    }
    return ret
  }
 
  isApiKeyValid (apiKey) {
    return Promise.resolve(false)
  }
}
 
exports.createPersist = () => {
  let mock
  Eif (!argv.use_redis_mock && !argv.use_redis_server) {
    mock = PapanUtils.isElectron()
  } else {
    if (argv.use_redis_mock && argv.use_redis_server) {
      throw Error('You can\'t have both --use_redis_mock and --use_redis_server')
    }
    mock = argv.use_redis_mock
  }
 
  const redis = mock ? require('redis-mock') : require('redis')
  const client = redis.createClient()
  if (mock) {
    redis.setMaxListeners(0)
    client.watch = () => {}
  }
  const rs = new RedisSessions({ client: client })
 
  return Promise.resolve(new PersistClient({ rs: rs, client: client, redis: redis }))
}