aboutsummaryrefslogtreecommitdiffstats
path: root/packet/command/a2cprint/a2cprint.go
blob: 01c6051b678a98ea3ff7fec3faf52b34f45434b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package a2cprint

import (
	"github.com/osm/quake/common/buffer"
	"github.com/osm/quake/common/context"
	"github.com/osm/quake/packet/command/ftedownload"
	"github.com/osm/quake/protocol"
)

type Command struct {
	String string

	IsChunkedDownload bool
	Download          *ftedownload.Command
}

func (cmd *Command) Bytes() []byte {
	buf := buffer.New()

	buf.PutByte(protocol.A2CPrint)

	if cmd.IsChunkedDownload && cmd.Download != nil {
		buf.PutBytes(cmd.Download.Bytes())
	} else {
		buf.PutString(cmd.String)
	}

	return buf.Bytes()
}

func Parse(ctx *context.Context, buf *buffer.Buffer) (*Command, error) {
	var err error
	var cmd Command

	bytes, _ := buf.PeekBytes(6)
	cmd.IsChunkedDownload = bytes != nil && string(bytes) == "\\chunk"

	if cmd.IsChunkedDownload {
		cmd.IsChunkedDownload = true

		if cmd.Download, err = ftedownload.Parse(ctx, buf); err != nil {
			return nil, err
		}

	}

	if cmd.String, err = buf.GetString(); err != nil {
		return nil, err
	}

	return &cmd, nil
}