-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
2025 lines (1735 loc) · 72.1 KB
/
server.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"github.com/krisek/gompd/mpd"
"github.com/go-redis/redis/v8"
"github.com/robfig/cron/v3"
"github.com/rs/cors"
"html/template"
"net/http"
"strconv"
"os"
"time"
"strings"
"context"
"path/filepath"
"regexp"
"io/ioutil"
"os/exec"
"math/rand"
"github.com/huin/goupnp"
"github.com/huin/goupnp/dcps/av1"
"net/url"
"bytes"
"github.com/PuerkitoBio/goquery"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type FileInfo struct {
Directory string `json:"directory,omitempty"`
LastModified string `json:"last-modified"`
Count map[string]interface{} `json:"count,omitempty"`
Artist string `json:"artist,omitempty"`
File string `json:"file,omitempty"`
Format string `json:"format,omitempty"`
Time string `json:"time,omitempty"`
Duration string `json:"duration,omitempty"`
Genre string `json:"genre,omitempty"`
Codec string `json:"codec,omitempty"`
Track string `json:"track,omitempty"`
Date string `json:"date,omitempty"`
Album string `json:"album,omitempty"`
Title string `json:"title,omitempty"`
Stream string `json:"stream,omitempty"`
}
var (
ctx = context.Background()
redisClient *redis.Client
bandcampEnabled, _ = strconv.ParseBool(getEnv("AL_BANDCAMP_ENABLED", "true"))
clientDB = getEnv("AL_CLIENT_DB", getEnv("HOME", "/tmp") + "/Music/audioloader-db")
defaultStream = getEnv("AL_DEFAULT_STREAM", "http://" + os.Getenv("HOST") + ":8000/audio.ogg")
mpdHost = getEnv("AL_MPD_HOST", "localhost")
mpdPort = getEnv("AL_MPD_PORT", "6600")
listeningPort = getEnv("AL_LISTENING_PORT", "3400")
libraryPath = getEnv("AL_LIBRARY_PATH", getEnv("HOME", "/media") + "/Music" )
logLevel = getEnv("AL_LOG_LEVEL", "info")
maxBackoffDuration = 256 * time.Second // Maximum backoff of 256 seconds
maxRetryDuration = 1 * time.Hour // Total maximum retry duration of 1 hour
bandcampHistorySize, _ = strconv.Atoi(getEnv("AL_BANDCAMP_HISTORY_SIZE", "100"))
)
// Helper function to get environment variables with a default value
func getEnv(key, defaultVal string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultVal
}
// getMPDClient creates a new MPD client connection using the provided host and port.
// It retries the connection in case of failure with an exponential backoff strategy.
func getMPDClient(host string, port string) (*mpd.Client, error) {
if port == "" {
port = mpdPort
}
address := fmt.Sprintf("%s:%s", host, port)
var backoff time.Duration = 1 * time.Second
var totalWaitTime time.Duration
for {
client, err := mpd.Dial("tcp", address)
if err == nil {
// Success! Return the client
return client, nil
}
// Log the error
log.Printf("Failed to connect to MPD server at %s: %v. Retrying in %v...", address, err, backoff)
// Check if we've exceeded the maximum retry duration
totalWaitTime += backoff
if totalWaitTime >= maxRetryDuration {
return nil, fmt.Errorf("could not connect to MPD server after multiple retries: %w", err)
}
// Sleep for the current backoff duration
time.Sleep(backoff)
// Increase the backoff time (exponential backoff)
backoff *= 2
if backoff > maxBackoffDuration {
backoff = maxBackoffDuration // Cap the backoff at the max duration
}
}
}
func main() {
// Configure zerolog
var level zerolog.Level
switch logLevel {
case "debug":
level = zerolog.DebugLevel
case "info":
level = zerolog.InfoLevel
case "warn":
level = zerolog.WarnLevel
case "error":
level = zerolog.ErrorLevel
default:
level = zerolog.WarnLevel
}
log.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: "2006-01-02 15:04:05"}).
Level(level).With().
Timestamp().
Logger()
// Initialize Redis client
redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 0,
})
// Initialize Cron scheduler
c := cron.New()
c.Start()
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// Set up HTTP routes
http.HandleFunc("/cover", coverHandler)
http.HandleFunc("/kodi", kodiHandler)
http.HandleFunc("/upnp", upnpHandler)
http.HandleFunc("/generate_randomset", generateRandomSetHandler)
http.HandleFunc("/remove_favourite", favouritesHandler)
http.HandleFunc("/add_favourite", favouritesHandler)
http.HandleFunc("/active_players", activePlayersHandler)
http.HandleFunc("/radio_history", radioHistoryHandler)
http.HandleFunc("/bandcamp_history", bandcampHistoryHandler)
http.HandleFunc("/history", dataHandler)
http.HandleFunc("/randomset", dataHandler)
http.HandleFunc("/favourites", dataHandler)
http.HandleFunc("/search_radio", searchRadioHandler)
http.HandleFunc("/search_bandcamp", searchBandcampHandler)
http.HandleFunc("/remove_history", removeHistoryHandler)
http.HandleFunc("/listfiles", mpdProxyHandler)
http.HandleFunc("/lsinfo", mpdProxyHandler)
http.HandleFunc("/ls", mpdProxyHandler)
http.HandleFunc("/search", mpdProxyHandler)
http.HandleFunc("/addplay", mpdProxyHandler)
http.HandleFunc("/play", mpdProxyHandler)
http.HandleFunc("/pause", mpdProxyHandler)
http.HandleFunc("/playpause", mpdProxyHandler)
http.HandleFunc("/next", mpdProxyHandler)
http.HandleFunc("/prev", mpdProxyHandler)
http.HandleFunc("/stop", mpdProxyHandler)
http.HandleFunc("/status", mpdProxyHandler)
http.HandleFunc("/poll_currentsong", pollCurrentSongHandler)
http.HandleFunc("/currentsong", currentSongHandler)
http.HandleFunc("/count", countHandler)
http.HandleFunc("/toggleoutput", toggleOutputHandler)
http.HandleFunc("/", catchAllHandler)
// Enable CORS
handler := cors.Default().Handler(http.DefaultServeMux)
// Start HTTP server
log.Info().Str("function", "main").Msg(fmt.Sprintf("Starting server on: http://localhost:%v/", listeningPort))
http.ListenAndServe(":" + listeningPort, handler)
// log.Fatal()
}
func coverHandler(w http.ResponseWriter, r *http.Request) {
directory := r.URL.Query().Get("directory")
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Getting cover for: %s", directory))
responseType := r.URL.Query().Get("response_type")
if responseType == "" {
responseType = "direct"
}
cover := "vinyl.webp"
// Connect to Redis
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
ctx := context.Background()
// Attempt to get the cover from Redis
val, err := rdb.Get(ctx, "audioloader:cover:"+directory).Result()
if err == redis.Nil {
cover = "vinyl.webp"
} else if err != nil {
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Redis error: %v", err))
cover = "vinyl.webp"
} else {
cover = val
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Got cover from Redis: %s", cover))
}
// If the cover is not found, search the MPD directory
if cover == "vinyl.webp" || cover == "" {
mpdClient, _ := getMPDClient(mpdHost, r.URL.Query().Get("mpd_port"))
dirContent, err := mpdClient.ListFiles(directory)
mpdClient.Close()
if err != nil {
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Error listing files: %v", err))
http.Error(w, "Failed to list files", http.StatusInternalServerError)
return
}
imagePattern := regexp.MustCompile(`\.(jpg|jpeg|png|gif)$`)
coverPattern := regexp.MustCompile(`(?i)folder|cover|front`)
images := []string{}
for _, fileData := range dirContent {
file := fileData["file"]
if imagePattern.MatchString(file) {
images = append(images, file)
}
}
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Found images: %v", images))
for _, image := range images {
if coverPattern.MatchString(image) {
cover = image
break
}
}
if cover == "vinyl.webp" && len(images) > 0 {
cover = images[0]
}
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Selected cover: %s", cover))
// Save the cover in Redis
if err := rdb.Set(ctx, "audioloader:cover:"+directory, cover, 0).Err(); err != nil {
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Error setting cover in Redis: %v", err))
}
}
// Determine response
if responseType == "redirect" {
var fullPath string
if cover == "vinyl.webp" {
fullPath = "/static/assets/vinyl.webp"
} else {
fullPath = "/music" + "/" + directory + "/" + cover
}
http.Redirect(w, r, fullPath, http.StatusFound)
} else {
var coverPath string
if cover == "vinyl.webp" {
coverPath = "./static/assets/vinyl.webp"
} else {
coverPath = filepath.Join(libraryPath, directory, cover)
}
if _, err := os.Stat(coverPath); os.IsNotExist(err) {
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Cover not found, falling back to default: %v", coverPath))
coverPath = "./static/assets/vinyl.webp"
}
log.Debug().Str("function", "coverHandler").Msg(fmt.Sprintf("Serving cover: %v", coverPath))
http.ServeFile(w, r, coverPath)
}
}
type ClientData struct {
History []string `json:"history,omitempty"`
Randomset []string `json:"randomset,omitempty"`
Favourites []string `json:"favourites,omitempty"`
RadioHistory []string `json:"radio_history,omitempty"`
BandcampHistory []string `json:"bandcamp_history,omitempty"`
Stations map[string]StationData `json:"stations,omitempty"`
Links map[string]LinkData `json:"links,omitempty"`
}
// StationData holds individual radio station info.
type StationData struct {
URL string `json:"url"`
StationUUID string `json:"stationuuid"`
Name string `json:"name"`
Favicon string `json:"favicon"`
}
// LinkData holds individual bandcamp album info.
type LinkData struct {
URL string `json:"url"`
Title string `json:"title"`
Favicon string `json:"favicon"`
Artist string `json:"artist"`
Date string `json:"date"`
}
// readData reads the client's data from a JSON file.
// readData reads client data from a JSON file and returns a ClientData struct.
func readData(clientID string, dataType string) (ClientData, error) {
// Construct the file path
clientDataFile := filepath.Join(clientDB, fmt.Sprintf("%s.%s.json", clientID, dataType))
// Validate clientID and file path
if clientID == "" || !filepath.HasPrefix(clientDataFile, clientDB) {
return ClientData{}, fmt.Errorf("invalid clientID or file path")
}
// Check for invalid characters in the clientID
if !regexp.MustCompile(`^[A-Za-z0-9_\-\.]+$`).MatchString(clientID) {
return ClientData{}, fmt.Errorf("invalid characters in clientID")
}
// Read the file
data, err := ioutil.ReadFile(clientDataFile)
if err != nil {
log.Debug().Str("function", "readData").Msg(fmt.Sprintf("Error %s for %s not readable: %v\n", dataType, clientID, err))
return ClientData{}, fmt.Errorf("not readable")
}
// Unmarshal JSON into ClientData struct
var clientdata ClientData
if err := json.Unmarshal(data, &clientdata); err != nil {
log.Debug().Str("function", "readData").Msg(fmt.Sprintf("Error parsing JSON for %s: %v\n", clientID, err))
return ClientData{}, fmt.Errorf("Cannot encode")
}
return clientdata, nil
}
func reverse(s []map[string]interface{}) []map[string]interface{} {
a := make([]map[string]interface{}, len(s))
for i, v := range s {
a[len(s)-1-i] = v
}
return a
}
func getRadioStationURL(stationUUID string) string {
// Placeholder for pyradios implementation
// Replace this with the actual implementation later
return ""
}
func kodiHandler(w http.ResponseWriter, r *http.Request) {
// Implement Kodi handler
}
// Define constants or use environment/config variables as needed
var defaultStreamURL = "http://localhost:8000/audio.ogg"
// upnpHandler manages both UPnP and MPD control
func upnpHandler(w http.ResponseWriter, r *http.Request) {
server := r.URL.Query().Get("server")
if server == "" || server == "undefined" {
json.NewEncoder(w).Encode(map[string]string{"result": "no server given"})
return
}
action := r.URL.Query().Get("action")
if action == "" {
action = "Player.Stop"
}
streamURL := r.URL.Query().Get("stream")
if streamURL == "" {
streamURL = defaultStreamURL
}
if strings.Contains(server, "upnp") || strings.Contains(server, "xml") {
// Handle UPnP device actions
err := handleUPnP(server, action, streamURL)
if err != nil {
log.Debug().Str("function", "upnpHandler").Msg(fmt.Sprintf("UPnP Error: %v", err))
json.NewEncoder(w).Encode(map[string]string{"result": "load failed"})
return
}
} else if strings.Contains(server, "_6600") {
// Handle MPD device actions
err := handleMPD(server, action, streamURL)
if err != nil {
log.Debug().Str("function", "upnpHandler").Msg(fmt.Sprintf("MPD Error: %v", err))
json.NewEncoder(w).Encode(map[string]string{"result": "load failed"})
return
}
} else {
// No matching device type
json.NewEncoder(w).Encode(map[string]string{"result": "unsupported server"})
return
}
// Success response
json.NewEncoder(w).Encode(map[string]string{"result": "loaded"})
}
// handleUPnP controls UPnP devices using the AVTransport service
func handleUPnP(server, action, streamURL string) error {
// Parse the server URL
parsedURL, err := url.Parse(server)
if err != nil {
return fmt.Errorf("failed to parse server URL: %v", err)
}
// Discover and connect to the UPnP device
device, err := goupnp.DeviceByURL(parsedURL)
if err != nil {
return fmt.Errorf("failed to discover UPnP device: %v", err)
}
// Parse the device's URLBase into *url.URL
deviceURL, err := url.Parse(device.URLBase.String())
if err != nil {
return fmt.Errorf("failed to parse device URLBase: %v", err)
}
// Access the AVTransport service
transport, err := av1.NewAVTransport1ClientsByURL(deviceURL)
if err != nil || len(transport) == 0 {
return fmt.Errorf("failed to connect to AVTransport service: %v", err)
}
client := transport[0] // Assuming there is at least one transport client
// Perform action based on the provided action string
switch action {
case "Player.Open":
// Set the URI for playback and start playing
err := client.SetAVTransportURI(0, streamURL, "Audioloader")
if err != nil {
return fmt.Errorf("failed to set AVTransport URI: %v", err)
}
err = client.Play(0, "1")
if err != nil {
return fmt.Errorf("failed to start playback: %v", err)
}
default:
// Stop playback
err := client.Stop(0)
if err != nil {
return fmt.Errorf("failed to stop playback: %v", err)
}
}
return nil
}
// handleMPD controls MPD servers
func handleMPD(server, action, streamURL string) error {
// Parse MPD host and port
mpdHostPort := strings.Split(server, "_")
if len(mpdHostPort) != 2 {
return fmt.Errorf("invalid MPD server format")
}
mpdHost := mpdHostPort[0]
mpdPort := mpdHostPort[1]
// Get MPD client
mpdClient, err := getMPDClient(mpdHost, mpdPort)
if err != nil {
return fmt.Errorf("failed to connect to MPD: %v", err)
}
defer mpdClient.Close()
switch action {
case "Player.Open":
err = mpdClient.Clear()
if err != nil {
return fmt.Errorf("failed to clear playlist: %v", err)
}
err = mpdClient.Add(streamURL)
if err != nil {
return fmt.Errorf("failed to add stream to playlist: %v", err)
}
err = mpdClient.Play(-1)
if err != nil {
return fmt.Errorf("failed to start playback: %v", err)
}
default:
err = mpdClient.Stop()
if err != nil {
return fmt.Errorf("failed to stop playback: %v", err)
}
}
return nil
}
func randomChoice(albums []string, k int) []string {
n := len(albums)
if k >= n {
k = n
}
shuffled := make([]string, n)
copy(shuffled, albums)
rand.Shuffle(n, func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
return shuffled[:k]
}
func uniqueStrings(input []string) []string {
uniqueMap := make(map[string]bool)
var result []string
for _, item := range input {
if _, exists := uniqueMap[item]; !exists {
uniqueMap[item] = true
result = append(result, item)
}
}
return result
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func isValidFileName(fileName string) bool {
return regexp.MustCompile(`^[A-Za-z0-9_\-\.\/]+$`).MatchString(fileName)
}
func generateRandomSet(w http.ResponseWriter, r *http.Request) bool {
clientID := r.URL.Query().Get("client_id")
filter := r.URL.Query().Get("set_filter")
clientData := ClientData{Randomset: []string{}}
artists := make(map[string]bool)
mpdClient, _ := getMPDClient(mpdHost, r.URL.Query().Get("mpd_port"))
albums, err := mpdClient.List("album")
if err != nil {
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("Error listing albums: %v\n", err))
http.Error(w, "failed to generate randomset", http.StatusInternalServerError)
return false
}
rand.Seed(time.Now().UnixNano()) // Seed for randomness
for i := 0; len(clientData.Randomset) < 12 && i < 20; i++ {
randomAlbums := randomChoice(albums, 12) // Get 12 random albums
for _, album := range randomAlbums {
albumData, err := mpdClient.Search("album", album)
if err != nil {
log.Debug().Str("function", "").Msg(fmt.Sprintf("Error searching album %s: %v\n", album, err))
continue
}
if len(albumData) == 0 {
continue
}
artist := albumData[0]["Artist"]
if _, exists := artists[artist]; exists {
continue
}
if filter == "" || !regexp.MustCompile(filter).MatchString(albumData[0]["file"]) {
clientData.Randomset = append(clientData.Randomset, filepath.Dir(albumData[0]["file"]))
artists[artist] = true
}
}
}
// Ensure randomset has unique albums and limit to 12
clientData.Randomset = uniqueStrings(clientData.Randomset)[:min(12, len(clientData.Randomset))]
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("clientdata unique - %v", clientData.Randomset))
// Save to file
clientDataFile := filepath.Join(clientDB, fmt.Sprintf("%s.randomset.json", clientID))
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("clientDataFile - %v", clientDataFile))
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("filepath.HasPrefix(clientDataFile, clientDB)- %v %v", filepath.HasPrefix(clientDataFile, clientDB), isValidFileName(clientDataFile)))
if clientID != "" && filepath.HasPrefix(clientDataFile, clientDB) && isValidFileName(clientDataFile) {
file, err := os.Create(clientDataFile)
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("clientDataFile created %v", clientDataFile))
if err != nil {
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("Error writing randomset file: %v\n", err))
http.Error(w, "failed to save randomset", http.StatusInternalServerError)
return false
}
defer file.Close()
encoder := json.NewEncoder(file)
if err := encoder.Encode(clientData); err != nil {
log.Debug().Str("function", "generateRandomSet").Msg(fmt.Sprintf("Error encoding JSON: %v\n", err))
http.Error(w, "failed to save randomset", http.StatusInternalServerError)
return false
}
}
mpdClient.Close()
return true
}
func generateRandomSetHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if(generateRandomSet(w, r)){
w.Write([]byte(`{"result": "ok"}`))
} else {
w.Write([]byte(`{"result": "nok"}`))
}
}
// WriteData writes client data to a formatted JSON file.
func writeData(clientID, dataType string, clientData ClientData) error {
clientDataFile := filepath.Join(clientDB, fmt.Sprintf("%s.%s.json", clientID, dataType))
if clientID == "" || !filepath.HasPrefix(clientDataFile, clientDB) {
return fmt.Errorf("invalid clientID or file path")
}
if !regexp.MustCompile(`^[A-Za-z0-9_\-\.]+$`).MatchString(clientID) {
return fmt.Errorf("invalid characters in clientID")
}
// Use json.MarshalIndent to write formatted (indented) JSON
data, err := json.MarshalIndent(clientData, "", " ") // 4-space indentation
if err != nil {
return err
}
return os.WriteFile(clientDataFile, data, 0644)
}
// FavouritesHandler handles adding or removing favourites.
func favouritesHandler(w http.ResponseWriter, r *http.Request) {
clientID := r.URL.Query().Get("client_id")
if clientID == "" {
http.Error(w, "client_id is required", http.StatusBadRequest)
return
}
directory := r.URL.Query().Get("directory")
if directory == "" {
directory = "."
}
// Read existing favourites data
clientData, err := readData(clientID, "favourites")
if err != nil {
log.Error().Str("function", "favouritesHandler").Msg(fmt.Sprintf("readData failed for favourites %s: %v\n", clientID, err))
// http.Error(w, "Failed to load favourites", http.StatusInternalServerError)
// return
}
if clientData.Favourites == nil {
clientData.Favourites = []string{}
}
// Handle adding or removing favourite
path := r.URL.Path
if path == "/add_favourite" {
if !contains(clientData.Favourites, directory) {
clientData.Favourites = append(clientData.Favourites, directory)
}
} else if path == "/remove_favourite" {
clientData.Favourites = remove(clientData.Favourites, directory)
} else {
http.Error(w, "Invalid endpoint", http.StatusBadRequest)
return
}
// Write updated data back to the file
if err := writeData(clientID, "favourites", clientData); err != nil {
log.Error().Str("function", "favouritesHandler").Msg(fmt.Sprintf("writeData failed for favourites %s: %v\n", clientID, err))
http.Error(w, "Failed to save favourites", http.StatusInternalServerError)
return
}
// Respond with success
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"result": "ok"})
}
// Helper function to check if a slice contains a specific item
func contains(slice []string, item string) bool {
for _, a := range slice {
if a == item {
return true
}
}
return false
}
// Helper function to remove an item from a slice
func remove(slice []string, item string) []string {
for i, a := range slice {
if a == item {
return append(slice[:i], slice[i+1:]...)
}
}
return slice
}
// ActivePlayersHandler handles requests to retrieve active players
func activePlayersHandler(w http.ResponseWriter, r *http.Request) {
players := getActivePlayers()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(players)
}
func radioHistoryHandler(w http.ResponseWriter, r *http.Request) {
clientID := r.URL.Query().Get("client_id")
if clientID == "" {
http.Error(w, "client_id is required", http.StatusBadRequest)
return
}
clientData, err := readData(clientID, "radio_history")
if err != nil {
log.Error().Str("function", "radioHistoryHandler").Msg(fmt.Sprintf("readData failed for radio_history %s: %v\n", clientID, err))
json.NewEncoder(w).Encode(map[string]interface{}{
"tree": []interface{}{},
"info": map[string]interface{}{},
})
return
}
// Return the clientData in JSON format
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(clientData); err != nil {
log.Error().Str("function", "radioHistoryHandler").Msg(fmt.Sprintf("Failed to encode radio history data for %s: %v\n", clientID, err))
json.NewEncoder(w).Encode(map[string]interface{}{
"tree": []interface{}{},
"info": map[string]interface{}{},
})
return
}
}
func bandcampHistoryHandler(w http.ResponseWriter, r *http.Request) {
clientID := r.URL.Query().Get("client_id")
if clientID == "" {
http.Error(w, "client_id is required", http.StatusBadRequest)
return
}
clientData, err := readData(clientID, "bandcamp_history")
w.Header().Set("Content-Type", "application/json")
if err != nil {
log.Error().Str("function", "bandcampHistoryHandler").Msg(fmt.Sprintf("readData failed for bandcamp_history %s: %v\n", clientID, err))
// http.Error(w, "Failed to load bandcamp history", http.StatusInternalServerError)
// return
json.NewEncoder(w).Encode(map[string]interface{}{
"tree": []interface{}{},
"info": map[string]interface{}{},
})
return
}
// Return the clientData in JSON format
if err := json.NewEncoder(w).Encode(clientData); err != nil {
log.Error().Str("function", "bandcampHistoryHandler").Msg(fmt.Sprintf("Failed to encode bandcamp history data for %s: %v\n", clientID, err))
json.NewEncoder(w).Encode(map[string]interface{}{
"tree": []interface{}{},
"info": map[string]interface{}{},
})
// http.Error(w, "Failed to encode data", http.StatusInternalServerError)
return
}
}
func isHTTP(s string) bool {
return strings.HasPrefix(s, "http:")
}
func formatPlaytime(playtime int) string {
hours := playtime / 3600
minutes := (playtime % 3600) / 60
seconds := playtime % 60
var playhours string
if playtime < 3600 {
// Omit the hour if it's less than an hour
playhours = fmt.Sprintf("%v:%v", minutes, seconds)
} else {
// Include the hour
playhours = fmt.Sprintf("%v:%v:%v", hours, minutes, seconds)
}
return playhours
}
func capitalizeFirstLetter(s string) string {
if len(s) == 0 {
return s
}
// Capitalize the first letter and append the rest of the string
return strings.ToUpper(string(s[0])) + s[1:]
}
func dataHandler(w http.ResponseWriter, r *http.Request) {
clientDataTree := map[string]interface{}{
"tree": []interface{}{},
"info": map[string]interface{}{},
}
clientID := r.URL.Query().Get("client_id")
dataPath := r.URL.Path[1:]
log.Debug().Str("function", "dataHandler").Msg(fmt.Sprintf("%v - %v", clientID, dataPath))
// Read the data based on the path (history, randomset, etc.)
ClientData, err := readData(clientID, dataPath)
if err != nil {
log.Error().Str("function", "dataHandler").Msg(fmt.Sprintf("readData failed %s: %v\n", clientID, err))
}
// Function to process the data for any string slice (History, Randomset, etc.)
processDirectories := func(directories []string) []FileInfo {
var fileInfos []FileInfo
mpdClient, _ := getMPDClient(mpdHost, r.URL.Query().Get("mpd_port"))
for _, directory := range directories {
log.Debug().Str("function", "dataHandler").Msg(fmt.Sprintf("processing %v", directory))
directoryStr := directory
// If it's not a root or HTTP directory
if directoryStr != "/" && !isHTTP(directoryStr) {
count, err := mpdClient.Count("base", directoryStr)
if err != nil {
log.Debug().Str("function", "dataHandler").Msg(fmt.Sprintf("Could not get count for %s: %v\n", directoryStr, err))
continue
}
seconds, err := strconv.Atoi(count[1])
fileInfo := FileInfo{
Directory: directoryStr,
Count: map[string]interface{}{
"playhours": formatPlaytime(seconds),
"playtime": count[1],
"songs": count[0],
},
}
fileInfos = append(fileInfos, fileInfo)
} else if isHTTP(directoryStr) {
// Handle HTTP directory
fileInfo := FileInfo{
Directory: directoryStr,
Stream: directoryStr,
}
fileInfos = append(fileInfos, fileInfo)
}
}
// Reverse the fileInfos slice
for i, j := 0, len(fileInfos)-1; i < j; i, j = i+1, j-1 {
fileInfos[i], fileInfos[j] = fileInfos[j], fileInfos[i]
}
mpdClient.Close()
return fileInfos
}
// Process different fields in ClientData
var fileInfos []FileInfo
// Check if History has data and process it
if len(ClientData.History) > 0 {
fileInfos = append(fileInfos, processDirectories(ClientData.History)...)
}
if dataPath == "randomset" && len(ClientData.Randomset) == 0 {
generateRandomSet(w, r)
dataHandler(w, r)
return
}
// Check if Randomset has data and process it
if len(ClientData.Randomset) > 0 {
fileInfos = append(fileInfos, processDirectories(ClientData.Randomset)...)
}
// Check if Favourites has data and process it
if len(ClientData.Favourites) > 0 {
fileInfos = append(fileInfos, processDirectories(ClientData.Favourites)...)
}
// Assign the processed fileInfos to the tree
clientDataTree["tree"] = fileInfos
// Write the response
json.NewEncoder(w).Encode(clientDataTree)
}
type RadioStation struct {
Name string `json:"name"`
Favicon string `json:"favicon"`
Bitrate int `json:"bitrate"`
UUID string `json:"stationuuid"`
Url string `json:"url"`
}
type Content struct {
Tree []RadioStation `json:"tree"`
}
func searchRadioHandler(w http.ResponseWriter, r *http.Request) {
content := Content{Tree: []RadioStation{}}
pattern := r.URL.Query().Get("pattern")
if len(pattern) < 3 {
json.NewEncoder(w).Encode(content)
return
}
client := &http.Client{Timeout: 10 * time.Second}
url := fmt.Sprintf("https://de1.api.radio-browser.info/json/stations/search?name=%s&name_exact=false", pattern)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Error().Str("function", "searchRadioHandler").Msg(fmt.Sprintf("Error creating request: %v", err))
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
resp, err := client.Do(req)
if err != nil {
log.Debug().Str("function", "").Msg(fmt.Sprintf("Error making request to Radio Browser API: %v", err))
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Error().Str("function", "searchRadioHandler").Msg(fmt.Sprintf("API responded with status code: %v", resp.StatusCode))
http.Error(w, "Failed to fetch radio stations", http.StatusBadRequest)
return
}
log.Debug().Str("function", "searchRadioHandler").Msg(fmt.Sprintf("radio stations: %s", resp.Body))
var stations []RadioStation
if err := json.NewDecoder(resp.Body).Decode(&stations); err != nil {
log.Error().Str("function", "searchRadioHandler").Msg(fmt.Sprintf("Error decoding response: %v", err))
http.Error(w, "Failed to process response", http.StatusInternalServerError)
return
}
// Filter and modify stations as necessary
for _, station := range stations {
if station.Name != "" && (station.Bitrate > 60 || station.Bitrate == 0) {
if station.Favicon == "" {
station.Favicon = "assets/radio.png"
}
content.Tree = append(content.Tree, station)
}
}
// Return the content as JSON
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(content)
}
// searchBandcampHandler handles the search_bandcamp route
func searchBandcampHandler(w http.ResponseWriter, r *http.Request) {
pattern := r.URL.Query().Get("pattern")
if len(pattern) < 20 || !(strings.Contains(pattern, "bandcamp.com/") || strings.Contains(pattern, "youtube") || strings.Contains(pattern, "youtu.be")) {
json.NewEncoder(w).Encode(map[string]interface{}{"tree": []interface{}{}})
return
}
content := map[string]interface{}{
"tree": []map[string]interface{}{},
}
// Check if the pattern is for Bandcamp
if strings.Contains(pattern, "bandcamp.com") {
albumList, err := handleBandcampSearch(pattern)
if err != nil {
log.Error().Str("function", "searchBandcampHandler").Msg(fmt.Sprintf("Exception during Bandcamp search: %v", err))
json.NewEncoder(w).Encode(content)
return
}
content["tree"] = albumList
}
// Check if the pattern is for YouTube
if strings.Contains(pattern, "youtube") || strings.Contains(pattern, "youtu.be") {