Compare commits

..
6 changed files with 93 additions and 33 deletions

No files matched your search

+24 -6
View File
@@ -219,11 +219,19 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
@ObservationIgnored private var stationGen = 0 @ObservationIgnored private var stationGen = 0
@ObservationIgnored private var stationBusy = false @ObservationIgnored private var stationBusy = false
private static let radioAlbumsAhead = 8 private static let radioAlbumsAhead = 8
private static let radioAlbumsLow = 3 /// Each new song adds an album, up to this many ahead (keeps the queue from growing without end).
private static let radioAlbumsMax = 40
/// Album radio: the song the last top-up saw, and songs started since that haven't added their album yet.
@ObservationIgnored private var radioSeenUid: Int64?
@ObservationIgnored private var radioOwed = 0
private static let radioSongsBatch = 100 private static let radioSongsBatch = 100
private static let radioSongsLow = 25 private static let radioSongsLow = 25
private func setStation(_ s: Station?) { station = s; stationGen += 1; stationBusy = false } private func setStation(_ s: Station?) {
station = s; stationGen += 1; stationBusy = false
radioSeenUid = queue.indices.contains(index) ? queue[index].uid : nil
radioOwed = 0
}
private func albumDeck() async throws -> [String] { private func albumDeck() async throws -> [String] {
var deck = (try? await plex.albums().map(\.ratingKey)) ?? [] var deck = (try? await plex.albums().map(\.ratingKey)) ?? []
@@ -268,18 +276,28 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
let gen = stationGen let gen = stationGen
switch st { switch st {
case .albums(let saved): case .albums(let saved):
// Every song that starts (the next track, a skip, a jump to another album) owes one more album,
// so the queue always runs on past what's playing.
let uid = queue[index].uid
if uid != radioSeenUid { radioSeenUid = uid; radioOwed += 1 }
let ahead = Set(queue[index...].map { $0.track.albumKey ?? $0.track.album }).count let ahead = Set(queue[index...].map { $0.track.albumKey ?? $0.track.album }).count
guard ahead <= Self.radioAlbumsLow else { return } let want = min(max(Self.radioAlbumsAhead + 1 - ahead, radioOwed), Self.radioAlbumsMax - ahead)
guard want > 0 else { radioOwed = 0; return }
stationBusy = true stationBusy = true
let owed = radioOwed
Task { @MainActor in Task { @MainActor in
defer { if gen == stationGen { stationBusy = false } } var got = false
// Checks again once the albums are in, unless nothing came back (server down: don't spin).
defer { if gen == stationGen { stationBusy = false; if got { topUpStation() } } }
var deck = saved var deck = saved
if deck.isEmpty { deck = (try? await albumDeck()) ?? [] } if deck.count < want { deck += (try? await albumDeck()) ?? [] }
let take = Array(deck.prefix(Self.radioAlbumsAhead + 1 - ahead)) let take = Array(deck.prefix(want))
deck.removeFirst(take.count) deck.removeFirst(take.count)
let tracks = await albumTracks(take) let tracks = await albumTracks(take)
guard gen == stationGen else { return } guard gen == stationGen else { return }
station = .albums(deck) station = .albums(deck)
radioOwed = max(radioOwed - owed, 0)
got = !tracks.isEmpty
addToQueue(tracks) addToQueue(tracks)
} }
case .songs: case .songs:
+10
View File
@@ -201,6 +201,16 @@ final class PlexClient: @unchecked Sendable {
} }
/// Made on the server of the first song; songs from other servers are left out. /// Made on the server of the first song; songs from other servers are left out.
/// Servers a new playlist can live on, as (id, name).
var playlistServers: [(String, String)] { sources.map { ($0.server.id, $0.server.name) } }
/// An empty playlist on one server (the only one when [serverId] is nil).
func createEmptyPlaylist(_ title: String, serverId: String?) async throws -> Playlist? {
let list = sources
guard let s = list.first(where: { $0.server.id == serverId }) ?? list.first else { throw NotSignedIn() }
return try await s.createPlaylist(title, trackKeys: [])?.tagged(s.server.id)
}
func createPlaylist(_ title: String, trackKeys: [String]) async throws -> Playlist? { func createPlaylist(_ title: String, trackKeys: [String]) async throws -> Playlist? {
guard let first = trackKeys.first else { return nil } guard let first = trackKeys.first else { return nil }
let (s, _) = try routed(first) let (s, _) = try routed(first)
+3 -1
View File
@@ -266,7 +266,9 @@ final class PlexServer: MediaSource, @unchecked Sendable {
} }
func createPlaylist(_ title: String, trackKeys: [String]) async throws -> Playlist? { func createPlaylist(_ title: String, trackKeys: [String]) async throws -> Playlist? {
let uri = try await libraryUri(trackKeys) // No songs: a bare library uri makes an empty playlist (newer Plex servers allow it).
if trackKeys.isEmpty, machine.isEmpty { machine = try await machineId() }
let uri = trackKeys.isEmpty ? "server://\(machine)/com.plexapp.plugins.library" : try await libraryUri(trackKeys)
return try await send("POST", "/playlists", [("type", "audio"), ("title", title), ("smart", 0), ("uri", uri)]) return try await send("POST", "/playlists", [("type", "audio"), ("title", title), ("smart", 0), ("uri", uri)])
.metadata.first?.toPlaylist() .metadata.first?.toPlaylist()
} }
+44 -3
View File
@@ -54,13 +54,13 @@ struct MediaMenu {
playlistKey: nil, extra: [], confirmDownload: true, stemmed: stemmed(cov)) playlistKey: nil, extra: [], confirmDownload: true, stemmed: stemmed(cov))
} }
/// [changed] hears the playlist after a rename or a new cover, so an open page can follow. /// [changed] hears the playlist after a rename or a new cover, so an open page can follow; [deleted] after a delete.
func playlist(_ pl: Playlist, extra: [SheetAction] = [], changed: ((Playlist) -> Void)? = nil) -> [SheetAction] { func playlist(_ pl: Playlist, extra: [SheetAction] = [], changed: ((Playlist) -> Void)? = nil, deleted: (() -> Void)? = nil) -> [SheetAction] {
let plex = g.plex let plex = g.plex
let copy = SheetAction("Copy to Stem Playlist…", icon: "doc.on.doc") { copyToStems(pl) } let copy = SheetAction("Copy to Stem Playlist…", icon: "doc.on.doc") { copyToStems(pl) }
let gr = DownloadGroup(kind: .playlist, key: pl.ratingKey, title: pl.title, subtitle: "Playlist", thumb: pl.thumb) let gr = DownloadGroup(kind: .playlist, key: pl.ratingKey, title: pl.title, subtitle: "Playlist", thumb: pl.thumb)
return collection(pl.title, gr, { try await plex.playlistTracks(pl.ratingKey) }, playlistKey: pl.ratingKey, return collection(pl.title, gr, { try await plex.playlistTracks(pl.ratingKey) }, playlistKey: pl.ratingKey,
extra: [copy] + (pl.smart ? [] : playlistEdits(pl, changed)) + extra, extra: [copy] + (pl.smart ? [] : playlistEdits(pl, changed)) + extra + [delete(pl, deleted)],
confirmDownload: pl.trackCount > 50) confirmDownload: pl.trackCount > 50)
} }
@@ -98,6 +98,24 @@ struct MediaMenu {
return [rename, cover] return [rename, cover]
} }
private func delete(_ pl: Playlist, _ deleted: (() -> Void)?) -> SheetAction {
let plex = g.plex
let overlays = overlays
let ui = ui
return SheetAction("Delete Playlist…", icon: "trash", destructive: true) {
overlays.confirm("Delete “\(pl.title)”?", "This removes it from the server for every app.", "Delete") {
Task {
do {
try await plex.deletePlaylist(pl.ratingKey)
ui.playlistEdits += 1
overlays.hud("Deleted “\(pl.title)”", "trash")
deleted?()
} catch { overlays.hud("Couldn't delete: \(error.localizedDescription)", "exclamationmark.triangle") }
}
}
}
}
func stemPlaylist(_ pl: StemPlaylist, extra: [SheetAction] = [], onPage: Bool = false) -> [SheetAction] { func stemPlaylist(_ pl: StemPlaylist, extra: [SheetAction] = [], onPage: Bool = false) -> [SheetAction] {
var a = [ var a = [
SheetAction("Play Next", icon: "text.line.first.and.arrowtriangle.forward") { SheetAction("Play Next", icon: "text.line.first.and.arrowtriangle.forward") {
@@ -296,6 +314,29 @@ struct MediaMenu {
} }
} }
/// Empty playlist; asks which server first when more than one is signed in.
func newEmptyPlaylist(onCreated: @escaping () -> Void = {}) {
let plex = g.plex
let servers = plex.playlistServers
let make: (String?) -> Void = { id in
overlays.prompt("New Playlist", "Add songs later with “Add to Playlist”.", "Create", placeholder: "Playlist name") { name in
Task {
do {
_ = try await plex.createEmptyPlaylist(name, serverId: id)
overlays.hud("Created “\(name)”")
ui.playlistEdits += 1
onCreated()
} catch {
overlays.hud("Couldn't create: \(error.localizedDescription)", "exclamationmark.triangle")
}
}
}
}
if servers.count > 1 {
overlays.actions("Which Server?", servers.map { s in SheetAction(s.1.isEmpty ? "Server" : s.1) { make(s.0) } })
} else { make(servers.first?.0) }
}
func newPlaylist(_ tracks: [Track], onCreated: @escaping () -> Void = {}) { func newPlaylist(_ tracks: [Track], onCreated: @escaping () -> Void = {}) {
let plex = g.plex let plex = g.plex
overlays.prompt("New Playlist", "Name it; you can add more songs later.", "Create", placeholder: "Playlist name") { name in overlays.prompt("New Playlist", "Name it; you can add more songs later.", "Create", placeholder: "Playlist name") { name in
+11 -22
View File
@@ -54,18 +54,16 @@ struct PlaylistsScreen: View {
} }
} }
/// Plex can't hold an empty playlist, so new ones start from songs you have.
private func newPlaylist() { private func newPlaylist() {
let queue = g.playback.queue let queue = g.playback.queue
var acts: [SheetAction] = [] var acts: [SheetAction] = [SheetAction("Empty Playlist…", icon: "plus") { ui.menu.newEmptyPlaylist { reload += 1 } }]
if !queue.isEmpty { if !queue.isEmpty {
acts.append(SheetAction("New Playlist from Queue (\(queue.count))") { ui.menu.newPlaylist(queue.map(\.track)) { reload += 1 } }) acts.append(SheetAction("New Playlist from Queue (\(queue.count))") { ui.menu.newPlaylist(queue.map(\.track)) { reload += 1 } })
} }
if let now = g.playback.current?.track { if let now = g.playback.current?.track {
acts.append(SheetAction("New Playlist with “\(now.title)”") { ui.menu.newPlaylist([now]) { reload += 1 } }) acts.append(SheetAction("New Playlist with “\(now.title)”") { ui.menu.newPlaylist([now]) { reload += 1 } })
} }
if acts.isEmpty { ui.overlays.hud("Play something first, or use “Add to Playlist” on any song.", "info.circle") } ui.overlays.actions("New Playlist", acts)
else { ui.overlays.actions("New Playlist", acts) }
} }
private func newStemPlaylist() { private func newStemPlaylist() {
@@ -159,9 +157,8 @@ struct StemPlaylistScreen: View {
} }
.toolbar { .toolbar {
ToolbarItemGroup(placement: .topBarTrailing) { ToolbarItemGroup(placement: .topBarTrailing) {
if !editing { MoreMenu(items: moreItems(pl)) }
if editing { Button("Done") { g.stemPlaylists.setItems(pl.id, items); editing = false }.bold() } if editing { Button("Done") { g.stemPlaylists.setItems(pl.id, items); editing = false }.bold() }
else if !pl.items.isEmpty { Button("Edit") { items = pl.items; editing = true } } else { MoreMenu(items: moreItems(pl)) }
} }
} }
.modifier(SplitHidesTitle()) .modifier(SplitHidesTitle())
@@ -179,18 +176,19 @@ struct StemPlaylistScreen: View {
} }
} }
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.padding(.top, 8).padding(.bottom, 16) .padding(.bottom, 16)
} }
private func moreItems(_ pl: StemPlaylist) -> [SheetAction] { private func moreItems(_ pl: StemPlaylist) -> [SheetAction] {
let lists = g.stemPlaylists let lists = g.stemPlaylists
let edit = pl.items.isEmpty ? [] : [SheetAction("Edit Songs", icon: "list.bullet") { items = pl.items; editing = true }]
let rename = SheetAction("Rename…", icon: "pencil") { let rename = SheetAction("Rename…", icon: "pencil") {
ui.overlays.prompt("Rename Stem Playlist", nil, initial: pl.title, "Save") { lists.rename(pl.id, $0) } ui.overlays.prompt("Rename Stem Playlist", nil, initial: pl.title, "Save") { lists.rename(pl.id, $0) }
} }
let mixAll = SheetAction("Set Mix for All Songs…", icon: "slider.horizontal.3") { let mixAll = SheetAction("Set Mix for All Songs…", icon: "slider.horizontal.3") {
ui.menu.chooseMix(pl.tracks) { m in lists.setItems(pl.id, pl.items.map { var it = $0; it.mix = MixPresets.normalized(m); return it }) } ui.menu.chooseMix(pl.tracks) { m in lists.setItems(pl.id, pl.items.map { var it = $0; it.mix = MixPresets.normalized(m); return it }) }
} }
return ui.menu.stemPlaylist(pl, extra: pl.items.isEmpty ? [rename] : [rename, mixAll], onPage: true) return ui.menu.stemPlaylist(pl, extra: edit + (pl.items.isEmpty ? [rename] : [rename, mixAll]), onPage: true)
} }
} }
@@ -270,12 +268,9 @@ struct PlaylistScreen: View {
} }
.toolbar { .toolbar {
ToolbarItemGroup(placement: .topBarTrailing) { ToolbarItemGroup(placement: .topBarTrailing) {
if !editing { MoreMenu(items: moreItems(list)) }
if !playlist.smart && !list.isEmpty {
if saving { ProgressView() } if saving { ProgressView() }
else if editing { Button("Done") { commit(list) }.bold() } else if editing { Button("Done") { commit(list) }.bold() }
else { Button("Edit") { items = list; removed = []; editing = true } } else { MoreMenu(items: moreItems(list)) }
}
} }
} }
.modifier(SplitHidesTitle()) .modifier(SplitHidesTitle())
@@ -297,7 +292,7 @@ struct PlaylistScreen: View {
} }
} }
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.padding(.top, 8).padding(.bottom, 16) .padding(.bottom, 16)
} }
private func removeAction(_ t: Track) -> [SheetAction] { private func removeAction(_ t: Track) -> [SheetAction] {
@@ -311,19 +306,13 @@ struct PlaylistScreen: View {
} }
private func moreItems(_ list: [Track]) -> [SheetAction] { private func moreItems(_ list: [Track]) -> [SheetAction] {
var extra: [SheetAction] = [] let extra = playlist.smart || list.isEmpty ? [] :
let plex = g.plex [SheetAction("Edit Songs", icon: "list.bullet") { items = list; removed = []; editing = true }]
let key = playlist.ratingKey
extra.append(SheetAction("Delete Playlist", icon: "trash", destructive: true) {
ui.overlays.confirm("Delete “\(title)”?", "This removes it from Plex for every app.", "Delete") {
Task { if (try? await plex.deletePlaylist(key)) != nil { ui.pop() } }
}
})
var pl = playlist var pl = playlist
pl.title = title pl.title = title
pl.thumb = thumb pl.thumb = thumb
pl.trackCount = list.count pl.trackCount = list.count
return ui.menu.playlist(pl, extra: extra) { title = $0.title; thumb = $0.thumb } return ui.menu.playlist(pl, extra: extra, changed: { title = $0.title; thumb = $0.thumb }, deleted: { ui.pop() })
} }
/// Sends removals, then replays the new order as "move after" calls against a simulated server list. /// Sends removals, then replays the new order as "move after" calls against a simulated server list.
+1 -1
View File
@@ -9,7 +9,7 @@ settings:
# iOS needs a plain number for the bundle version; the label is what the app and releases show. # iOS needs a plain number for the bundle version; the label is what the app and releases show.
MARKETING_VERSION: "0.10.1" MARKETING_VERSION: "0.10.1"
VERSION_LABEL: "0.10.1" VERSION_LABEL: "0.10.1"
CURRENT_PROJECT_VERSION: "60" CURRENT_PROJECT_VERSION: "62"
# Dev builds override these (build-ipa.sh dev) so they install next to the release app. # Dev builds override these (build-ipa.sh dev) so they install next to the release app.
APP_ID: org.cdnutter.stemify APP_ID: org.cdnutter.stemify
APP_NAME: Stemify APP_NAME: Stemify