PreviewCache.swift (1437B)
1 // 2 // PreviewCache.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-01-02. 6 // 7 8 import Foundation 9 import LinkPresentation 10 11 class CachedMetadata { 12 let meta: LPLinkMetadata 13 var intrinsic_height: CGFloat? 14 15 init(meta: LPLinkMetadata) { 16 self.meta = meta 17 self.intrinsic_height = nil 18 } 19 } 20 21 enum Preview { 22 case value(CachedMetadata) 23 case failed 24 25 init(meta: LPLinkMetadata?) { 26 if let meta { 27 self = .value(CachedMetadata(meta: meta)) 28 } else { 29 self = .failed 30 } 31 } 32 33 static func fetch_metadata(for url: URL) async -> LPLinkMetadata? { 34 // iOS 15 is crashing for some reason 35 guard #available(iOS 16, *) else { 36 return nil 37 } 38 39 let provider = LPMetadataProvider() 40 41 do { 42 return try await provider.startFetchingMetadata(for: url) 43 } catch { 44 return nil 45 } 46 } 47 48 } 49 50 enum PreviewState { 51 case not_loaded 52 case loading 53 case loaded(Preview) 54 55 var should_preload: Bool { 56 switch self { 57 case .loaded: 58 return false 59 case .loading: 60 return false 61 case .not_loaded: 62 return true 63 } 64 } 65 } 66 67 class PreviewCache { 68 private var previews: [NoteId: Preview] = [:] 69 70 func lookup(_ evid: NoteId) -> Preview? { 71 return previews[evid] 72 } 73 }