1package services
2
3import (
4 "errors"
5 "io"
6 "os"
7 "path/filepath"
8
9 "github.com/dinkelspiel/cdn/dao"
10 "github.com/dinkelspiel/cdn/db"
11 "github.com/dinkelspiel/cdn/models"
12 "github.com/google/uuid"
13)
14
15func getCacheDirectory() string {
16 config, _ := LoadConfig()
17 cacheDirectory := filepath.Join(config.StorageUrl, "/.cache")
18 return cacheDirectory
19}
20
21func CacheImage(teamProject models.TeamProject, db *db.DB, image io.Reader, directory string, file string, width int, height int) error {
22 cacheDirectory := getCacheDirectory()
23 cacheFile := uuid.NewString() + filepath.Ext(file)
24 cacheFilePath := filepath.Join(cacheDirectory, cacheFile)
25
26 if err := os.MkdirAll(cacheDirectory, os.ModePerm); err != nil {
27 return err
28 }
29
30 outFile, err := os.Create(cacheFilePath)
31 if err != nil {
32 return err
33 }
34 defer outFile.Close()
35
36 size, err := io.Copy(outFile, image)
37 if err != nil {
38 return err
39 }
40
41 cachedImage := models.CachedImage{
42 Width: width,
43 Height: height,
44 CacheFile: cacheFile,
45 Directory: directory,
46 File: file,
47 SizeBytes: size,
48 TeamProjectId: *teamProject.Id,
49 TeamProject: &teamProject,
50 }
51
52 _, err = dao.CreateCachedImage(db, cachedImage)
53 if err != nil {
54 return err
55 }
56 return nil
57}
58
59func RetrieveCachedImagePath(db *db.DB, directory string, file string, width int, height int) (*string, error) {
60 cachedImage, err := dao.GetCachedImageByOriginalAndWidthAndHeight(db, directory, file, width, height)
61 if err != nil {
62 return nil, err
63 }
64 if cachedImage == nil {
65 return nil, errors.New("no cache exists")
66 }
67
68 cacheDirectory := getCacheDirectory()
69 cacheFilePath := filepath.Join(cacheDirectory, cachedImage.CacheFile)
70 return &cacheFilePath, nil
71}