Re-pick Plex server address on network change, foreground, and stream failure (dev 36)
The address chosen at sign-in (LAN first) was kept forever, so away from home streams hit a dead LAN address (TLS error) or the relay (503). Store every address plex.tv lists, probe them all bypassing the offline cache, and keep the best one that answers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f68aa588b
commit
e02428ab70
7 files changed
+100
-17
No files matched your search
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user