You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

84 lines
2.5 KiB

  1. package main
  2. import (
  3. "mime"
  4. "net/http"
  5. "path/filepath"
  6. "strings"
  7. )
  8. func HandleMedia(w http.ResponseWriter, r *http.Request) {
  9. if SelectedMediaStorage == nil {
  10. w.WriteHeader(http.StatusInternalServerError)
  11. _, _ = w.Write([]byte("No media storage configured"))
  12. return
  13. }
  14. if r.Method != "POST" {
  15. w.WriteHeader(http.StatusMethodNotAllowed)
  16. _, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
  17. return
  18. }
  19. if contentType := r.Header.Get("content-type"); !strings.Contains(contentType, "multipart/form-data") {
  20. w.WriteHeader(http.StatusBadRequest)
  21. _, _ = w.Write([]byte("Wrong Content-Type"))
  22. return
  23. }
  24. err := r.ParseMultipartForm(0)
  25. if err != nil {
  26. w.WriteHeader(http.StatusInternalServerError)
  27. _, _ = w.Write([]byte("Failed to parse Multipart"))
  28. return
  29. }
  30. authCode := r.Header.Get("authorization")
  31. if formAuth := r.FormValue("access_token"); len(authCode) == 0 && len(formAuth) > 0 {
  32. authCode = "Bearer " + formAuth
  33. }
  34. if CheckAuthorization(authCode) {
  35. file, header, err := r.FormFile("file")
  36. if err != nil {
  37. w.WriteHeader(http.StatusInternalServerError)
  38. _, _ = w.Write([]byte("Failed to get file"))
  39. return
  40. }
  41. defer func() { _ = file.Close() }()
  42. hashFile, _, _ := r.FormFile("file")
  43. defer func() { _ = hashFile.Close() }()
  44. fileName, err := getSHA256(hashFile)
  45. if err != nil {
  46. w.WriteHeader(http.StatusInternalServerError)
  47. _, _ = w.Write([]byte(err.Error()))
  48. return
  49. }
  50. fileExtension := filepath.Ext(header.Filename)
  51. if len(fileExtension) == 0 {
  52. // Find correct file extension if original filename does not contain one
  53. mimeType := header.Header.Get("content-type")
  54. if len(mimeType) > 0 {
  55. allExtensions, _ := mime.ExtensionsByType(mimeType)
  56. if len(allExtensions) > 0 {
  57. fileExtension = allExtensions[0]
  58. }
  59. }
  60. }
  61. fileName += strings.ToLower(fileExtension)
  62. location, err := SelectedMediaStorage.Upload(fileName, file)
  63. if err != nil {
  64. w.WriteHeader(http.StatusInternalServerError)
  65. _, _ = w.Write([]byte("Failed to upload original file"))
  66. return
  67. }
  68. if SelectedImageCompression != nil {
  69. compressedLocation, err := SelectedImageCompression.Compress(location)
  70. if err == nil && len(compressedLocation) > 0 {
  71. location = compressedLocation
  72. }
  73. }
  74. w.Header().Add("Location", location)
  75. w.WriteHeader(http.StatusCreated)
  76. } else {
  77. w.WriteHeader(http.StatusForbidden)
  78. _, _ = w.Write([]byte("Forbidden, there was a problem with the provided access token"))
  79. return
  80. }
  81. }