Download cover when importing from inventaire
This commit is contained in:
@@ -1,9 +1,15 @@
|
||||
package fileutils
|
||||
|
||||
import (
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/model"
|
||||
@@ -24,6 +30,56 @@ func SaveStaticFile(ac *appcontext.AppContext, file *multipart.FileHeader) (mode
|
||||
return staticFile, nil
|
||||
}
|
||||
|
||||
func DownloadFile(ac appcontext.AppContext, fileUrl string) (model.StaticFile, error) {
|
||||
var staticFile model.StaticFile
|
||||
u, err := url.Parse(fileUrl)
|
||||
if err != nil {
|
||||
return staticFile, err
|
||||
}
|
||||
path := u.Path
|
||||
segments := strings.Split(path, "/")
|
||||
fileName := segments[len(segments)-1]
|
||||
|
||||
response, err := http.Get(fileUrl)
|
||||
if err != nil {
|
||||
return staticFile, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
//get file extension from http header if needed
|
||||
if filepath.Ext(fileName) == "" {
|
||||
contentType := response.Header.Get("content-type")
|
||||
if contentType != "" {
|
||||
extensions, err := mime.ExtensionsByType(contentType)
|
||||
if err != nil {
|
||||
return staticFile, err
|
||||
}
|
||||
if len(extensions) > 0 {
|
||||
fileName = fileName + extensions[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filePath := computePathFromName(&ac, fileName)
|
||||
|
||||
file, err := os.Create(ac.Config.ImageFolderPath + "/" + filePath)
|
||||
if err != nil {
|
||||
return staticFile, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(file, response.Body)
|
||||
if err != nil {
|
||||
return staticFile, err
|
||||
}
|
||||
staticFile = model.StaticFile{
|
||||
Name: fileName,
|
||||
Path: filePath,
|
||||
}
|
||||
err = ac.Db.Save(&staticFile).Error
|
||||
return staticFile, err
|
||||
}
|
||||
|
||||
func computePathFromName(ac *appcontext.AppContext, filename string) string {
|
||||
var existingFiles []model.StaticFile
|
||||
ac.Db.Where("name = ?", filename).Find(&existingFiles)
|
||||
|
||||
Reference in New Issue
Block a user