package http import ( "dwelling-radio/internal/radio" "dwelling-radio/pkg/oggtag" "encoding/json" "fmt" "log" "net/http" "time" ) var songList radio.SongList type DJHandlers struct { listeners *radio.ListenerCounter playlist *radio.Playlist } func NewDJHandlers(l *radio.ListenerCounter, p *radio.Playlist, slLen int) *DJHandlers { songList = *radio.NewSongList(slLen) return &DJHandlers{listeners: l, playlist: p} } func (dj *DJHandlers) ListenersGet(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Type", "text/plain") fmt.Fprint(w, dj.listeners.Current(), dj.listeners.Peak()) } func (dj *DJHandlers) ListenersInc(w http.ResponseWriter, _ *http.Request) { l := dj.listeners.Inc() go func() { if l > songList.Current().MaxListeners { songList.Current().MaxListeners = l } }() w.WriteHeader(http.StatusCreated) w.Header().Add("Content-Type", "text/plain") fmt.Fprint(w, l) } func (dj *DJHandlers) ListenersDec(w http.ResponseWriter, _ *http.Request) { l, err := dj.listeners.Dec() if err != nil { log.Print(err) http.Error(w, err.Error(), http.StatusBadRequest) } w.WriteHeader(http.StatusOK) w.Header().Add("Content-Type", "text/plain") fmt.Fprint(w, l) } func (dj *DJHandlers) PlaylistNext(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Type", "text/plain") nxt := dj.playlist.Next() if nxt == "" { log.Println("the end of a playlist has been reached") } else { go func() { bs, be, err := oggtag.ReadFile(nxt) if err != nil { log.Println("cannot read an OGG file", nxt, ":", err) } song := radio.Song_{ Artist: oggtag.GetTag(bs, "artist"), Title: oggtag.GetTag(bs, "title"), Duration: oggtag.GetDuration(bs, be), MaxListeners: dj.listeners.Current(), StartAt: time.Now()} // radio.CheckAndUpdateMostListenedSong(song, currentSong) songList.Add(song) }() } fmt.Fprint(w, nxt) } func (dj *DJHandlers) Song(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") err := json.NewEncoder(w).Encode(songList.Current()) if err != nil { log.Println("DJHandlers.Song:", err) http.Error(w, "cannot obtain current song", http.StatusInternalServerError) } } func (dj *DJHandlers) Songs(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") err := json.NewEncoder(w).Encode(songList.List()) if err != nil { log.Println("DJHandlers.Songs:", err) http.Error(w, "cannot obtain list of last songs", http.StatusInternalServerError) } } func (dj *DJHandlers) Status(w http.ResponseWriter, r *http.Request) { withList := r.URL.Query().Has("with-list") if withList { err := json.NewEncoder(w).Encode(&struct { Current *radio.Song_ `json:"current_song,omitempty"` Listeners *radio.ListenerCounter `json:"listeners"` List []radio.Song_ `json:"last_songs,omitempty"` }{ Current: songList.Current(), Listeners: dj.listeners, List: songList.List()}) if err != nil { log.Println("DJHandlers.Status-withList:", err) } } }