2020-02-26 01:54:12 +00:00
|
|
|
package cdr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"unicode"
|
|
|
|
|
|
|
|
"github.com/dhowden/tag"
|
|
|
|
)
|
|
|
|
|
|
|
|
var trackNameReg = regexp.MustCompile("^([0-9]{2}).+")
|
|
|
|
|
|
|
|
// RenameTrack takes a filename, opens it, reads the metadata, and returns both
|
|
|
|
// the old and new filename.
|
2020-02-26 03:20:12 +00:00
|
|
|
func RenameTrack(file string) string {
|
2020-02-26 01:54:12 +00:00
|
|
|
f, err := os.Open(file)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("error loading file: %v", err)
|
2020-02-26 03:20:12 +00:00
|
|
|
return ""
|
2020-02-26 01:54:12 +00:00
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
2020-02-26 03:20:12 +00:00
|
|
|
fName := f.Name()
|
|
|
|
fMatch := trackNameReg.FindStringSubmatch(fName)
|
2020-02-26 01:54:12 +00:00
|
|
|
if len(fMatch) < 2 {
|
|
|
|
log.Fatal("Unexpect filename format")
|
|
|
|
}
|
|
|
|
trackNum := fMatch[1]
|
2020-02-26 03:20:12 +00:00
|
|
|
ext := fName[strings.LastIndex(fName, "."):]
|
2020-02-26 01:54:12 +00:00
|
|
|
|
|
|
|
m, err := tag.ReadFrom(f)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2020-02-26 03:20:12 +00:00
|
|
|
return fmt.Sprintf("%s-%s-%s%s", trackNum, Sanitize(m.Artist()), Sanitize(m.Title()), ext)
|
2020-02-26 01:54:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Sanitize takes a string and removes problematic characters from it.
|
|
|
|
func Sanitize(s string) string {
|
|
|
|
s = strings.Map(func(r rune) rune {
|
|
|
|
if r == '(' || r == ')' || r == '[' || r == ']' || r == '.' {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
if unicode.IsSpace(r) {
|
|
|
|
return '_'
|
|
|
|
}
|
|
|
|
return r
|
|
|
|
}, s)
|
|
|
|
return s
|
|
|
|
}
|