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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
|
//
// rhimportd
//
// The Radio Helsinki Rivendell Import Daemon
//
//
// Copyright (C) 2015 Christian Pointner <equinox@helsinki.at>
//
// This file is part of rhimportd.
//
// rhimportd is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// rhimportd is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rhimportd. If not, see <http://www.gnu.org/licenses/>.
//
package main
import (
"bufio"
"fmt"
"helsinki.at/rhimport"
"net"
"net/http"
"strconv"
"strings"
)
const (
prompt = "> "
)
type TelnetClient struct {
conn net.Conn
scanner *bufio.Scanner
writer *bufio.Writer
conf *rhimport.Config
rddb *rhimport.RdDbChan
ctx *rhimport.ImportContext
}
func (c *TelnetClient) write_string(text string) (err error) {
if _, err = c.writer.WriteString(text); err != nil {
return
}
return c.writer.Flush()
}
func (c *TelnetClient) say(format string, a ...interface{}) (err error) {
return c.write_string(fmt.Sprintf(format, a...) + "\n")
}
func (c *TelnetClient) handle_cmd_help(args []string) {
switch len(args) {
case 1:
switch args[0] {
case "quit":
c.say("usage: quit")
c.say(" terminates the client connection.")
return
case "help":
c.say("usage: help [ <cmd> ]")
c.say(" prints command overview or detailed info to <cmd>.")
return
case "set":
c.say("usage: set <param> <value>")
c.say(" this sets the import parameter <param> to <value>.")
c.say("")
c.say(" available parameters:")
c.say(" UserName string username to use for rdxport interface")
c.say(" Password string password to use for rdxport interface")
c.say(" SourceUri string uri to the file to import")
c.say(" ShowId uint the RHRD show id to import to")
c.say(" ClearShowCarts bool clear all show-carts before importing?")
c.say(" GroupName string name of music-pool group to import to")
c.say(" Cart uint cart to import to")
c.say(" ClearCart bool remove/add cart before import")
c.say(" Cut uint cut to import to")
c.say(" Channels uint number of audio channels (default: %v)", c.conf.ImportParamDefaults.Channels)
c.say(" NormalizationLevel int normalization level in dB (default: %v)", c.conf.ImportParamDefaults.NormalizationLevel)
c.say(" AutotrimLevel int autotrim level in dB (default: %v)", c.conf.ImportParamDefaults.AutotrimLevel)
c.say(" UseMetaData bool extract meta data from file (default: %v)", c.conf.ImportParamDefaults.UseMetaData)
c.say("")
c.say(" UserName, Password and SourceUri are mandatory parameters.")
c.say("")
c.say(" If ShowId is supplied GroupName, Channels, NomalizationLevel, AutorimLevel,")
c.say(" UseMetaData and Cut will be ignored. The values from the shows' dropbox will")
c.say(" be used instead. Cart may be specified but must point to an empty cart within")
c.say(" that show. If ClearCut is true the specified cart will get deleted before")
c.say(" importing. If Cart is 0 the next free cart in the show will be used. Show")
c.say(" carts will always be imported into cut 1.")
c.say("")
c.say(" If GroupName is supplied Channels, NomalizationLevel, AutorimLevel,")
c.say(" UseMetaData, Cut, Cart and ClearCart will be ignored. The values from")
c.say(" the music pools' dropbox will be used instead. The file will always be")
c.say(" imported into cut 1 of the first free cart within the music pool.")
c.say("")
c.say(" If ShowId and GroupName are omitted a Cart must be specified. Cut may be")
c.say(" supplied in which case both cart and cut must already exist. The import will")
c.say(" then replace the contents of the current data stored in Cart/Cut. If only Cart")
c.say(" and no Cut is supplied and ClearCut is false the file will either get imported")
c.say(" into the next cut of an existing cart or the cart will be created and the file")
c.say(" will be imported into cut 1 of this cart.")
c.say("")
c.say(" In case of an error carts/cuts which might got created will be removed. Carts")
c.say(" which got deleted because of ClearShowCarts or ClearCart are however gone for")
c.say(" good.")
return
case "show":
c.say("usage: show")
c.say(" this prints the current values of all import parameters.")
return
case "reset":
c.say("usage: reset")
c.say(" this resets all import parameters to default values.")
return
case "run":
c.say("usage: run")
c.say(" this starts the fetch/import process according to the current")
c.say(" import parameters.")
return
}
fallthrough
default:
c.say("usage: <cmd> [ [ <arg1> ] ... ]")
c.say(" available commands:")
c.say(" quit close connection")
c.say(" help [ <cmd> ] print this, or help for specific command")
c.say(" set <param> <value> sets parameter <param> on current import context")
c.say(" show shows current import context")
c.say(" reset resets current import context")
c.say(" run runs fetch/import using current import context")
}
}
func (c *TelnetClient) handle_cmd_set(args []string) {
if len(args) != 2 {
c.say("wrong number of arguments")
return
}
if c.ctx == nil {
c.ctx = rhimport.NewImportContext(c.conf, c.rddb, "")
c.ctx.Trusted = true
}
switch strings.ToLower(args[0]) {
case "username":
if args[1] == "\"\"" || args[1] == "''" {
c.ctx.UserName = ""
} else {
c.ctx.UserName = args[1]
}
case "password":
if args[1] == "\"\"" || args[1] == "''" {
c.ctx.Password = ""
} else {
c.ctx.Password = args[1]
}
case "sourceuri":
if args[1] == "\"\"" || args[1] == "''" {
c.ctx.SourceUri = ""
} else {
c.ctx.SourceUri = args[1]
}
case "showid":
if id, err := strconv.ParseUint(args[1], 10, 32); err != nil {
c.say("invalid value (must be an positive integer)")
} else {
c.ctx.ShowId = uint(id)
}
case "clearshowcarts":
if val, err := strconv.ParseBool(args[1]); err != nil {
c.say("invalid value (must be true or false)")
} else {
c.ctx.ClearShowCarts = val
}
case "groupname":
if args[1] == "\"\"" || args[1] == "''" {
c.ctx.GroupName = ""
} else {
c.ctx.GroupName = args[1]
}
case "cart":
if cart, err := strconv.ParseUint(args[1], 10, 32); err != nil {
c.say("invalid value (must be an positive integer)")
} else {
c.ctx.Cart = uint(cart)
}
case "clearcart":
if val, err := strconv.ParseBool(args[1]); err != nil {
c.say("invalid value (must be true or false)")
} else {
c.ctx.ClearCart = val
}
case "cut":
if cut, err := strconv.ParseUint(args[1], 10, 32); err != nil {
c.say("invalid value (must be an positive integer)")
} else {
c.ctx.Cut = uint(cut)
}
case "channels":
if channels, err := strconv.ParseUint(args[1], 10, 32); err != nil {
c.say("invalid value (must be an positive integer)")
} else {
c.ctx.Channels = uint(channels)
}
case "normalizationlevel":
if normalizationlevel, err := strconv.ParseInt(args[1], 10, 32); err != nil {
c.say("invalid value (must be an positive integer)")
} else {
c.ctx.NormalizationLevel = int(normalizationlevel)
}
case "autotrimlevel":
if autotrimlevel, err := strconv.ParseInt(args[1], 10, 32); err != nil {
c.say("invalid value (must be an positive integer)")
} else {
c.ctx.AutotrimLevel = int(autotrimlevel)
}
case "usemetadata":
if val, err := strconv.ParseBool(args[1]); err != nil {
c.say("invalid value (must be true or false)")
} else {
c.ctx.UseMetaData = val
}
default:
c.say("unknown parameter, use 'help set' for a list of available parameters")
}
}
func (c *TelnetClient) handle_cmd_reset(args []string) {
if len(args) > 0 {
c.say("too many arguments")
return
}
c.ctx = nil
}
func (c *TelnetClient) handle_cmd_show(args []string) {
if len(args) > 0 {
c.say("too many arguments")
return
}
if c.ctx != nil {
c.say(" UserName: %v", c.ctx.UserName)
c.say(" Password: %v", c.ctx.Password)
c.say(" SourceUri: %v", c.ctx.SourceUri)
c.say(" ShowId: %v", c.ctx.ShowId)
c.say(" ClearShowCarts: %v", c.ctx.ClearShowCarts)
c.say(" GroupName: %v", c.ctx.GroupName)
c.say(" Cart: %v", c.ctx.Cart)
c.say(" ClearCart: %v", c.ctx.ClearCart)
c.say(" Cut: %v", c.ctx.Cut)
c.say(" Channels: %v", c.ctx.Channels)
c.say(" NormalizationLevel: %v", c.ctx.NormalizationLevel)
c.say(" AutotrimLevel: %v", c.ctx.AutotrimLevel)
c.say(" UseMetaData: %v", c.ctx.UseMetaData)
} else {
c.say("context is empty")
}
}
func telnet_progress_callback(step int, step_name string, progress float64, userdata interface{}) {
out := userdata.(chan<- string)
out <- fmt.Sprintf("%s: %3.2f%%\r", step_name, progress*100)
}
func telnet_cmd_run(ctx rhimport.ImportContext, out chan<- string) {
out <- fmt.Sprintf("fetching file from '%s'\n", ctx.SourceUri)
if res, err := rhimport.FetchFile(&ctx); err != nil {
out <- fmt.Sprintf("fetch file error: %s\n", err)
return
} else if res.ResponseCode != http.StatusOK {
out <- fmt.Sprintf("fetch file error: %s\n", res.ErrorString)
return
}
out <- fmt.Sprintf("\nimporting file '%s'\n", ctx.SourceFile)
if res, err := rhimport.ImportFile(&ctx); err != nil {
out <- fmt.Sprintf("import file error: %s\n", err)
return
} else {
if res.ResponseCode == http.StatusOK {
out <- fmt.Sprintf("\nFile got succesfully imported into Cart/Cut %d/%d\n", res.Cart, res.Cut)
rhl.Printf("File got succesfully imported into Cart/Cut %d/%d", res.Cart, res.Cut)
} else {
out <- fmt.Sprintf("Fileimport has failed (Cart/Cut %d/%d): %s\n", res.Cart, res.Cut, res.ErrorString)
rhl.Printf("Fileimport has failed (Cart/Cut %d/%d): %s", res.Cart, res.Cut, res.ErrorString)
}
}
close(out)
}
func (c *TelnetClient) handle_cmd_run(args []string) {
if c.ctx == nil {
c.say("context is empty please set at least one option")
return
}
if err := c.ctx.SanityCheck(); err != nil {
c.say("sanity check for import context returned: %s", err)
return
}
stdout := make(chan string)
c.ctx.ProgressCallBack = telnet_progress_callback
c.ctx.ProgressCallBackData = (chan<- string)(stdout)
go telnet_cmd_run(*c.ctx, stdout)
for str := range stdout {
c.write_string(str)
}
}
func (c *TelnetClient) handle_cmd(cmdstr string) bool {
cmdslice := strings.Fields(cmdstr)
if len(cmdslice) == 0 || cmdslice[0] == "" {
return false
}
cmd := cmdslice[0]
args := cmdslice[1:]
if cmd == "quit" {
return true
} else if cmd == "help" {
c.handle_cmd_help(args)
} else if cmd == "set" {
c.handle_cmd_set(args)
} else if cmd == "reset" {
c.handle_cmd_reset(args)
} else if cmd == "show" {
c.handle_cmd_show(args)
} else if cmd == "run" {
c.handle_cmd_run(args)
} else {
c.say("unknown command")
}
return false
}
func (c *TelnetClient) handle() {
defer c.conn.Close()
if err := c.write_string(prompt); err != nil {
return
}
for c.scanner.Scan() {
if exit := c.handle_cmd(c.scanner.Text()); exit {
return
}
if err := c.write_string(prompt); err != nil {
return
}
}
if err := c.scanner.Err(); err != nil {
rhdl.Printf("telnet-ctrl(%s): read command error: %s", c.conn.RemoteAddr(), err)
} else {
rhdl.Printf("telnet-ctrl(%s): connection closed", c.conn.RemoteAddr())
}
}
func newTelnetClient(conn net.Conn, conf *rhimport.Config, rddb *rhimport.RdDbChan) (c *TelnetClient) {
rhl.Println("telnet-ctrl: new client from:", conn.RemoteAddr())
c = &TelnetClient{}
c.conn = conn
c.scanner = bufio.NewScanner(conn)
c.writer = bufio.NewWriter(conn)
c.conf = conf
c.rddb = rddb
c.ctx = nil
return c
}
func StartControlTelnet(addr_s string, conf *rhimport.Config, rddb *rhimport.RdDbChan) {
rhl.Println("telnet-ctrl: listening on", addr_s)
server, err := net.Listen("tcp", addr_s)
if err != nil {
rhl.Println("telnet-ctrl: Listen() Error:", err)
return
}
for {
conn, err := server.Accept()
if err != nil {
rhl.Println("telnet-ctrl: Accept() Error:", err)
return
}
c := newTelnetClient(conn, conf, rddb)
go c.handle()
}
}
|