81 lines
2.3 KiB
Go
81 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func HandleMedia(w http.ResponseWriter, r *http.Request) {
|
|
if SelectedMediaStorage == nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("No media storage configured"))
|
|
return
|
|
}
|
|
if r.Method != "POST" {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
_, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
|
|
return
|
|
}
|
|
if contentType := r.Header.Get("content-type"); !strings.Contains(contentType, "multipart/form-data") {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
_, _ = w.Write([]byte("Wrong Content-Type"))
|
|
return
|
|
}
|
|
err := r.ParseMultipartForm(0)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to parse Multipart"))
|
|
return
|
|
}
|
|
authCode := r.Header.Get("authorization")
|
|
if formAuth := r.FormValue("access_token"); len(authCode) == 0 && len(formAuth) > 0 {
|
|
authCode = "Bearer " + formAuth
|
|
}
|
|
if CheckAuthorization(authCode) {
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to get file"))
|
|
return
|
|
}
|
|
hashFile, _, _ := r.FormFile("file")
|
|
h := sha256.New()
|
|
defer func() { _ = hashFile.Close() }()
|
|
if _, err := io.Copy(h, hashFile); err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to calculate hash of file"))
|
|
return
|
|
}
|
|
fileName := fmt.Sprintf("%x", h.Sum(nil))
|
|
fileExtension := filepath.Ext(header.Filename)
|
|
if len(fileExtension) == 0 {
|
|
// Find correct file extension if original filename does not contain one
|
|
mimeType := header.Header.Get("content-type")
|
|
if len(mimeType) > 0 {
|
|
allExtensions, _ := mime.ExtensionsByType(mimeType)
|
|
if len(allExtensions) > 0 {
|
|
fileExtension = allExtensions[0]
|
|
}
|
|
}
|
|
}
|
|
fileName += fileExtension
|
|
location, err := SelectedMediaStorage.Upload(fileName, file)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("Failed to upload file"))
|
|
return
|
|
}
|
|
w.Header().Add("Location", location)
|
|
w.WriteHeader(http.StatusCreated)
|
|
} else {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
_, _ = w.Write([]byte("Forbidden, there was a problem with the provided access token"))
|
|
return
|
|
}
|
|
}
|