stufflog graphql server
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.

53 lines
1.1 KiB

  1. package services
  2. import (
  3. "context"
  4. "git.aiterp.net/stufflog/server/internal/slerrors"
  5. "git.aiterp.net/stufflog/server/internal/space"
  6. "io"
  7. "strings"
  8. )
  9. type Upload struct {
  10. s3 *space.Space
  11. }
  12. func (upload *Upload) UploadImage(ctx context.Context, name string, contentType string, size int64, reader io.Reader) (string, error) {
  13. if !allowedImages[contentType] {
  14. return "", slerrors.Forbidden("Content type " + contentType + " is not allowed as an image.")
  15. }
  16. if !strings.HasSuffix(name, extensions[contentType]) {
  17. name += extensions[contentType]
  18. }
  19. err := upload.s3.UploadFile(ctx, name, contentType, reader, size)
  20. if err != nil {
  21. return "", err
  22. }
  23. return upload.s3.URLFromPath(name), nil
  24. }
  25. func (upload *Upload) Delete(ctx context.Context, url string) error {
  26. name, err := upload.s3.PathFromURL(url)
  27. if err != nil {
  28. return err
  29. }
  30. return upload.s3.RemoveFile(ctx, name)
  31. }
  32. var allowedImages = map[string]bool{
  33. "image/jpg": true,
  34. "image/jpeg": true,
  35. "image/gif": true,
  36. "image/png": true,
  37. "image/bmp": false,
  38. }
  39. var extensions = map[string]string{
  40. "image/jpg": ".jpg",
  41. "image/jpeg": ".jpg",
  42. "image/gif": ".gif",
  43. "image/png": ".png",
  44. }