gosplash/internal/unsplash/image.go
2023-11-23 14:24:28 +01:00

64 lines
1.4 KiB
Go

package unsplash
import (
"io"
"net/http"
"os"
"path/filepath"
"time"
"git.velvettear.de/velvettear/gosplash/internal/config"
"git.velvettear.de/velvettear/loggo"
)
// struct for images
type Image struct {
Id string
Name string
Url string
}
// download an image to the specified output path
func (image *Image) Download() (string, error) {
timestamp := time.Now().UnixMilli()
if !image.IsValid() {
return "image is invalid", nil
}
if image.Exists() {
return "image already exists", nil
}
path := image.getPath()
loggo.Info("downloading image '" + image.Name + "' from unsplash...")
loggo.Debug("id: " + image.Id + " | url: " + image.Url + " | path: " + path)
response, error := http.Get(image.Url)
if error != nil {
return "", error
}
data, error := io.ReadAll(response.Body)
if error != nil {
return "", error
}
error = os.WriteFile(path, data, 0775)
if error != nil {
return "", error
}
loggo.InfoTimed("successfully saved image '"+image.Name+"' to '"+path+"'", timestamp)
return "", nil
}
// check if an image already exists
func (image *Image) Exists() bool {
_, error := os.Stat(image.getPath())
return !os.IsNotExist(error)
}
// check if an image is valid
func (image *Image) IsValid() bool {
return len(image.Id) > 0 && len(image.Name) > 0 && len(image.Url) > 0
}
// get the output path for an image
func (image *Image) getPath() string {
return filepath.Join(config.Output, image.Name) + ".jpeg"
}