arimelody.me/view/music.go

85 lines
2.3 KiB
Go
Raw Normal View History

package view
import (
"fmt"
"net/http"
"arimelody-web/admin"
"arimelody-web/controller"
2024-09-03 07:07:45 +00:00
"arimelody-web/global"
"arimelody-web/model"
2024-09-03 07:07:45 +00:00
"arimelody-web/templates"
)
// HTTP HANDLER METHODS
func MusicHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
ServeCatalog().ServeHTTP(w, r)
return
}
release, err := controller.GetRelease(global.DB, r.URL.Path[1:], true)
if err != nil {
http.NotFound(w, r)
return
}
ServeGateway(release).ServeHTTP(w, r)
}))
return mux
}
func ServeCatalog() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
releases, err := controller.GetAllReleases(global.DB, true, 0, true)
if err != nil {
fmt.Printf("FATAL: Failed to pull releases for catalog: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
2024-09-03 07:07:45 +00:00
for _, release := range releases {
if !release.IsReleased() {
release.ReleaseType = model.Upcoming
}
}
err = templates.Pages["music"].Execute(w, releases)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
})
}
func ServeGateway(release *model.Release) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// only allow authorised users to view hidden releases
authorised := admin.GetSession(r) != nil
if !authorised && !release.Visible {
http.NotFound(w, r)
return
}
response := *release
if authorised || release.IsReleased() {
response.Tracks = release.Tracks
response.Credits = release.Credits
response.Links = release.Links
}
err := templates.Pages["music-gateway"].Execute(w, response)
if err != nil {
fmt.Printf("Error rendering music gateway for %s: %s\n", release.ID, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
})
}