package http import ( "dwelling-radio/internal/radio" "dwelling-radio/pkg/utils" "dwelling-radio/web" "encoding/json" "log" "net/http" "os" "time" ) type Handlers struct { songListLen int filelistPath string icecastUrl string icecastPlaylistPath string } func NewHandlers(icecastUrl, icecastPlaylistPath, filelistPath string, songListLen int) *Handlers { return &Handlers{ songListLen: songListLen, filelistPath: filelistPath, icecastUrl: icecastUrl, icecastPlaylistPath: icecastPlaylistPath} } func (h *Handlers) Index(w http.ResponseWriter, r *http.Request) { status, err := radio.IcecastGetStatus(h.icecastUrl) if err != nil { log.Println("failed to get Icecast status:", err) } songs := radio.IcecastLastSongs(h.icecastPlaylistPath) if songs != nil { for i := 0; i < len(songs); i++ { if tim, err := time.Parse(radio.SongTimeFormat, songs[i].Time); err == nil { songs[i].Time = utils.ToClientTimezone(tim, r).Format("15:04") } } } web.Index(utils.MainSite(r.Host), h.songListLen, status, &songs, r, w) } func (h *Handlers) Status(w http.ResponseWriter, r *http.Request) { status, err := radio.IcecastGetStatus(h.icecastUrl) if err != nil { log.Println("cannot retrieve Icecast status:", err) http.Error(w, "cannot retrieve Icecast status", http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") json.NewEncoder(w).Encode(status) } func (h *Handlers) LastSong(w http.ResponseWriter, r *http.Request) { song := radio.IcecastLastSong(h.icecastPlaylistPath) if song == nil { w.WriteHeader(http.StatusNotFound) return } if tim, err := time.Parse(radio.SongTimeFormat, song.Time); err == nil { song.Time = utils.ToClientTimezone(tim, r).Format("15:04") } w.Header().Add("Content-Type", "application/json") json.NewEncoder(w).Encode(song) } func (h *Handlers) Playlist(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Disposition", "attachment; filename=\"radio.arav.su.m3u\"") fc, _ := web.AssetsGetFile("playlist.m3u") w.Write(fc) } func (h *Handlers) Filelist(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Type", "text/html") data, _ := os.ReadFile(h.filelistPath) w.Write(data) } func RobotsTxt(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Disposition", "attachment; filename=\"robots.txt\"") w.Write([]byte("User-agent: *\nDisallow: /assets/\nDisallow: /live/")) } func Favicon(w http.ResponseWriter, r *http.Request) { data, _ := web.AssetsGetFile("img/favicon.svg") w.Write(data) } func SitemapXML(w http.ResponseWriter, r *http.Request) { data, _ := web.AssetsGetFile("sitemap.xml") w.Write(data) }