file.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package model
  2. import (
  3. _ "gorm.io/driver/sqlite"
  4. "gorm.io/gorm"
  5. "one-api/common"
  6. "os"
  7. "path"
  8. )
  9. type File struct {
  10. Id int `json:"id"`
  11. Filename string `json:"filename" gorm:"index"`
  12. Description string `json:"description"`
  13. Uploader string `json:"uploader" gorm:"index"`
  14. UploaderId int `json:"uploader_id" gorm:"index"`
  15. Link string `json:"link" gorm:"unique;index"`
  16. UploadTime string `json:"upload_time"`
  17. DownloadCounter int `json:"download_counter"`
  18. }
  19. func GetAllFiles(startIdx int, num int) ([]*File, error) {
  20. var files []*File
  21. var err error
  22. err = DB.Order("id desc").Limit(num).Offset(startIdx).Find(&files).Error
  23. return files, err
  24. }
  25. func SearchFiles(keyword string) (files []*File, err error) {
  26. err = DB.Select([]string{"id", "filename", "description", "uploader", "uploader_id", "link", "upload_time", "download_counter"}).Where(
  27. "filename LIKE ? or uploader LIKE ? or uploader_id = ?", keyword+"%", keyword+"%", keyword).Find(&files).Error
  28. return files, err
  29. }
  30. func (file *File) Insert() error {
  31. var err error
  32. err = DB.Create(file).Error
  33. return err
  34. }
  35. // Delete Make sure link is valid! Because we will use os.Remove to delete it!
  36. func (file *File) Delete() error {
  37. var err error
  38. err = DB.Delete(file).Error
  39. err = os.Remove(path.Join(common.UploadPath, file.Link))
  40. return err
  41. }
  42. func UpdateDownloadCounter(link string) {
  43. DB.Model(&File{}).Where("link = ?", link).UpdateColumn("download_counter", gorm.Expr("download_counter + 1"))
  44. }