104 lines
1.8 KiB
Go
104 lines
1.8 KiB
Go
package ripsort
|
|
|
|
import (
|
|
"io/fs"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
|
|
"git.kapelle.org/niklas/ripsort/internal/metadata"
|
|
)
|
|
|
|
func FixComment(path string, dry bool) {
|
|
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
slog.Error("Failed to stat path", "file", path, "err", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Handle single file
|
|
if !info.IsDir() {
|
|
if !fileSupported(path) {
|
|
slog.Error("Unsupported file format", "file", path)
|
|
os.Exit(1)
|
|
}
|
|
|
|
err = fixCommentForFile(path, dry)
|
|
if err != nil {
|
|
slog.Error("Failed to fix comment on file", "file", path, "err", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// Handle directory
|
|
err = filepath.WalkDir(path, func(p string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
slog.Error("Failed to walk path", "path", path, "file", p, "err", err)
|
|
return err
|
|
}
|
|
|
|
if !d.IsDir() {
|
|
if !fileSupported(p) {
|
|
return nil
|
|
}
|
|
err = fixCommentForFile(p, dry)
|
|
if err != nil {
|
|
slog.Error("Failed to fix comment on file", "file", path, "err", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
if err != nil {
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func fixCommentForFile(file string, dry bool) error {
|
|
|
|
info, err := metadata.ReadAudioTags(file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var re = regexp.MustCompile(`(?m)(https:\/\/open\.spotify\.com\/track\/)(.*)`)
|
|
|
|
if info.Comment == nil {
|
|
slog.Debug("Song does not contain comment", "file", file)
|
|
return nil
|
|
}
|
|
|
|
matches := re.FindAllStringSubmatch(*info.Comment, -1)
|
|
|
|
if len(matches) != 1 {
|
|
slog.Debug("Song does not match regex", "file", file, "comment", info.Comment)
|
|
return nil
|
|
}
|
|
|
|
id := matches[0][2]
|
|
|
|
slog.Debug("Spotify tag found", "file", file, "id", id)
|
|
|
|
if dry {
|
|
slog.Info("Dryrun: Don't wite id", "file", file, "id", id)
|
|
return nil
|
|
}
|
|
|
|
info.SpotifyID = &id
|
|
info.Comment = nil
|
|
|
|
err = metadata.UpdateMetadata(file, file, *info)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|