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() 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(" [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[.. [Entry] { var files: [Int: Entry] = [:] for raw in t.components(separatedBy: .newlines) { guard let eq = raw.firstIndex(of: "=") else { continue } let k = raw[.. String { s.replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">") .replacingOccurrences(of: """, with: "\"").replacingOccurrences(of: "'", with: "'") .replacingOccurrences(of: "&", with: "&") } nonisolated static func inner(_ s: String, _ tag: String) -> String? { guard let a = s.range(of: "<\(tag)>", options: .caseInsensitive), let b = s.range(of: "", options: .caseInsensitive, range: a.upperBound.. [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: "&").replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) } /// 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 = "\n\n" out += " \(Playlists.xmlEscape(pl.name))\n \n" for s in songs { let path = loc(s).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? loc(s) out += " \(Playlists.xmlEscape(path))\(Playlists.xmlEscape(s.displayTitle))" out += "\(Playlists.xmlEscape(s.displayArtist))\(Playlists.xmlEscape(s.album))" out += "\(Int(s.duration * 1000))\n" } return out + " \n\n" case "wpl": var out = "\n\n \(Playlists.xmlEscape(pl.name))\n \n \n" for s in songs { out += " \n" } return out + " \n \n\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 } } }