added caching of images to the drive

This commit is contained in:
partisan 2024-10-13 00:04:46 +02:00
parent 48994ee32d
commit 3d47c80446
11 changed files with 451 additions and 33 deletions

View file

@ -1,6 +1,8 @@
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"net/http"
"time"
@ -96,16 +98,41 @@ func fetchImageResults(query, safe, lang string, page int) []ImageSearchResult {
}
for _, result := range searchResults {
results = append(results, result.(ImageSearchResult))
imageResult := result.(ImageSearchResult)
if config.HardCacheDuration > 0 {
// Save the original Media URL before overwriting
originalMediaURL := imageResult.Media
// Generate hash from the original media URL
hasher := md5.New()
hasher.Write([]byte(originalMediaURL))
hash := hex.EncodeToString(hasher.Sum(nil))
filename := hash + ".webp"
// Set the Media URL to point to the cached image path
cacheURL := "/image_cache/" + filename
imageResult.Media = cacheURL
imageResult.ThumbProxy = cacheURL
// Assign the ID
imageResult.ID = hash
// Start caching in the background
go func(originalURL, filename string) {
_, err := cacheImage(originalURL, filename)
if err != nil {
printWarn("Failed to cache image %s: %v", originalURL, err)
}
}(originalMediaURL, filename)
}
results = append(results, imageResult)
}
// If results are found, break out of the loop
if len(results) > 0 {
break
}
}
// If no results found after trying all engines
if len(results) == 0 {
printWarn("No image results found for query: %s, trying other nodes", query)
results = tryOtherNodesForImageSearch(query, safe, lang, page, []string{hostID})