Glimmer / app · glimmertoday.ai / native / Glimmer / GalleryCatalog.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import ImageIO |
| 4 | import Observation |
| 5 | |
| 6 | struct GalleryPlate: Codable, Equatable { |
| 7 | let id: String |
| 8 | let description: String |
| 9 | let aspectRatio: Double |
| 10 | let wholeSubject: Bool? |
| 11 | let video: String? |
| 12 | let poster: String? |
| 13 | var ambience: String? = nil |
| 14 | var ambienceURL: URL? { GalleryCatalog.asset(ambience, extensions: ["m4a"]) } |
| 15 | |
| 16 | var localPoster: URL? { AppResources.url(id, extension: "jpg", folder: "LibraryContent/Gallery") } |
| 17 | var filmURL: URL? { GalleryCatalog.asset(video, extensions: ["mp4"]) } |
| 18 | var posterURL: URL? { GalleryCatalog.asset(poster, extensions: ["jpg", "jpeg"]) } |
| 19 | } |
| 20 | |
| 21 | struct GalleryCatalog: Codable, Equatable { |
| 22 | let schemaVersion: Int |
| 23 | let plates: [GalleryPlate] |
| 24 | |
| 25 | // Only this discovery address is fixed. Each catalog controls its own media paths. |
| 26 | static let endpoint = URL(string: "https://media.protomota.com/glimmer/gallery/gallery.json")! |
| 27 | static let bundled = AppResources.url("Gallery", extension: "json", folder: "LibraryContent/Gallery") |
| 28 | .flatMap { try? load($0) } ?? Self(schemaVersion: 1, plates: []) |
| 29 | |
| 30 | static func load(_ url: URL) throws -> Self { |
| 31 | try JSONDecoder().decode(Self.self, from: Data(contentsOf: url)) |
| 32 | } |
| 33 | |
| 34 | static func asset(_ path: String?, extensions: Set<String>) -> URL? { |
| 35 | guard let path, !path.isEmpty, path.utf8.count <= 500, |
| 36 | path.range(of: #"^[A-Za-z0-9_-][A-Za-z0-9._-]*(/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$"#, options: .regularExpression) == path.startIndex..<path.endIndex, |
| 37 | extensions.contains((path as NSString).pathExtension.lowercased()) |
| 38 | else { return nil } |
| 39 | return endpoint.deletingLastPathComponent().appending(path: path) |
| 40 | } |
| 41 | |
| 42 | func validate(bundledIDs: Set<String>) throws { |
| 43 | guard schemaVersion == 1, !plates.isEmpty, Set(plates.map(\.id)).count == plates.count else { |
| 44 | throw CocoaError(.fileReadCorruptFile) |
| 45 | } |
| 46 | for plate in plates { |
| 47 | guard plate.id.utf8.count <= 96, |
| 48 | plate.id.range(of: #"^[A-Za-z0-9_-]+$"#, options: .regularExpression) == plate.id.startIndex..<plate.id.endIndex, |
| 49 | !plate.description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, |
| 50 | plate.description.utf8.count <= 2048, (0.1...20).contains(plate.aspectRatio), |
| 51 | plate.video == nil || plate.filmURL != nil, |
| 52 | plate.poster == nil || plate.posterURL != nil, |
| 53 | plate.ambience == nil || (plate.filmURL != nil && plate.ambienceURL != nil), |
| 54 | plate.poster != nil || bundledIDs.contains(plate.id) |
| 55 | else { throw CocoaError(.fileReadCorruptFile) } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | func pick(slot: Int, date: Date, aspect: Double, featured: Bool = false) -> GalleryPlate? { |
| 60 | let films = featured ? plates.filter { $0.video != nil } : [] |
| 61 | let collection = films.isEmpty ? plates : films |
| 62 | let fitting = collection.filter { |
| 63 | $0.wholeSubject != true || abs(log($0.aspectRatio / max(0.01, aspect))) < 0.20 |
| 64 | } |
| 65 | // A themed remote collection might consist entirely of portrait subjects. |
| 66 | // Preserve the complete image with aspect fit in that case, even in a wide slot. |
| 67 | let candidates = fitting.isEmpty ? collection : fitting |
| 68 | guard !candidates.isEmpty else { return nil } |
| 69 | let day = Calendar.current.ordinality(of: .day, in: .era, for: date) ?? 0 |
| 70 | return candidates[(day + slot) % candidates.count] |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | private final class GalleryTransfer: NSObject, URLSessionDownloadDelegate { |
| 75 | let limit: Int64 |
| 76 | init(limit: Int) { self.limit = Int64(limit) } |
| 77 | |
| 78 | func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, |
| 79 | newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { |
| 80 | // R2 publishes the canonical endpoints directly. |
| 81 | completionHandler(nil) |
| 82 | } |
| 83 | func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {} |
| 84 | func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, |
| 85 | totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { |
| 86 | if totalBytesWritten > limit || totalBytesExpectedToWrite > limit { downloadTask.cancel() } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | enum GalleryHTTP { |
| 91 | private static let session: URLSession = { |
| 92 | let config = URLSessionConfiguration.ephemeral |
| 93 | config.httpCookieStorage = nil |
| 94 | config.urlCredentialStorage = nil |
| 95 | config.timeoutIntervalForRequest = 15 |
| 96 | config.timeoutIntervalForResource = 30 |
| 97 | return URLSession(configuration: config) |
| 98 | }() |
| 99 | |
| 100 | static func fetch(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) { |
| 101 | let (file, response) = try await session.download(for: request, delegate: GalleryTransfer(limit: limit)) |
| 102 | defer { try? FileManager.default.removeItem(at: file) } |
| 103 | guard let http = response as? HTTPURLResponse, http.url == request.url, |
| 104 | [200,304].contains(http.statusCode) else { throw URLError(.badServerResponse) } |
| 105 | if http.statusCode == 304 { return (Data(), http) } |
| 106 | let size = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize |
| 107 | guard let size, size > 0, size <= limit else { throw URLError(.dataLengthExceedsMaximum) } |
| 108 | return (try Data(contentsOf: file), http) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | @Observable @MainActor |
| 113 | final class GalleryLibrary { |
| 114 | struct Snapshot: Codable { |
| 115 | let catalog: GalleryCatalog |
| 116 | let etag: String? |
| 117 | let checked: Date |
| 118 | } |
| 119 | |
| 120 | static let shared = GalleryLibrary() |
| 121 | private(set) var catalog: GalleryCatalog |
| 122 | @ObservationIgnored private let location: URL |
| 123 | @ObservationIgnored private let bundledIDs: Set<String> |
| 124 | @ObservationIgnored private var snapshot: Snapshot? |
| 125 | @ObservationIgnored private var lastAttempt: Date? |
| 126 | @ObservationIgnored private var refreshing = false |
| 127 | |
| 128 | init(bundled: GalleryCatalog = .bundled, directory: URL = URL.applicationSupportDirectory.appending(path: "GlimmerMedia")) { |
| 129 | location = directory.appending(path: "catalog-v1.json") |
| 130 | bundledIDs = Set(bundled.plates.map(\.id)) |
| 131 | catalog = bundled |
| 132 | if let bytes = try? Data(contentsOf: location), let saved = try? JSONDecoder().decode(Snapshot.self, from: bytes), |
| 133 | (try? saved.catalog.validate(bundledIDs: bundledIDs)) != nil { |
| 134 | snapshot = saved |
| 135 | catalog = saved.catalog |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | var secondsUntilRefresh: TimeInterval { |
| 140 | if let checked = snapshot?.checked, checked.timeIntervalSinceNow > -6 * 3600 { |
| 141 | return max(120, 6 * 3600 + checked.timeIntervalSinceNow) |
| 142 | } |
| 143 | return 15 * 60 |
| 144 | } |
| 145 | |
| 146 | func refreshIfNeeded(now: Date = .now, |
| 147 | fetch: (URLRequest, Int) async throws -> (Data, HTTPURLResponse) = GalleryHTTP.fetch) async { |
| 148 | guard !refreshing, now.timeIntervalSince(snapshot?.checked ?? .distantPast) >= 6 * 3600, |
| 149 | now.timeIntervalSince(lastAttempt ?? .distantPast) >= 120 else { return } |
| 150 | refreshing = true |
| 151 | lastAttempt = now |
| 152 | defer { refreshing = false } |
| 153 | var request = URLRequest(url: GalleryCatalog.endpoint, cachePolicy: .reloadIgnoringLocalCacheData) |
| 154 | request.setValue("application/json", forHTTPHeaderField: "Accept") |
| 155 | request.setValue(snapshot?.etag, forHTTPHeaderField: "If-None-Match") |
| 156 | do { |
| 157 | let (data, response) = try await fetch(request, 2 * 1024 * 1024) |
| 158 | try Task.checkCancellation() |
| 159 | let next: Snapshot |
| 160 | if response.statusCode == 304, let previous = snapshot { |
| 161 | next = Snapshot(catalog: previous.catalog, etag: previous.etag, checked: now) |
| 162 | } else { |
| 163 | guard response.statusCode == 200, data.count <= 2 * 1024 * 1024 else { return } |
| 164 | let decoded = try JSONDecoder().decode(GalleryCatalog.self, from: data) |
| 165 | try decoded.validate(bundledIDs: bundledIDs) |
| 166 | next = Snapshot(catalog: decoded, etag: response.value(forHTTPHeaderField: "ETag"), checked: now) |
| 167 | } |
| 168 | try FileManager.default.createDirectory(at: location.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 169 | try JSONEncoder().encode(next).write(to: location, options: .atomic) |
| 170 | snapshot = next |
| 171 | if catalog != next.catalog { catalog = next.catalog } |
| 172 | } catch { |
| 173 | // A corrupt index or a temporary outage never replaces the last accepted snapshot. |
| 174 | if Task.isCancelled { lastAttempt = nil } |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | actor GalleryPosters { |
| 180 | static let shared = GalleryPosters() |
| 181 | private let folder: URL |
| 182 | private let fetch: @Sendable (URLRequest, Int) async throws -> (Data, HTTPURLResponse) |
| 183 | private let memory = NSCache<NSURL, CGImage>() |
| 184 | private var inFlight: [URL: Task<CGImage?, Never>] = [:] |
| 185 | |
| 186 | init(directory: URL = URL.cachesDirectory.appending(path: "GlimmerGalleryPosters"), |
| 187 | fetch: @escaping @Sendable (URLRequest, Int) async throws -> (Data, HTTPURLResponse) = { try await GalleryHTTP.fetch($0, limit: $1) }) { |
| 188 | folder = directory |
| 189 | self.fetch = fetch |
| 190 | memory.totalCostLimit = 24 * 1024 * 1024 |
| 191 | } |
| 192 | |
| 193 | private func decode(_ data: Data) -> CGImage? { |
| 194 | guard let source = CGImageSourceCreateWithData(data as CFData, nil), |
| 195 | CGImageSourceGetType(source) as String? == "public.jpeg" else { return nil } |
| 196 | let options = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: 1800, |
| 197 | kCGImageSourceShouldCacheImmediately: true, kCGImageSourceCreateThumbnailWithTransform: true] as CFDictionary |
| 198 | return CGImageSourceCreateThumbnailAtIndex(source, 0, options) |
| 199 | } |
| 200 | |
| 201 | func image(for url: URL) async -> CGImage? { |
| 202 | if let hit = memory.object(forKey: url as NSURL) { return hit } |
| 203 | if let task = inFlight[url] { return await task.value } |
| 204 | let task = Task { await self.retrieve(url) } |
| 205 | inFlight[url] = task |
| 206 | let image = await task.value |
| 207 | inFlight[url] = nil |
| 208 | if let image { memory.setObject(image, forKey: url as NSURL, cost: image.height * image.bytesPerRow) } |
| 209 | return image |
| 210 | } |
| 211 | |
| 212 | private func retrieve(_ url: URL) async -> CGImage? { |
| 213 | let name = SHA256.hash(data: Data(url.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined() |
| 214 | let file = folder.appending(path: name) |
| 215 | if let data = try? Data(contentsOf: file), let image = decode(data) { return image } |
| 216 | guard let (data, response) = try? await fetch(URLRequest(url: url), 4 * 1024 * 1024), |
| 217 | response.statusCode == 200, let image = decode(data) else { return nil } |
| 218 | do { |
| 219 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 220 | try data.write(to: file, options: .atomic) |
| 221 | try trimDiskCache() |
| 222 | } catch { /* The image is still available for this session. */ } |
| 223 | return image |
| 224 | } |
| 225 | |
| 226 | private func trimDiskCache() throws { |
| 227 | let keys: Set<URLResourceKey> = [.fileSizeKey,.contentModificationDateKey] |
| 228 | let files = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: Array(keys)) |
| 229 | let entries = try files.map { ($0, try $0.resourceValues(forKeys: keys)) } |
| 230 | var bytes = entries.reduce(0) { $0 + ($1.1.fileSize ?? 0) } |
| 231 | for (url, values) in entries.sorted(by: { ($0.1.contentModificationDate ?? .distantPast) < ($1.1.contentModificationDate ?? .distantPast) }) { |
| 232 | guard bytes > 64 * 1024 * 1024 else { break } |
| 233 | try FileManager.default.removeItem(at: url) |
| 234 | bytes -= values.fileSize ?? 0 |
| 235 | } |
| 236 | } |
| 237 | } |