-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
357 lines (311 loc) · 8.76 KB
/
api.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Copyright 2021-22 Kirill Scherba <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Teonet command api module
package teonet
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/kirill-scherba/bslice"
)
// ApiInterface
type ApiInterface interface {
ProcessPacket(p interface{})
}
// addApiReader sets teonet reader. This reader process received API commands
func (teo *Teonet) addApiReader(api ApiInterface) {
if api == nil {
return
}
teo.clientReaders.add(func(teo *Teonet, c *Channel, p *Packet, e *Event) (ret bool) {
// Process API commands
if e.Event == EventData {
api.ProcessPacket(p.setCommandMode())
}
return
})
}
// APInterface is teonet api interface
type APInterface interface {
Name() string
Short() string
Long() string
Usage() string
Ret() string
Cmd() byte
ExecMode() (APIconnectMode, APIanswerMode)
Reader(c *Channel, p *Packet, data []byte) bool
Reader2(data []byte, answer func(data []byte)) bool
}
// API teonet api receiver
type API struct {
*Teonet
name string // API (application) name
short string // API short name
long string // API decription (or long name)
version string // API version
cmds []APInterface // API commands
cmd byte // API cmdApi command number
bslice.ByteSlice
}
// APIconnectMode connection type of received command:
//
// Server: execute command if there is server connection;
// Client: execute command if there is client connection;
// Both: execute command if there is any server or client connection
//
// Server connection mode: any Peer connected to this application with function
// ConnectTo (and Peer send commands to this application). Client connection mode:
// this application connected to Peer with function ConnectTo (and Peer send
// commands to this application)
type APIconnectMode byte
const (
// ServerMode - execute command if there is server connection
ServerMode APIconnectMode = 1 << iota
// ClientMode - execute command if there is client connection
ClientMode
// AnyMode - execute command if there is any server or client connection
AnyMode = ClientMode & ServerMode
)
// APIexecMode how to answer to this command will be send. Constan may be
// combined, f.e. answer with Command and ID and Data:
// answerMode = CmdAnswer | PacketIDAnswer | DataAnswer
type APIanswerMode byte
const (
// DataAnswer - send data in answer
DataAnswer APIanswerMode = 1 << iota
// CmdAnswer - send command in answer
CmdAnswer
// PacketIDAnswer - send received packet ID in answer
PacketIDAnswer
// NoAnswer - answer does not send
NoAnswer APIanswerMode = 0
)
// MakeAPI is teonet API interface builder
func MakeAPI(name, short, long, usage, ret string, cmd byte,
execMode APIconnectMode, answerMode APIanswerMode,
reader func(c *Channel, p *Packet, data []byte) bool,
reader2 func(data []byte, answer func(data []byte)) bool,
) APInterface {
apiData := &APIData{
name: name,
short: short,
long: long,
usage: usage,
ret: ret,
cmd: cmd,
reader: reader,
reader2: reader2,
connectMode: execMode,
answerMode: answerMode,
}
return apiData
}
// MakeAPI2 is second teonet API interface builder
func MakeAPI2() *APIData {
return &APIData{
connectMode: ServerMode,
answerMode: CmdAnswer,
reader: func(c *Channel, p *Packet, data []byte) bool {
return true
},
reader2: func(data []byte, answer func(data []byte)) bool {
return true
},
}
}
// NewAPI create new teonet api
func (teo *Teonet) NewAPI(name, short, long, version string, cmdAPIs ...byte) (api *API) {
api = &API{
Teonet: teo,
name: name,
short: short,
long: long,
version: version,
}
var cmdApi APInterface
var cmd byte = CmdServerAPI
if len(cmdAPIs) > 0 {
cmd = cmdAPIs[0]
}
cmdApi = MakeAPI2().SetName("api").SetCmd(cmd).SetShort("get api").SetReturn("<api APIDataAr>").
SetConnectMode(AnyMode).SetAnswerMode(CmdAnswer).
SetReader(func(c *Channel, p *Packet, data []byte) bool {
log.Debug.Println("got api request, cmd:", cmdApi.Cmd(), p.From())
outData, _ := api.MarshalBinary()
api.SendAnswer(cmdApi, c, outData, p)
return true
})
api.Add(cmdApi)
return api
}
// Short get app short name
func (a API) Short() string {
return a.short
}
// Send answer to request
func (a *API) SendAnswer(cmd APInterface, c *Channel, data []byte, p *Packet) (id uint32, err error) {
// Get answer mode
_, answerMode := cmd.ExecMode()
if answerMode&PacketIDAnswer > 0 {
id := make([]byte, 4)
binary.LittleEndian.PutUint32(id, uint32(p.ID()))
data = append(id, data...)
}
// Send answer
if answerMode&CmdAnswer > 0 {
a.Command(cmd.Cmd(), data).Send(c)
} else {
c.Send(data)
}
return
}
// Send answer to request
func (a *API) SendAnswer2(data []byte, answer func(data []byte)) (id uint32, err error) {
answer(data)
return
}
// Cmd return API command number and save this command to use in CmdNext
func (a *API) Cmd(cmd byte) byte {
a.cmd = cmd
return cmd
}
// CmdNext return next API command number
func (a *API) CmdNext() byte {
a.cmd++
return a.cmd
}
// Add api command
func (a *API) Add(cmds ...APInterface) {
a.cmds = append(a.cmds, cmds...)
}
// Reader process teonet commands as described in API
func (a API) Reader() func(c *Channel, p *Packet, e *Event) (processed bool) {
return func(c *Channel, p *Packet, e *Event) (processed bool) {
// Skip not Data Events
if e.Event != EventData {
return
}
// Execute reader
return a.readerExec(
p.Data(),
func(i int) bool { return a.canExecute(a.cmds[i], c) },
func(i int, data []byte) bool { return a.cmds[i].Reader(c, p, data) },
)
}
}
// Reader2 process not teonet (webrtc for example) commands as described in API
func (a API) Reader2() func(data []byte, answer func(data []byte)) (processed bool) {
return func(data []byte, answer func(data []byte)) (processed bool) {
return a.readerExec(
data,
func(i int) bool { return true },
func(i int, data []byte) bool { return a.cmds[i].Reader2(data, answer) },
)
}
}
// readerExec parce and execute command
func (a API) readerExec(data []byte, canExecute func(i int) bool,
execute func(i int, data []byte) bool) (processed bool) {
// Parse command
cmd := a.Command(data)
// Select and Execute commands readers
for i := range a.cmds {
switch {
// Check if we can execute this command depend of ExecMode
case !canExecute(i):
continue
// Check command number
case a.cmds[i].Cmd() != cmd.Cmd:
continue
// Execute command
case execute(i, cmd.Data):
return true
}
// All done in 'unic command mode' when only one command with this
// number may be added
break
}
return
}
// String return strin with api commands
func (a API) Help(shorts ...bool) (str string) {
var short bool
if len(shorts) > 0 {
short = shorts[0]
}
// Calculate name lenngth
var max int
for i := range a.cmds {
if l := len(a.cmds[i].Name()); l > max {
max = l
}
}
// Create output string
for i := range a.cmds {
if i > 0 {
str += "\n"
if !short {
str += "\n"
}
}
if short {
str += fmt.Sprintf("%-*s %3d - %s", max, a.cmds[i].Name(), a.cmds[i].Cmd(), a.cmds[i].Short())
continue
}
str += fmt.Sprintf("%-*s %s\n", max, a.cmds[i].Name(), a.cmds[i].Short())
str += fmt.Sprintf("%*s command: %d\n", max, "", a.cmds[i].Cmd())
str += fmt.Sprintf("%*s usage: %s\n", max, "", a.cmds[i].Name()+" "+a.cmds[i].Usage())
str += fmt.Sprintf("%*s return: %s", max, "", a.cmds[i].Ret())
}
return
}
// String is API stringlify, it return help text in string
func (a API) String() (str string) {
return a.Help()
}
// canExecute check can execute this command
func (a API) canExecute(api APInterface, c *Channel) bool {
connectMode, _ := api.ExecMode()
switch connectMode {
case AnyMode:
return true
case ServerMode:
return c.ServerMode()
case ClientMode:
return c.ClientMode()
}
return false
}
// makeAPIData make APIData struct
func (a API) makeAPIData(in APInterface) (ret *APIData) {
connectMode, answerMode := in.ExecMode()
ret = &APIData{
name: in.Name(),
short: in.Short(),
long: in.Long(),
usage: in.Usage(),
ret: in.Ret(),
cmd: in.Cmd(),
connectMode: connectMode,
answerMode: answerMode,
}
return
}
// MarshalBinary binary marshal API
func (a API) MarshalBinary() (data []byte, err error) {
buf := new(bytes.Buffer)
a.WriteSlice(buf, []byte(a.name))
a.WriteSlice(buf, []byte(a.short))
a.WriteSlice(buf, []byte(a.long))
a.WriteSlice(buf, []byte(a.version))
numCmds := uint16(len(a.cmds))
binary.Write(buf, binary.LittleEndian, numCmds)
for i := range a.cmds {
data, _ := a.makeAPIData(a.cmds[i]).MarshalBinary()
binary.Write(buf, binary.LittleEndian, data)
}
data = buf.Bytes()
return
}