Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e02428ab70 | ||
|
|
9f68aa588b |
No files matched your search
@@ -45,6 +45,14 @@ final class AppGraph {
|
||||
mediaSession = URLSession(configuration: m)
|
||||
|
||||
plex = PlexClient(http: apiHttp, settings: settings)
|
||||
let plex = plex
|
||||
// Left home or joined Wi-Fi: the saved Plex address may be dead now. Give the new link a moment first.
|
||||
net.onChange {
|
||||
Task.detached {
|
||||
try? await Task.sleep(nanoseconds: 1_500_000_000)
|
||||
await plex.reroute("network changed")
|
||||
}
|
||||
}
|
||||
reach = HomeReach(settings: settings, net: net)
|
||||
let reach = reach
|
||||
carHttp.forceCache = { !reach.lastKnown }
|
||||
|
||||
@@ -34,13 +34,13 @@ final class AppDelegate: NSObject, UIApplicationDelegate {
|
||||
enum Orientation {
|
||||
nonisolated(unsafe) static var mask: UIInterfaceOrientationMask = .allButUpsideDown
|
||||
|
||||
@MainActor static func lock(_ upright: Bool) {
|
||||
let m: UIInterfaceOrientationMask = upright ? .portrait : .allButUpsideDown
|
||||
/// Folded Duo: portrait only. Unfolded Duo: landscape only. Anything else turns freely.
|
||||
@MainActor static func lock(_ m: UIInterfaceOrientationMask) {
|
||||
guard m != mask else { return }
|
||||
mask = m
|
||||
for case let scene as UIWindowScene in UIApplication.shared.connectedScenes {
|
||||
scene.keyWindow?.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
|
||||
if upright { scene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) { _ in } }
|
||||
if m != .allButUpsideDown { scene.requestGeometryUpdate(.iOS(interfaceOrientations: m)) { _ in } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@ struct StemifyApp: App {
|
||||
AppActivity.setPhone(p != .background)
|
||||
guard p == .active else { return }
|
||||
AppGraph.shared.eq.refreshRoute()
|
||||
Task.detached { await AppGraph.shared.plex.reroute("foreground") }
|
||||
// Keep downloaded playlists in step with the server, like Plexamp.
|
||||
Task { await AppGraph.shared.downloads.refresh() }
|
||||
}
|
||||
|
||||
@@ -722,9 +722,19 @@ final class PlaybackManager: StemEngineListener, @unchecked Sendable {
|
||||
|
||||
private func openDetached(_ track: Track, _ startMs: Int64) async throws -> (TrackSession, StemEntry?) {
|
||||
// Plain Plex files need a playback session first, or a Remote Access upload limit fails them.
|
||||
var stream: URL?
|
||||
if stems.find(track) == nil, !cache.isComplete(Self.plexKey(track)) { stream = await plex.streamUrl(track) }
|
||||
return try await withCheckedThrowingContinuation { [stream] cont in
|
||||
let plain = stems.find(track) == nil && !cache.isComplete(Self.plexKey(track))
|
||||
let stream = plain ? await plex.streamUrl(track) : nil
|
||||
do {
|
||||
return try await openOn(track, startMs, stream)
|
||||
} catch {
|
||||
// A dead saved address (left home, network changed): pick a working one and try once more.
|
||||
guard plain, !Task.isCancelled, await plex.reroute("stream failed") else { throw error }
|
||||
return try await openOn(track, startMs, await plex.streamUrl(track))
|
||||
}
|
||||
}
|
||||
|
||||
private func openOn(_ track: Track, _ startMs: Int64, _ stream: URL?) async throws -> (TrackSession, StemEntry?) {
|
||||
try await withCheckedThrowingContinuation { cont in
|
||||
DispatchQueue.global(qos: .userInitiated).async { [self] in
|
||||
cont.resume(with: Result { try open(track, startMs, stream: stream) })
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ struct MediaServer: Codable, Hashable, Identifiable {
|
||||
var machineId = ""
|
||||
var sections: [String] = []
|
||||
var sectionTitles = ""
|
||||
/// Every address plex.tv lists for this server, best first (local, remote, relay).
|
||||
/// Optional so servers saved before it still decode.
|
||||
var connections: [String]? = nil
|
||||
|
||||
var signedIn: Bool { !token.isEmpty }
|
||||
var ready: Bool { signedIn && !sections.isEmpty }
|
||||
|
||||
@@ -21,6 +21,7 @@ final class PlexClient: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var builtFrom = "\u{0}"
|
||||
private var built: [MediaSource] = []
|
||||
private var rerouting = false
|
||||
|
||||
init(http: Http, settings: Settings) {
|
||||
self.http = http
|
||||
@@ -285,6 +286,45 @@ final class PlexClient: @unchecked Sendable {
|
||||
return box.url
|
||||
}
|
||||
|
||||
// ---- address re-picking ------------------------------------------------------------
|
||||
|
||||
/// Re-picks each Plex server's address. Sign-in picks one (a LAN address at home) and it
|
||||
/// used to stick forever, so away from home every stream hit a dead LAN address (TLS error)
|
||||
/// or a relay (503). Probes every known address and keeps the best one that answers;
|
||||
/// when none answer, asks plex.tv for the current list. Returns true if any address changed.
|
||||
@discardableResult
|
||||
func reroute(_ why: String) async -> Bool {
|
||||
lock.lock()
|
||||
if rerouting { lock.unlock(); return false }
|
||||
rerouting = true
|
||||
lock.unlock()
|
||||
defer { lock.lock(); rerouting = false; lock.unlock() }
|
||||
|
||||
let tv = plexTv()
|
||||
var changed = false
|
||||
for srv in settings.servers where srv.kind == .plex && srv.signedIn {
|
||||
var uris = srv.connections ?? []
|
||||
if !uris.contains(srv.base) { uris.append(srv.base) }
|
||||
var best = await tv.firstAlive(uris, machineId: srv.machineId, token: srv.token)
|
||||
var fresh: [String]?
|
||||
if best == nil || srv.connections == nil, !srv.machineId.isEmpty,
|
||||
let r = (try? await tv.resources(token: srv.token))?.first(where: { $0.clientIdentifier == srv.machineId }) {
|
||||
fresh = PlexServer.ranked(r)
|
||||
if best == nil, let f = fresh { best = await tv.firstAlive(f, machineId: srv.machineId, token: srv.token) }
|
||||
}
|
||||
var s = srv
|
||||
if let fresh { s.connections = fresh }
|
||||
if let best { s.url = best }
|
||||
guard s != srv else { continue }
|
||||
if s.url != srv.url {
|
||||
changed = true
|
||||
Log.shared.info("plex", "\(srv.label) (\(why)): \(srv.base) -> \(s.base)")
|
||||
}
|
||||
settings.save(s)
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// ---- sign-in helpers --------------------------------------------------------------
|
||||
|
||||
/// A Plex client for plex.tv calls and for a server that isn't saved yet.
|
||||
@@ -323,6 +363,7 @@ final class PlexClient: @unchecked Sendable {
|
||||
?? settings.servers.first { $0.kind == .plex && $0.machineId.isEmpty && $0.base == h.url.trimmingCharacters(in: CharacterSet(charactersIn: "/")) }
|
||||
var srv = known ?? MediaServer(id: settings.nextServerId(), kind: .plex)
|
||||
srv.url = h.url
|
||||
srv.connections = PlexServer.ranked(h.res)
|
||||
srv.token = h.res.accessToken.isEmpty ? token : h.res.accessToken
|
||||
srv.machineId = h.res.clientIdentifier
|
||||
srv.user = user
|
||||
|
||||
@@ -375,21 +375,41 @@ final class PlexServer: MediaSource, @unchecked Sendable {
|
||||
/// The first address that answers /identity as the expected server, local ones first, relay last.
|
||||
func reach(_ r: PlexResource, userToken: String) async -> String? {
|
||||
let tok = r.accessToken.isEmpty ? userToken : r.accessToken
|
||||
let ordered = r.connections.filter { !$0.uri.isEmpty }.sorted { rank($0) < rank($1) }
|
||||
for c in ordered {
|
||||
let base = c.uri.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
|
||||
guard let u = URL(string: base + "/identity") else { continue }
|
||||
var req = request(u, withToken: false)
|
||||
req.setValue(tok, forHTTPHeaderField: "X-Plex-Token")
|
||||
req.timeoutInterval = 3.5
|
||||
guard let body = try? await http.data(req),
|
||||
let id = try? decode(body).machineIdentifier, id == r.clientIdentifier || r.clientIdentifier.isEmpty else { continue }
|
||||
return base
|
||||
}
|
||||
return nil
|
||||
return await firstAlive(Self.ranked(r), machineId: r.clientIdentifier, token: tok)
|
||||
}
|
||||
|
||||
private func rank(_ c: PlexResource.Connection) -> Int { c.relay ? 2 : (c.local ? 0 : 1) }
|
||||
/// A resource's addresses, local first, then remote, relay last.
|
||||
static func ranked(_ r: PlexResource) -> [String] {
|
||||
r.connections.filter { !$0.uri.isEmpty }
|
||||
.sorted { ($0.relay ? 2 : ($0.local ? 0 : 1)) < ($1.relay ? 2 : ($1.local ? 0 : 1)) }
|
||||
.map { $0.uri.trimmingCharacters(in: CharacterSet(charactersIn: "/")) }
|
||||
}
|
||||
|
||||
/// Probes every address's /identity at once, straight to the network (the offline cache
|
||||
/// would make a dead LAN address look alive), and returns the earliest one in [uris] that
|
||||
/// answers as [machineId].
|
||||
func firstAlive(_ uris: [String], machineId: String, token: String, timeout: TimeInterval = 4) async -> String? {
|
||||
let bases = uris.map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "/")) }
|
||||
let alive: [Int] = await withTaskGroup(of: Int?.self) { group in
|
||||
for (i, b) in bases.enumerated() {
|
||||
group.addTask { [self] in
|
||||
guard let u = URL(string: b + "/identity") else { return nil }
|
||||
var req = request(u, withToken: false)
|
||||
req.setValue(token, forHTTPHeaderField: "X-Plex-Token")
|
||||
req.timeoutInterval = timeout
|
||||
guard let (body, resp) = try? await http.session.data(for: req),
|
||||
(resp as? HTTPURLResponse)?.statusCode == 200,
|
||||
let id = try? decode(body).machineIdentifier,
|
||||
machineId.isEmpty || id == machineId else { return nil }
|
||||
return i
|
||||
}
|
||||
}
|
||||
var out: [Int] = []
|
||||
for await i in group { if let i { out.append(i) } }
|
||||
return out
|
||||
}
|
||||
return alive.min().map { bases[$0] }
|
||||
}
|
||||
|
||||
func checkPin(_ id: Int64) async throws -> PlexPin {
|
||||
let req = request(URL(string: "https://plex.tv/api/v2/pins/\(id)")!, withToken: false)
|
||||
|
||||
@@ -131,13 +131,24 @@ final class Ui {
|
||||
duo = true
|
||||
UserDefaults.standard.set(true, forKey: "duoSeen")
|
||||
}
|
||||
Orientation.lock(folded)
|
||||
lockOrientation()
|
||||
}
|
||||
|
||||
/// Split (unfolded) goes landscape at once. Portrait waits a moment and checks again, so a
|
||||
/// frame without a hinge reading mid-rotation can't throw an unfolded phone back upright.
|
||||
private func lockOrientation() {
|
||||
if split { Orientation.lock(.landscape); return }
|
||||
guard folded else { Orientation.lock(.allButUpsideDown); return }
|
||||
Task { @MainActor in
|
||||
try? await Task.sleep(for: .milliseconds(400))
|
||||
if self.folded { Orientation.lock(.portrait) }
|
||||
}
|
||||
}
|
||||
|
||||
func setSplit(_ on: Bool) {
|
||||
guard on != split else { return }
|
||||
split = on
|
||||
Orientation.lock(folded)
|
||||
lockOrientation()
|
||||
if on {
|
||||
nowPlayingOpen = false
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ settings:
|
||||
# iOS needs a plain number for the bundle version; the label is what the app and releases show.
|
||||
MARKETING_VERSION: "0.9.0"
|
||||
VERSION_LABEL: "0.9.0"
|
||||
CURRENT_PROJECT_VERSION: "34"
|
||||
CURRENT_PROJECT_VERSION: "36"
|
||||
# Dev builds override these (build-ipa.sh dev) so they install next to the release app.
|
||||
APP_ID: org.cdnutter.stemify
|
||||
APP_NAME: Stemify
|
||||
|
||||
Reference in new issue
Block a user