download_file_info.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package cache_center
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/allanpk716/ChineseSubFinder/internal/pkg/cache_center/models"
  6. "github.com/allanpk716/ChineseSubFinder/internal/pkg/my_util"
  7. "github.com/allanpk716/ChineseSubFinder/internal/types/supplier"
  8. "os"
  9. "path/filepath"
  10. "time"
  11. )
  12. func (c *CacheCenter) DownloadFileAdd(subInfo *supplier.SubInfo) error {
  13. defer c.locker.Unlock()
  14. c.locker.Lock()
  15. if subInfo.FileUrl == "" {
  16. return errors.New("subInfo FileUrl is empty")
  17. }
  18. // 只支持秒或者小时为单位
  19. tmpTTL := time.Duration(c.Settings.AdvancedSettings.DownloadFileCache.TTL) * time.Second
  20. if c.Settings.AdvancedSettings.DownloadFileCache.Unit == "hour" {
  21. tmpTTL = time.Duration(c.Settings.AdvancedSettings.DownloadFileCache.TTL) * time.Hour
  22. } else {
  23. tmpTTL = time.Duration(c.Settings.AdvancedSettings.DownloadFileCache.TTL) * time.Second
  24. }
  25. b, err := json.Marshal(subInfo)
  26. if err != nil {
  27. return err
  28. }
  29. // 保存到本地文件
  30. todayString := time.Now().Format("2006-01-02")
  31. saveFPath := filepath.Join(c.downloadFileSaveRootPath, todayString, subInfo.GetUID())
  32. err = my_util.WriteFile(saveFPath, b)
  33. if err != nil {
  34. return err
  35. }
  36. relPath, err := filepath.Rel(c.downloadFileSaveRootPath, saveFPath)
  37. if err != nil {
  38. return err
  39. }
  40. df := models.DownloadFileInfo{
  41. UID: subInfo.GetUID(),
  42. RelPath: relPath,
  43. ExpirationTime: time.Now().Add(tmpTTL),
  44. }
  45. c.db.Save(&df)
  46. return nil
  47. }
  48. func (c *CacheCenter) DownloadFileGet(fileUrlUID string) (bool, *supplier.SubInfo, error) {
  49. defer c.locker.Unlock()
  50. c.locker.Lock()
  51. var dfs []models.DownloadFileInfo
  52. c.db.Where("uid = ?", fileUrlUID).Find(&dfs)
  53. if len(dfs) == 0 {
  54. return false, nil, nil
  55. }
  56. localFileFPath := filepath.Join(c.downloadFileSaveRootPath, dfs[0].RelPath)
  57. if my_util.IsFile(localFileFPath) == false {
  58. return false, nil, nil
  59. }
  60. bytes, err := os.ReadFile(localFileFPath)
  61. if err != nil {
  62. return false, nil, err
  63. }
  64. var subInfo supplier.SubInfo
  65. err = json.Unmarshal(bytes, &subInfo)
  66. if err != nil {
  67. return false, nil, err
  68. }
  69. return true, &subInfo, nil
  70. }