Exemplo n.º 1
0
func (Lobby) LobbySpectatorJoin(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, authority.AuthAction(0), true)

	if reqerr != nil {
		bytes, _ := json.Marshal(reqerr)
		return bytes
	}

	var args struct {
		Id *uint `json:"id"`
	}

	if err := chelpers.GetParams(data, &args); err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	var lob *models.Lobby
	lob, tperr := models.GetLobbyById(*args.Id)

	if tperr != nil {
		return tperr.Encode()
	}

	player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
	if tperr != nil {
		return tperr.Encode()
	}

	var specSameLobby bool

	arr, tperr := player.GetSpectatingIds()
	if len(arr) != 0 {
		for _, id := range arr {
			if id == *args.Id {
				specSameLobby = true
				continue
			}

			lobby, _ := models.GetLobbyById(id)
			lobby.RemoveSpectator(player, true)

			server.RemoveClient(so.Id(), fmt.Sprintf("%d_public", id))
		}
	}

	// If the player is already in the lobby (either joined a slot or is spectating), don't add them.
	// Just Broadcast the lobby to them, so the frontend displays it.
	if id, _ := player.GetLobbyId(); id != *args.Id && !specSameLobby {
		tperr = lob.AddSpectator(player)

		if tperr != nil {
			return tperr.Encode()
		}

		chelpers.AfterLobbySpec(server, so, lob)
	}

	models.BroadcastLobbyToUser(lob, player.SteamId)
	return chelpers.EmptySuccessJS
}
Exemplo n.º 2
0
Arquivo: debug.go Projeto: N1xx1/Helen
func DebugLobbyFill(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, debugLobbyFillFilter,
		func(param map[string]interface{}) string {
			id := param["id"].(uint)
			lobby, _ := models.GetLobbyById(id)
			var players []*models.Player

			for i := 1; i < int(lobby.Type)*2; i++ {
				steamid := "DEBUG" + strconv.FormatUint(uint64(time.Now().Unix()), 10) + strconv.Itoa(i)

				player, _ := models.NewPlayer(steamid)
				player.Debug = true
				player.Save()
				players = append(players, player)
				lobby.AddPlayer(player, i)
			}

			lobby.State = models.LobbyStateReadyingUp
			lobby.Save()
			room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobby.ID))
			broadcaster.SendMessageToRoom(room, "lobbyReadyUp", "")
			lobby.ReadyUpTimeoutCheck()
			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)

		})
}
Exemplo n.º 3
0
func removePlayerFromLobby(lobbyId uint, steamId string) (*models.Lobby, *models.Player, *helpers.TPError) {
	player, tperr := models.GetPlayerBySteamId(steamId)
	if tperr != nil {
		return nil, nil, tperr
	}

	lob, tperr := models.GetLobbyById(lobbyId)
	if tperr != nil {
		return nil, nil, tperr
	}

	switch lob.State {
	case models.LobbyStateInProgress:
		return lob, player, helpers.NewTPError("Lobby is in progress.", 1)
	case models.LobbyStateEnded:
		return lob, player, helpers.NewTPError("Lobby has closed.", 1)
	}

	_, err := lob.GetPlayerSlot(player)
	if err != nil {
		return lob, player, helpers.NewTPError("Player not playing", 2)
	}

	if err := lob.RemovePlayer(player); err != nil {
		return lob, player, err
	}

	return lob, player, lob.AddSpectator(player)
}
Exemplo n.º 4
0
func LobbyClose(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, lobbyCloseFilters,
		func(params map[string]interface{}) string {
			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			lobbyid := params["id"].(uint)

			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if player.SteamId != lob.CreatedBySteamID && player.Role != helpers.RoleAdmin {
				bytes, _ := chelpers.BuildFailureJSON("Player not authorized to close lobby.", 1).Encode()
				return string(bytes)
			}

			if lob.State == models.LobbyStateEnded {
				bytes, _ := chelpers.BuildFailureJSON("Lobby already closed.", -1).Encode()
				return string(bytes)
			}

			helpers.LockRecord(lob.ID, lob)
			lob.Close(true)
			helpers.UnlockRecord(lob.ID, lob)
			chelpers.StopLogger(lobbyid)
			models.BroadcastLobbyList() // has to be done manually for now

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})

}
Exemplo n.º 5
0
func onDisconnect(id string) {
	//defer helpers.Logger.Debug("Disconnected from Socket")
	defer chelpers.DeauthenticateSocket(id)
	if chelpers.IsLoggedInSocket(id) {
		steamid := chelpers.GetSteamId(id)
		broadcaster.RemoveSocket(steamid)
		player, tperr := models.GetPlayerBySteamId(steamid)
		if tperr != nil || player == nil {
			helpers.Logger.Error(tperr.Error())
			return
		}

		ids, tperr := player.GetSpectatingIds()
		if tperr != nil {
			helpers.Logger.Error(tperr.Error())
			return
		}

		for _, id := range ids {
			lobby, _ := models.GetLobbyById(id)
			err := lobby.RemoveSpectator(player, true)
			if err != nil {
				helpers.Logger.Error(err.Error())
				continue
			}
			//helpers.Logger.Debug("removing %s from %d", player.SteamId, id)
		}

	}
}
Exemplo n.º 6
0
func DebugLobbyReady(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, 0, true)

	if reqerr != nil {
		return reqerr.Encode()
	}

	var args struct {
		Id *uint `json:"id"`
	}

	err := chelpers.GetParams(data, &args)
	if err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	lobby, _ := models.GetLobbyById(*args.Id)

	var slots []models.LobbySlot
	db.DB.Where("lobby_id = ?", lobby.ID).Find(&slots)
	for _, slot := range slots {
		slot.Ready = true
		db.DB.Save(slot)
	}
	lobby.OnChange(true)

	return chelpers.EmptySuccessJS
}
Exemplo n.º 7
0
Arquivo: debug.go Projeto: N1xx1/Helen
func DebugRequestLobbyStart(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, debugRequestLobbyStartFilter,
		func(params map[string]interface{}) string {
			lobby, _ := models.GetLobbyById(params["id"].(uint))
			bytes, _ := models.DecorateLobbyConnectJSON(lobby).Encode()
			room := fmt.Sprintf("%s_private", chelpers.GetLobbyRoom(lobby.ID))
			broadcaster.SendMessageToRoom(room,
				"lobbyStart", string(bytes))

			bytes, _ = chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 8
0
func PlayerReady(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, playerReadyFilter,
		func(_ map[string]interface{}) string {
			steamid := chelpers.GetSteamId(so.Id())
			player, tperr := models.GetPlayerBySteamId(steamid)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobbyid, tperr := player.GetLobbyId()
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobby, tperr := models.GetLobbyById(lobbyid)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if lobby.State != models.LobbyStateReadyingUp {
				bytes, _ := helpers.NewTPError("Lobby hasn't been filled up yet.", 4).ErrorJSON().Encode()
				return string(bytes)
			}

			helpers.LockRecord(lobby.ID, lobby)
			tperr = lobby.ReadyPlayer(player)
			defer helpers.UnlockRecord(lobby.ID, lobby)

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if lobby.IsEveryoneReady() {
				lobby.State = models.LobbyStateInProgress
				lobby.Save()
				bytes, _ := models.DecorateLobbyConnectJSON(lobby).Encode()
				room := fmt.Sprintf("%s_private",
					chelpers.GetLobbyRoom(lobby.ID))
				broadcaster.SendMessageToRoom(room,
					"lobbyStart", string(bytes))
				models.BroadcastLobbyList()
			}

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 9
0
func DebugPlayerSub(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, 0, true)

	if reqerr != nil {
		return reqerr.Encode()
	}

	var args struct {
		Id    *uint   `json:"id"`
		Team  *string `json:"team"`
		Class *string `json:"class"`
	}

	err := chelpers.GetParams(data, &args)
	if err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	lob, tperr := models.GetLobbyById(*args.Id)
	if tperr != nil {
		return tperr.Encode()
	}

	s, tperr := models.LobbyGetPlayerSlot(lob.Type, *args.Team, *args.Class)
	if tperr != nil {
		return tperr.Encode()
	}

	slot := models.LobbySlot{}
	err = db.DB.Where("slot = ?", s).First(&slot).Error
	if err != nil {
		helpers.Logger.Debug("", slot, s)
		return helpers.NewTPErrorFromError(err).Encode()
	}

	player := models.Player{}
	err = db.DB.First(&player, slot.PlayerId).Error
	if err != nil {
		helpers.Logger.Debug("", player)
		return helpers.NewTPErrorFromError(err).Encode()
	}

	sub, _ := models.NewSub(*args.Id, player.SteamId)
	db.DB.Save(sub)

	models.BroadcastSubList()

	return chelpers.EmptySuccessJS
}
Exemplo n.º 10
0
func playerCanKick(lobbyId uint, steamId string) (bool, *helpers.TPError) {
	lob, tperr := models.GetLobbyById(lobbyId)
	if tperr != nil {
		return false, tperr
	}

	player, tperr2 := models.GetPlayerBySteamId(steamId)
	if tperr2 != nil {
		return false, tperr2
	}
	if steamId != lob.CreatedBySteamID && player.Role != helpers.RoleAdmin {
		return false, helpers.NewTPError("Not authorized to kick players", 1)
	}
	return true, nil
}
Exemplo n.º 11
0
Arquivo: lobby.go Projeto: N1xx1/Helen
func PlayerNotReady(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, playerUnreadyFilter,
		func(_ map[string]interface{}) string {
			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobbyid, tperr := player.GetLobbyId()
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobby, tperr := models.GetLobbyById(lobbyid)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if lobby.State != models.LobbyStateReadyingUp {
				bytes, _ := helpers.NewTPError("Lobby hasn't been filled up yet.", 4).ErrorJSON().Encode()
				return string(bytes)
			}

			helpers.LockRecord(lobby.ID, lobby)
			tperr = lobby.UnreadyPlayer(player)
			lobby.RemovePlayer(player)
			helpers.UnlockRecord(lobby.ID, lobby)

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobby.UnreadyAllPlayers()

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 12
0
func TestLobbyCreation(t *testing.T) {
	testhelpers.CleanupDB()
	lobby := models.NewLobby("cp_badlands", models.LobbyTypeSixes, "ugc", models.ServerRecord{0, "testip", "", ""}, 0, false)
	lobby.Save()

	lobby2, _ := models.GetLobbyById(lobby.ID)

	assert.Equal(t, lobby.ID, lobby2.ID)
	assert.Equal(t, lobby.ServerInfo.Host, lobby2.ServerInfo.Host)
	assert.Equal(t, lobby.ServerInfo.ID, lobby2.ServerInfo.ID)

	lobby.MapName = "cp_granary"
	lobby.Save()

	db.DB.First(lobby2)
	assert.Equal(t, "cp_granary", lobby2.MapName)
}
Exemplo n.º 13
0
func LobbyNoLoginSpectatorJoin(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, lobbyNoLoginSpectatorJoinFilters,
		func(params map[string]interface{}) string {
			id := params["id"].(uint)

			lobby, err := models.GetLobbyById(id)
			if err != nil {
				bytes, _ := err.ErrorJSON().Encode()
				return string(bytes)
			}

			chelpers.AfterLobbySpec(so, lobby)
			bytes, _ := models.DecorateLobbyDataJSON(lobby, true).Encode()
			so.Emit("lobbyData", string(bytes))

			bytes, _ = chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 14
0
Arquivo: debug.go Projeto: N1xx1/Helen
func DebugLobbyReady(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, debugLobbyReadyFilter,
		func(param map[string]interface{}) string {
			id := param["id"].(uint)
			lobby, _ := models.GetLobbyById(id)

			var slots []models.LobbySlot
			db.DB.Where("lobby_id = ?", lobby.ID).Find(&slots)
			for _, slot := range slots {
				slot.Ready = true
				db.DB.Save(slot)
			}
			lobby.OnChange(true)

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)

		})
}
Exemplo n.º 15
0
func (Lobby) LobbyServerReset(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, authority.AuthAction(0), true)

	if reqerr != nil {
		return reqerr.Encode()
	}

	var args struct {
		ID *uint `json:"id"`
	}

	if err := chelpers.GetParams(data, &args); err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	player, err := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
	if err != nil {
		return err.Encode()
	}

	lobby, tperr := models.GetLobbyById(*args.ID)

	if player.SteamId != lobby.CreatedBySteamID {
		return helpers.NewTPError("Player not authorized to close lobby.", -1).Encode()

	}

	if tperr != nil {
		return tperr.Encode()
	}

	if lobby.State == models.LobbyStateEnded {
		return helpers.NewTPError("Lobby has ended", 1).Encode()
	}

	if err := models.ReExecConfig(lobby.ID); err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	return chelpers.EmptySuccessJS

}
Exemplo n.º 16
0
func TestLobbyCreation(t *testing.T) {
	migrations.TestCleanup()
	lobby := models.NewLobby("cp_badlands", models.LobbyTypeSixes, models.ServerRecord{0, "testip", ""}, 0)
	lobby.Save()

	lobby2, _ := models.GetLobbyById(lobby.ID)

	assert.Equal(t, lobby.ID, lobby2.ID)
	assert.Equal(t, lobby.ServerInfo.Host, lobby2.ServerInfo.Host)
	assert.Equal(t, lobby.ServerInfo.ID, lobby2.ServerInfo.ID)
	//testing password creation
	assert.Equal(t, len(lobby.Server.ServerPassword), 8)
	lobby3 := models.NewLobby("cp_process_final", models.LobbyTypeSixes, models.ServerRecord{0, "testip", ""}, 0)
	lobby3.Save()
	assert.NotEqual(t, lobby.Server.ServerPassword, lobby3.Server.ServerPassword)

	lobby.MapName = "cp_granary"
	lobby.Save()

	db.DB.First(lobby2)
	assert.Equal(t, "cp_granary", lobby2.MapName)
}
Exemplo n.º 17
0
func (Lobby) LobbySpectatorLeave(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, authority.AuthAction(0), true)

	if reqerr != nil {
		return reqerr.Encode()
	}

	var args struct {
		Id *uint `json:"id"`
	}
	if err := chelpers.GetParams(data, &args); err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	steamId := chelpers.GetSteamId(so.Id())
	player, tperr := models.GetPlayerBySteamId(steamId)
	if tperr != nil {
		return tperr.Encode()
	}

	lob, tperr := models.GetLobbyById(*args.Id)
	if tperr != nil {
		return tperr.Encode()
	}

	if !player.IsSpectatingId(lob.ID) {
		if id, _ := player.GetLobbyId(); id == *args.Id {
			chelpers.AfterLobbySpecLeave(server, so, lob)
			return chelpers.EmptySuccessJS
		}

		return helpers.NewTPError("Player is not spectating", -1).Encode()
	}

	lob.RemoveSpectator(player, true)
	chelpers.AfterLobbySpecLeave(server, so, lob)

	return chelpers.EmptySuccessJS
}
Exemplo n.º 18
0
func PlayerUnready(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, playerUnreadyFilter,
		func(_ map[string]interface{}) string {
			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobbyid, tperr := player.GetLobbyId()
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobby, tperr := models.GetLobbyById(lobbyid)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			helpers.LockRecord(lobby.ID, lobby)
			tperr = lobby.UnreadyPlayer(player)
			helpers.UnlockRecord(lobby.ID, lobby)

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 19
0
func LobbySpectatorJoin(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, lobbySpectatorJoinFilters,
		func(params map[string]interface{}) string {

			lobbyid := params["id"].(uint)

			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			var lob *models.Lobby
			lob, tperr = models.GetLobbyById(uint(lobbyid))

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if id, _ := player.GetLobbyId(); id != lobbyid {
				helpers.LockRecord(lob.ID, lob)
				tperr = lob.AddSpectator(player)
				helpers.UnlockRecord(lob.ID, lob)
			}

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			chelpers.AfterLobbySpec(so, lob)
			models.BroadcastLobbyToUser(lob, player.SteamId)
			return string(bytes)
		})
}
Exemplo n.º 20
0
func (Player) PlayerNotReady(_ *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, authority.AuthAction(0), true)

	if reqerr != nil {
		return reqerr.Encode()
	}

	player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

	if tperr != nil {
		return tperr.Encode()
	}

	lobbyid, tperr := player.GetLobbyId()
	if tperr != nil {
		return tperr.Encode()
	}

	lobby, tperr := models.GetLobbyById(lobbyid)
	if tperr != nil {
		return tperr.Encode()
	}

	if lobby.State != models.LobbyStateReadyingUp {
		return helpers.NewTPError("Lobby hasn't been filled up yet.", 4).Encode()
	}

	tperr = lobby.UnreadyPlayer(player)
	lobby.RemovePlayer(player)

	if tperr != nil {
		return tperr.Encode()
	}

	lobby.UnreadyAllPlayers()
	return chelpers.EmptySuccessJS
}
Exemplo n.º 21
0
func AfterConnectLoggedIn(so socketio.Socket, player *models.Player) {
	lobbyIdPlaying, err := player.GetLobbyId()
	if err == nil {
		lobby, _ := models.GetLobbyById(lobbyIdPlaying)
		AfterLobbyJoin(so, lobby, player)
		AfterLobbySpec(so, lobby)
		models.BroadcastLobbyToUser(lobby, GetSteamId(so.Id()))
		slot := &models.LobbySlot{}
		err := db.DB.Where("lobby_id = ? AND player_id = ?", lobby.ID, player.ID).First(slot).Error
		if err == nil {
			if lobby.State == models.LobbyStateInProgress && !slot.InGame {
				bytes, _ := models.DecorateLobbyConnectJSON(lobby).Encode()
				broadcaster.SendMessage(player.SteamId, "lobbyStart", string(bytes))
			} else if lobby.State == models.LobbyStateReadyingUp && !slot.Ready {
				left := simplejson.New()
				left.Set("timeout", lobby.ReadyUpTimeLeft())
				bytes, _ := left.Encode()
				broadcaster.SendMessage(player.SteamId, "lobbyReadyUp", string(bytes))
			}
		}
	}

	settings, err2 := player.GetSettings()
	if err2 == nil {
		json := models.DecoratePlayerSettingsJson(settings)
		bytes, _ := json.Encode()
		broadcaster.SendMessage(player.SteamId, "playerSettings", string(bytes))
	}

	profilePlayer, err3 := models.GetPlayerWithStats(player.SteamId)
	if err3 == nil {
		json := models.DecoratePlayerProfileJson(profilePlayer)
		bytes, _ := json.Encode()
		broadcaster.SendMessage(player.SteamId, "playerProfile", string(bytes))
	}

}
Exemplo n.º 22
0
func DebugUpdateStatsFilter(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, 0, true)

	if reqerr != nil {
		return reqerr.Encode()
	}

	var args struct {
		Id *uint `json:"id"`
	}

	err := chelpers.GetParams(data, &args)
	if err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	lobby, tperr := models.GetLobbyById(*args.Id)
	if tperr != nil {
		return tperr.Encode()
	}
	lobby.UpdateStats()

	return chelpers.EmptySuccessJS
}
Exemplo n.º 23
0
func ServerInit(server *wsevent.Server, noAuthServer *wsevent.Server) {
	server.OnDisconnect = onDisconnect
	server.Extractor = getEvent

	noAuthServer.OnDisconnect = onDisconnect
	noAuthServer.Extractor = getEvent

	server.On("authenticationTest", func(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
		reqerr := chelpers.FilterRequest(so, 0, true)

		if reqerr != nil {
			bytes, _ := json.Marshal(reqerr)
			return bytes
		}

		bytes, _ := json.Marshal(struct {
			Message string `json:"message"`
		}{"authenticated"})
		return bytes
	})
	//Global Handlers
	server.Register(handler.Global{})
	//Lobby Handlers
	server.Register(handler.Lobby{})
	//server.On("lobbyCreate", handler.LobbyCreate)
	//Player Handlers
	server.Register(handler.Player{})
	//Chat Handlers
	server.Register(handler.Chat{})
	//Admin Handlers
	server.Register(handler.Admin{})
	//Debugging handlers
	// if config.Constants.ServerMockUp {
	// 	server.On("debugLobbyFill", handler.DebugLobbyFill)
	// 	server.On("debugLobbyReady", handler.DebugLobbyReady)
	// 	server.On("debugUpdateStatsFilter", handler.DebugUpdateStatsFilter)
	// 	server.On("debugPlayerSub", handler.DebugPlayerSub)
	// }

	noAuthServer.On("lobbySpectatorJoin", func(s *wsevent.Server, so *wsevent.Client, data []byte) []byte {
		var args struct {
			Id *uint `json:"id"`
		}

		if err := chelpers.GetParams(data, &args); err != nil {
			return helpers.NewTPErrorFromError(err).Encode()
		}

		var lob *models.Lobby
		lob, tperr := models.GetLobbyById(*args.Id)

		if tperr != nil {
			return tperr.Encode()
		}

		chelpers.AfterLobbySpec(s, so, lob)
		bytes, _ := json.Marshal(models.DecorateLobbyData(lob, true))

		so.EmitJSON(helpers.NewRequest("lobbyData", string(bytes)))

		return chelpers.EmptySuccessJS
	})
	noAuthServer.On("getSocketInfo", (handler.Global{}).GetSocketInfo)

	noAuthServer.DefaultHandler = func(_ *wsevent.Server, so *wsevent.Client, data []byte) []byte {
		return helpers.NewTPError("Player isn't logged in.", -4).Encode()
	}
}
Exemplo n.º 24
0
func LobbyJoin(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, lobbyJoinFilters,
		func(params map[string]interface{}) string {
			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobbyid := params["id"].(uint)
			classString := params["class"].(string)
			teamString := params["team"].(string)

			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			//Check if player is in the same lobby
			var sameLobby bool
			if id, err := player.GetLobbyId(); err == nil && id == lobbyid {
				sameLobby = true
			}

			slot, tperr := models.LobbyGetPlayerSlot(lob.Type, teamString, classString)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			helpers.LockRecord(lob.ID, lob)
			defer helpers.UnlockRecord(lob.ID, lob)
			tperr = lob.AddPlayer(player, slot)

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if !sameLobby {
				chelpers.AfterLobbyJoin(so, lob, player)
			}

			if lob.IsFull() {
				lob.State = models.LobbyStateReadyingUp
				lob.Save()
				lob.ReadyUpTimeoutCheck()
				room := fmt.Sprintf("%s_private",
					chelpers.GetLobbyRoom(lob.ID))
				broadcaster.SendMessageToRoom(room, "lobbyReadyUp",
					`{"timeout":30}`)
				models.BroadcastLobbyList()
			}

			models.BroadcastLobbyToUser(lob, player.SteamId)
			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 25
0
func LobbyKick(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, lobbyKickFilters,
		func(params map[string]interface{}) string {
			steamid := params["steamid"].(string)
			ban := params["ban"].(bool)
			lobbyid := params["id"].(uint)
			var self bool

			selfSteamid := chelpers.GetSteamId(so.Id())
			// TODO check authorization, currently can kick anyone
			if steamid == "" {
				self = true
				steamid = selfSteamid
			}

			//player to kick
			player, tperr := models.GetPlayerBySteamId(steamid)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := chelpers.BuildFailureJSON(tperr.Error(), -1).Encode()
				return string(bytes)
			}

			if !self && selfSteamid != lob.CreatedBySteamID {
				// TODO proper authorization checks
				bytes, _ := chelpers.BuildFailureJSON(
					"Not authorized to remove players", 1).Encode()
				return string(bytes)
			}

			_, err := lob.GetPlayerSlot(player)
			helpers.LockRecord(lob.ID, lob)
			defer helpers.UnlockRecord(lob.ID, lob)

			var spec bool
			if err == nil {
				lob.RemovePlayer(player)
			} else if player.IsSpectatingId(lob.ID) {
				spec = true
				lob.RemoveSpectator(player)
			} else {
				bytes, _ := chelpers.BuildFailureJSON("Player neither playing nor spectating", 2).Encode()
				return string(bytes)
			}

			if ban {
				lob.BanPlayer(player)
			}

			if !spec {
				chelpers.AfterLobbyLeave(so, lob, player)
			} else {
				chelpers.AfterLobbySpecLeave(so, lob)
			}

			if !self {
				broadcaster.SendMessage(steamid, "sendNotification",
					fmt.Sprintf("You have been removed from Lobby #%d", lobbyid))

			}

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})
}
Exemplo n.º 26
0
func eventListener(eventChanMap map[string](chan map[string]interface{})) {
	for {
		select {
		case event := <-eventChanMap["playerDisc"]:
			lobbyid := event["lobbyId"].(uint)
			steamId := event["steamId"].(string)

			player, _ := models.GetPlayerBySteamId(steamId)
			lobby, _ := models.GetLobbyById(lobbyid)

			lobby.SetNotInGame(player)

			helpers.Logger.Debug("#%d, player %s<%s> disconnected",
				lobby.ID, player.Name, player.SteamId)

			room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
			broadcaster.SendMessageToRoom(room,
				"sendNotification",
				fmt.Sprintf(`{"notification": "%s has disconected from the server."}`,
					player.Name))
			t := time.After(time.Minute * 2)
			go func() {
				<-t
				lobby, _ := models.GetLobbyById(lobbyid)
				ingame, err := lobby.IsPlayerInGame(player)
				if err != nil {
					helpers.Logger.Error(err.Error())
				}
				if !ingame {
					sub, _ := models.NewSub(lobby.ID, player.SteamId)
					db.DB.Save(sub)
					models.BroadcastSubList()
					lobby.RemovePlayer(player)
				}

			}()

		case event := <-eventChanMap["playerConn"]:
			lobbyid := event["lobbyId"].(uint)
			steamId := event["steamId"].(string)

			player, _ := models.GetPlayerBySteamId(steamId)
			lobby, _ := models.GetLobbyById(lobbyid)

			lobby.SetInGame(player)

		case event := <-eventChanMap["playerSub"]:
			lobbyid := event["lobbyId"].(uint)
			steamId := event["steamId"].(string)

			sub, err := models.NewSub(lobbyid, steamId)
			if err != nil {
				helpers.Logger.Error(err.Error())
				continue
			}
			db.DB.Save(sub)

			models.BroadcastSubList()

			player, _ := models.GetPlayerBySteamId(steamId)
			room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
			broadcaster.SendMessageToRoom(room,
				"sendNotification",
				fmt.Sprintf(`{"notification": "%s has been reported."}`,
					player.Name))

			//helpers.Logger.Debug("#%d: Reported player %s<%s>",
			//	lobbyid, player.Name, player.SteamId)

		case event := <-eventChanMap["discFromServer"]:
			lobbyid := event["lobbyId"].(uint)

			lobby, _ := models.GetLobbyByIdServer(lobbyid)

			helpers.Logger.Debug("#%d: Lost connection to %s", lobby.ID, lobby.ServerInfo.Host)

			lobby.Close(false)
			room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
			broadcaster.SendMessageToRoom(room,
				"sendNotification", `{"notification": "Lobby Closed (Connection to server lost)."}`)

		case event := <-eventChanMap["matchEnded"]:
			lobbyid := event["lobbyId"].(uint)

			lobby, _ := models.GetLobbyByIdServer(lobbyid)

			helpers.Logger.Debug("#%d: Match Ended", lobbyid)

			lobby.UpdateStats()
			lobby.Close(false)
			room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
			broadcaster.SendMessageToRoom(room,
				"sendNotification", `{"notification": ""Lobby Ended."}`)

		case <-eventChanMap["getServers"]:
			var lobbies []*models.Lobby
			var activeStates = []models.LobbyState{models.LobbyStateWaiting, models.LobbyStateInProgress}
			db.DB.Preload("ServerInfo").Model(&models.Lobby{}).Where("state IN (?)", activeStates).Find(&lobbies)
			for _, lobby := range lobbies {
				info := models.ServerBootstrap{
					LobbyId: lobby.ID,
					Info:    lobby.ServerInfo,
				}
				for _, player := range lobby.BannedPlayers {
					info.BannedPlayers = append(info.BannedPlayers, player.SteamId)
				}
				for _, slot := range lobby.Slots {
					var player = &models.Player{}
					db.DB.Find(player, slot.PlayerId)
					info.Players = append(info.Players, player.SteamId)
				}
				models.Pauling.Call("Pauling.SetupVerifier", &info, &struct{}{})
			}
		}
	}
}
Exemplo n.º 27
0
func (Lobby) LobbyJoin(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, authority.AuthAction(0), true)

	if reqerr != nil {
		return reqerr.Encode()

	}

	var args struct {
		Id    *uint   `json:"id"`
		Class *string `json:"class"`
		Team  *string `json:"team" valid:"red,blu"`
	}

	if err := chelpers.GetParams(data, &args); err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}
	//helpers.Logger.Debug("id %d class %s team %s", *args.Id, *args.Class, *args.Team)

	player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

	if tperr != nil {
		return tperr.Encode()
	}

	lob, tperr := models.GetLobbyById(*args.Id)
	if tperr != nil {
		return tperr.Encode()
	}

	if lob.State == models.LobbyStateEnded {
		return helpers.NewTPError("Cannot join a closed lobby.", -1).Encode()

	}

	//Check if player is in the same lobby
	var sameLobby bool
	if id, err := player.GetLobbyId(); err == nil && id == *args.Id {
		sameLobby = true
	}

	slot, tperr := models.LobbyGetPlayerSlot(lob.Type, *args.Team, *args.Class)
	if tperr != nil {
		return tperr.Encode()

	}

	if prevId, err := player.GetLobbyId(); err != nil {
		server.RemoveClient(so.Id(), fmt.Sprintf("%d_public", prevId))
		server.RemoveClient(so.Id(), fmt.Sprintf("%d_private", prevId))
	}

	tperr = lob.AddPlayer(player, slot, *args.Team, *args.Class)

	if tperr != nil {
		return tperr.Encode()
	}

	if !sameLobby {
		chelpers.AfterLobbyJoin(server, so, lob, player)
	}

	if lob.IsFull() {
		lob.State = models.LobbyStateReadyingUp
		lob.ReadyUpTimestamp = time.Now().Unix() + 30
		lob.Save()

		tick := time.After(time.Second * 30)
		id := lob.ID
		stop := make(chan struct{})

		go func() {
			select {
			case <-tick:
				lobby := &models.Lobby{}
				db.DB.First(lobby, id)

				if lobby.State != models.LobbyStateInProgress {
					err := lobby.RemoveUnreadyPlayers()
					if err != nil {
						helpers.Logger.Error("RemoveUnreadyPlayers: ", err.Error())
						err = nil
					}

					err = lobby.UnreadyAllPlayers()
					if err != nil {
						helpers.Logger.Error("UnreadyAllPlayers: ", err.Error())
					}

					lobby.State = models.LobbyStateWaiting
					lobby.Save()
				}

			case <-stop:
				return
			}
		}()

		room := fmt.Sprintf("%s_private",
			chelpers.GetLobbyRoom(lob.ID))
		broadcaster.SendMessageToRoom(room, "lobbyReadyUp",
			`{"timeout":30}`)
		models.BroadcastLobbyList()
	}

	err := models.AllowPlayer(*args.Id, player.SteamId, *args.Team+*args.Class)
	if err != nil {
		helpers.Logger.Error(err.Error())
	}

	if lob.State == models.LobbyStateInProgress {
		bytes, _ := json.Marshal(models.DecorateLobbyConnect(lob, player.Name, *args.Class))
		broadcaster.SendMessage(player.SteamId, "lobbyStart", string(bytes))
	}

	return chelpers.EmptySuccessJS
}
Exemplo n.º 28
0
func SocketInit(so socketio.Socket) {
	chelpers.AuthenticateSocket(so.Id(), so.Request())
	if chelpers.IsLoggedInSocket(so.Id()) {
		steamid := chelpers.GetSteamId(so.Id())
		SteamIdSocketMap[steamid] = &so
	}

	so.On("disconnection", func() {
		chelpers.DeauthenticateSocket(so.Id())
		if chelpers.IsLoggedInSocket(so.Id()) {
			steamid := chelpers.GetSteamId(so.Id())
			delete(SteamIdSocketMap, steamid)
		}
		helpers.Logger.Debug("on disconnect")
	})

	so.On("authenticationTest", chelpers.AuthFilter(so.Id(), func(val string) string {
		return "authenticated"
	}))

	helpers.Logger.Debug("on connection")
	so.Join("-1") //room for global chat

	if chelpers.IsLoggedInSocket(so.Id()) {
		player, err := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
		if err != nil {
			helpers.Logger.Warning("User has a cookie with but a matching player record doesn't exist: %s",
				chelpers.GetSteamId(so.Id()))
			return
		}
		lobbyid, err := player.GetLobbyId()
		if err != nil {
			so.Join(strconv.FormatUint(uint64(lobbyid), 10))
		}
	}

	var lobbyCreateParams = map[string]chelpers.Param{
		"mapName":        chelpers.Param{Type: chelpers.PTypeString},
		"type":           chelpers.Param{Type: chelpers.PTypeString},
		"server":         chelpers.Param{Type: chelpers.PTypeString},
		"rconpwd":        chelpers.Param{Type: chelpers.PTypeString},
		"whitelist":      chelpers.Param{Type: chelpers.PTypeInt},
		"mumbleRequired": chelpers.Param{Type: chelpers.PTypeBool},
	}

	so.On("lobbyCreate", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(lobbyCreateParams, func(js *simplejson.Json) string {

			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			mapName, _ := js.Get("mapName").String()
			lobbytypestring, _ := js.Get("type").String()
			server, _ := js.Get("server").String()
			rconPwd, _ := js.Get("rconpwd").String()
			whitelist, err := js.Get("whitelist").Int()

			var playermap = map[string]models.LobbyType{
				"sixes":      models.LobbyTypeSixes,
				"highlander": models.LobbyTypeHighlander,
			}

			lobbytype, ok := playermap[lobbytypestring]
			if !ok {
				bytes, _ := chelpers.BuildFailureJSON("Lobby type invalid.", -1).Encode()
				return string(bytes)
			}

			//mumble, _ := js.Get("mumbleRequired").Bool()
			//TODO: Configure server here

			//TODO what if playermap[lobbytype] is nil?
			lob := models.NewLobby(mapName, lobbytype,
				models.ServerRecord{Host: server, RconPassword: rconPwd}, whitelist)
			lob.CreatedBy = *player
			err = lob.Save()

			if err != nil {
				bytes, _ := err.(*helpers.TPError).ErrorJSON().Encode()
				return string(bytes)
			}

			// setup server info
			go func() {
				err := lob.TrySettingUp()
				if err != nil {
					SendMessage(chelpers.GetSteamId(so.Id()), "sendNotification", err.Error())
				} else {
					// for debug
					SendMessage(chelpers.GetSteamId(so.Id()), "sendNotification", fmt.Sprintf("Lobby %d created successfully", lob.ID))
				}
			}()

			lobby_id := simplejson.New()
			lobby_id.Set("id", lob.ID)
			bytes, _ := chelpers.BuildSuccessJSON(lobby_id).Encode()
			return string(bytes)
		})))

	var lobbyCloseParams = map[string]chelpers.Param{
		"id": chelpers.Param{Type: chelpers.PTypeInt},
	}

	so.On("lobbyClose", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(lobbyCloseParams, func(js *simplejson.Json) string {
			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			lobbyid, _ := js.Get("id").Uint64()

			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			if player.ID != lob.CreatedByID {
				bytes, _ := chelpers.BuildFailureJSON("Player not authorized to close lobby.", 1).Encode()
				return string(bytes)
			}

			if lob.State == models.LobbyStateEnded {
				bytes, _ := chelpers.BuildFailureJSON("Lobby already closed.", -1).Encode()
				return string(bytes)
			}

			lob.Close()

			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})))

	var lobbyJoinParams = map[string]chelpers.Param{
		"id":    chelpers.Param{Type: chelpers.PTypeInt},
		"class": chelpers.Param{Type: chelpers.PTypeString},
		"team":  chelpers.Param{Type: chelpers.PTypeString},
	}

	so.On("lobbyJoin", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(lobbyJoinParams, func(js *simplejson.Json) string {
			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lobbyid, _ := js.Get("id").Uint64()
			classString, _ := js.Get("class").String()
			teamString, _ := js.Get("team").String()

			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			slot, tperr := chelpers.GetPlayerSlot(lob.Type, teamString, classString)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			tperr = lob.AddPlayer(player, slot)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			so.Join(strconv.FormatUint(lobbyid, 10))
			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})))

	var lobbyRemovePlayerParams = map[string]chelpers.Param{
		"id":      chelpers.Param{Type: chelpers.PTypeInt},
		"steamid": chelpers.Param{Type: chelpers.PTypeString, Default: ""},
		"ban":     chelpers.Param{Type: chelpers.PTypeBool, Default: false},
	}

	so.On("lobbyRemovePlayer", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(lobbyRemovePlayerParams, func(js *simplejson.Json) string {
			steamid, _ := js.Get("steamid").String()
			ban, _ := js.Get("ban").Bool()
			lobbyid, _ := js.Get("id").Int()
			self := false

			// TODO check authorization, currently can kick anyone
			if steamid == "" || steamid == chelpers.GetSteamId(so.Id()) {
				self = true
				steamid = chelpers.GetSteamId(so.Id())
			}

			player, tperr := models.GetPlayerBySteamId(steamid)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := chelpers.BuildFailureJSON(tperr.Error(), -1).Encode()
				return string(bytes)
			}

			if !self && lob.CreatedByID != player.ID {
				// TODO proper authorization checks
				bytes, _ := chelpers.BuildFailureJSON("Not authorized to remove players", 1).Encode()
				return string(bytes)
			}

			_, err := lob.GetPlayerSlot(player)
			if err == nil {
				lob.RemovePlayer(player)
			} else if player.IsSpectatingId(lob.ID) {
				lob.RemoveSpectator(player)
			} else {
				bytes, _ := chelpers.BuildFailureJSON("Player neither playing nor spectating", 2).Encode()
				return string(bytes)
			}

			if ban {
				lob.BanPlayer(player)
			}

			so.Leave(strconv.FormatInt(int64(lobbyid), 10))
			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(bytes)
		})))

	so.On("playerReady", chelpers.AuthFilter(so.Id(), func(val string) string {
		steamid := chelpers.GetSteamId(so.Id())
		player, tperr := models.GetPlayerBySteamId(steamid)
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		lobbyid, tperr := player.GetLobbyId()
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		lobby, tperr := models.GetLobbyById(lobbyid)
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		tperr = lobby.ReadyPlayer(player)
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		if lobby.IsEveryoneReady() {
			bytes, _ := decorators.GetLobbyConnectJSON(lobby).Encode()
			SendMessageToRoom(strconv.FormatUint(uint64(lobby.ID), 10),
				"lobbyStart", string(bytes))
		}

		bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
		return string(bytes)
	}))

	so.On("playerUnready", chelpers.AuthFilter(so.Id(), func(val string) string {
		player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		lobbyid, tperr := player.GetLobbyId()
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		lobby, tperr := models.GetLobbyById(lobbyid)
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		tperr = lobby.UnreadyPlayer(player)
		if tperr != nil {
			bytes, _ := tperr.ErrorJSON().Encode()
			return string(bytes)
		}

		bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
		return string(bytes)
	}))

	var lobbyJoinSpectatorParams = map[string]chelpers.Param{
		"id": chelpers.Param{Type: chelpers.PTypeInt},
	}

	so.On("lobbySpectatorJoin", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(lobbyJoinSpectatorParams, func(js *simplejson.Json) string {
			lobbyid, _ := js.Get("id").Uint64()

			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}
			lob, tperr := models.GetLobbyById(uint(lobbyid))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}
			bytes, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			tperr = lob.AddSpectator(player)
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}
			lob.Save()
			return string(bytes)
		})))

	var playerSettingsGetParams = map[string]chelpers.Param{
		"key": chelpers.Param{Type: chelpers.PTypeString, Default: ""},
	}

	so.On("playerSettingsGet", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(playerSettingsGetParams, func(js *simplejson.Json) string {
			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			key, _ := js.Get("key").String()

			var err error
			var settings []models.PlayerSetting
			var setting models.PlayerSetting
			if key == "" {
				settings, err = player.GetSettings()
			} else {
				setting, err = player.GetSetting(key)
				settings = append(settings, setting)
			}

			if err != nil {
				bytes, _ := chelpers.BuildFailureJSON(err.Error(), 0).Encode()
				return string(bytes)
			}

			result := decorators.GetPlayerSettingsJson(settings)
			resp, _ := chelpers.BuildSuccessJSON(result).Encode()
			return string(resp)
		})))

	var playerSettingsSetParams = map[string]chelpers.Param{
		"key":   chelpers.Param{Type: chelpers.PTypeString},
		"value": chelpers.Param{Type: chelpers.PTypeString},
	}

	so.On("playerSettingsSet", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(playerSettingsSetParams, func(js *simplejson.Json) string {
			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			key, _ := js.Get("key").String()
			value, _ := js.Get("value").String()

			err := player.SetSetting(key, value)
			if err != nil {
				bytes, _ := chelpers.BuildFailureJSON(err.Error(), 0).Encode()
				return string(bytes)
			}

			resp, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(resp)
		})))

	var playerProfileParams = map[string]chelpers.Param{
		"steamid": chelpers.Param{Type: chelpers.PTypeString, Default: ""},
	}

	so.On("playerProfile", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(playerProfileParams, func(js *simplejson.Json) string {
			steamid, _ := js.Get("steamid").String()

			if steamid == "" {
				steamid = chelpers.GetSteamId(so.Id())
			}

			player, playErr := models.GetPlayerWithStats(steamid)

			if playErr != nil {
				bytes, _ := chelpers.BuildFailureJSON(playErr.Error(), 0).Encode()
				return string(bytes)
			}

			result := decorators.GetPlayerProfileJson(player)
			resp, _ := chelpers.BuildSuccessJSON(result).Encode()
			return string(resp)
		})))

	var chatSendParams = map[string]chelpers.Param{
		"message": chelpers.Param{Type: chelpers.PTypeString},
		"room":    chelpers.Param{Type: chelpers.PTypeInt},
	}

	so.On("chatSend", chelpers.AuthFilter(so.Id(),
		chelpers.JsonVerifiedFilter(chatSendParams, func(js *simplejson.Json) string {
			message, _ := js.Get("message").String()
			room, _ := js.Get("room").Int()

			player, tperr := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))
			if tperr != nil {
				bytes, _ := tperr.ErrorJSON().Encode()
				return string(bytes)
			}

			//Check if player has either joined, or is spectating lobby
			lobbyId, tperr := player.GetLobbyId()
			if room > 0 {
				// if room is a lobby room
				if tperr != nil {
					bytes, _ := tperr.ErrorJSON().Encode()
					return string(bytes)
				} else if lobbyId != uint(room) && !player.IsSpectatingId(uint(room)) {
					bytes, _ := chelpers.BuildFailureJSON("Player is not in the lobby.", 5).Encode()
					return string(bytes)
				}
			} else {
				// else room is the lobby list room
				room = -1
			}

			t := time.Now()
			chatMessage := simplejson.New()
			// TODO send proper timestamps
			chatMessage.Set("timestamp", strconv.Itoa(t.Hour())+strconv.Itoa(t.Minute()))
			chatMessage.Set("message", html.EscapeString(message))
			chatMessage.Set("room", room)

			user := simplejson.New()
			user.Set("id", player.SteamId)
			user.Set("name", player.Name)

			chatMessage.Set("user", user)
			bytes, _ := chatMessage.Encode()
			so.BroadcastTo(strconv.Itoa(room), "chatReceive", string(bytes))

			resp, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
			return string(resp)
		})))
}
Exemplo n.º 29
0
func handleEvent(event map[string]interface{}) {
	switch event["name"] {
	case "playerDisc":
		slot := &models.LobbySlot{}
		lobbyid := event["lobbyId"].(uint)
		steamId := event["steamId"].(string)

		player, _ := models.GetPlayerBySteamId(steamId)

		db.DB.Where("player_id = ? AND lobby_id = ?", player.ID, lobbyid).First(slot)
		helpers.LockRecord(slot.ID, slot)
		slot.InGame = false
		db.DB.Save(slot)
		helpers.UnlockRecord(slot.ID, slot)
		room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
		broadcaster.SendMessageToRoom(room,
			"sendNotification", fmt.Sprintf("%s has disconected from the server .",
				player.Name))
		go func() {
			t := time.After(time.Minute * 2)
			<-t
			lobby, _ := models.GetLobbyById(lobbyid)
			slot := &models.LobbySlot{}
			db.DB.Where("player_id = ? AND lobby_id = ?", player.ID, lobbyid).First(slot)
			if !slot.InGame {
				helpers.LockRecord(lobby.ID, lobby)
				defer helpers.UnlockRecord(lobby.ID, lobby)
				lobby.RemovePlayer(player)
				broadcaster.SendMessage(player.SteamId, "sendNotification",
					"You have been removed from the lobby.")
			}

		}()

	case "playerConn":
		slot := &models.LobbySlot{}
		lobbyid := event["lobbyId"].(uint)
		steamId := event["steamId"].(string)

		player, _ := models.GetPlayerBySteamId(steamId)
		err := db.DB.Where("player_id = ? AND lobby_id = ?", player.ID, lobbyid).First(slot).Error
		if err == nil { //else, player isn't in the lobby, will be kicked by Pauling
			helpers.LockRecord(slot.ID, slot)
			slot.InGame = true
			db.DB.Save(slot)
			helpers.UnlockRecord(slot.ID, slot)
		}

	case "playerRep":
		lobbyid := event["lobbyId"].(uint)
		steamId := event["steamId"].(string)

		player, _ := models.GetPlayerBySteamId(steamId)

		var slot *models.LobbySlot
		db.DB.Where("player_id = ? AND lobby_id = ?", player.ID, lobbyid).Find(slot)
		slot.NeedSub = true
		db.DB.Save(slot)
		room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
		broadcaster.SendMessageToRoom(room,
			"sendNotification", fmt.Sprintf("%s has been reported.",
				player.Name))

	case "discFromServer":
		lobbyid := event["lobbyId"].(uint)

		lobby, _ := models.GetLobbyById(lobbyid)
		helpers.LockRecord(lobby.ID, lobby)
		lobby.Close(false)
		helpers.UnlockRecord(lobby.ID, lobby)
		room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
		broadcaster.SendMessageToRoom(room,
			"sendNotification", "Disconnected from Server.")

	case "matchEnded":
		lobbyid := event["lobbyId"].(uint)

		lobby, _ := models.GetLobbyById(lobbyid)
		helpers.LockRecord(lobby.ID, lobby)
		lobby.UpdateStats()
		lobby.Close(false)
		helpers.UnlockRecord(lobby.ID, lobby)
		room := fmt.Sprintf("%s_public", chelpers.GetLobbyRoom(lobbyid))
		broadcaster.SendMessageToRoom(room,
			"sendNotification", "Lobby Ended.")

	case "getServers":
		var lobbies []*models.Lobby
		var activeStates = []models.LobbyState{models.LobbyStateWaiting, models.LobbyStateInProgress}
		db.DB.Model(&models.Lobby{}).Where("state IN (?)", activeStates).Find(&lobbies)
		for _, lobby := range lobbies {
			info := models.ServerBootstrap{
				LobbyId: lobby.ID,
				Info:    lobby.ServerInfo,
			}
			for _, player := range lobby.BannedPlayers {
				info.BannedPlayers = append(info.BannedPlayers, player.SteamId)
			}
			for _, slot := range lobby.Slots {
				var player *models.Player
				db.DB.Find(player, slot.PlayerId)
				info.Players = append(info.Players, player.SteamId)
			}
			models.Pauling.Call("Pauling.SetupVerifier", &info, &struct{}{})
		}
	}
}