2020-01-19 09:55:18 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-01-23 20:56:02 +00:00
|
|
|
tfgo "codeberg.org/jlelse/tinify"
|
2020-01-19 09:55:18 +00:00
|
|
|
"errors"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"sort"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ImageCompression interface {
|
|
|
|
Compress(url string) (location string, err error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Tinify
|
|
|
|
type Tinify struct {
|
|
|
|
// API Key
|
|
|
|
key string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t Tinify) Compress(url string) (location string, err error) {
|
|
|
|
fileExtension := func() string {
|
|
|
|
spliced := strings.Split(url, ".")
|
|
|
|
return spliced[len(spliced)-1]
|
|
|
|
}()
|
|
|
|
supportedTypes := []string{"jpg", "jpeg", "png"}
|
|
|
|
sort.Strings(supportedTypes)
|
|
|
|
i := sort.SearchStrings(supportedTypes, strings.ToLower(fileExtension))
|
|
|
|
if !(i < len(supportedTypes) && supportedTypes[i] == strings.ToLower(fileExtension)) {
|
|
|
|
err = errors.New("file not supported")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
tfgo.SetKey(t.key)
|
|
|
|
s, e := tfgo.FromUrl(url)
|
|
|
|
if e != nil {
|
|
|
|
err = errors.New("failed to compress file")
|
|
|
|
return
|
|
|
|
}
|
2020-01-23 20:56:02 +00:00
|
|
|
e = s.Resize(&tfgo.ResizeOption{
|
|
|
|
Method: tfgo.ResizeMethodScale,
|
|
|
|
Width: 2000,
|
|
|
|
})
|
|
|
|
if e != nil {
|
|
|
|
err = errors.New("failed to resize file")
|
|
|
|
return
|
|
|
|
}
|
2020-01-19 09:55:18 +00:00
|
|
|
file, e := ioutil.TempFile("", "tiny-*."+fileExtension)
|
|
|
|
if e != nil {
|
|
|
|
err = errors.New("failed to create temporary file")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
_ = os.Remove(file.Name())
|
|
|
|
}()
|
|
|
|
e = s.ToFile(file.Name())
|
|
|
|
if e != nil {
|
|
|
|
err = errors.New("failed to save compressed file")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
hashFile, e := os.Open(file.Name())
|
|
|
|
defer func() { _ = hashFile.Close() }()
|
|
|
|
if e != nil {
|
|
|
|
err = errors.New("failed to open temporary file")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fileName, err := getSHA256(hashFile)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
location, err = SelectedMediaStorage.Upload(fileName+"."+fileExtension, file)
|
|
|
|
return
|
|
|
|
}
|