forked from thebaer/cdr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitize.go
69 lines (58 loc) · 1.44 KB
/
sanitize.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package cdr
import (
"fmt"
"log"
"os"
"regexp"
"strings"
"unicode"
"github.com/dhowden/tag"
"github.com/rainycape/unidecode"
)
var trackNameReg = regexp.MustCompile("^([0-9]{2}).+")
func NewTrack(file string) (*Track, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("error loading file: %v", err)
}
defer f.Close()
m, err := tag.ReadFrom(f)
if err != nil {
return nil, fmt.Errorf("unable to read file: %v", err)
}
return &Track{
Title: m.Title(),
Artist: m.Artist(),
Filename: f.Name(),
}, nil
}
// RenameTrack takes a filename, opens it, reads the metadata, and returns both
// the old and new filename.
func RenameTrack(file string) string {
t, err := NewTrack(file)
if err != nil {
return ""
}
// Extract playlist track number from filename
fMatch := trackNameReg.FindStringSubmatch(t.Filename)
if len(fMatch) < 2 {
log.Fatal("Unexpect filename format")
}
trackNum := fMatch[1]
ext := t.Filename[strings.LastIndex(t.Filename, "."):]
return fmt.Sprintf("%s-%s-%s%s", trackNum, Sanitize(t.Artist), Sanitize(t.Title), ext)
}
// Sanitize takes a string and removes problematic characters from it.
func Sanitize(s string) string {
s = unidecode.Unidecode(s)
s = strings.Map(func(r rune) rune {
if r == '(' || r == ')' || r == '[' || r == ']' || r == '.' || r == ',' || r == '\'' || r == '"' || r == ';' {
return -1
}
if unicode.IsSpace(r) {
return '_'
}
return r
}, s)
return s
}