canape/backend/web/download.go
Grégoire Delattre d585a59c83 Download movie fanart and better torrent list on mobile
Show the thumb on wide screens and the fanart on small screens.
2021-08-22 11:33:36 -10:00

57 lines
991 B
Go

package web
import (
"fmt"
"image"
"image/jpeg"
"net/http"
"os"
"path"
"time"
"github.com/nfnt/resize"
)
// Download used for downloading file
var Download = func(srcURL, dest string, maxWidth uint) error {
if err := createDirectory(dest); err != nil {
return err
}
var httpClient = &http.Client{
Timeout: time.Second * 10,
}
resp, err := httpClient.Get(srcURL)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("got HTTP error %s", resp.Status)
}
image, _, err := image.Decode(resp.Body)
if err != nil {
return err
}
if maxWidth != 0 {
image = resize.Resize(maxWidth, 0, image, resize.Lanczos3)
}
// Create the file
file, err := os.Create(dest)
if err != nil {
return err
}
defer file.Close()
return jpeg.Encode(file, image, nil)
}
// createDirectory creates the destination directory
func createDirectory(dest string) error {
return os.MkdirAll(path.Dir(dest), os.ModePerm)
}