handlers

package
v0.0.0-...-c40e111 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2024 License: GPL-3.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const MaxPayloadLength = 4096

Variables

View Source
var ChangePasswordHandler = &handler.Handler{
	Description: "Changes the lobby password",
	Syntax:      "(password?)",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundMax(1)),
	StateLevel:  util.StateAny,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, args []string) error {
		var newPass string
		if len(args) > 0 {
			newPass = args[0]
		}
		game.Password = newPass
		log.Debugf("changed password for game '%s' to '%s'", game.ID, newPass)
		return model.NewResponse("CHANGE_PASS").Respond(conn)
	}),
}
View Source
var ChangePermissionHandler = &handler.Handler{
	Description: "Changes the enhanced permission for the game",
	Syntax:      "(permission!)",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundExact(1)),
	StateLevel:  util.StateAny,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) (err error) {
		var value int
		if value, err = strconv.Atoi(message[0]); err != nil {
			return
		}
		game.Preferences.Permissions = model.EnhancedPermission(uint8(value))
		game.Broadcast(model.PPreferences(game.Preferences))
		game.BroadcastTopicListToLeaders()
		return nil
	}),
}
View Source
var ChangePreferenceHandler = &handler.Handler{
	Description: "Changes a game-setting",
	Syntax:      `{ "key": (key!), "value": (value!)" }`,
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundMin(1)),
	StateLevel:  util.StateAny,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, args []string) (err error) {
		data := []byte(strings.Join(args, " "))
		type changePreferencesPayload struct {
			Key   string      `json:"key"`
			Value interface{} `json:"value"`
		}
		var payload changePreferencesPayload
		if err = json.Unmarshal(data, &payload); err != nil {
			return
		}
		switch payload.Key {
		case "AutoSkip":
			i, ok := payload.Value.(bool)
			if !ok {
				return gerrors.ErrTypeInvalid
			}
			game.Preferences.AutoSkip = i
		case "ShuffleTopics":
			i, ok := payload.Value.(bool)
			if !ok {
				return gerrors.ErrTypeInvalid
			}
			game.Preferences.ShuffleTopics = i
		default:
			return gerrors.ErrUnknownPreference
		}

		game.Broadcast(model.PPreferences(game.Preferences))
		return nil
	}),
}
View Source
var ChatHandler = &handler.Handler{
	Description: "Sends a chat message",
	Syntax:      "(...message!)",
	AccessLevel: handler.AccessJoined,
	Bounds:      util.Bounds(util.BoundMin(1)),
	StateLevel:  util.StateAny,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) error {
		msg := strings.TrimSpace(strings.Join(message, " "))

		if len(msg) < 2 {
			return gerrors.ErrChatMessageTooShort
		}

		if len(msg) > 100 {
			return gerrors.ErrChatMessageTooLong
		}

		if chat, ok := chats[client]; ok {
			if time.Since(chat.Time) < 1*time.Second {
				return gerrors.ErrChatMessageTooFast
			}
			if strings.EqualFold(chat.Previous, msg) {
				return gerrors.ErrChatMessageRepeat
			}
		}
		chats[client] = &chatSpam{msg, time.Now()}
		game.Broadcast(model.PChat(client, msg))
		return nil
	}),
}
View Source
var EndGameHandler = &handler.Handler{
	Description: "Ends the Game (skips to the result screen)",
	Syntax:      "",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateInGame,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return game.ForceEndGame("Ended by Host")
	}),
}
View Source
var ExplainHandler = &handler.Handler{
	Description: "Returns help for a handler",
	Syntax:      "(handler!)",
	AccessLevel: handler.AccessAny,
	Bounds:      util.Bounds(util.BoundExact(1)),
	StateLevel:  util.StateAny,
	Handler: handler.HandlersHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, msg []string, handlers map[string]*handler.Handler) error {
		name := strings.ToUpper(msg[0])
		h, ok := handlers[name]
		if !ok {
			return gerrors.ErrInvalidHandler
		}
		var bob util.Bob
		stringify.HandlerToString(&bob, name, h)
		return model.NewResponse("EXPLAIN", util.WrapStringArray(strings.Split(bob.String(), "\n")...)...).Respond(conn)
	}),
	DevOnly: true,
}
View Source
var Handlers = map[string]*handler.Handler{
	"WHOAMI":        WhoAmIHandler,
	"JOIN":          JoinHandler,
	"LIST":          ListHandler,
	"CHAT":          ChatHandler,
	"TOPIC_LIST":    TopicListHandler,
	"TOPIC_ADD":     TopicAddHandler,
	"TOPIC_ADD_ALL": TopicAddAllHandler,
	"TOPIC_REMOVE":  TopicRemoveHandler,
	"TOPIC_CLEAR":   TopicClearHandler,
	"START":         StartHandler,
	"SKIP":          SkipHandler,
	"SUBMIT_GIF":    SubmitGIFHandler,
	"VOTE":          VoteCastHandler,
	"NEXT_ROUND":    NextRoundHandler,
	"STATS":         StatsHandler,
	"CHANGE_PREF":   ChangePreferenceHandler,
	"EXPLAIN":       ExplainHandler,
	"PERM":          ChangePermissionHandler,
	"CHANGE_PASS":   ChangePasswordHandler,
	"KICK":          KickPlayerHandler,
	"END_GAME":      EndGameHandler,
}
View Source
var JoinHandler = &handler.Handler{
	Description: "Joins a game with a username",
	Syntax:      "(username!)",
	AccessLevel: handler.AccessGuest,
	Bounds:      util.Bounds(util.BoundMin(1), util.BoundMax(2)),
	StateLevel:  util.StateAny,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) error {

		if len(game.Clients) >= game.Preferences.MaxPlayers {
			return gerrors.ErrTooManyPlayers
		}

		if game.Password != "" {
			if len(message) != 2 || message[1] != game.Password {
				return gerrors.ErrInvalidPassword
			}
		}

		username := strings.TrimSpace(message[0])

		if !util.IsNameValid(username) {
			return gerrors.ErrNameInvalid
		}

		for _, c := range game.Clients {
			if strings.EqualFold(c.Name, username) {
				return gerrors.ErrNameExists
			}
		}

		if client != nil {
			if client.Name != "" {

				return gerrors.ErrAlreadyJoined
			}
			client.Name = username
		} else {
			client = model.NewClient(conn, username)

			game.Clients[client.Name] = client
		}

		log.Infof("[%s] %s joined", game.ID, client.Name)

		if len(game.Clients) == 1 {
			game.SetLeader(client)
		}

		game.Broadcast(model.PJoin(client, game))
		game.Broadcast(model.PList(game.Clients))
		game.Broadcast(model.PState(game.State()))

		if util.StateInGame.Contains(game.State()) {
			game.Broadcast(model.PStats(game))
			game.BroadcastWaitingFor()

			if topic := game.CurrentTopic; topic != nil {

				if util.StateShowVotes.In(game.State()) {
					results := topic.Submissions.AsArray().Results()
					_ = model.PVoteResults(results...).Respond(conn)
				} else {

					if util.StateSubmitGIF.In(game.State()) {
						_ = model.PNextRound(topic.Description, game.Topics.PlayedTopicsCount(), len(game.Topics)).Respond(conn)
					}
					if util.StateCastVotes.In(game.State()) {
						submissions := topic.Submissions.AllExceptFrom(client)
						urls := submissions.URLs()

						rand.Shuffle(len(urls), func(i, j int) {
							urls[i], urls[j] = urls[j], urls[i]
						})
						_ = model.PVoteStart(urls...).Respond(conn)
					}
				}
			}
		}

		if game.Preferences.Permissions&model.PermissionListTopics == model.PermissionListTopics {
			_ = model.PTopicList(game).Respond(conn)
		}

		return model.PPreferences(game.Preferences).Respond(conn)
	}),
}
View Source
var KickPlayerHandler = &handler.Handler{
	Description: "Kicks a player from the game",
	Syntax:      "(player!)",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundExact(1)),
	StateLevel:  util.StateAny,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, msg []string) error {

		kick, ok := game.Clients[msg[0]]
		if !ok {
			return gerrors.ErrClientNotFound
		}
		if kick == client {
			return gerrors.ErrSelf
		}

		game.KickClient(kick)
		return nil
	}),
}
View Source
var ListHandler = &handler.Handler{
	Description: "Returns a list of all connected players from the current game",
	Syntax:      "",
	AccessLevel: handler.AccessJoined,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateAny,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return model.PList(game.Clients).Respond(conn)
	}),
}
View Source
var NextRoundHandler = &handler.Handler{
	Description: "Starts the next round (displays the next topic)",
	Syntax:      "",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateShowVotes,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return game.ForceNextRound()
	}),
}
View Source
var SkipHandler = &handler.Handler{
	Description: "Skips to the next game circle",
	Syntax:      "",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateInGame,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return game.CheckCycle(false, true)
	}),
}
View Source
var SpacesRegEx = regexp.MustCompile(`\s+`)
View Source
var StartHandler = &handler.Handler{
	Description: "Starts a game",
	Syntax:      "",
	AccessLevel: handler.AccessLeader,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateLobby,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {

		if len(game.Topics) < game.Preferences.MinTopics {
			return gerrors.ErrTooFewTopics
		}

		if len(game.Topics) > game.Preferences.MaxTopics {
			return gerrors.ErrTooManyTopics
		}

		if len(game.Clients) < game.Preferences.MinPlayers {
			return gerrors.ErrTooFewPlayers
		}

		if len(game.Clients) > game.Preferences.MaxPlayers {
			return gerrors.ErrTooManyPlayers
		}

		game.Broadcast(model.PStart())
		return game.ForceNextRound()
	}),
}
View Source
var StatsHandler = &handler.Handler{
	Description: "Returns the points for each player",
	Syntax:      "",
	AccessLevel: handler.AccessJoined,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateInGame & ^util.StateCastVotes,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return model.PStats(game).Respond(conn)
	}),
}
View Source
var SubmitGIFHandler = &handler.Handler{
	Description: "Submits a GIF",
	Syntax:      "(url!)",
	AccessLevel: handler.AccessJoined,
	Bounds:      util.Bounds(util.BoundExact(1)),
	StateLevel:  util.StateSubmitGIF,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) error {
		if game.CurrentTopic == nil {
			return gerrors.ErrTopicNotFound
		}
		topic := game.CurrentTopic
		url := message[0]

		if sub, found, err := topic.Submissions.ByURLLoose(url); found || err != nil {
			if err != nil {
				return err
			}
			if sub.Creator == client {
				return gerrors.ErrAlreadySubmitted
			}
			return gerrors.ErrGIFTaken
		}

		if allowed, err := util.IsURLAllowed(url); err != nil {
			return err
		} else if !allowed {
			return gerrors.ErrGIFNotAllowed
		}

		sub := model.NewSubmission(client, url)
		topic.Submissions[client.Name] = sub

		game.Broadcast(model.PSubmitGIF(client))

		return game.CheckCycle(true, false)
	}),
}
View Source
var TopicAddAllHandler = &handler.Handler{
	Description:  "Adds all topics from a JSON array",
	Syntax:       "(...topics: Array<string>!)",
	AccessLevel:  handler.AccessLeader,
	EnhancedPerm: model.PermissionCreateTopics,
	Bounds:       util.Bounds(util.BoundMin(1)),
	StateLevel:   util.StateLobby,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) (err error) {
		data := strings.Join(message, " ")
		var topics []string
		if err = json.Unmarshal([]byte(data), &topics); err != nil {
			return
		}

		defer game.BroadcastTopicListToLeaders()

		for _, t := range topics {
			t = strings.TrimSpace(t)
			if t == "" {
				continue
			}
			if game.Topics.Exists(t) {
				continue
			}

			if len(game.Topics) >= game.Preferences.MaxTopics {
				return gerrors.ErrTooManyTopics
			}
			game.Topics.Add(t)
		}
		return nil
	}),
}
View Source
var TopicAddHandler = &handler.Handler{
	Description:  "Adds a new topic to the game",
	Syntax:       "(topic!)",
	AccessLevel:  handler.AccessLeader,
	EnhancedPerm: model.PermissionCreateTopics,
	Bounds:       util.Bounds(util.BoundMin(1)),
	StateLevel:   util.StateLobby,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) error {
		if len(game.Topics) >= game.Preferences.MaxTopics {
			return gerrors.ErrTooManyTopics
		}

		defer game.BroadcastTopicListToLeaders()

		topic := strings.TrimSpace(strings.Join(message, " "))
		if game.Topics.Exists(topic) {
			return gerrors.ErrTopicAlreadyExists
		}
		game.Topics.Add(topic)
		return model.PTopicAdd(topic).Respond(conn)
	}),
}
View Source
var TopicClearHandler = &handler.Handler{
	Description:  "Removes all topics from the current game",
	Syntax:       "",
	AccessLevel:  handler.AccessLeader,
	EnhancedPerm: model.PermissionDeleteTopics,
	Bounds:       util.Bounds(util.BoundExact(0)),
	StateLevel:   util.StateLobby,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {

		defer game.BroadcastTopicListToLeaders()

		game.Topics.Clear()
		return nil
	}),
}
View Source
var TopicListHandler = &handler.Handler{
	Description:  "Returns a list with all topics from the current game",
	Syntax:       "",
	AccessLevel:  handler.AccessLeader,
	EnhancedPerm: model.PermissionListTopics,
	Bounds:       util.Bounds(util.BoundExact(0)),
	StateLevel:   util.StateAny,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return model.PTopicList(game).Respond(conn)
	}),
}
View Source
var TopicRemoveHandler = &handler.Handler{
	Description:  "Removes a topic from the game",
	Syntax:       "(topic!)",
	AccessLevel:  handler.AccessLeader,
	EnhancedPerm: model.PermissionDeleteTopics,
	Bounds:       util.Bounds(util.BoundMin(1)),
	StateLevel:   util.StateLobby,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) error {
		topic := strings.TrimSpace(strings.Join(message, " "))
		if !game.Topics.Exists(topic) {
			return gerrors.ErrTopicNotFound
		}

		defer game.BroadcastTopicListToLeaders()

		game.Topics.Delete(topic)
		return model.PTopicRemove(topic).Respond(conn)
	}),
}
View Source
var VoteCastHandler = &handler.Handler{
	Description: "Votes for a submission",
	Syntax:      "(url!)",
	AccessLevel: handler.AccessJoined,
	Bounds:      util.Bounds(util.BoundExact(1)),
	StateLevel:  util.StateCastVotes,
	Handler: handler.MessagedHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client, message []string) error {
		if game.CurrentTopic == nil {
			return gerrors.ErrTopicNotFound
		}
		topic := game.CurrentTopic
		u := message[0]

		// get submission for URL
		var (
			submission *model.Submission
			found      bool
		)
		if submission, found = topic.Submissions.ByURL(u); !found {
			return gerrors.ErrSubmissionNotFound
		}

		if submission.Creator == client {
			return gerrors.ErrVoteSelf
		}

		for _, sub := range topic.Submissions {
			sub.Voters.Delete(client)
		}

		submission.Voters = append(submission.Voters, client)

		return game.CheckCycle(true, false)
	}),
}
View Source
var WhoAmIHandler = &handler.Handler{
	Description: "Returns information about the client and game",
	Syntax:      "",
	AccessLevel: handler.AccessAny,
	Bounds:      util.Bounds(util.BoundExact(0)),
	StateLevel:  util.StateAny,
	DevOnly:     true,
	Handler: handler.BasicHandler(func(conn *websocket.Conn, game *model.Game, client *model.Client) error {
		return model.NewResponse("WHOAMI", "YOU", client, "GAME", game).Respond(conn)
	}),
}

Functions

func JanitorChatChats

func JanitorChatChats()

func OnClientMessage

func OnClientMessage(conn *websocket.Conn, game *model.Game, msg string, devMode bool) error

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址