diff --git a/.gitignore b/.gitignore index 4c852ee..00c37a0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ out .env assets/ samples/ + +.idea \ No newline at end of file diff --git a/handler_upload_thumbnail.go b/handler_upload_thumbnail.go index 765d87d..67594fb 100644 --- a/handler_upload_thumbnail.go +++ b/handler_upload_thumbnail.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "io" "net/http" "github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth" @@ -28,10 +29,57 @@ func (cfg *apiConfig) handlerUploadThumbnail(w http.ResponseWriter, r *http.Requ return } - fmt.Println("uploading thumbnail for video", videoID, "by user", userID) - // TODO: implement the upload here + var maxMemory int64 + maxMemory = 10 << 20 - respondWithJSON(w, http.StatusOK, struct{}{}) + err = r.ParseMultipartForm(maxMemory) + + if err != nil { + respondWithError(w, http.StatusBadRequest, "Couldn't parse multipart form", err) + } + + image, header, err := r.FormFile("thumbnail") + if err != nil { + respondWithError(w, http.StatusBadRequest, "Couldn't get file", err) + } + + mediaType := header.Header.Get("Content-Type") + + imageData, err := io.ReadAll(image) + if err != nil { + respondWithError(w, http.StatusBadRequest, "Couldn't read image", err) + } + + video, err := cfg.db.GetVideo(videoID) + if err != nil { + respondWithError(w, http.StatusBadRequest, "Couldn't find video", err) + } + if video.UserID != userID { + respondWithError(w, http.StatusUnauthorized, "You are not authorized to upload this video", err) + } + + thumb := thumbnail{ + data: imageData, + mediaType: mediaType, + } + + videoThumbnails[videoID] = thumb + + url := "http://localhost:" + cfg.port + "/api/thumbnails/" + videoID.String() + + video.ThumbnailURL = &url + + err = cfg.db.UpdateVideo(video) + if err != nil { + respondWithError(w, http.StatusBadRequest, "Couldn't update video", err) + } + + video, err = cfg.db.GetVideo(videoID) + if err != nil { + respondWithError(w, http.StatusBadRequest, "Couldn't find video", err) + } + + respondWithJSON(w, http.StatusOK, video) }