geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import Foundation
import MediaPlayer
import Observation
import UIKit
#if compiler(>=6.2) && !targetEnvironment(macCatalyst)
import NowPlaying
#endif
/// Publishes one coherent native media item, keeping asynchronous artwork tied to its URL.
@MainActor
final class NativeNowPlayingPublisher {
private var info: [String: Any] = [:]
private var artworkURL: URL?
private var artwork: MPMediaItemArtwork?
private var artworkTask: Task<Void, Never>?
#if compiler(>=6.2) && !targetEnvironment(macCatalyst)
private var systemSession: AnyObject?
private var systemSessionModel: AnyObject?
private var primaryRequestTask: Task<Void, Never>?
private var didAttemptPrimaryRequest = false
private var carPlaySceneIsActive = false
private var systemSessionGeneration = 0
private var systemContentKey: String?
private var systemCommandKey: String?
private var systemSnapshotPublishedAt: Date?
private var systemSnapshotPosition: TimeInterval?
private var systemSnapshotPlaying: Bool?
private var systemIsPlaying = false
private var systemHasArtwork = false
#endif
func clear() {
artworkTask?.cancel()
artworkTask = nil
artworkURL = nil
artwork = nil
info = [:]
#if compiler(>=6.2) && !targetEnvironment(macCatalyst)
if #available(iOS 27.0, *) {
primaryRequestTask?.cancel()
primaryRequestTask = nil
didAttemptPrimaryRequest = false
systemSessionGeneration &+= 1
systemContentKey = nil
systemCommandKey = nil
systemSnapshotPublishedAt = nil
systemSnapshotPosition = nil
systemSnapshotPlaying = nil
systemIsPlaying = false
systemHasArtwork = false
(systemSessionModel as? HydraulophoneMediaSession)?.content = nil
(systemSessionModel as? HydraulophoneMediaSession)?.playbackSnapshot =
MediaPlaybackSnapshot(state: .stopped)
systemSession = nil
systemSessionModel = nil
} else {
MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
}
#else
MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
#endif
}
func publish(
_ metadata: [String: Any], artworkURL url: URL?, isPlaying: Bool = false,
elapsedTime: TimeInterval = 0, duration: TimeInterval = 0,
canSkipNext: Bool = true, canSkipPrevious: Bool = true, canSeek: Bool = true,
onPlay: @escaping @MainActor () -> Void = {},
onPause: @escaping @MainActor () -> Void = {},
onNext: @escaping @MainActor () -> Void = {},
onPrevious: @escaping @MainActor () -> Void = {},
onSeek: @escaping @MainActor (TimeInterval) -> Void = { _ in }
) {
info = metadata
#if compiler(>=6.2) && !targetEnvironment(macCatalyst)
if #available(iOS 27.0, *) {
publishSystemSession(
metadata, artworkURL: url, isPlaying: isPlaying,
elapsedTime: elapsedTime, duration: duration,
canSkipNext: canSkipNext, canSkipPrevious: canSkipPrevious, canSeek: canSeek,
onPlay: onPlay, onPause: onPause, onNext: onNext,
onPrevious: onPrevious, onSeek: onSeek
)
return
}
#endif
if artworkURL != url {
artworkTask?.cancel()
artworkURL = url
artwork = nil
if let url, url.scheme == "https" || url.isFileURL {
artworkTask = Task { [weak self] in
var image: UIImage?
for candidate in ArtworkURL.nowPlayingCandidates(from: url) {
do {
let data: Data
if candidate.isFileURL {
guard let local = await OfflineArtwork.shared.data(at: candidate) else { continue }
data = local
} else {
var request = URLRequest(url: candidate)
request.timeoutInterval = 15
let (remote, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse,
(200..<300).contains(response.statusCode)
else { continue }
data = remote
}
guard data.count <= 10_000_000, let decodedImage = UIImage(data: data) else {
continue
}
image = decodedImage
break
} catch {
continue
}
}
guard let image,
Self.shouldApplyArtwork(
requestedURL: url,
currentURL: self?.artworkURL,
isCancelled: Task.isCancelled
),
let self, self.artworkURL == url
else { return }
self.artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
self.apply()
}
}
}
apply()
}
static func shouldApplyArtwork(
requestedURL: URL,
currentURL: URL?,
isCancelled: Bool
) -> Bool {
!isCancelled && currentURL == requestedURL
}
private func apply() {
var value = info
if let artwork { value[MPMediaItemPropertyArtwork] = artwork }
MPNowPlayingInfoCenter.default().nowPlayingInfo = value
}
#if compiler(>=6.2) && !targetEnvironment(macCatalyst)
@available(iOS 27.0, *)
private func publishSystemSession(
_ metadata: [String: Any], artworkURL: URL?, isPlaying: Bool,
elapsedTime: TimeInterval, duration: TimeInterval,
canSkipNext: Bool, canSkipPrevious: Bool, canSeek: Bool,
onPlay: @escaping @MainActor () -> Void,
onPause: @escaping @MainActor () -> Void,
onNext: @escaping @MainActor () -> Void,
onPrevious: @escaping @MainActor () -> Void,
onSeek: @escaping @MainActor (TimeInterval) -> Void
) {
let title = metadata[MPMediaItemPropertyTitle] as? String ?? ""
let artist = metadata[MPMediaItemPropertyArtist] as? String ?? ""
let album = metadata[MPMediaItemPropertyAlbumTitle] as? String ?? ""
let identifier =
metadata[MPNowPlayingInfoPropertyExternalContentIdentifier] as? String
?? UUID().uuidString
let safeDuration = duration.isFinite && duration > 0 ? duration : nil
systemIsPlaying = isPlaying
let contentKey = [
identifier, title, artist, album, String(describing: safeDuration),
artworkURL?.absoluteString ?? "",
].joined(separator: "\u{1f}")
let model: HydraulophoneMediaSession
if let existing = systemSessionModel as? HydraulophoneMediaSession {
model = existing
} else {
model = HydraulophoneMediaSession()
systemSessionModel = model
systemSession = MediaSession(model)
}
let contentChanged = systemContentKey != contentKey
if contentChanged {
model.content = MusicContent(
id: identifier,
songTitle: title,
artistName: artist,
albumName: album,
type: .audio,
duration: safeDuration.map(MediaDuration.finite),
artwork: makeArtwork(url: artworkURL)
)
systemContentKey = contentKey
systemHasArtwork = artworkURL != nil
}
let commandKey = "\(identifier):\(canSkipNext):\(canSkipPrevious):\(canSeek)"
if systemCommandKey != commandKey {
model.commands = [
.play { onPlay() },
.pause { onPause() },
.next { onNext() }.enabled(canSkipNext),
.previous { onPrevious() }.enabled(canSkipPrevious),
.seekToPosition { position in onSeek(position) }.enabled(canSeek),
]
systemCommandKey = commandKey
}
let now = Date()
let position = elapsedTime.isFinite ? max(0, elapsedTime) : 0
let predictedPosition =
(systemSnapshotPosition ?? position)
+ (systemSnapshotPlaying == true
? now.timeIntervalSince(systemSnapshotPublishedAt ?? now) : 0)
let shouldPublishSnapshot =
contentChanged
|| systemSnapshotPublishedAt == nil
|| systemSnapshotPlaying != isPlaying
|| abs(position - predictedPosition) > 1.5
|| now.timeIntervalSince(systemSnapshotPublishedAt ?? .distantPast) >= 5
if shouldPublishSnapshot {
model.playbackSnapshot = MediaPlaybackSnapshot(
state: isPlaying ? .playing(rate: 1) : .paused,
defaultPlaybackRate: 1,
elapsedTime: position,
timestamp: now
)
systemSnapshotPublishedAt = now
systemSnapshotPosition = position
systemSnapshotPlaying = isPlaying
}
requestSystemPrimaryIfNeeded(artworkAvailable: artworkURL != nil)
}
@available(iOS 27.0, *)
func applicationDidBecomeActive() {
didAttemptPrimaryRequest = false
requestSystemPrimaryIfNeeded(artworkAvailable: systemHasArtwork)
}
@available(iOS 27.0, *)
func carPlaySceneDidConnect() {
carPlaySceneIsActive = true
didAttemptPrimaryRequest = false
requestSystemPrimaryIfNeeded(artworkAvailable: systemHasArtwork)
}
@available(iOS 27.0, *)
func carPlaySceneDidDisconnect() {
carPlaySceneIsActive = false
}
@available(iOS 27.0, *)
private func requestSystemPrimaryIfNeeded(artworkAvailable: Bool) {
guard systemIsPlaying,
UIApplication.shared.applicationState == .active || carPlaySceneIsActive,
let session = systemSession as? MediaSession<HydraulophoneMediaSession>,
!session.isSystemPrimary, primaryRequestTask == nil, !didAttemptPrimaryRequest
else { return }
didAttemptPrimaryRequest = true
let generation = systemSessionGeneration
primaryRequestTask = Task { [weak self, weak session] in
guard let self, let session else { return }
defer { self.primaryRequestTask = nil }
do {
try await session.requestToBecomeSystemPrimary()
guard self.systemSessionGeneration == generation else { return }
self.logSystemSession(
"primary-request-succeeded primary=\(session.isSystemPrimary) "
+ "artworkAvailable=\(artworkAvailable)"
)
} catch {
guard self.systemSessionGeneration == generation else { return }
let reason: String
if let mediaError = error as? MediaSessionError {
switch mediaError {
case .invalidState: reason = "invalidState"
case .internalFailure: reason = "internalFailure"
case .sessionInvalidated: reason = "sessionInvalidated"
@unknown default: reason = "unknownMediaSessionError"
}
} else {
reason = "other"
}
self.logSystemSession(
"primary-request-failed reason=\(reason) "
+ "canBecomeApplicationPrimary=\(session.canBecomeApplicationPrimary) "
+ "applicationPrimary=\(session.isApplicationPrimary)")
}
}
}
@available(iOS 27.0, *)
private func makeArtwork(url: URL?) -> NowPlaying.Artwork? {
guard let url, url.scheme == "https" || url.isFileURL else { return nil }
return NowPlaying.Artwork(id: url.absoluteString) { _ in
for candidate in ArtworkURL.nowPlayingCandidates(from: url) {
do {
let data: Data
if candidate.isFileURL {
guard let local = await OfflineArtwork.shared.data(at: candidate) else { continue }
data = local
} else {
var request = URLRequest(url: candidate)
request.timeoutInterval = 15
let (remote, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse,
(200..<300).contains(response.statusCode), remote.count <= 10_000_000
else { continue }
data = remote
}
guard data.count <= 10_000_000 else { continue }
return try ArtworkRepresentation(data: data)
} catch {
continue
}
}
throw URLError(.badServerResponse)
}
}
@available(iOS 27.0, *)
private func logSystemSession(_ message: String) {
#if DEBUG
FileHandle.standardOutput.write(
Data(("Hydraulophone NowPlaying system-session " + message + "\n").utf8))
#endif
}
#endif
}
#if compiler(>=6.2) && !targetEnvironment(macCatalyst)
@available(iOS 27.0, *)
@Observable
@MainActor
private final class HydraulophoneMediaSession: MediaSessionRepresentable {
let id = "com.hydraulophone.local-playback"
var content: (any MediaContentRepresentable)?
var playbackSnapshot: MediaPlaybackSnapshot?
var commands: [MediaCommand] = []
}
#endif