diff --git a/main.go b/main.go index 08e2756..d8232e7 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "io" "math/rand" "net/http" "net/url" @@ -36,7 +37,8 @@ func main() { r.HandleFunc("/playlist-names/", GetPlaylistNamesHandler).Methods("GET") r.HandleFunc("/playlist/{playlist}/", GetPlaylistHandler).Methods("GET") r.HandleFunc("/file/{file}/", GetFileHandler).Methods("GET") - r.HandleFunc("/file/{file}/{format}/", GetEncodeFileHandler).Methods("GET") + r.HandleFunc("/file/{file}/hash/", GetFileHashHandler).Methods("GET") + r.HandleFunc("/file/{file}/format/{format}/", GetEncodeFileHandler).Methods("GET") r.HandleFunc("/file/", GetAllFilesHandler).Methods("GET") fmt.Printf("Starting music server on port %d\n", HttpPort) @@ -89,6 +91,34 @@ func GetFileHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, filepath.Join(LibraryPath, ".songs", fileName)) } +func GetFileHashHandler(w http.ResponseWriter, r *http.Request) { + fileName, err := url.QueryUnescape(mux.Vars(r)["file"]) + if err != nil { + InternalServerError(w, err) + return + } + + filePath := filepath.Join(LibraryPath, ".songs", fileName) + + f, err := os.Open(filePath) + if err != nil { + InternalServerError(w, err) + return + } + defer f.Close() + + hasher := sha512.New() + if _, err := io.Copy(hasher, f); err != nil { + InternalServerError(w, err) + return + } + + if _, err := fmt.Fprint(w, hex.EncodeToString(hasher.Sum(nil))); err != nil { + InternalServerError(w, err) + return + } +} + func GetPlaylistHandler(w http.ResponseWriter, r *http.Request) { playlistName := mux.Vars(r)["playlist"]