103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package http
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"go-socket/packages/convertions"
|
|
"go-socket/packages/globals"
|
|
"go-socket/packages/minio"
|
|
"go-socket/packages/postgresql"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func handleExistingUpload() {
|
|
|
|
}
|
|
|
|
func HandleFileUpload(response http.ResponseWriter, request *http.Request) {
|
|
if !postValidCheckWithResponseOnFail(&response, request, true) {
|
|
return
|
|
}
|
|
ctx := request.Context()
|
|
|
|
user, err := getUserByToken(ctx, request.Header.Get("token"))
|
|
if err != nil {
|
|
http.Error(response, "invalid token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
connectionId, err := convertions.ConvertStringUuid(request.FormValue("connectionid"))
|
|
if err != nil {
|
|
http.Error(response, "invalid connectionid", http.StatusBadRequest)
|
|
return
|
|
}
|
|
_, ok := user.Connections[connectionId]
|
|
if !ok {
|
|
http.Error(response, "no such connection", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
request.Body = http.MaxBytesReader(response, request.Body, int64(globals.MaxPostWithFileBytes))
|
|
multipartReader, err := request.MultipartReader()
|
|
if err != nil {
|
|
http.Error(response, "expected multipart form", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
uploaded := false
|
|
for {
|
|
part, err := multipartReader.NextPart()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
http.Error(response, "bad request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if part.FileName() == "" {
|
|
part.Close()
|
|
continue
|
|
}
|
|
|
|
if len(part.FileName()) != sha256.Size*2 {
|
|
part.Close()
|
|
http.Error(response, "filename must be hex-encoded sha256 of whole file", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
contentType := part.Header.Get("Content-Type")
|
|
key := minio.GetKey(part.FileName(), contentType)
|
|
|
|
if minio.DoesExist(ctx, key) {
|
|
part.Close()
|
|
uploaded = true
|
|
handleExistingUpload()
|
|
continue
|
|
}
|
|
|
|
id := uuid.New()
|
|
err = minio.Upload(ctx, key, part, -1, contentType, id)
|
|
|
|
postgresql.FileMetadataSave()
|
|
|
|
part.Close()
|
|
|
|
if err != nil {
|
|
http.Error(response, "upload failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
uploaded = true
|
|
}
|
|
|
|
if !uploaded {
|
|
http.Error(response, "no file in request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
response.WriteHeader(http.StatusAccepted)
|
|
}
|