Files
AppleSync/internal/m3u/m3u.go
T
2026-11-26 15:11:41 +01:00

166 lines
3.9 KiB
Go

// Package m3u writes extended m3u playlists in replace or append mode.
package m3u
import (
"fmt"
"os"
"path/filepath"
"strings"
"applesync/internal/model"
"applesync/internal/state"
)
// Entry is one playlist track mapped to a downloaded file.
type Entry struct {
File *model.FileEntry
Track *model.Track
}
// Write writes entries to path. In replace mode the file is rebuilt; in append
// mode existing path lines are kept and only new files are appended. Paths are
// rendered relative to the m3u file or as absolute paths.
func Write(path string, entries []Entry, mode, pathStyle string, extended bool) (int, error) {
mode = strings.ToLower(strings.TrimSpace(mode))
if mode == "" {
mode = "replace"
}
pathStyle = strings.ToLower(strings.TrimSpace(pathStyle))
if pathStyle == "" {
pathStyle = "relative"
}
switch mode {
case "replace":
var b strings.Builder
b.WriteString("#EXTM3U\n")
written := 0
for _, entry := range entries {
line, err := renderPath(path, entry.File.Path, pathStyle)
if err != nil {
return 0, err
}
if extended {
b.WriteString(extinf(entry.Track))
}
b.WriteString(line)
b.WriteString("\n")
written++
}
if err := state.WriteFileAtomic(path, []byte(b.String())); err != nil {
return 0, err
}
_ = os.Chmod(path, 0o644)
return written, nil
case "append":
existing, err := os.ReadFile(path)
if err != nil && !os.IsNotExist(err) {
return 0, err
}
existingSet := existingPaths(string(existing), filepath.Dir(path))
var b strings.Builder
b.Write(existing)
if len(existing) > 0 && !strings.HasSuffix(string(existing), "\n") {
b.WriteString("\n")
}
if len(existing) == 0 {
b.WriteString("#EXTM3U\n")
}
written := 0
for _, entry := range entries {
identity := identityPath(entry.File.Path, filepath.Dir(path))
if existingSet[identity] {
continue
}
line, err := renderPath(path, entry.File.Path, pathStyle)
if err != nil {
return written, err
}
if extended {
b.WriteString(extinf(entry.Track))
}
b.WriteString(line)
b.WriteString("\n")
existingSet[identity] = true
written++
}
if written == 0 {
return 0, nil
}
if err := state.WriteFileAtomic(path, []byte(b.String())); err != nil {
return written, err
}
_ = os.Chmod(path, 0o644)
return written, nil
default:
return 0, fmt.Errorf("unknown m3u mode %q", mode)
}
}
func extinf(track *model.Track) string {
if track == nil {
return "#EXTINF:-1,\n"
}
seconds := track.DurationMS / 1000
if seconds < 0 {
seconds = 0
}
label := strings.TrimSpace(track.ArtistName + " - " + track.Title)
if label == "" {
label = track.Title
}
return fmt.Sprintf("#EXTINF:%d,%s\n", seconds, sanitize(label))
}
func sanitize(value string) string {
value = strings.ReplaceAll(value, "\r", " ")
value = strings.ReplaceAll(value, "\n", " ")
return strings.TrimSpace(value)
}
func renderPath(m3uPath, filePath, style string) (string, error) {
abs, err := filepath.Abs(filePath)
if err != nil {
return "", err
}
if style == "absolute" {
return filepath.ToSlash(abs), nil
}
dir, err := filepath.Abs(filepath.Dir(m3uPath))
if err != nil {
return "", err
}
rel, err := filepath.Rel(dir, abs)
if err != nil {
return filepath.ToSlash(abs), nil
}
return filepath.ToSlash(rel), nil
}
func identityPath(filePath, m3uDir string) string {
if strings.Contains(filePath, "://") {
return filePath
}
if !filepath.IsAbs(filePath) {
filePath = filepath.Join(m3uDir, filePath)
}
abs, err := filepath.Abs(filePath)
if err != nil {
return filepath.Clean(filePath)
}
return filepath.Clean(abs)
}
func existingPaths(content, m3uDir string) map[string]bool {
out := map[string]bool{}
for _, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(strings.TrimSuffix(line, "\r"))
if line == "" || strings.HasPrefix(line, "#") {
continue
}
out[identityPath(line, m3uDir)] = true
}
return out
}