Mulberry/App/Model/Playlists.swift
astar76 8e6f8a86a4 Mulberry for iOS: initial SwiftUI port of the Android app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:30:49 -05:00

303 lines
14 KiB
Swift

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Foundation
/// User playlists plus import/export (Android Playlists.java, desktop playlistio.rs).
@MainActor
final class Playlists: ObservableObject {
static let shared = Playlists()
struct PL: Codable, Identifiable, Hashable {
var id = UUID()
var name: String
var paths: [String]
var created = Date().timeIntervalSince1970
/// Entries that didn't match any library file at import time (shown greyed).
var missing: [String] = []
}
@Published private(set) var all: [PL] = []
private var file: URL { Library.support.appendingPathComponent("playlists.json") }
private var importedFile: URL { Library.support.appendingPathComponent("playlists_imported.json") }
private var imported: [String: Double] = [:]
static var folder: URL { Library.root.appendingPathComponent("Playlists") }
private init() {
if let d = try? Data(contentsOf: file), let a = try? JSONDecoder().decode([PL].self, from: d) { all = a }
if let d = try? Data(contentsOf: importedFile), let m = try? JSONDecoder().decode([String: Double].self, from: d) { imported = m }
}
private func save() {
if let d = try? JSONEncoder().encode(all) { try? d.write(to: file, options: .atomic) }
}
func songs(_ pl: PL) -> [Song] {
let lib = Library.shared
return pl.paths.compactMap { lib.song(path: $0) ?? ($0.hasPrefix("http") ? Song(path: $0, title: $0) : nil) }
}
func uniqueName(_ base: String) -> String {
let names = Set(all.map { $0.name.lowercased() })
if !names.contains(base.lowercased()) { return base }
var i = 2
while names.contains("\(base) (\(i))".lowercased()) { i += 1 }
return "\(base) (\(i))"
}
@discardableResult
func create(_ name: String, _ songs: [Song]) -> PL {
let pl = PL(name: uniqueName(name.isEmpty ? "New playlist" : name), paths: songs.map(\.id))
all.append(pl)
save()
return pl
}
/// Creates or replaces by name (used for "Save queue" and folder sync).
func put(_ name: String, _ songs: [Song], missing: [String] = []) {
if let i = all.firstIndex(where: { $0.name == name }) {
all[i].paths = songs.map(\.id)
all[i].missing = missing
} else {
all.append(PL(name: name, paths: songs.map(\.id), missing: missing))
}
save()
}
func delete(_ pl: PL) { all.removeAll { $0.id == pl.id }; save() }
func rename(_ pl: PL, _ name: String) {
guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return }
all[i].name = name
save()
}
func add(_ pl: PL, _ songs: [Song]) {
guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return }
all[i].paths += songs.map(\.id)
save()
}
func removeAt(_ pl: PL, _ idx: IndexSet) {
guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return }
all[i].paths.remove(atOffsets: idx)
save()
}
func move(_ pl: PL, _ from: IndexSet, _ to: Int) {
guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return }
all[i].paths.move(fromOffsets: from, toOffset: to)
save()
}
func removeDuplicates(_ pl: PL) {
guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return }
var seen = Set<String>()
all[i].paths = all[i].paths.filter { seen.insert($0).inserted }
save()
}
func removeMissing(_ pl: PL) {
guard let i = all.firstIndex(where: { $0.id == pl.id }) else { return }
let lib = Library.shared
all[i].paths = all[i].paths.filter { lib.song(path: $0) != nil || $0.hasPrefix("http") }
all[i].missing = []
save()
}
// MARK: Import
struct Entry {
var path: String
var title = ""
var artist = ""
var duration: Double = 0
}
/// Imports a playlist file; returns (playlist, matched, total).
@discardableResult
func importFile(_ url: URL, name: String? = nil) throws -> (PL, Int, Int) {
let data = try Data(contentsOf: url)
let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .utf16) ??
String(data: data, encoding: .isoLatin1) ?? ""
let entries = Playlists.parse(text, ext: url.pathExtension.lowercased())
let dir = url.deletingLastPathComponent()
let lib = Library.shared
var songs: [Song] = []
var missing: [String] = []
for e in entries {
if e.path.hasPrefix("http://") || e.path.hasPrefix("https://") {
var s = Song(path: e.path)
s.title = e.title.isEmpty ? e.path : e.title
s.artist = e.artist
songs.append(s)
continue
}
// Relative to the playlist first, then anywhere in the library.
let rel = e.path.hasPrefix("/") ? e.path : dir.appendingPathComponent(e.path).standardizedFileURL.path
if let s = lib.match(rel, title: e.title, artist: e.artist) ?? lib.match(e.path, title: e.title, artist: e.artist) {
songs.append(s)
} else {
missing.append(e.title.isEmpty ? e.path : "\(e.artist) – \(e.title)")
}
}
let n = name ?? url.deletingPathExtension().lastPathComponent
put(n, songs, missing: missing)
return (all.first { $0.name == n }!, songs.count, entries.count)
}
/// Auto-imports playlist files dropped into Documents/Playlists (re-imports when they change).
func syncFolder() {
let fm = FileManager.default
guard let files = try? fm.contentsOfDirectory(at: Playlists.folder, includingPropertiesForKeys: [.contentModificationDateKey]) else { return }
var changed = false
for f in files where Library.playlistExts.contains(f.pathExtension.lowercased()) {
let m = (try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate?.timeIntervalSince1970) ?? 0
if imported[f.lastPathComponent] == m { continue }
if (try? importFile(f)) != nil { imported[f.lastPathComponent] = m; changed = true }
}
if changed, let d = try? JSONEncoder().encode(imported) { try? d.write(to: importedFile, options: .atomic) }
}
nonisolated static func parse(_ text: String, ext: String) -> [Entry] {
let t = text.trimmingCharacters(in: CharacterSet(charactersIn: "\u{FEFF}").union(.whitespacesAndNewlines))
if ext == "pls" || t.lowercased().hasPrefix("[playlist]") { return parsePLS(t) }
if ext == "xspf" || t.contains("<playlist") && t.contains("xspf") { return parseXML(t, tag: "location", titleTag: "title", artistTag: "creator", wrapper: "track") }
if ext == "wpl" || t.contains("<smil") { return parseAttr(t, element: "media", attr: "src") }
if ext == "asx" || t.lowercased().contains("<asx") { return parseAttr(t, element: "ref", attr: "href") }
return parseM3U(t)
}
nonisolated static func parseM3U(_ t: String) -> [Entry] {
var out: [Entry] = []
var pending: Entry?
for raw in t.components(separatedBy: .newlines) {
let line = raw.trimmingCharacters(in: .whitespaces)
if line.isEmpty { continue }
if line.hasPrefix("#EXTINF:") {
var e = Entry(path: "")
let body = line.dropFirst(8)
if let comma = body.firstIndex(of: ",") {
e.duration = Double(body[..<comma].split(separator: " ").first ?? "") ?? 0
let info = String(body[body.index(after: comma)...])
if let r = info.range(of: " - ") {
e.artist = String(info[..<r.lowerBound]); e.title = String(info[r.upperBound...])
} else { e.title = info }
}
pending = e
} else if !line.hasPrefix("#") {
var e = pending ?? Entry(path: "")
e.path = line
out.append(e)
pending = nil
}
}
return out
}
nonisolated static func parsePLS(_ t: String) -> [Entry] {
var files: [Int: Entry] = [:]
for raw in t.components(separatedBy: .newlines) {
guard let eq = raw.firstIndex(of: "=") else { continue }
let k = raw[..<eq].trimmingCharacters(in: .whitespaces).lowercased()
let v = raw[raw.index(after: eq)...].trimmingCharacters(in: .whitespaces)
for (prefix, apply) in [("file", 0), ("title", 1), ("length", 2)] where k.hasPrefix(prefix) {
guard let n = Int(k.dropFirst(prefix.count)) else { continue }
var e = files[n] ?? Entry(path: "")
switch apply {
case 0: e.path = v
case 1: e.title = v
default: e.duration = Double(v) ?? 0
}
files[n] = e
}
}
return files.keys.sorted().compactMap { files[$0] }.filter { !$0.path.isEmpty }
}
nonisolated static func xmlUnescape(_ s: String) -> String {
s.replacingOccurrences(of: "&lt;", with: "<").replacingOccurrences(of: "&gt;", with: ">")
.replacingOccurrences(of: "&quot;", with: "\"").replacingOccurrences(of: "&apos;", with: "'")
.replacingOccurrences(of: "&amp;", with: "&")
}
nonisolated static func inner(_ s: String, _ tag: String) -> String? {
guard let a = s.range(of: "<\(tag)>", options: .caseInsensitive),
let b = s.range(of: "</\(tag)>", options: .caseInsensitive, range: a.upperBound..<s.endIndex) else { return nil }
return xmlUnescape(String(s[a.upperBound..<b.lowerBound]).trimmingCharacters(in: .whitespacesAndNewlines))
}
nonisolated static func parseXML(_ t: String, tag: String, titleTag: String, artistTag: String, wrapper: String) -> [Entry] {
t.components(separatedBy: "<\(wrapper)>").dropFirst().compactMap { chunk in
guard var loc = inner(chunk, tag) else { return nil }
if loc.hasPrefix("file://"), let u = URL(string: loc) { loc = u.path }
return Entry(path: loc.removingPercentEncoding ?? loc, title: inner(chunk, titleTag) ?? "",
artist: inner(chunk, artistTag) ?? "", duration: (Double(inner(chunk, "duration") ?? "") ?? 0) / 1000)
}
}
nonisolated static func parseAttr(_ t: String, element: String, attr: String) -> [Entry] {
let re = try! NSRegularExpression(pattern: "<\(element)[^>]*\\b\(attr)\\s*=\\s*\"([^\"]*)\"", options: .caseInsensitive)
return re.matches(in: t, range: NSRange(t.startIndex..., in: t)).compactMap { m in
Range(m.range(at: 1), in: t).map { Entry(path: xmlUnescape(String(t[$0]))) }
}
}
// MARK: Export (M3U, M3U8, PLS, XSPF, WPL)
nonisolated static func xmlEscape(_ s: String) -> String {
s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
/// Paths are written relative to the Mulberry folder so the playlist works next to the music on any device.
func render(_ pl: PL, format: String) -> String {
let songs = self.songs(pl)
func loc(_ s: Song) -> String { s.isStream ? s.path : "../" + s.path }
switch format {
case "pls":
var out = "[playlist]\n"
for (i, s) in songs.enumerated() {
out += "File\(i + 1)=\(loc(s))\nTitle\(i + 1)=\(s.displayArtist) - \(s.displayTitle)\nLength\(i + 1)=\(Int(s.duration))\n"
}
return out + "NumberOfEntries=\(songs.count)\nVersion=2\n"
case "xspf":
var out = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<playlist version=\"1\" xmlns=\"http://xspf.org/ns/0/\">\n"
out += " <title>\(Playlists.xmlEscape(pl.name))</title>\n <trackList>\n"
for s in songs {
let path = loc(s).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? loc(s)
out += " <track><location>\(Playlists.xmlEscape(path))</location><title>\(Playlists.xmlEscape(s.displayTitle))</title>"
out += "<creator>\(Playlists.xmlEscape(s.displayArtist))</creator><album>\(Playlists.xmlEscape(s.album))</album>"
out += "<duration>\(Int(s.duration * 1000))</duration></track>\n"
}
return out + " </trackList>\n</playlist>\n"
case "wpl":
var out = "<?wpl version=\"1.0\"?>\n<smil>\n <head><title>\(Playlists.xmlEscape(pl.name))</title></head>\n <body>\n <seq>\n"
for s in songs { out += " <media src=\"\(Playlists.xmlEscape(loc(s).replacingOccurrences(of: "/", with: "\\")))\"/>\n" }
return out + " </seq>\n </body>\n</smil>\n"
default:
var out = "#EXTM3U\n#PLAYLIST:\(pl.name)\n"
for s in songs { out += "#EXTINF:\(Int(s.duration)),\(s.displayArtist) - \(s.displayTitle)\n\(loc(s))\n" }
return out
}
}
nonisolated static func safeName(_ s: String) -> String {
let bad = CharacterSet(charactersIn: "/\\:*?\"<>|")
return s.components(separatedBy: bad).joined(separator: "_").trimmingCharacters(in: .whitespaces)
}
/// Writes a playlist into Documents/Playlists (visible in Files) and returns the file URL.
@discardableResult
func export(_ pl: PL, format: String) throws -> URL {
try FileManager.default.createDirectory(at: Playlists.folder, withIntermediateDirectories: true)
let url = Playlists.folder.appendingPathComponent(Playlists.safeName(pl.name) + "." + format)
try render(pl, format: format).write(to: url, atomically: true, encoding: .utf8)
let m = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate?.timeIntervalSince1970) ?? 0
imported[url.lastPathComponent] = m // don't re-import our own export
if let d = try? JSONEncoder().encode(imported) { try? d.write(to: importedFile, options: .atomic) }
return url
}
func exportAll(format: String) -> Int {
all.reduce(0) { n, pl in (try? export(pl, format: format)) != nil ? n + 1 : n }
}
}