organizer/handle_file.go
2023-01-13 19:23:36 +01:00

100 lines
2.1 KiB
Go

package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"git.milar.in/milarin/adverr"
"git.milar.in/nyaanime/logic"
"git.milar.in/nyaanime/model"
"git.milar.in/nyaanime/parsers"
)
func HandleFile(path string) {
for _, parser := range parsers.Parsers {
parsedFile, ok := parser.FileParser(&parser, path)
if !ok {
continue
}
anime, err := logic.SearchAnimeByTitle(parsedFile.OriginalAnimeTitle)
if err != nil {
continue
}
parsedFile.Anime = anime
HandleParsedFile(parsedFile)
}
}
func HandleParsedFile(parsedFile *model.ParsedFile) {
newFilePrio := logic.NewFilePriority(parsedFile)
oldFilePrio, animeEpNotExistLocally := logic.GetAnimeEpProps(parsedFile.AnimeEpisode())
if !animeEpNotExistLocally || newFilePrio.Priority > oldFilePrio.Priority {
fmt.Println(animeEpNotExistLocally, newFilePrio, oldFilePrio)
go func(parsedFile *model.ParsedFile) {
if err := OrganizeAnimeEpisode(parsedFile); err != nil {
adverr.Println(err)
}
}(parsedFile)
}
}
func OrganizeAnimeEpisode(parsedFile *model.ParsedFile) error {
oldFile := filepath.Join(DownloadPath, parsedFile.File)
newFile := logic.GetAnimeEpFilepath(parsedFile.AnimeEpisode(), filepath.Ext(parsedFile.File))
lockFile := logic.GetAnimeEpFilepath(parsedFile.AnimeEpisode(), "lock")
fmt.Printf("move file '%s' to '%s'\n", oldFile, newFile)
if err := os.MkdirAll(filepath.Dir(newFile), os.ModePerm); err != nil {
return err
}
if err := os.Chown(filepath.Dir(newFile), Uid, Gid); err != nil {
return err
}
if _, err := os.Stat(newFile); !errors.Is(err, os.ErrNotExist) {
fmt.Fprintln(os.Stderr, "file already exists:", newFile)
return err
}
inputFile, err := os.Open(oldFile)
if err != nil {
return err
}
defer inputFile.Close()
outputFile, err := os.Create(newFile)
if err != nil {
return err
}
defer outputFile.Close()
if err := os.Chown(newFile, Uid, Gid); err != nil {
return err
}
_, err = io.Copy(outputFile, inputFile)
if err != nil {
return err
}
if err = os.Remove(oldFile); err != nil {
return err
}
if err = os.Remove(lockFile); err != nil {
return err
}
fmt.Printf("file '%s' moved\n", newFile)
return nil
}