From b527e7e6d29d67a2906e053423768898d2109942 Mon Sep 17 00:00:00 2001 From: restitux Date: Wed, 13 Apr 2022 21:09:08 -0600 Subject: [PATCH] Parse SXXEYY filenames using regex --- main.go | 50 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index d1a11d5..168d4e4 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" "path/filepath" + "regexp" _ "github.com/mattn/go-sqlite3" @@ -172,19 +173,26 @@ func scan_tvshow_root(root string, db *sql.DB) error { for _, file := range files { if file.IsDir() { - insert_tvshow_nfo(filepath.Join(root, file.Name()), stmt) + show_path := filepath.Join(root, file.Name()) + if insert_tvshow_nfo(show_path, stmt) { + err = scan_tvshow_episodes(show_path) + if err != nil { + fmt.Fprintf(os.Stderr, "Could not scan for episodes in %v: %v", show_path, err) + continue + } + } } } return nil } -func insert_tvshow_nfo(show_dir string, stmt *sql.Stmt) { +func insert_tvshow_nfo(show_dir string, stmt *sql.Stmt) bool { tvshow_nfo_path := filepath.Join(show_dir, "tvshow.nfo") tvshow_nfo_file, err := os.OpenFile(tvshow_nfo_path, os.O_RDONLY, 0755) if err != nil { fmt.Fprintf(os.Stderr, "Could not open tvshow.nfo file in \"%v\"\n", show_dir) - return + return false } defer tvshow_nfo_file.Close() @@ -192,14 +200,14 @@ func insert_tvshow_nfo(show_dir string, stmt *sql.Stmt) { data, err := ioutil.ReadAll(tvshow_nfo_file) if err != nil { fmt.Fprintf(os.Stderr, "ERROR: Could not read data from tvshow.nfo file: %v\n", err) - return + return false } var tvshow TVShow err = xml.Unmarshal(data, &tvshow) if err != nil { fmt.Fprintf(os.Stderr, "ERROR: Could not parse tvshow.nfo file contents: %v\n", err) - return + return false } // TODO: Replace with print formatting logic @@ -210,9 +218,39 @@ func insert_tvshow_nfo(show_dir string, stmt *sql.Stmt) { _, err = stmt.Exec(tvshow.Title, tvshow.OriginalTile, tvshow.ShowTitle, tvshow.Year) if err != nil { fmt.Fprintf(os.Stderr, "ERROR: Could not insert tvshow into database: %v\n", err) - return + return false + } + return true +} + +type Episode struct { + XMLName xml.Name `xml:"episodedetails"` + Title string `xml:"title"` + ShowTitle string `xml:"showtitle"` + Year int `xml:"year"` +} + +func scan_tvshow_episodes(show_dir string) error { + + files, err := ioutil.ReadDir(show_dir) + if err != nil { + return fmt.Errorf("Could not enumerate files in folder: %v", err) } + // Regex to see if filename contains SXXEYY string + var re = regexp.MustCompile(".*S(\\d+)E(\\d+).*") + + for _, file := range files { + parts := re.FindStringSubmatch(file.Name()) + if len(parts) != 3 { + fmt.Fprintf(os.Stderr, "Filename \"%v\" failed regex capture (%v)\n", file.Name(), len(parts)) + continue + } + fmt.Printf("%v: S%vE%v\n", file.Name(), parts[1], parts[2]) + + + } + return nil } func main() {