Work on media-parsing

This commit is contained in:
Jan Bader 2017-09-16 18:03:32 +02:00
parent 1ed0b0b201
commit 73cc5d7f55
3 changed files with 129 additions and 0 deletions

35
main.go
View File

@ -3,6 +3,7 @@ package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
@ -17,9 +18,43 @@ func main() {
fallthrough
case "rs":
suffix := args[1]
removeSuffix(suffix)
break
default:
fmt.Println("Invalid action specified")
return
}
}
func removeSuffix(suffix string) {
filepath.Walk(".", removeSuffixFunc(suffix))
}
func removeSuffixFunc(suffix string) filepath.WalkFunc {
return func(p string, f os.FileInfo, err error) error {
filename := f.Name()
if filename == "." || filename == ".." {
return nil
}
element := newMediaElement(p)
fmt.Println(element.String())
dir := filepath.Dir(p)
ext := filepath.Ext(filename)
filenameNoExt := trimSuffix(filename, ext)
filenameNoSuff := trimSuffix(filenameNoExt, suffix)
if filenameNoSuff != filenameNoExt {
newFilename := filenameNoSuff + ext
err := os.Rename(filepath.Join(dir, filename), filepath.Join(dir, newFilename))
if err != nil {
fmt.Printf("Could not rename %s: %v\n", filename, err)
} else {
fmt.Println("Renamed " + filename + " to " + newFilename)
}
}
return nil
}
}

82
media.go Normal file
View File

@ -0,0 +1,82 @@
package main
import (
"fmt"
"path/filepath"
"strings"
)
type mediaElement struct {
Directory string
Name string
Episode string
Title string
Tags []string
Extension string
}
func newMediaElement(p string) *mediaElement {
dir := filepath.Dir(p)
name := filepath.Base(p)
ext := filepath.Ext(name)
name = trimSuffix(name, ext)
dash := strings.Index(name, " - ")
episode := ""
if dash != -1 {
episode = name[dash+3:]
name = name[:dash]
}
dash = strings.Index(episode, " - ")
title := ""
if dash != -1 {
title = episode[dash+3:]
episode = episode[:dash]
}
element := &mediaElement{
Directory: dir,
Extension: ext,
Name: name,
Episode: episode,
Title: title,
}
words := strings.Split(title, " ")
titleWords := []string{}
for i := len(words) - 1; i >= 0; i-- {
word := words[i]
switch word {
case "EN":
fallthrough
case "DE":
fallthrough
case "FORCED":
fallthrough
case "3D":
fallthrough
case "UNCUT":
element.Tags = append(element.Tags, word)
default:
titleWords = append(titleWords, word)
}
}
fmt.Printf("%v\n", titleWords)
return element
}
func (element *mediaElement) String() string {
result := ""
result += fmt.Sprintf("Directory: %s\n", element.Directory)
result += fmt.Sprintf("Name: %s\n", element.Name)
result += fmt.Sprintf("Episode: %s\n", element.Episode)
result += fmt.Sprintf("Title: %s\n", element.Title)
result += fmt.Sprintf("Extension: %s\n", element.Extension)
result += "Tags:"
for _, tag := range element.Tags {
result += " " + tag
}
return result
}

12
util.go Normal file
View File

@ -0,0 +1,12 @@
package main
import (
"strings"
)
func trimSuffix(s, suffix string) string {
if strings.HasSuffix(s, suffix) {
s = s[:len(s)-len(suffix)]
}
return s
}