arimelody.me/music/view/release.go

106 lines
2.6 KiB
Go
Raw Normal View History

package view
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"strings"
"arimelody.me/arimelody.me/admin"
"arimelody.me/arimelody.me/global"
"arimelody.me/arimelody.me/music/model"
)
type (
gatewayTrack struct {
*model.Track
Lyrics template.HTML
Number int
}
gatewayRelease struct {
*model.Release
Tracks []gatewayTrack
Authorised bool
}
)
// HTTP HANDLERS
func ServeRelease() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.NotFound(w, r)
return
}
releaseID := r.URL.Path[1:]
var releaseRef = global.GetRelease(releaseID)
if releaseRef == nil {
http.NotFound(w, r)
return
}
var release = *releaseRef
// only allow authorised users to view hidden releases
authorised := admin.GetSession(r) != nil
if !authorised && !release.Visible {
http.NotFound(w, r)
return
}
if !authorised && !release.IsReleased() {
release.Tracks = nil
release.Credits = nil
}
w.Header().Add("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(release)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
})
}
func ServeGateway() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/music", http.StatusPermanentRedirect)
return
}
id := r.URL.Path[1:]
release := global.GetRelease(id)
if release == nil {
http.NotFound(w, r)
return
}
// only allow authorised users to view hidden releases
authorised := admin.GetSession(r) != nil
if !release.Visible && !authorised {
http.NotFound(w, r)
return
}
tracks := []gatewayTrack{}
for i, track := range release.Tracks {
tracks = append(tracks, gatewayTrack{
Track: track,
Lyrics: template.HTML(strings.Replace(track.Lyrics, "\n", "<br>", -1)),
Number: i + 1,
})
}
lrw := global.LoggingResponseWriter{ResponseWriter: w, Code: http.StatusOK}
global.ServeTemplate("music-gateway.html", gatewayRelease{release, tracks, authorised}).ServeHTTP(&lrw, r)
if lrw.Code != http.StatusOK {
fmt.Printf("Error rendering music gateway for %s\n", id)
return
}
})
}