- Add image handler
- Store images locally
This commit is contained in:
Daniel Mason 2021-04-11 20:10:52 +12:00
parent 489527c8f9
commit 8bc462878a
Signed by: idanoo
GPG key ID: 387387CDBC02F132
19 changed files with 158 additions and 54 deletions

View file

@ -129,7 +129,7 @@ func getArtistByUUID(uuid string) (Artist, error) {
func getTopArtists(userUuid string) (TopArtists, error) {
var topArtist TopArtists
rows, err := db.Query("SELECT BIN_TO_UUID(`artists`.`uuid`, true), `artists`.`name`, IFNULL(`artists`.`img`,''), count(*) "+
rows, err := db.Query("SELECT BIN_TO_UUID(`artists`.`uuid`, true), `artists`.`name`, IFNULL(BIN_TO_UUID(`artists`.`uuid`, true),''), count(*) "+
"FROM `scrobbles` "+
"JOIN `tracks` ON `tracks`.`uuid` = `scrobbles`.`track` "+
"JOIN track_artist ON track_artist.track = tracks.uuid "+

View file

@ -0,0 +1,46 @@
package goscrobble
import (
"fmt"
"io"
"net/http"
"os"
)
func importImage(uuid string, url string) error {
// Create the file
path, err := os.Getwd()
if err != nil {
return err
}
out, err := os.Create(path + string(os.PathSeparator) + StaticDirectory + string(os.PathSeparator) + "img" + string(os.PathSeparator) + uuid + "_full.jpg")
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Check server response
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Bad response status: %s", resp.Status)
}
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func resizeImage(uuid string) error {
return nil
}

View file

@ -84,7 +84,6 @@ func (user *User) updateNavidromePlaydata(tx *sql.Tx) error {
}
response, err := getNavidromeNowPlaying(&tokens)
fmt.Println(response)
if err != nil {
return errors.New(fmt.Sprintf("Failed to fetch Navidrome Tokens %+v", err))
}

View file

@ -238,7 +238,7 @@ func (user *User) updateImageDataFromSpotify() error {
client := auth.NewClient(token)
client.AutoRetry = true
rows, err := db.Query("SELECT BIN_TO_UUID(`uuid`, true), `name` FROM `artists` WHERE IFNULL(`img`,'') = '' LIMIT 50")
rows, err := db.Query("SELECT BIN_TO_UUID(`uuid`, true), `name` FROM `artists` WHERE IFNULL(`img`,'') NOT IN ('pending', 'complete') LIMIT 50")
if err != nil {
log.Printf("Failed to fetch config: %+v", err)
return errors.New("Failed to fetch artists")
@ -271,11 +271,18 @@ func (user *User) updateImageDataFromSpotify() error {
if err != nil {
continue
}
_ = artist.updateArtist("img", img, tx)
err = importImage(uuid, img)
if err != nil {
fmt.Printf("Failed to import image: %+v", err)
continue
}
_ = artist.updateArtist("img", "pending", tx)
}
tx.Commit()
rows, err = db.Query("SELECT BIN_TO_UUID(`uuid`, true), `name` FROM `albums` WHERE IFNULL(`img`,'') = '' LIMIT 50")
rows, err = db.Query("SELECT BIN_TO_UUID(`uuid`, true), `name` FROM `albums` WHERE IFNULL(`img`,'') NOT IN ('pending', 'complete') LIMIT 50")
if err != nil {
log.Printf("Failed to fetch config: %+v", err)
return errors.New("Failed to fetch artists")
@ -305,10 +312,12 @@ func (user *User) updateImageDataFromSpotify() error {
tx, _ = db.Begin()
for uuid, img := range toUpdate {
album, err = getAlbumByUUID(uuid)
err = importImage(uuid, img)
if err != nil {
continue
}
_ = album.updateAlbum("img", img, tx)
_ = album.updateAlbum("img", "pending", tx)
}
tx.Commit()
return nil

View file

@ -22,6 +22,9 @@ type jsonResponse struct {
// List of Reverse proxies
var ReverseProxies []string
// Static image directory
var StaticDirectory string
// RequestRequest - Incoming JSON!
type RequestRequest struct {
URL string `json:"url"`
@ -88,6 +91,10 @@ func HandleRequests(port string) {
// This just prevents it serving frontend stuff over /api
r.PathPrefix("/api")
// SERVE STATIC FILES - NO AUTH
spaStatic := spaStaticHandler{staticPath: StaticDirectory}
r.PathPrefix("/img").Handler(spaStatic)
// SERVE FRONTEND - NO AUTH
spa := spaHandler{staticPath: "web/build", indexPath: "index.html"}
r.PathPrefix("/").Handler(spa)
@ -733,7 +740,7 @@ func getServerInfo(w http.ResponseWriter, r *http.Request) {
}
info := ServerInfo{
Version: "0.0.28",
Version: "0.0.29",
RegistrationEnabled: cachedRegistrationEnabled,
}

View file

@ -6,12 +6,43 @@ import (
"path/filepath"
)
// spaStaticHandler - Handles static imges
type spaStaticHandler struct {
staticPath string
indexPath string
}
// spaHandler - Handles Single Page Applications (React)
type spaHandler struct {
staticPath string
indexPath string
}
// ServerHTTP - Frontend React server
func (h spaStaticHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
http.ServeFile(w, r, filepath.Join(h.staticPath, "img/placeholder.jpg"))
return
}
path = filepath.Join(h.staticPath, path)
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve placeholder
http.ServeFile(w, r, filepath.Join(h.staticPath, "img/placeholder.jpg"))
return
} else if err != nil {
http.ServeFile(w, r, filepath.Join(h.staticPath, "img/placeholder.jpg"))
return
}
// otherwise, use http.FileServer to serve the static images
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}
// ServerHTTP - Frontend React server
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get the absolute path to prevent directory traversal

View file

@ -8,6 +8,9 @@ import (
var endTicker chan bool
func StartBackgroundWorkers() {
user, _ := getUserByUsername("idanoo")
go user.updateImageDataFromSpotify()
endTicker := make(chan bool)
hourTicker := time.NewTicker(time.Duration(1) * time.Hour)

View file

@ -166,7 +166,7 @@ func (track *Track) updateTrack(col string, val string, tx *sql.Tx) error {
func getTrackByUUID(uuid string) (Track, error) {
var track Track
err := db.QueryRow("SELECT BIN_TO_UUID(`tracks`.`uuid`, true), `tracks`.`name`, IFNULL(`albums`.`desc`,''), IFNULL(`albums`.`img`,''), `tracks`.`length`, `tracks`.`mbid`, `tracks`.`spotify_id` "+
err := db.QueryRow("SELECT BIN_TO_UUID(`tracks`.`uuid`, true), `tracks`.`name`, IFNULL(`albums`.`desc`,''), IFNULL(BIN_TO_UUID(`albums`.`uuid`, true),''), `tracks`.`length`, `tracks`.`mbid`, `tracks`.`spotify_id` "+
"FROM `tracks` "+
"LEFT JOIN track_album ON track_album.track = tracks.uuid "+
"LEFT JOIN albums ON track_album.album = albums.uuid "+
@ -184,7 +184,7 @@ func getTrackByUUID(uuid string) (Track, error) {
func getTopTracks(userUuid string) (TopTracks, error) {
var topTracks TopTracks
rows, err := db.Query("SELECT BIN_TO_UUID(`tracks`.`uuid`, true), `tracks`.`name`, IFNULL(`albums`.`img`,''), count(*) "+
rows, err := db.Query("SELECT BIN_TO_UUID(`tracks`.`uuid`, true), `tracks`.`name`, IFNULL(BIN_TO_UUID(`albums`.`uuid`, true),''), count(*) "+
"FROM `scrobbles` "+
"JOIN `tracks` ON `tracks`.`uuid` = `scrobbles`.`track` "+
"JOIN track_album ON track_album.track = tracks.uuid "+