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.

attachment.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package attachment
  4. import (
  5. "bytes"
  6. "context"
  7. "fmt"
  8. "io"
  9. "code.gitea.io/gitea/models/db"
  10. repo_model "code.gitea.io/gitea/models/repo"
  11. "code.gitea.io/gitea/modules/storage"
  12. "code.gitea.io/gitea/modules/upload"
  13. "code.gitea.io/gitea/modules/util"
  14. "github.com/google/uuid"
  15. )
  16. // NewAttachment creates a new attachment object, but do not verify.
  17. func NewAttachment(attach *repo_model.Attachment, file io.Reader, size int64) (*repo_model.Attachment, error) {
  18. if attach.RepoID == 0 {
  19. return nil, fmt.Errorf("attachment %s should belong to a repository", attach.Name)
  20. }
  21. err := db.WithTx(db.DefaultContext, func(ctx context.Context) error {
  22. attach.UUID = uuid.New().String()
  23. size, err := storage.Attachments.Save(attach.RelativePath(), file, size)
  24. if err != nil {
  25. return fmt.Errorf("Create: %w", err)
  26. }
  27. attach.Size = size
  28. return db.Insert(ctx, attach)
  29. })
  30. return attach, err
  31. }
  32. // UploadAttachment upload new attachment into storage and update database
  33. func UploadAttachment(file io.Reader, allowedTypes string, fileSize int64, opts *repo_model.Attachment) (*repo_model.Attachment, error) {
  34. buf := make([]byte, 1024)
  35. n, _ := util.ReadAtMost(file, buf)
  36. buf = buf[:n]
  37. if err := upload.Verify(buf, opts.Name, allowedTypes); err != nil {
  38. return nil, err
  39. }
  40. return NewAttachment(opts, io.MultiReader(bytes.NewReader(buf), file), fileSize)
  41. }