Static site generator for making web mixtapes in 2020.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.4 KiB

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