Fix invalid image URLs & dynamic scrolling

This commit is contained in:
partisan 2024-11-14 16:33:04 +01:00
parent 01c48fd366
commit b6fd92673c
2 changed files with 129 additions and 56 deletions

View file

@ -25,7 +25,7 @@ import (
var (
cachingImages = make(map[string]*sync.Mutex)
cachingImagesMu sync.Mutex
cachingSemaphore = make(chan struct{}, 10) // Limit to 10 concurrent downloads
cachingSemaphore = make(chan struct{}, 30) // Limit to concurrent downloads
invalidImageIDs = make(map[string]struct{})
invalidImageIDsMu sync.Mutex
@ -34,6 +34,7 @@ var (
func cacheImage(imageURL, filename, imageID string) (string, bool, error) {
cacheDir := "image_cache"
cachedImagePath := filepath.Join(cacheDir, filename)
tempImagePath := cachedImagePath + ".tmp"
// Check if the image is already cached
if _, err := os.Stat(cachedImagePath); err == nil {
@ -96,8 +97,15 @@ func cacheImage(imageURL, filename, imageID string) (string, bool, error) {
os.Mkdir(cacheDir, os.ModePerm)
}
// Save the SVG file as-is
err = os.WriteFile(cachedImagePath, data, 0644)
// Save the SVG file as-is to the temp path
err = os.WriteFile(tempImagePath, data, 0644)
if err != nil {
recordInvalidImageID(imageID)
return "", false, err
}
// Atomically rename the temp file to the final cached image path
err = os.Rename(tempImagePath, cachedImagePath)
if err != nil {
recordInvalidImageID(imageID)
return "", false, err
@ -141,17 +149,25 @@ func cacheImage(imageURL, filename, imageID string) (string, bool, error) {
os.Mkdir(cacheDir, os.ModePerm)
}
// Open the cached file for writing
outFile, err := os.Create(cachedImagePath)
// Open the temp file for writing
outFile, err := os.Create(tempImagePath)
if err != nil {
recordInvalidImageID(imageID)
return "", false, err
}
defer outFile.Close()
// Encode the image to WebP and save
// Encode the image to WebP and save to the temp file
options := &webp.Options{Lossless: false, Quality: 80}
err = webp.Encode(outFile, img, options)
if err != nil {
outFile.Close()
recordInvalidImageID(imageID)
return "", false, err
}
outFile.Close()
// Atomically rename the temp file to the final cached image path
err = os.Rename(tempImagePath, cachedImagePath)
if err != nil {
recordInvalidImageID(imageID)
return "", false, err