2020-02-26 01:54:12 +00:00
|
|
|
package cdr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"unicode"
|
|
|
|
|
|
|
|
"github.com/dhowden/tag"
|
2020-02-29 15:51:10 +00:00
|
|
|
"github.com/rainycape/unidecode"
|
2020-02-26 01:54:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var trackNameReg = regexp.MustCompile("^([0-9]{2}).+")
|
|
|
|
|
2020-02-26 05:13:51 +00:00
|
|
|
func NewTrack(file string) (*Track, error) {
|
2020-02-26 01:54:12 +00:00
|
|
|
f, err := os.Open(file)
|
|
|
|
if err != nil {
|
2020-02-26 05:13:51 +00:00
|
|
|
return nil, fmt.Errorf("error loading file: %v", err)
|
2020-02-26 01:54:12 +00:00
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
2020-02-26 04:23:03 +00:00
|
|
|
m, err := tag.ReadFrom(f)
|
|
|
|
if err != nil {
|
2020-02-26 05:13:51 +00:00
|
|
|
return nil, fmt.Errorf("unable to read file: %v", err)
|
2020-02-26 04:23:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return &Track{
|
|
|
|
Title: m.Title(),
|
|
|
|
Artist: m.Artist(),
|
|
|
|
Filename: f.Name(),
|
2020-02-26 05:28:15 +00:00
|
|
|
}, nil
|
2020-02-26 04:23:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// RenameTrack takes a filename, opens it, reads the metadata, and returns both
|
|
|
|
// the old and new filename.
|
|
|
|
func RenameTrack(file string) string {
|
2020-02-26 05:13:51 +00:00
|
|
|
t, err := NewTrack(file)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
2020-02-26 04:23:03 +00:00
|
|
|
|
2022-03-31 03:32:17 +00:00
|
|
|
ext := t.Filename[strings.LastIndex(t.Filename, "."):]
|
|
|
|
|
2020-02-26 04:23:03 +00:00
|
|
|
// Extract playlist track number from filename
|
|
|
|
fMatch := trackNameReg.FindStringSubmatch(t.Filename)
|
2020-02-26 01:54:12 +00:00
|
|
|
if len(fMatch) < 2 {
|
2022-03-31 03:32:17 +00:00
|
|
|
log.Printf("No track number found: '%s'. Continuing anyway.\n", t.Filename)
|
|
|
|
return fmt.Sprintf("%s-%s%s", Sanitize(t.Artist), Sanitize(t.Title), ext)
|
2020-02-26 01:54:12 +00:00
|
|
|
}
|
2020-02-26 04:23:03 +00:00
|
|
|
|
2022-03-31 03:32:17 +00:00
|
|
|
trackNum := fMatch[1]
|
2020-02-26 04:23:03 +00:00
|
|
|
return fmt.Sprintf("%s-%s-%s%s", trackNum, Sanitize(t.Artist), Sanitize(t.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 {
|
2020-02-29 18:28:19 +00:00
|
|
|
s = unidecode.Unidecode(s)
|
2020-02-26 01:54:12 +00:00
|
|
|
s = strings.Map(func(r rune) rune {
|
2020-02-29 18:28:19 +00:00
|
|
|
if r == '(' || r == ')' || r == '[' || r == ']' || r == '.' || r == ',' || r == '\'' || r == '"' || r == ';' {
|
2020-02-26 01:54:12 +00:00
|
|
|
return -1
|
|
|
|
}
|
|
|
|
if unicode.IsSpace(r) {
|
|
|
|
return '_'
|
|
|
|
}
|
|
|
|
return r
|
|
|
|
}, s)
|
|
|
|
return s
|
|
|
|
}
|