GraphQL API and utilities for the rpdata project
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.

52 lines
1.0 KiB

  1. package files
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "time"
  7. "git.aiterp.net/rpdata/api/internal/store"
  8. "git.aiterp.net/rpdata/api/models"
  9. )
  10. // Upload adds a file to the space.
  11. func Upload(ctx context.Context, name, mimeType, author string, size int64, input io.Reader) (models.File, error) {
  12. if !allowdMimeTypes[mimeType] {
  13. return models.File{}, errors.New("File type not allowed:" + mimeType)
  14. }
  15. if name == "" {
  16. date := time.Now().UTC().Format("Jan 02 2006 15:04:05 MST")
  17. name = "Unnamed file (" + date + ")"
  18. }
  19. if mimeType == "" {
  20. mimeType = "binary/octet-stream"
  21. }
  22. id := makeID()
  23. path, err := store.UploadFile(ctx, "files", id, mimeType, input, size)
  24. if err != nil {
  25. return models.File{}, err
  26. }
  27. file := models.File{
  28. ID: id,
  29. Kind: "upload",
  30. Time: time.Now(),
  31. Public: false,
  32. Author: author,
  33. Name: name,
  34. MimeType: mimeType,
  35. Size: size,
  36. URL: store.URLFromPath(path),
  37. }
  38. err = collection.Insert(file)
  39. if err != nil {
  40. return models.File{}, err
  41. }
  42. return file, nil
  43. }