-
Notifications
You must be signed in to change notification settings - Fork 1
/
audio.go
522 lines (447 loc) · 15.6 KB
/
audio.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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package api
import (
crypto_rand "crypto/rand"
"encoding/binary"
"encoding/json"
"fmt"
"github.com/danesparza/fxaudio/internal/event"
"github.com/danesparza/fxaudio/internal/media"
"github.com/danesparza/fxaudio/internal/mediatype"
"github.com/go-chi/chi/v5"
"io"
math_rand "math/rand"
"net/http"
"os"
"os/exec"
"path"
"strings"
"github.com/rs/xid"
"github.com/spf13/viper"
)
// UploadFile godoc
// @Summary Upload a file
// @Description Upload file
// @Tags audio
// @Accept mpfd
// @Produce json
// @Param file formData file true "The file to upload"
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Failure 413 {object} api.ErrorResponse
// @Failure 500 {object} api.ErrorResponse
// @Router /audio [put]
func (service Service) UploadFile(rw http.ResponseWriter, req *http.Request) {
MAX_UPLOAD_SIZE := viper.GetInt64("upload.bytelimit")
UploadPath := viper.GetString("upload.path")
// First check for maximum uplooad size and return an error if we exceed it.
req.Body = http.MaxBytesReader(rw, req.Body, MAX_UPLOAD_SIZE)
if err := req.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
err = fmt.Errorf("could not parse multipart form: %v", err)
sendErrorResponse(rw, err, http.StatusRequestEntityTooLarge)
return
}
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, fileHeader, err := req.FormFile("file")
if err != nil {
err = fmt.Errorf("error retrieving file: %v", err)
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
defer file.Close()
// Create the uploads folder if it doesn't
// already exist
err = os.MkdirAll(UploadPath, os.ModePerm)
if err != nil {
err = fmt.Errorf("error creating uploads path: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
// Create a new file in the uploads directory
destinationFile := path.Join(UploadPath, fileHeader.Filename)
dst, err := os.Create(destinationFile)
if err != nil {
err = fmt.Errorf("error creating file: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
defer dst.Close()
// Copy the uploaded file to the filesystem
// at the specified destination
_, err = io.Copy(dst, file)
if err != nil {
err = fmt.Errorf("error saving file: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
// Add it to our system database
service.DB.AddFile(destinationFile, "Audio file")
// Record the event:
service.DB.AddEvent(event.FileUploaded, mediatype.Audio, fileHeader.Filename, GetIP(req), service.HistoryTTL)
// If we've gotten this far, indicate a successful upload
response := SystemResponse{
Message: "File uploaded",
}
// Serialize to JSON & return the response:
rw.WriteHeader(http.StatusCreated)
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// ListAllFiles godoc
// @Summary List all files in the system
// @Description List all files in the system
// @Tags audio
// @Accept json
// @Produce json
// @Success 200 {object} api.SystemResponse
// @Failure 500 {object} api.ErrorResponse
// @Router /audio [get]
func (service Service) ListAllFiles(rw http.ResponseWriter, req *http.Request) {
// Get a list of files
retval, err := service.DB.GetAllFiles()
if err != nil {
err = fmt.Errorf("error getting a list of files: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
// Construct our response
response := SystemResponse{
Message: fmt.Sprintf("%v file(s)", len(retval)),
Data: retval,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// DeleteFile godoc
// @Summary Deletes a file in the system
// @Description Deletes a file in the system
// @Tags audio
// @Accept json
// @Produce json
// @Param id path string true "The file id to delete"
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Failure 500 {object} api.ErrorResponse
// @Failure 503 {object} api.ErrorResponse
// @Router /audio/{id} [delete]
func (service Service) DeleteFile(rw http.ResponseWriter, req *http.Request) {
// Get the id from the url (if it's blank, return an error)
audioId := chi.URLParam(req, "id")
if audioId == "" {
err := fmt.Errorf("requires an id of a file to delete")
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
// Delete the file
err := service.DB.DeleteFile(audioId)
if err != nil {
err = fmt.Errorf("error deleting file: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
// Record the event:
service.DB.AddEvent(event.FileDeleted, mediatype.Audio, audioId, GetIP(req), service.HistoryTTL)
// Construct our response
response := SystemResponse{
Message: "File deleted",
Data: audioId,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// PlayAudio godoc
// @Summary Play an audio file
// @Description Play an audio file
// @Tags audio
// @Accept json
// @Produce json
// @Param id path string true "The file id to play"
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Failure 500 {object} api.ErrorResponse
// @Failure 503 {object} api.ErrorResponse
// @Router /audio/play/{id} [post]
func (service Service) PlayAudio(rw http.ResponseWriter, req *http.Request) {
// Get the id from the url (if it's blank, return an error)
audioId := chi.URLParam(req, "id")
if audioId == "" {
err := fmt.Errorf("requires an id of a file to play")
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
// Get the file information
fileToPlay, err := service.DB.GetFile(audioId)
if err != nil {
err = fmt.Errorf("error getting file information: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
/*
// Make sure omxplayer is installed (for HDMI based audio)
// Instructions on how to install it:
// https://www.gaggl.com/2013/01/installing-omxplayer-on-raspberry-pi/
_, err := exec.LookPath("omxplayer")
if err != nil {
err = fmt.Errorf("Didn't find omxplayer executable in the path: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
*/
// Make sure mpg123 is installed (for i2s / ALSA based digital audio)
// Instructions on how to install it:
// https://learn.adafruit.com/adafruit-speaker-bonnet-for-raspberry-pi/raspberry-pi-test
_, err = exec.LookPath("mpg123")
if err != nil {
err = fmt.Errorf("didn't find mpg123 executable in the path: %v", err)
sendErrorResponse(rw, err, http.StatusServiceUnavailable)
return
}
// Send to the channel:
playRequest := media.PlayAudioRequest{
ProcessID: xid.New().String(), // Generate a new id
ID: fileToPlay.ID,
FilePath: fileToPlay.FilePath,
LoopTimes: "1",
}
service.PlayMedia <- playRequest
// Record the event:
service.DB.AddEvent(event.RequestPlay, mediatype.Audio, fmt.Sprintf("%+v", playRequest), GetIP(req), service.HistoryTTL)
// Create our response and send information back:
response := SystemResponse{
Message: "Audio playing",
Data: playRequest,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// LoopAudio godoc
// @Summary Loop an audio file n times
// @Description Play an audio file over and over. (-1 to loop until stopped)
// @Tags audio
// @Accept json
// @Produce json
// @Param id path string true "The file id to play"
// @Param loopTimes path string true "The number of times to play. The value -1 will cause it to loop until stopped"
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Failure 500 {object} api.ErrorResponse
// @Failure 503 {object} api.ErrorResponse
// @Router /audio/loop/{id}/{loopTimes} [post]
func (service Service) LoopAudio(rw http.ResponseWriter, req *http.Request) {
// Get the id from the url (if it's blank, return an error)
audioId := chi.URLParam(req, "id")
if audioId == "" {
err := fmt.Errorf("requires an id of a file to loop")
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
loopTimes := chi.URLParam(req, "loopTimes")
if audioId == "" {
err := fmt.Errorf("requires a number of times to loop")
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
// Get the file information
fileToPlay, err := service.DB.GetFile(audioId)
if err != nil {
err = fmt.Errorf("error getting file information: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
// Make sure mpg123 is installed (for i2s / ALSA based digital audio)
// Instructions on how to install it:
// https://learn.adafruit.com/adafruit-speaker-bonnet-for-raspberry-pi/raspberry-pi-test
_, err = exec.LookPath("mpg123")
if err != nil {
err = fmt.Errorf("didn't find mpg123 executable in the path: %v", err)
sendErrorResponse(rw, err, http.StatusServiceUnavailable)
return
}
// Send to the channel:
playRequest := media.PlayAudioRequest{
ProcessID: xid.New().String(), // Generate a new id
ID: fileToPlay.ID,
FilePath: fileToPlay.FilePath,
LoopTimes: loopTimes,
}
service.PlayMedia <- playRequest
// Record the event:
service.DB.AddEvent(event.RequestPlay, mediatype.Audio, fmt.Sprintf("%+v", playRequest), GetIP(req), service.HistoryTTL)
// Create our response and send information back:
response := SystemResponse{
Message: "Audio playing",
Data: playRequest,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// StreamAudio godoc
// @Summary Stream from an audio endpoint
// @Description Stream from an audio endpoint
// @Tags audio
// @Accept json
// @Produce json
// @Param endpoint body api.PlayAudioRequest true "The endpoint url to stream"
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Failure 503 {object} api.ErrorResponse
// @Router /audio/stream [post]
func (service Service) StreamAudio(rw http.ResponseWriter, req *http.Request) {
// req.Body is a ReadCloser -- we need to remember to close it:
defer req.Body.Close()
// Decode the request
request := PlayAudioRequest{}
err := json.NewDecoder(req.Body).Decode(&request)
if err != nil {
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
// Get just the file endpoint:
fileendpoint := strings.TrimSpace(request.Endpoint)
// Make sure mpg123 is installed (for i2s / ALSA based digital audio)
_, err = exec.LookPath("mpg123")
if err != nil {
err = fmt.Errorf("didn't find mpg123 executable in the path: %v", err)
sendErrorResponse(rw, err, http.StatusServiceUnavailable)
return
}
// Send to the channel:
playRequest := media.PlayAudioRequest{
ProcessID: xid.New().String(), // Generate a new id
FilePath: fileendpoint,
LoopTimes: "1",
}
service.PlayMedia <- playRequest
// Record the event:
service.DB.AddEvent(event.RequestPlay, mediatype.Audio, fmt.Sprintf("%+v", playRequest), GetIP(req), service.HistoryTTL)
// Create our response and send information back:
response := SystemResponse{
Message: "Audio playing",
Data: playRequest,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// PlayRandomAudio godoc
// @Summary Play a random file already uploaded
// @Description Play a random file already uploaded
// @Tags audio
// @Accept json
// @Produce json
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Failure 500 {object} api.ErrorResponse
// @Router /audio/play [post]
func (service Service) PlayRandomAudio(rw http.ResponseWriter, req *http.Request) {
// req.Body is a ReadCloser -- we need to remember to close it:
defer req.Body.Close()
// Get just the file endpoint:
fileendpoint := ""
// If we don't have an endpoint specified, get a random file that we manage
if fileendpoint == "" {
retval, err := service.DB.GetAllFiles()
if err != nil {
err = fmt.Errorf("error getting a list of files: %v", err)
sendErrorResponse(rw, err, http.StatusInternalServerError)
return
}
// If we don't have anything to pick from, bomb out
if len(retval) < 1 {
err = fmt.Errorf("can't play anything -- no endpoint specified, and no files to randomly pick from: %v", err)
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
// Pick a random file:
randomIndex := math_rand.Intn(len(retval))
// Set fileendpoint to the random file's path:
fileendpoint = retval[randomIndex].FilePath
}
// Make sure mpg123 is installed (for i2s / ALSA based digital audio)
_, err := exec.LookPath("mpg123")
if err != nil {
err = fmt.Errorf("didn't find mpg123 executable in the path: %v", err)
sendErrorResponse(rw, err, http.StatusServiceUnavailable)
return
}
// Send to the channel:
playRequest := media.PlayAudioRequest{
ProcessID: xid.New().String(), // Generate a new id
FilePath: fileendpoint,
LoopTimes: "1",
}
service.PlayMedia <- playRequest
// Record the event:
service.DB.AddEvent(event.RequestPlay, mediatype.Audio, fmt.Sprintf("%+v", playRequest), GetIP(req), service.HistoryTTL)
// Create our response and send information back:
response := SystemResponse{
Message: "Audio playing",
Data: playRequest,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// StopAudio godoc
// @Summary Stops a specific audio file 'play' process
// @Description Stops a specific audio file 'play' process
// @Tags audio
// @Accept json
// @Produce json
// @Param pid path string true "The process id to stop"
// @Success 200 {object} api.SystemResponse
// @Failure 400 {object} api.ErrorResponse
// @Router /audio/stop/{pid} [post]
func (service Service) StopAudio(rw http.ResponseWriter, req *http.Request) {
// Get the id from the url (if it's blank, return an error)
processId := chi.URLParam(req, "pid")
if processId == "" {
err := fmt.Errorf("requires a processid of a process to stop")
sendErrorResponse(rw, err, http.StatusBadRequest)
return
}
// Send to the channel:
service.StopMedia <- processId
// Record the event:
service.DB.AddEvent(event.RequestStop, mediatype.Audio, processId, GetIP(req), service.HistoryTTL)
// Create our response and send information back:
response := SystemResponse{
Message: "Audio stopping",
Data: processId,
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
// StopAllAudio godoc
// @Summary Stops all audio 'play' processes
// @Description Stops all audio 'play' processes
// @Tags audio
// @Accept json
// @Produce json
// @Success 200 {object} api.SystemResponse
// @Router /audio/stop [post]
func (service Service) StopAllAudio(rw http.ResponseWriter, req *http.Request) {
// Send to the channel:
service.StopAllMedia <- true
// Record the event:
service.DB.AddEvent(event.RequestStopAll, mediatype.Audio, "Stop all plays", GetIP(req), service.HistoryTTL)
// Create our response and send information back:
response := SystemResponse{
Message: "All Audio stopping",
Data: ".",
}
// Serialize to JSON & return the response:
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(rw).Encode(response)
}
func init() {
var b [8]byte
crypto_rand.Read(b[:])
math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}