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

208 lines
4.7 KiB

4 years ago
package service
import (
4 years ago
"archive/tar"
"compress/gzip"
"errors"
"fmt"
4 years ago
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
4 years ago
"sort"
"strconv"
4 years ago
"time"
4 years ago
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 {
4 years ago
Logger.Errorw("Error getting response", err)
4 years ago
return "", err
}
fileName := getFileName(link, episodeTitle, ".mp3")
folder := createIfFoldeDoesntExist(podcastName)
finalPath := path.Join(folder, fileName)
file, err := os.Create(finalPath)
if err != nil {
4 years ago
Logger.Errorw("Error creating file", err)
4 years ago
return "", err
}
defer resp.Body.Close()
_, erra := io.Copy(file, resp.Body)
//fmt.Println(size)
defer file.Close()
if erra != nil {
4 years ago
Logger.Errorw("Error saving file", err)
4 years ago
return "", erra
}
4 years ago
changeOwnership(finalPath)
4 years ago
return finalPath, nil
}
func changeOwnership(path string) {
uid, err1 := strconv.Atoi(os.Getenv("PUID"))
gid, err2 := strconv.Atoi(os.Getenv("PGID"))
fmt.Println(path)
if err1 == nil && err2 == nil {
fmt.Println(path + " : Attempting change")
os.Chown(path, uid, gid)
}
4 years ago
}
func DeleteFile(filePath string) error {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return err
}
if err := os.Remove(filePath); err != nil {
return err
}
return nil
}
func FileExists(filePath string) bool {
_, err := os.Stat(filePath)
return err == nil
}
4 years ago
4 years ago
func GetAllBackupFiles() ([]string, error) {
4 years ago
var files []string
folder := createIfFoldeDoesntExist("backups")
err := filepath.Walk(folder, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
4 years ago
sort.Sort(sort.Reverse(sort.StringSlice(files)))
return files, err
}
func deleteOldBackup() {
files, err := GetAllBackupFiles()
4 years ago
if err != nil {
return
}
if len(files) <= 5 {
return
}
toDelete := files[5:]
for _, file := range toDelete {
fmt.Println(file)
DeleteFile(file)
}
}
func CreateBackup() (string, error) {
backupFileName := "podgrab_backup_" + time.Now().Format("2006.01.02_150405") + ".tar.gz"
folder := createIfFoldeDoesntExist("backups")
configPath := os.Getenv("CONFIG")
tarballFilePath := path.Join(folder, backupFileName)
file, err := os.Create(tarballFilePath)
if err != nil {
return "", errors.New(fmt.Sprintf("Could not create tarball file '%s', got error '%s'", tarballFilePath, err.Error()))
}
defer file.Close()
dbPath := path.Join(configPath, "podgrab.db")
_, err = os.Stat(dbPath)
if err != nil {
return "", errors.New(fmt.Sprintf("Could not find db file '%s', got error '%s'", dbPath, err.Error()))
}
gzipWriter := gzip.NewWriter(file)
defer gzipWriter.Close()
tarWriter := tar.NewWriter(gzipWriter)
defer tarWriter.Close()
err = addFileToTarWriter(dbPath, tarWriter)
if err == nil {
deleteOldBackup()
}
return backupFileName, err
}
func addFileToTarWriter(filePath string, tarWriter *tar.Writer) error {
file, err := os.Open(filePath)
if err != nil {
return errors.New(fmt.Sprintf("Could not open file '%s', got error '%s'", filePath, err.Error()))
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return errors.New(fmt.Sprintf("Could not get stat for file '%s', got error '%s'", filePath, err.Error()))
}
header := &tar.Header{
Name: filePath,
Size: stat.Size(),
Mode: int64(stat.Mode()),
ModTime: stat.ModTime(),
}
err = tarWriter.WriteHeader(header)
if err != nil {
return errors.New(fmt.Sprintf("Could not write header for file '%s', got error '%s'", filePath, err.Error()))
}
_, err = io.Copy(tarWriter, file)
if err != nil {
return errors.New(fmt.Sprintf("Could not copy the file '%s' data to the tarball, got error '%s'", filePath, err.Error()))
}
return nil
}
4 years ago
func httpClient() *http.Client {
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
// r.URL.Opaque = r.URL.Path
4 years ago
return nil
},
}
return &client
}
func createIfFoldeDoesntExist(folder string) string {
str := stringy.New(folder)
folder = str.RemoveSpecialCharacter()
4 years ago
dataPath := os.Getenv("DATA")
folderPath := path.Join(dataPath, folder)
4 years ago
if _, err := os.Stat(folderPath); os.IsNotExist(err) {
os.MkdirAll(folderPath, 0777)
changeOwnership(folderPath)
4 years ago
}
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)
}
}