dumb/handlers/lyrics.go

73 lines
1.7 KiB
Go
Raw Permalink Normal View History

package handlers
import (
"fmt"
"net/http"
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/data"
2024-05-02 21:29:50 +01:00
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
)
2024-05-02 21:29:50 +01:00
func lyrics(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2024-04-06 00:14:51 -06:00
// prefer artist-song over annotation-id for cache key when available
id := mux.Vars(r)["artist-song"]
if id == "" {
id = mux.Vars(r)["annotation-id"]
} else {
id = id + "-lyrics"
}
if s, err := getCache[data.Song](id); err == nil {
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.LyricsPage(s), l)
return
}
2024-04-06 00:14:51 -06:00
url := fmt.Sprintf("https://genius.com/%s", id)
resp, err := utils.SendRequest(url)
if err != nil {
2024-05-02 21:29:50 +01:00
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(500, "cannot reach Genius servers"), l)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
w.WriteHeader(http.StatusNotFound)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(404, "page not found"), l)
return
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
2024-05-02 21:29:50 +01:00
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(500, "something went wrong"), l)
return
}
cf := doc.Find(".cloudflare_content").Length()
if cf > 0 {
2024-05-02 21:29:50 +01:00
l.Error("cloudflare got in the way")
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(500, "cloudflare is detected"), l)
return
}
var s data.Song
2024-05-02 21:29:50 +01:00
if err := s.Parse(doc); err != nil {
l.Error(err.Error())
}
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.LyricsPage(s), l)
2024-03-04 18:46:23 +01:00
if err = setCache(id, s); err != nil {
2024-05-02 21:29:50 +01:00
l.Error(err.Error())
2024-03-04 18:46:23 +01:00
}
}
}