-
Notifications
You must be signed in to change notification settings - Fork 21
/
cmd.go
115 lines (98 loc) · 2.45 KB
/
cmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package ts3
import (
"fmt"
"strings"
)
// Cmd represents a TeamSpeak 3 ServerQuery command.
type Cmd struct {
cmd string
args []CmdArg
options []string
response interface{}
}
// NewCmd creates a new Cmd.
func NewCmd(cmd string) *Cmd {
return &Cmd{cmd: cmd}
}
// WithArgs sets the command Args.
func (c *Cmd) WithArgs(args ...CmdArg) *Cmd {
c.args = args
return c
}
// WithOptions sets the command Options.
func (c *Cmd) WithOptions(options ...string) *Cmd {
c.options = options
return c
}
// WithResponse sets the command Response which will have the data returned from the server decoded into it.
func (c *Cmd) WithResponse(r interface{}) *Cmd {
c.response = r
return c
}
func (c *Cmd) String() string {
args := make([]interface{}, 1, len(c.args)+len(c.options)+1)
args[0] = c.cmd
for _, v := range c.args {
args = append(args, v.ArgString())
}
for _, v := range c.options {
args = append(args, v)
}
return fmt.Sprintln(args...)
}
// CmdArg is implemented by types which can be used as a command argument.
type CmdArg interface {
ArgString() string
}
// ArgGroup represents a group of TeamSpeak 3 ServerQuery command arguments.
type ArgGroup struct {
grp []CmdArg
}
// NewArgGroup returns a new ArgGroup.
func NewArgGroup(args ...CmdArg) *ArgGroup {
return &ArgGroup{grp: args}
}
// ArgString implements CmdArg.
func (ag *ArgGroup) ArgString() string {
args := make([]string, len(ag.grp))
for i, arg := range ag.grp {
args[i] = arg.ArgString()
}
return strings.Join(args, "|")
}
// ArgSet represents a set of TeamSpeak 3 ServerQuery command arguments.
type ArgSet struct {
set []CmdArg
}
// NewArgSet returns a new ArgSet.
func NewArgSet(args ...CmdArg) *ArgSet {
return &ArgSet{set: args}
}
// ArgString implements CmdArg.
func (ag *ArgSet) ArgString() string {
args := make([]string, len(ag.set))
for i, arg := range ag.set {
args[i] = arg.ArgString()
}
return strings.Join(args, " ")
}
// Arg represents a TeamSpeak 3 ServerQuery command argument.
// Args automatically escape white space and special characters before being sent to the server.
type Arg struct {
key string
val string
}
// NewArg returns a new Arg with key val.
func NewArg(key string, val interface{}) *Arg {
switch val {
case false:
val = "0"
case true:
val = "1"
}
return &Arg{key: key, val: fmt.Sprint(val)}
}
// ArgString implements CmdArg.
func (a *Arg) ArgString() string {
return fmt.Sprintf("%v=%v", encoder.Replace(a.key), encoder.Replace(a.val))
}