code.gitea.io/gitea@v1.21.7/models/repo/upload.go (about)

     1  // Copyright 2016 The Gogs Authors. All rights reserved.
     2  // Copyright 2019 The Gitea Authors. All rights reserved.
     3  // SPDX-License-Identifier: MIT
     4  
     5  package repo
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"io"
    11  	"mime/multipart"
    12  	"os"
    13  	"path"
    14  
    15  	"code.gitea.io/gitea/models/db"
    16  	"code.gitea.io/gitea/modules/log"
    17  	"code.gitea.io/gitea/modules/setting"
    18  	"code.gitea.io/gitea/modules/util"
    19  
    20  	gouuid "github.com/google/uuid"
    21  )
    22  
    23  // ErrUploadNotExist represents a "UploadNotExist" kind of error.
    24  type ErrUploadNotExist struct {
    25  	ID   int64
    26  	UUID string
    27  }
    28  
    29  // IsErrUploadNotExist checks if an error is a ErrUploadNotExist.
    30  func IsErrUploadNotExist(err error) bool {
    31  	_, ok := err.(ErrUploadNotExist)
    32  	return ok
    33  }
    34  
    35  func (err ErrUploadNotExist) Error() string {
    36  	return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
    37  }
    38  
    39  func (err ErrUploadNotExist) Unwrap() error {
    40  	return util.ErrNotExist
    41  }
    42  
    43  // Upload represent a uploaded file to a repo to be deleted when moved
    44  type Upload struct {
    45  	ID   int64  `xorm:"pk autoincr"`
    46  	UUID string `xorm:"uuid UNIQUE"`
    47  	Name string
    48  }
    49  
    50  func init() {
    51  	db.RegisterModel(new(Upload))
    52  }
    53  
    54  // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
    55  func UploadLocalPath(uuid string) string {
    56  	return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
    57  }
    58  
    59  // LocalPath returns where uploads are temporarily stored in local file system.
    60  func (upload *Upload) LocalPath() string {
    61  	return UploadLocalPath(upload.UUID)
    62  }
    63  
    64  // NewUpload creates a new upload object.
    65  func NewUpload(ctx context.Context, name string, buf []byte, file multipart.File) (_ *Upload, err error) {
    66  	upload := &Upload{
    67  		UUID: gouuid.New().String(),
    68  		Name: name,
    69  	}
    70  
    71  	localPath := upload.LocalPath()
    72  	if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
    73  		return nil, fmt.Errorf("MkdirAll: %w", err)
    74  	}
    75  
    76  	fw, err := os.Create(localPath)
    77  	if err != nil {
    78  		return nil, fmt.Errorf("Create: %w", err)
    79  	}
    80  	defer fw.Close()
    81  
    82  	if _, err = fw.Write(buf); err != nil {
    83  		return nil, fmt.Errorf("Write: %w", err)
    84  	} else if _, err = io.Copy(fw, file); err != nil {
    85  		return nil, fmt.Errorf("Copy: %w", err)
    86  	}
    87  
    88  	if _, err := db.GetEngine(ctx).Insert(upload); err != nil {
    89  		return nil, err
    90  	}
    91  
    92  	return upload, nil
    93  }
    94  
    95  // GetUploadByUUID returns the Upload by UUID
    96  func GetUploadByUUID(ctx context.Context, uuid string) (*Upload, error) {
    97  	upload := &Upload{}
    98  	has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(upload)
    99  	if err != nil {
   100  		return nil, err
   101  	} else if !has {
   102  		return nil, ErrUploadNotExist{0, uuid}
   103  	}
   104  	return upload, nil
   105  }
   106  
   107  // GetUploadsByUUIDs returns multiple uploads by UUIDS
   108  func GetUploadsByUUIDs(ctx context.Context, uuids []string) ([]*Upload, error) {
   109  	if len(uuids) == 0 {
   110  		return []*Upload{}, nil
   111  	}
   112  
   113  	// Silently drop invalid uuids.
   114  	uploads := make([]*Upload, 0, len(uuids))
   115  	return uploads, db.GetEngine(ctx).In("uuid", uuids).Find(&uploads)
   116  }
   117  
   118  // DeleteUploads deletes multiple uploads
   119  func DeleteUploads(ctx context.Context, uploads ...*Upload) (err error) {
   120  	if len(uploads) == 0 {
   121  		return nil
   122  	}
   123  
   124  	ctx, committer, err := db.TxContext(ctx)
   125  	if err != nil {
   126  		return err
   127  	}
   128  	defer committer.Close()
   129  
   130  	ids := make([]int64, len(uploads))
   131  	for i := 0; i < len(uploads); i++ {
   132  		ids[i] = uploads[i].ID
   133  	}
   134  	if _, err = db.GetEngine(ctx).
   135  		In("id", ids).
   136  		Delete(new(Upload)); err != nil {
   137  		return fmt.Errorf("delete uploads: %w", err)
   138  	}
   139  
   140  	if err = committer.Commit(); err != nil {
   141  		return err
   142  	}
   143  
   144  	for _, upload := range uploads {
   145  		localPath := upload.LocalPath()
   146  		isFile, err := util.IsFile(localPath)
   147  		if err != nil {
   148  			log.Error("Unable to check if %s is a file. Error: %v", localPath, err)
   149  		}
   150  		if !isFile {
   151  			continue
   152  		}
   153  
   154  		if err := util.Remove(localPath); err != nil {
   155  			return fmt.Errorf("remove upload: %w", err)
   156  		}
   157  	}
   158  
   159  	return nil
   160  }
   161  
   162  // DeleteUploadByUUID deletes a upload by UUID
   163  func DeleteUploadByUUID(ctx context.Context, uuid string) error {
   164  	upload, err := GetUploadByUUID(ctx, uuid)
   165  	if err != nil {
   166  		if IsErrUploadNotExist(err) {
   167  			return nil
   168  		}
   169  		return fmt.Errorf("GetUploadByUUID: %w", err)
   170  	}
   171  
   172  	if err := DeleteUploads(ctx, upload); err != nil {
   173  		return fmt.Errorf("DeleteUpload: %w", err)
   174  	}
   175  
   176  	return nil
   177  }