code.gitea.io/gitea@v1.21.7/services/attachment/attachment.go (about)

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