You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
podgrab/service/fileService.go

81 lines
1.6 KiB

package service
import (
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
stringy "github.com/gobeam/stringy"
)
func Download(link string, episodeTitle string, podcastName string) (string, error) {
client := httpClient()
resp, err := client.Get(link)
if err != nil {
return "", err
}
fileName := getFileName(link, episodeTitle, ".mp3")
folder := createIfFoldeDoesntExist(podcastName)
finalPath := path.Join(folder, fileName)
file, err := os.Create(finalPath)
if err != nil {
return "", err
}
defer resp.Body.Close()
_, erra := io.Copy(file, resp.Body)
//fmt.Println(size)
defer file.Close()
if erra != nil {
return "", erra
}
return finalPath, nil
}
func httpClient() *http.Client {
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
return &client
}
func createIfFoldeDoesntExist(folder string) string {
str := stringy.New(folder)
folder = str.RemoveSpecialCharacter()
dataPath := os.Getenv("DATA")
folderPath := path.Join(dataPath, folder)
if _, err := os.Stat(folderPath); os.IsNotExist(err) {
os.MkdirAll(folderPath, 0755)
}
return folderPath
}
func getFileName(link string, title string, defaultExtension string) string {
fileUrl, err := url.Parse(link)
checkError(err)
parsed := fileUrl.Path
ext := filepath.Ext(parsed)
if len(ext) == 0 {
ext = defaultExtension
}
str := stringy.New(title)
str = stringy.New(str.RemoveSpecialCharacter())
return str.KebabCase().Get() + ext
}
func checkError(err error) {
if err != nil {
panic(err)
}
}