Select Git revision
api_views.go 7.76 KiB
package frontend
import (
"encoding/json"
// "fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"time"
"git.autistici.org/ale/djrandom/api"
"git.autistici.org/ale/djrandom/util"
db_client "git.autistici.org/ale/djrandom/services/database/client"
"github.com/gorilla/mux"
)
var (
numParallelQueries = 20
)
func sendJsonResponse(w http.ResponseWriter, resp interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// Upload receives files from sync clients, saves them to permanent
// storage and creates new Song objects in the db.
func Upload(w http.ResponseWriter, r *djRequest) {
// Create a local temporary file, and copy the request body to
// it. As soon as this is done, return an 'ok' response to the
// client (and process the file in the background).
tmpf, err := util.TempFile("djrandom-upload-", "")
if err != nil {
log.Printf("Upload(): Error creating temporary file: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer r.Request.Body.Close()
_, err = io.Copy(tmpf, r.Request.Body)
if err != nil {
log.Printf("Upload(): Error saving file to local storage: %s", err)
os.Remove(tmpf.Name())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
tmpf.Close()
// Run further processing in the background. AnalyzeAndStore
// will remove the file when it's done.
go AnalyzeAndStore(r.Ctx, tmpf.Name())
sendJsonResponse(w, &api.UploadResponse{Ok: true})
}
// GetSongInfo returns data on a specific song.
func GetSongInfo(w http.ResponseWriter, r *djRequest) {
vars := mux.Vars(r.Request)
songId := vars["id"]
log.Printf("GetSongInfo(%s)", songId)
song, ok := r.Ctx.Db.GetSong(nil, songId)
if !ok {
http.Error(w, "Not Found", http.StatusNotFound)
return
}