mirror of
https://github.com/Luzifer/streamdeck.git
synced 2024-12-20 09:41:19 +00:00
Add URL-support for images
Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
parent
3b9fd45282
commit
b537cc0d31
1 changed files with 49 additions and 1 deletions
|
@ -2,10 +2,15 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
@ -19,7 +24,36 @@ type displayElementImage struct{}
|
|||
func (d displayElementImage) Display(ctx context.Context, idx int, attributes map[string]interface{}) error {
|
||||
filename, ok := attributes["path"].(string)
|
||||
if !ok {
|
||||
return errors.New("No path attribute specified")
|
||||
url, ok := attributes["url"].(string)
|
||||
if !ok {
|
||||
return errors.New("No path or url attribute specified")
|
||||
}
|
||||
|
||||
var err error
|
||||
filename, err = d.getCacheFileName(url)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Unable to get cache filename for image url")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Unable to request image url")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
imgFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Unable to create cache file")
|
||||
}
|
||||
|
||||
if _, err = io.Copy(imgFile, resp.Body); err != nil {
|
||||
imgFile.Close()
|
||||
return errors.Wrap(err, "Unable to download file")
|
||||
}
|
||||
|
||||
imgFile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.Open(filename)
|
||||
|
@ -42,3 +76,17 @@ func (d displayElementImage) Display(ctx context.Context, idx int, attributes ma
|
|||
|
||||
return errors.Wrap(sd.FillImage(idx, img), "Unable to set image")
|
||||
}
|
||||
|
||||
func (d displayElementImage) getCacheFileName(url string) (string, error) {
|
||||
ucd, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "Unable to get user cache dir")
|
||||
}
|
||||
|
||||
cacheDir := path.Join(ucd, "io.luzifer.streamdeck")
|
||||
if err = os.MkdirAll(cacheDir, 0750); err != nil {
|
||||
return "", errors.Wrap(err, "Unable to create cache dir")
|
||||
}
|
||||
|
||||
return path.Join(cacheDir, fmt.Sprintf("%x", sha256.Sum256([]byte(url)))), nil
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue