caching icons automatically

This commit is contained in:
Hazel Noack
2025-07-15 13:08:23 +02:00
parent e627d02d08
commit 808ce89dfc
4 changed files with 95 additions and 4 deletions

View File

@@ -136,3 +136,12 @@ func (rc *Config) LoadConfigFile(file string) error {
return toml.Unmarshal(content, rc)
}
func (c *Config) Init() error {
for i, w := range c.Template.Websites {
c.Template.Websites[i].Cache()
fmt.Println(w.ImageUrl)
}
return nil
}

View File

@@ -1,7 +1,76 @@
package rendering
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
)
type Website struct {
Url string
Name string
ImageUrl string
Url string
Name string
ImageUrl string
IsFetched bool
}
const CacheUrl = "cache"
func GetCacheDir() (string, error) {
baseDir, err := os.UserCacheDir()
if err != nil {
return "", err
}
cacheDir := filepath.Join(baseDir, "startpage")
err = os.MkdirAll(cacheDir, 0o755)
if err != nil {
return "", err
}
return cacheDir, nil
}
func hashUrl(url string) string {
h := sha1.New()
io.WriteString(h, url)
return hex.EncodeToString(h.Sum(nil))
}
func (w *Website) Cache() error {
if w.IsFetched {
return nil
}
cacheDir, err := GetCacheDir()
if err != nil {
return err
}
filename := hashUrl(w.ImageUrl)
fmt.Println(w.ImageUrl + " => " + filename)
targetPath := filepath.Join(cacheDir, filename)
resp, err := http.Get(w.ImageUrl)
if err != nil {
return err
}
defer resp.Body.Close()
file, err := os.Create(targetPath)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
return err
}
w.ImageUrl, _ = url.JoinPath(CacheUrl, filename)
w.IsFetched = true
return nil
}