Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/NFTs/NFTMedia.swift10// Description : NFT media, defensively. Bytes only ever come from the11// server's media proxy (by opaque id — no URL of a metadata12// document is requested by this app). The type served is13// checked against the bytes; images are decoded by ImageIO14// off the main thread, downsampled, re-encoded and kept in a15// size-capped offline cache; an MP4 plays from a temporary16// file only after an explicit tap. HTML, SVG and anything17// that looks like markup is NEVER rendered: there is no web18// engine in this app. Everything else is a neutral tile that19// says what was not shown, and why.20// Module : Features21// Repository : https://git.spboucher.ai/sp-wallet-ios22// Created : 2026-11-1823// Last Modified : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author : Simon-Pierre Boucher30// Position : Professor of Finance31// Institution : Université du Québec en Outaouais (UQO)32// Department : Département des sciences administratives33// Organization : SP Boucher34//35// Website : https://spboucher.ai36// Git : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General : info@spboucher.ai43// Professional : contact@spboucher.ai44// Direct : simon@spboucher.ai45// Research : research@spboucher.ai46// Development : dev@spboucher.ai47// Support : support@spboucher.ai48// Security/Admin : admin@spboucher.ai49// Notifications : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification : Public76// Distribution : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License : None specified (no license file in this repository)90// Maintainer : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI98import AVKit99import ImageIO100import UniformTypeIdentifiers101import SPWalletCore102103// MARK: - gating (pure)104105enum NFTMediaKind: Equatable, Sendable { case image, video, unplayableVideo, audio, activeContent, model, unknown }106107enum NFTMediaRefusal: Error, Equatable, Sendable {108 /** HTML, SVG or bytes that look like markup: never rendered. */109 case activeContent110 /** The bytes are not of the type the proxy announced. */111 case typeMismatch112 case notAnImage113 case notAPlayableVideo114 /** Dimensions beyond what is decoded (decompression bomb guard). */115 case tooManyPixels116 case undecodable117}118119enum NFTMediaGate {120 /** Raster types ImageIO decodes without executing anything. SVG is deliberately absent. */121 static let decodableImages: Set<String> = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]122 /** What AVPlayer plays among the proxy's video types (WebM is served by the proxy but not playable here). */123 static let playableVideos: Set<String> = ["video/mp4"]124 static let maxImageBytes = 16 * 1024 * 1024125 static let maxVideoBytes = 48 * 1024 * 1024126 static let maxPixels = 120_000_000127 static let maxSide = 20_000128129 /** What a media file is for this app, from the type the SERVER established (`mime`) or, before it was fetched, its `kind`. */130 static func kind(mime: String?, kind: String?) -> NFTMediaKind {131 let m = mime?.lowercased()132 if m == "text/html" || m == "image/svg+xml" || m == "application/xhtml+xml" || kind == "html" { return .activeContent }133 if let m {134 if decodableImages.contains(m) { return .image }135 if playableVideos.contains(m) { return .video }136 if m.hasPrefix("video/") { return .unplayableVideo }137 if m.hasPrefix("audio/") { return .audio }138 if m.hasPrefix("model/") { return .model }139 return .unknown140 }141 switch kind {142 case "image": return .image143 case "video": return .video144 case "audio": return .audio145 case "model": return .model146 default: return .unknown147 }148 }149 static func kind(of m: NFTMedia) -> NFTMediaKind { kind(mime: m.mime, kind: m.kind) }150151 /** The type the bytes themselves say they are, by signature. `nil` when unrecognised. Markup is reported as `text/html`. */152 static func sniff(_ d: Data) -> String? {153 let b = [UInt8](d.prefix(64))154 if looksLikeMarkup(d) { return "text/html" }155 if b.starts(with: [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) { return "image/png" }156 if b.starts(with: [0xFF, 0xD8, 0xFF]) { return "image/jpeg" }157 if b.starts(with: Array("GIF87a".utf8)) || b.starts(with: Array("GIF89a".utf8)) { return "image/gif" }158 if b.count >= 12, b.starts(with: Array("RIFF".utf8)), Array(b[8..<12]) == Array("WEBP".utf8) { return "image/webp" }159 if b.count >= 12, Array(b[4..<8]) == Array("ftyp".utf8) {160 let brands = String(decoding: b[8...], as: UTF8.self)161 if brands.contains("avif") || brands.contains("avis") { return "image/avif" }162 if brands.hasPrefix("M4A") { return "audio/mp4" }163 return "video/mp4"164 }165 return nil166 }167168 /** True when the first meaningful byte opens a tag (HTML, SVG, XML): such bytes are never handed to a decoder or a renderer. */169 static func looksLikeMarkup(_ d: Data) -> Bool {170 var bytes = d.prefix(512)[...]171 if bytes.starts(with: [0xEF, 0xBB, 0xBF]) { bytes = bytes.dropFirst(3) }172 for c in bytes {173 if c == 0x20 || c == 0x09 || c == 0x0A || c == 0x0D { continue }174 return c == 0x3C // "<"175 }176 return false177 }178179 /** nil when the served content may be decoded as an image. */180 static func refuseAsImage(_ c: NFTMediaContent) -> NFTMediaRefusal? {181 if c.isActiveContent || looksLikeMarkup(c.data) { return .activeContent }182 guard kind(mime: c.mime, kind: c.kind) == .image else { return .notAnImage }183 guard sniff(c.data) == c.mime else { return .typeMismatch }184 return nil185 }186187 /** nil when the served content may be written to a file and played. */188 static func refuseAsVideo(_ c: NFTMediaContent) -> NFTMediaRefusal? {189 if c.isActiveContent || looksLikeMarkup(c.data) { return .activeContent }190 guard kind(mime: c.mime, kind: c.kind) == .video else { return .notAPlayableVideo }191 guard sniff(c.data) == "video/mp4" else { return .typeMismatch }192 return nil193 }194}195196// MARK: - decoding (off the main thread)197198enum NFTImageCodec {199 struct Output: Sendable { let image: UIImage; let encoded: Data; let pixelWidth: Int; let pixelHeight: Int }200201 /**202 Decode with ImageIO at no more than `maxPixel` on the long side and re-encode (PNG when there is transparency, JPEG203 otherwise). What is cached and displayed is this re-encoding — never the remote bytes. Animated files give their first frame.204 */205 static func downsample(_ data: Data, maxPixel: Int) -> Result<Output, NFTMediaRefusal> {206 if NFTMediaGate.looksLikeMarkup(data) { return .failure(.activeContent) }207 guard let src = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),208 let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any],209 let w = props[kCGImagePropertyPixelWidth] as? Int, let h = props[kCGImagePropertyPixelHeight] as? Int, w > 0, h > 0 else { return .failure(.undecodable) }210 guard w <= NFTMediaGate.maxSide, h <= NFTMediaGate.maxSide, w * h <= NFTMediaGate.maxPixels else { return .failure(.tooManyPixels) }211 let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,212 kCGImageSourceShouldCacheImmediately: true, kCGImageSourceThumbnailMaxPixelSize: max(16, maxPixel)]213 guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, options as CFDictionary) else { return .failure(.undecodable) }214 let alpha: Bool = { switch cg.alphaInfo { case .none, .noneSkipFirst, .noneSkipLast: false; default: true } }()215 let out = NSMutableData()216 let type = (alpha ? UTType.png : UTType.jpeg).identifier as CFString217 guard let dest = CGImageDestinationCreateWithData(out, type, 1, nil) else { return .failure(.undecodable) }218 CGImageDestinationAddImage(dest, cg, [kCGImageDestinationLossyCompressionQuality: 0.86] as CFDictionary)219 guard CGImageDestinationFinalize(dest) else { return .failure(.undecodable) }220 return .success(Output(image: UIImage(cgImage: cg), encoded: out as Data, pixelWidth: cg.width, pixelHeight: cg.height))221 }222223 /** Decode bytes this app re-encoded itself (the offline cache). */224 static func decodeCached(_ data: Data) -> UIImage? {225 guard let src = CGImageSourceCreateWithData(data as CFData, nil),226 let cg = CGImageSourceCreateImageAtIndex(src, 0, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary) else { return nil }227 return UIImage(cgImage: cg)228 }229}230231// MARK: - store232233enum NFTMediaFailure: Error, Equatable, Sendable {234 /** No network and nothing cached for this file. */235 case notCachedOffline236 case refused(NFTMediaRefusal)237 /** The proxy's own refusal: its code and, when it names one, the reason. */238 case server(code: String, reason: String?)239 case tooLarge(bytes: Int?)240 case unreachable241}242243/** The media cache of the NFT screens: downsampled re-encodings in an `OfflineStore` blob cache (LRU, capped), plus a small memory cache. */244actor NFTMediaStore {245 enum Size: String, Sendable { case thumb, full246 var maxPixel: Int { self == .thumb ? 480 : 1600 }247 }248 typealias Fetch = @Sendable (_ id: String, _ maxBytes: Int) async throws -> NFTMediaContent249 typealias Info = @Sendable (_ id: String) async throws -> NFTMediaInfo250251 private let store: OfflineStore252 private let fetch: Fetch253 private let info: Info254 private let memory = NSCache<NSString, UIImage>()255 private var inFlight: [String: Task<Result<UIImage, NFTMediaFailure>, Never>] = [:]256 nonisolated let videoDirectory: URL257258 init(directory: URL, capBytes: Int = 96 * 1024 * 1024, fetch: @escaping Fetch, info: @escaping Info) {259 store = OfflineStore(directory: directory, blobCapBytes: capBytes)260 self.fetch = fetch; self.info = info261 memory.countLimit = 160262 videoDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("nft-video", isDirectory: true)263 // files left by a session that ended while a video was open264 try? FileManager.default.removeItem(at: videoDirectory)265 }266267 static func cacheKey(_ id: String, _ size: Size) -> String { "img.\(id).\(size.rawValue)" }268269 /** The image of one media id: memory, then the offline cache, then — only when `online` — the server's proxy. */270 func image(id: String, size: Size, online: Bool) async -> Result<UIImage, NFTMediaFailure> {271 let key = Self.cacheKey(id, size)272 if let hit = memory.object(forKey: key as NSString) { return .success(hit) }273 if let blob = await store.loadBlob(key), let img = await Task.detached(operation: { NFTImageCodec.decodeCached(blob) }).value {274 memory.setObject(img, forKey: key as NSString)275 return .success(img)276 }277 guard online else { return .failure(.notCachedOffline) }278 if let running = inFlight[key] { return await running.value }279 let fetch = self.fetch, store = self.store280 let task = Task<Result<UIImage, NFTMediaFailure>, Never>.detached(priority: .userInitiated) {281 let content: NFTMediaContent282 do { content = try await fetch(id, NFTMediaGate.maxImageBytes) } catch { return .failure(Self.failure(of: error)) }283 if let refusal = NFTMediaGate.refuseAsImage(content) { return .failure(.refused(refusal)) }284 switch NFTImageCodec.downsample(content.data, maxPixel: size.maxPixel) {285 case .failure(let r): return .failure(.refused(r))286 case .success(let out):287 try? await store.saveBlob(out.encoded, key: key)288 return .success(out.image)289 }290 }291 inFlight[key] = task292 let result = await task.value293 inFlight[key] = nil294 if case .success(let img) = result { memory.setObject(img, forKey: key as NSString) }295 return result296 }297298 static func failure(of error: Error) -> NFTMediaFailure {299 guard let e = error as? APIError else { return .unreachable }300 if e.isOffline { return .unreachable }301 if e.code == "media_too_large" || e.status == 413 { return .tooLarge(bytes: nil) }302 return .server(code: e.code, reason: e.data?["code"]?.stringValue)303 }304305 /** What the server established about a file, without its bytes. */306 func describe(id: String) async -> Result<NFTMediaInfo, NFTMediaFailure> {307 do { return .success(try await info(id)) } catch { return .failure(Self.failure(of: error)) }308 }309310 /**311 The proxied bytes of a playable video, written to a temporary file for AVPlayer. Nothing is kept: the caller removes the312 file when the player goes away (`removeVideo`), and the directory is emptied when the store is created.313 */314 func videoFile(id: String) async -> Result<URL, NFTMediaFailure> {315 let content: NFTMediaContent316 do { content = try await fetch(id, NFTMediaGate.maxVideoBytes) } catch { return .failure(Self.failure(of: error)) }317 if let refusal = NFTMediaGate.refuseAsVideo(content) { return .failure(.refused(refusal)) }318 do { return .success(try Self.writeVideo(content.data, in: videoDirectory)) } catch { return .failure(.refused(.undecodable)) }319 }320321 static func writeVideo(_ data: Data, in directory: URL) throws -> URL {322 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)323 let url = directory.appendingPathComponent(UUID().uuidString + ".mp4")324 try data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])325 return url326 }327 nonisolated static func removeVideo(_ url: URL) { try? FileManager.default.removeItem(at: url) }328329 func cachedBytes() async -> Int { await store.blobBytes() }330331 /** Erase every cached image (sign-out, or the owner's request). */332 func wipe() async {333 memory.removeAllObjects()334 await store.removeAll()335 try? FileManager.default.removeItem(at: videoDirectory)336 }337}338339// MARK: - words for what was not shown340341enum NFTMediaText {342 static func tile(for kind: NFTMediaKind) -> (icon: String, text: String)? {343 switch kind {344 case .image, .video: nil345 case .unplayableVideo: ("film", String(localized: "Vidéo dans un format non lisible sur cet appareil"))346 case .audio: ("waveform", String(localized: "Audio : non lu dans cette version"))347 case .activeContent: ("shield.lefthalf.filled", String(localized: "Contenu actif non affiché"))348 case .model: ("cube", String(localized: "Modèle 3D : non affiché dans cette version"))349 case .unknown: ("questionmark.square.dashed", String(localized: "Type de média non pris en charge"))350 }351 }352353 /** The tile of a media whose stored status says it cannot be served. nil when a fetch may be attempted. */354 static func tile(status: String, errorCode: String?) -> (icon: String, text: String)? {355 switch status {356 case "available", "not_fetched": return nil357 case "blocked": return ("hand.raised", String(localized: "Contenu bloqué pour ta sécurité") + (errorCode.map { " — " + NFTText.mediaBlock($0) } ?? ""))358 case "unreachable": return ("wifi.exclamationmark", String(localized: "Média injoignable"))359 case "unsupported_type": return ("questionmark.square.dashed", String(localized: "Type de fichier non pris en charge"))360 case "too_large": return ("arrow.up.left.and.arrow.down.right", String(localized: "Fichier trop volumineux"))361 default: return ("questionmark.square.dashed", String(localized: "Média : \(status)"))362 }363 }364365 static func tile(for f: NFTMediaFailure) -> (icon: String, text: String) {366 switch f {367 case .notCachedOffline: ("wifi.slash", String(localized: "Non disponible hors ligne"))368 case .unreachable: ("wifi.exclamationmark", String(localized: "Média injoignable"))369 case .tooLarge: ("arrow.up.left.and.arrow.down.right", String(localized: "Fichier trop volumineux"))370 case .refused(.activeContent): ("shield.lefthalf.filled", String(localized: "Contenu actif non affiché"))371 case .refused(.typeMismatch): ("hand.raised", String(localized: "Contenu refusé : le fichier n’est pas du type annoncé"))372 case .refused(.tooManyPixels): ("arrow.up.left.and.arrow.down.right", String(localized: "Image trop grande pour être décodée"))373 case .refused: ("photo.badge.exclamationmark", String(localized: "Le média n’a pas pu être affiché"))374 case .server(let code, let reason):375 switch code {376 case "media_blocked": ("hand.raised", String(localized: "Contenu bloqué pour ta sécurité") + (reason.map { " — " + NFTText.mediaBlock($0) } ?? ""))377 case "media_unreachable": ("wifi.exclamationmark", String(localized: "Média injoignable"))378 case "media_unexpected_type": ("hand.raised", String(localized: "Contenu refusé : type hors de la liste autorisée"))379 case "not_found": ("photo", String(localized: "Média introuvable sur le serveur"))380 default: ("photo.badge.exclamationmark", String(localized: "Média indisponible (\(code))"))381 }382 }383 }384385 static func bytes(_ n: Int) -> String { ByteCountFormatter.string(fromByteCount: Int64(n), countStyle: .file) }386}387388// MARK: - views389390/** A neutral tile: an icon and, unless `compact`, the sentence that says what is not shown. */391struct NFTMediaTile: View {392 let icon: String393 let text: String394 var compact = false395 var body: some View {396 ZStack {397 Theme.elev398 VStack(spacing: 6) {399 Image(systemName: icon).font(.system(size: compact ? 22 : 30)).foregroundStyle(Theme.mute)400 Text(text).font(compact ? .system(size: 11.5, weight: .medium) : .spFootnote).foregroundStyle(Theme.mute)401 .multilineTextAlignment(.center).lineLimit(compact ? 3 : 6).minimumScaleFactor(0.85)402 }.padding(compact ? 8 : 16)403 }404 .accessibilityElement(children: .ignore).accessibilityLabel(text)405 }406}407408/** One still image through the proxy and the offline cache; a tile for everything that is not a decodable raster image. */409struct NFTMediaImage: View {410 let ctx: NFTContext411 @Environment(AppModel.self) private var model412 let id: String?413 var mime: String?414 var kind: String?415 var status: String = "available"416 var errorCode: String?417 var size: NFTMediaStore.Size = .thumb418 var fill = true419 var compact = true420421 private enum Phase { case loading, image(UIImage), tile(String, String) }422 @State private var phase: Phase = .loading423424 var body: some View {425 ZStack {426 switch phase {427 case .loading: Theme.elev.overlay(ProgressView())428 case .image(let img):429 if fill { Color.clear.overlay(Image(uiImage: img).resizable().scaledToFill()).clipped() }430 else { Image(uiImage: img).resizable().scaledToFit() }431 case .tile(let icon, let text): NFTMediaTile(icon: icon, text: text, compact: compact)432 }433 }434 .task(id: "\(id ?? "")|\(model.canOperate)") { await load() }435 }436437 private func load() async {438 guard let id else { phase = .tile("photo", String(localized: "Aucun média")); return }439 let k = NFTMediaGate.kind(mime: mime, kind: kind)440 if k != .image {441 // a video is represented by its poster elsewhere; here it is only named442 let t = NFTMediaText.tile(for: k) ?? ("film", String(localized: "Vidéo"))443 phase = .tile(t.icon, t.text); return444 }445 if let t = NFTMediaText.tile(status: status, errorCode: errorCode) { phase = .tile(t.icon, t.text); return }446 if case .image = phase {} else { phase = .loading }447 switch await ctx.media.image(id: id, size: size, online: model.canOperate) {448 case .success(let img): phase = .image(img)449 case .failure(let f): let t = NFTMediaText.tile(for: f); phase = .tile(t.icon, t.text)450 }451 }452}453454/** A proxied video: the poster (when the metadata names an image), and playback only after an explicit tap, from a temporary file. */455struct NFTVideoView: View {456 let ctx: NFTContext457 @Environment(AppModel.self) private var model458 let media: NFTMedia459 let poster: NFTMedia?460461 private enum Phase { case idle, working, playing(URL, AVPlayer), note(String) }462 @State private var phase: Phase = .idle463464 var body: some View {465 ZStack {466 if case .playing(_, let player) = phase {467 VideoPlayer(player: player)468 } else {469 if let p = poster, NFTMediaGate.kind(of: p) == .image {470 NFTMediaImage(ctx: ctx, id: p.id, mime: p.mime, kind: p.kind, status: p.status, errorCode: p.errorCode, size: .full, fill: false, compact: false)471 } else { NFTMediaTile(icon: "film", text: String(localized: "Vidéo — aucune image fixe déclarée")) }472 overlay473 }474 }475 .onDisappear(perform: stop)476 }477478 @ViewBuilder private var overlay: some View {479 VStack {480 Spacer()481 switch phase {482 case .idle:483 Button { Task { await play() } } label: { Label(String(localized: "Lire la vidéo"), systemImage: "play.fill") }484 .buttonStyle(.borderedProminent).disabled(!model.canOperate).accessibilityIdentifier("nft.video.play")485 if !model.canOperate { Text(String(localized: "Lecture indisponible hors ligne")).font(.spFootnote).foregroundStyle(.white).padding(6).background(.black.opacity(0.55), in: Capsule()) }486 case .working: ProgressView().padding(10).background(.thinMaterial, in: Circle())487 case .note(let s):488 Text(s).font(.spFootnote).foregroundStyle(.white).multilineTextAlignment(.center)489 .padding(10).background(.black.opacity(0.6), in: RoundedRectangle(cornerRadius: 12)).accessibilityIdentifier("nft.video.note")490 case .playing: EmptyView()491 }492 }.padding(14)493 }494495 private func play() async {496 phase = .working497 // ask what the file IS before downloading it498 switch await ctx.media.describe(id: media.id) {499 case .failure(let f): phase = .note(NFTMediaText.tile(for: f).text); return500 case .success(let info):501 guard info.isAvailable else {502 phase = .note(NFTMediaText.tile(for: .server(code: info.status, reason: info.code)).text); return503 }504 guard NFTMediaGate.kind(mime: info.mime, kind: info.kind) == .video else {505 let t = NFTMediaText.tile(for: NFTMediaGate.kind(mime: info.mime, kind: info.kind))506 phase = .note((t?.text ?? String(localized: "Ce fichier n’est pas une vidéo lisible")) + String(localized: " — seule l’image fixe est affichée.")); return507 }508 if let n = info.bytes, n > NFTMediaGate.maxVideoBytes {509 phase = .note(String(localized: "Vidéo trop volumineuse pour être lue ici (\(NFTMediaText.bytes(n)), limite \(NFTMediaText.bytes(NFTMediaGate.maxVideoBytes))) : seule l’image fixe est affichée.")); return510 }511 }512 switch await ctx.media.videoFile(id: media.id) {513 case .failure(.tooLarge):514 phase = .note(String(localized: "Vidéo trop volumineuse pour être lue ici (limite \(NFTMediaText.bytes(NFTMediaGate.maxVideoBytes))) : seule l’image fixe est affichée."))515 case .failure(let f): phase = .note(NFTMediaText.tile(for: f).text)516 case .success(let url):517 let player = AVPlayer(url: url)518 phase = .playing(url, player)519 player.play()520 }521 }522523 private func stop() {524 if case .playing(let url, let player) = phase {525 player.pause(); player.replaceCurrentItem(with: nil)526 NFTMediaStore.removeVideo(url)527 phase = .idle528 }529 }530}531