cache_center.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package cache_center
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "sync"
  7. "github.com/ChineseSubFinder/ChineseSubFinder/pkg"
  8. "github.com/ChineseSubFinder/ChineseSubFinder/pkg/cache_center/models"
  9. "github.com/sirupsen/logrus"
  10. "gorm.io/driver/sqlite"
  11. "gorm.io/gorm"
  12. )
  13. type CacheCenter struct {
  14. Log *logrus.Logger
  15. centerFolder string
  16. downloadFileSaveRootPath string
  17. taskQueueSaveRootPath string
  18. dbFPath string
  19. cacheName string
  20. db *gorm.DB
  21. locker sync.Mutex
  22. }
  23. func NewCacheCenter(cacheName string, Log *logrus.Logger) *CacheCenter {
  24. c := CacheCenter{}
  25. c.Log = Log
  26. var err error
  27. c.centerFolder, err = pkg.GetRootCacheCenterFolder()
  28. if err != nil {
  29. panic(err)
  30. }
  31. c.taskQueueSaveRootPath = filepath.Join(c.centerFolder, taskQueueFolderName, cacheName)
  32. c.downloadFileSaveRootPath = filepath.Join(c.centerFolder, downloadFilesFolderName, cacheName)
  33. c.dbFPath = filepath.Join(c.centerFolder, cacheName+"_"+dbFileName)
  34. c.db, err = gorm.Open(sqlite.Open(c.dbFPath), &gorm.Config{})
  35. if err != nil {
  36. panic(fmt.Sprintf("failed to connect database, %s", err.Error()))
  37. }
  38. // 迁移 schema
  39. err = c.db.AutoMigrate(&models.DailyDownloadInfo{}, &models.TaskQueueInfo{}, &models.DownloadFileInfo{})
  40. if err != nil {
  41. panic(fmt.Sprintf("db AutoMigrate error, %s", err.Error()))
  42. }
  43. return &c
  44. }
  45. func (c *CacheCenter) GetName() string {
  46. return c.cacheName
  47. }
  48. func (c *CacheCenter) Close() {
  49. defer c.locker.Unlock()
  50. c.locker.Lock()
  51. sqlDB, err := c.db.DB()
  52. if err != nil {
  53. return
  54. }
  55. err = sqlDB.Close()
  56. if err != nil {
  57. return
  58. }
  59. }
  60. func DelDb(cacheName string) {
  61. centerFolder, err := pkg.GetRootCacheCenterFolder()
  62. if err != nil {
  63. return
  64. }
  65. dbFPath := filepath.Join(centerFolder, cacheName+"_"+dbFileName)
  66. if pkg.IsFile(dbFPath) == true {
  67. err = os.Remove(dbFPath)
  68. if err != nil {
  69. return
  70. }
  71. }
  72. taskQueueSaveRootPath := filepath.Join(centerFolder, taskQueueFolderName, cacheName)
  73. err = pkg.ClearFolder(taskQueueSaveRootPath)
  74. if err != nil {
  75. return
  76. }
  77. downloadFileSaveRootPath := filepath.Join(centerFolder, downloadFilesFolderName, cacheName)
  78. err = pkg.ClearFolder(downloadFileSaveRootPath)
  79. if err != nil {
  80. return
  81. }
  82. }
  83. const (
  84. taskQueueFolderName = "task_queue"
  85. downloadFilesFolderName = "download_files"
  86. dbFileName = "cache_center.db"
  87. )