2020-06-16 05:37:51 +02:00
|
|
|
package compression
|
|
|
|
|
|
|
|
import (
|
|
|
|
"mime"
|
2023-05-30 18:17:46 +02:00
|
|
|
"os"
|
2020-06-16 05:37:51 +02:00
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/lbryio/lbry.go/v2/extras/errors"
|
|
|
|
giftowebp "github.com/sizeofint/gif-to-webp"
|
|
|
|
"go.uber.org/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
var inUse atomic.Bool
|
|
|
|
var AlreadyInUseErr = errors.Base("already busy compressing")
|
|
|
|
var UnsupportedErr = errors.Base("unsupported compression")
|
|
|
|
|
|
|
|
// returns a compressedPath, a mimeType or an error
|
|
|
|
func Compress(path, fileName, mimeType, storePath string) (string, string, error) {
|
|
|
|
swapped := inUse.CAS(false, true)
|
|
|
|
if !swapped {
|
|
|
|
return "", "", AlreadyInUseErr
|
|
|
|
}
|
|
|
|
defer inUse.Store(false)
|
2023-05-30 18:17:46 +02:00
|
|
|
file, err := os.ReadFile(path)
|
2020-06-16 05:37:51 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", "", errors.Err(err)
|
|
|
|
}
|
|
|
|
switch mimeType {
|
|
|
|
case "image/gif":
|
|
|
|
converter := giftowebp.NewConverter()
|
|
|
|
converter.LoopCompatibility = false
|
2020-07-16 04:44:53 +02:00
|
|
|
if len(file) > 500*1024 {
|
|
|
|
converter.WebPConfig.SetTargetSize(500 * 1024)
|
|
|
|
} else {
|
|
|
|
converter.WebPConfig.SetTargetSize(len(file))
|
|
|
|
}
|
|
|
|
converter.WebPConfig.SetMethod(4)
|
2020-06-16 05:37:51 +02:00
|
|
|
webpBin, err := converter.Convert(file)
|
|
|
|
if err != nil {
|
|
|
|
return "", "", errors.Err(err)
|
|
|
|
}
|
|
|
|
compressedPath := filepath.Join(storePath, fileName+".webp")
|
2023-05-30 18:17:46 +02:00
|
|
|
err = os.WriteFile(compressedPath, webpBin, 0600)
|
2020-06-16 05:37:51 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", "", errors.Err(err)
|
|
|
|
}
|
2020-07-16 04:44:53 +02:00
|
|
|
//err = os.Remove(path)
|
|
|
|
return fileName + ".webp", mime.TypeByExtension(".webp"), nil
|
2020-06-16 05:37:51 +02:00
|
|
|
case mime.TypeByExtension("png"):
|
|
|
|
case mime.TypeByExtension("jpeg"):
|
|
|
|
case mime.TypeByExtension("jpg"):
|
|
|
|
|
|
|
|
}
|
|
|
|
return "", "", UnsupportedErr
|
|
|
|
}
|