Ejemplo n.º 1
0
func PlayerSettingsGet(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, playerSettingsGetFilter,
		func(params map[string]interface{}) string {
			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			key := params["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 := models.DecoratePlayerSettingsJson(settings)
			resp, _ := chelpers.BuildSuccessJSON(result).Encode()
			return string(resp)
		})
}
Ejemplo n.º 2
0
func (Player) PlayerSettingsGet(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, 0, true)

	if reqerr != nil {
		return reqerr.Encode()
	}
	var args struct {
		Key string `json:"key"`
	}

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

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

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

	if err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	result := models.DecoratePlayerSettingsJson(settings)
	resp, _ := chelpers.BuildSuccessJSON(result).Encode()
	return resp
}
Ejemplo n.º 3
0
func (Player) PlayerProfile(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	reqerr := chelpers.FilterRequest(so, 0, true)

	if reqerr != nil {
		return reqerr.Encode()
	}
	var args struct {
		Steamid string `json:"steamid"`
	}

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

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

	player, playErr := models.GetPlayerWithStats(steamid)

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

	result := models.DecoratePlayerProfileJson(player)
	resp, _ := chelpers.BuildSuccessJSON(result).Encode()
	return resp
}
Ejemplo n.º 4
0
Archivo: debug.go Proyecto: 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)

		})
}
Ejemplo n.º 5
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)
		})

}
Ejemplo n.º 6
0
func LobbyCreate(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, lobbyCreateFilters,
		func(params map[string]interface{}) string {

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

			mapName := params["mapName"].(string)
			lobbytypestring := params["type"].(string)
			league := params["league"].(string)
			server := params["server"].(string)
			rconPwd := params["rconpwd"].(string)
			whitelist := int(params["whitelist"].(uint))
			mumble := params["mumbleRequired"].(bool)

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

			lobbytype, _ := playermap[lobbytypestring]

			randBytes := make([]byte, 6)
			rand.Read(randBytes)
			serverPwd := base64.URLEncoding.EncodeToString(randBytes)

			//TODO what if playermap[lobbytype] is nil?
			info := models.ServerRecord{
				Host:           server,
				RconPassword:   rconPwd,
				ServerPassword: serverPwd}
			err := models.VerifyInfo(info)
			if err != nil {
				return err.Error()
			}

			lob := models.NewLobby(mapName, lobbytype, league, info, whitelist, mumble)
			lob.CreatedBySteamID = player.SteamId
			lob.Save()
			err = lob.SetupServer()

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

			lob.State = models.LobbyStateWaiting
			lob.Save()
			lobby_id := simplejson.New()
			lobby_id.Set("id", lob.ID)
			bytes, _ := chelpers.BuildSuccessJSON(lobby_id).Encode()
			return string(bytes)
		})
}
Ejemplo n.º 7
0
Archivo: debug.go Proyecto: 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)
		})
}
Ejemplo 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)
		})
}
Ejemplo n.º 9
0
func RequestLobbyListData(so socketio.Socket) func(string) string {
	return func(s string) string {
		var lobbies []models.Lobby
		db.DB.Where("state = ?", models.LobbyStateWaiting).Order("id desc").Find(&lobbies)
		list, err := models.DecorateLobbyListData(lobbies)
		if err != nil {
			helpers.Logger.Warning("Failed to send lobby list: %s", err.Error())
		} else {
			so.Emit("lobbyListData", list)
		}

		resp, _ := chelpers.BuildSuccessJSON(simplejson.New()).Encode()
		return string(resp)
	}
}
Ejemplo n.º 10
0
Archivo: chat.go Proyecto: N1xx1/Helen
func ChatSend(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, chatSendFilter,
		func(params map[string]interface{}) string {
			message := params["message"].(string)
			room := params["room"].(int)

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

			helpers.Logger.Debug("received chat message: %s %s", message, player.Name)

			spec := player.IsSpectatingId(uint(room))
			//Check if player has either joined, or is spectating lobby
			lobbyId, tperr := player.GetLobbyId()
			if room > 0 {
				if tperr != nil && !spec && lobbyId != 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, _ = strconv.Atoi(config.Constants.GlobalChatRoom)
			}

			chatMessage := simplejson.New()
			// TODO send proper timestamps
			chatMessage.Set("timestamp", time.Now().Unix())
			chatMessage.Set("message", message)
			chatMessage.Set("room", room)

			chatMessage.Set("player", models.DecoratePlayerSummaryJson(player))
			bytes, _ := chatMessage.Encode()
			broadcaster.SendMessageToRoom(fmt.Sprintf("%s_public",
				chelpers.GetLobbyRoom(uint(room))),
				"chatReceive", string(bytes))

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

			chelpers.LogChat(uint(room), player.Name, player.SteamId, message)

			chelpers.AddScrollbackMessage(uint(room), string(bytes))
			return string(resp)
		})
}
Ejemplo n.º 11
0
Archivo: lobby.go Proyecto: 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)
		})
}
Ejemplo n.º 12
0
func PlayerSettingsSet(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, playerSettingsSetFilter,
		func(params map[string]interface{}) string {
			player, _ := models.GetPlayerBySteamId(chelpers.GetSteamId(so.Id()))

			key := params["key"].(string)
			value := params["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)
		})
}
Ejemplo n.º 13
0
func ServerVerify(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, serverVerifyFilters,
		func(params map[string]interface{}) string {
			info := models.ServerRecord{
				Host:         params["server"].(string),
				RconPassword: params["rconpwd"].(string),
			}
			err := models.VerifyInfo(info)
			if err != nil {
				bytes, _ := chelpers.BuildFailureJSON(err.Error(), -1).Encode()
				return string(bytes)
			}

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

		})
}
Ejemplo n.º 14
0
func (Global) GetConstant(server *wsevent.Server, so *wsevent.Client, data []byte) []byte {
	var args struct {
		Constant string `json:"constant"`
	}
	if err := chelpers.GetParams(data, &args); err != nil {
		return helpers.NewTPErrorFromError(err).Encode()
	}

	output := simplejson.New()
	switch args.Constant {
	case "lobbySettingsList":
		output = models.LobbySettingsToJson()
	default:
		return helpers.NewTPError("Unknown constant.", -1).Encode()
	}

	bytes, _ := chelpers.BuildSuccessJSON(output).Encode()
	return bytes
}
Ejemplo n.º 15
0
Archivo: debug.go Proyecto: 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)

		})
}
Ejemplo n.º 16
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)
		})
}
Ejemplo n.º 17
0
func PlayerProfile(so socketio.Socket) func(string) string {
	return chelpers.FilterRequest(so, playerProfileFilter,
		func(params map[string]interface{}) string {

			steamid := params["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 := models.DecoratePlayerProfileJson(player)
			resp, _ := chelpers.BuildSuccessJSON(result).Encode()
			return string(resp)
		})
}
Ejemplo 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)
		})
}
Ejemplo 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)
		})
}
Ejemplo n.º 20
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)
		})
}
Ejemplo n.º 21
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)
		})
}
Ejemplo n.º 22
0
func (Lobby) LobbyCreate(_ *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 {
		Map         *string `json:"map"`
		Type        *string `json:"type" valid:"debug,6s,highlander,4v4,ultiduo,bball"`
		League      *string `json:"league" valid:"ugc,etf2l,esea,asiafortress,ozfortress"`
		Server      *string `json:"server"`
		RconPwd     *string `json:"rconpwd"`
		WhitelistID *uint   `json:"whitelistID"`
		Mumble      *bool   `json:"mumbleRequired"`
	}

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

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

	var playermap = map[string]models.LobbyType{
		"debug":      models.LobbyTypeDebug,
		"6s":         models.LobbyTypeSixes,
		"highlander": models.LobbyTypeHighlander,
		"ultiduo":    models.LobbyTypeUltiduo,
		"bball":      models.LobbyTypeBball,
		"4v4":        models.LobbyTypeFours,
	}

	lobbyType := playermap[*args.Type]

	var count int
	db.DB.Table("server_records").Where("host = ?", *args.Server).Count(&count)
	if count != 0 {
		return helpers.NewTPError("A lobby is already using this server.", -1).Encode()
	}

	randBytes := make([]byte, 6)
	rand.Read(randBytes)
	serverPwd := base64.URLEncoding.EncodeToString(randBytes)

	//TODO what if playermap[lobbytype] is nil?
	info := models.ServerRecord{
		Host:           *args.Server,
		RconPassword:   *args.RconPwd,
		ServerPassword: serverPwd}
	// err = models.VerifyInfo(info)
	// if err != nil {
	// 	bytes, _ := helpers.NewTPErrorFromError(err).Encode()
	// 	return string(bytes)
	// }

	lob := models.NewLobby(*args.Map, lobbyType, *args.League, info, int(*args.WhitelistID), *args.Mumble)
	lob.CreatedBySteamID = player.SteamId
	lob.RegionCode, lob.RegionName = chelpers.GetRegion(*args.Server)
	if (lob.RegionCode == "" || lob.RegionName == "") && config.Constants.GeoIP != "" {
		return helpers.NewTPError("Couldn't find region server.", 1).Encode()
	}
	lob.Save()

	err = lob.SetupServer()
	if err != nil {
		qerr := db.DB.Where("id = ?", lob.ID).Delete(&models.Lobby{}).Error
		if qerr != nil {
			helpers.Logger.Warning(qerr.Error())
		}
		db.DB.Delete(&lob.ServerInfo)
		return helpers.NewTPErrorFromError(err).Encode()
	}

	lob.State = models.LobbyStateWaiting
	lob.Save()

	reply_str := struct {
		ID uint `json:"id"`
	}{lob.ID}

	models.FumbleLobbyCreated(lob)

	bytes, _ := chelpers.BuildSuccessJSON(reply_str).Encode()
	return bytes
}
Ejemplo n.º 23
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)
		})))
}