2024-03-04 14:59:47 +01:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-03-06 20:53:29 +01:00
|
|
|
"mime"
|
2024-03-04 14:59:47 +01:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
2024-05-02 21:29:50 +01:00
|
|
|
"github.com/rramiachraf/dumb/utils"
|
2024-03-04 14:59:47 +01:00
|
|
|
"github.com/rramiachraf/dumb/views"
|
|
|
|
)
|
|
|
|
|
|
|
|
func isValidExt(ext string) bool {
|
|
|
|
valid := []string{"jpg", "jpeg", "png", "gif"}
|
|
|
|
for _, c := range valid {
|
|
|
|
if strings.ToLower(ext) == c {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-05-02 21:29:50 +01:00
|
|
|
func imageProxy(l *utils.Logger) http.HandlerFunc {
|
2024-03-04 14:59:47 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
v := mux.Vars(r)
|
|
|
|
f := v["filename"]
|
|
|
|
ext := v["ext"]
|
|
|
|
|
|
|
|
if !isValidExt(ext) {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
views.ErrorPage(400, "something went wrong").Render(context.Background(), w)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// first segment of URL resize the image to reduce bandwith usage.
|
|
|
|
url := fmt.Sprintf("https://t2.genius.com/unsafe/300x300/https://images.genius.com/%s.%s", f, ext)
|
|
|
|
|
2024-05-03 12:45:58 +01:00
|
|
|
res, err := utils.SendRequest(url)
|
2024-03-04 14:59:47 +01:00
|
|
|
if err != nil {
|
2024-05-02 21:29:50 +01:00
|
|
|
l.Error(err.Error())
|
2024-03-04 14:59:47 +01:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
views.ErrorPage(500, "cannot reach Genius servers").Render(context.Background(), w)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if res.StatusCode != http.StatusOK {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
views.ErrorPage(500, "something went wrong").Render(context.Background(), w)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-03 14:47:57 +01:00
|
|
|
w.Header().Set("Content-type", mime.TypeByExtension("."+ext))
|
2024-03-06 12:08:01 +01:00
|
|
|
w.Header().Add("Cache-Control", "max-age=1296000")
|
2024-03-04 18:46:23 +01:00
|
|
|
if _, err = io.Copy(w, res.Body); err != nil {
|
2024-05-02 21:29:50 +01:00
|
|
|
l.Error("unable to write image, %s", err.Error())
|
2024-03-04 18:46:23 +01:00
|
|
|
}
|
2024-03-04 14:59:47 +01:00
|
|
|
}
|
|
|
|
}
|