Files
photoview/api/utils/media_cache.go
Kostiantyn 2b1240b88b Refactor API video route (#1202)
* Refactored code; temp disable workflows on push

* remove printf leftovers

* A better sanitizing code

* extend auth routes tests

* more tests, fix 2 bugs in token processing

* more refactoring and fixes

* optimize video mediaURLs DB query and make testCachePath in utils thread-safe

* fix always passing test

* and more refactoring; 1 more test, but cleanup still has to be fixed

* more debug code in the test

* fix the test

* Final commit

* Adding a defer function just in case of panic

* Address some of review comments

* Protect the shared var by mutex; implement correct context-aware scanning

* Better error; better initial func wrap/capture; better log messages in `photos.go`;

* Addressing a few more review comments

* Order the query results; a better error type catch; setting the MP4 content type header explicitly

* try to fix the cancelation detection condition

* Extract a function and call it by name

---------

Co-authored-by: Konstantin Koval
2025-06-18 20:38:19 +03:00

74 lines
1.8 KiB
Go

package utils
import (
"os"
"path"
"strconv"
"sync"
"github.com/pkg/errors"
)
// CachePathForMedia is a low-level implementation for Media.CachePath()
func CachePathForMedia(albumID int, mediaID int) (string, error) {
// Make root cache dir if not exists
if _, err := os.Stat(MediaCachePath()); os.IsNotExist(err) {
if err := os.Mkdir(MediaCachePath(), os.ModePerm); err != nil {
return "", errors.Wrap(err, "could not make root image cache directory")
}
}
// Make album cache dir if not exists
albumCachePath := path.Join(MediaCachePath(), strconv.Itoa(int(albumID)))
if _, err := os.Stat(albumCachePath); os.IsNotExist(err) {
if err := os.Mkdir(albumCachePath, os.ModePerm); err != nil {
return "", errors.Wrap(err, "could not make album image cache directory")
}
}
// Make photo cache dir if not exists
photoCachePath := path.Join(albumCachePath, strconv.Itoa(int(mediaID)))
if _, err := os.Stat(photoCachePath); os.IsNotExist(err) {
if err := os.Mkdir(photoCachePath, os.ModePerm); err != nil {
return "", errors.Wrap(err, "could not make photo image cache directory")
}
}
return photoCachePath, nil
}
var (
testCachePath string = ""
testCachePathLocker sync.RWMutex
)
func GetTestCachePath() string {
testCachePathLocker.RLock()
defer testCachePathLocker.RUnlock()
return testCachePath
}
func ConfigureTestCache(tmpDir string) {
testCachePathLocker.Lock()
defer testCachePathLocker.Unlock()
testCachePath = tmpDir
}
// MediaCachePath returns the path for where the media cache is located on the file system
func MediaCachePath() string {
testCachePathLocker.RLock()
cachedPath := testCachePath
testCachePathLocker.RUnlock()
if cachedPath != "" {
return cachedPath
}
photoCache := EnvMediaCachePath.GetValue()
if photoCache == "" {
photoCache = "./media_cache"
}
return photoCache
}