From 7f65e87bbda4f05cdd5e58d48f6ad8c798360f18 Mon Sep 17 00:00:00 2001 From: Cassio Rossi Date: Wed, 18 Nov 2026 19:06:07 +0000 Subject: [PATCH 1/2] fix(#340): add widget image downscaler, refresh schedule and posts cache Co-Authored-By: Claude Opus 5.5 --- .../Services/WidgetImageDownscaler.swift | 47 ++++++++ .../Services/WidgetPostsCache.swift | 26 +++++ .../Services/WidgetRefreshSchedule.swift | 12 ++ .../WidgetImageDownscalerTests.swift | 109 ++++++++++++++++++ .../WidgetPostsCacheTests.swift | 61 ++++++++++ .../WidgetRefreshScheduleTests.swift | 24 ++++ 6 files changed, 279 insertions(+) create mode 100644 MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetImageDownscaler.swift create mode 100644 MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetPostsCache.swift create mode 100644 MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetRefreshSchedule.swift create mode 100644 MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetImageDownscalerTests.swift create mode 100644 MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetPostsCacheTests.swift create mode 100644 MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetRefreshScheduleTests.swift diff --git a/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetImageDownscaler.swift b/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetImageDownscaler.swift new file mode 100644 index 00000000..e03dd266 --- /dev/null +++ b/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetImageDownscaler.swift @@ -0,0 +1,47 @@ +import Foundation +import ImageIO +import UniformTypeIdentifiers + +/// Shrinks widget thumbnails so timeline entries stay well inside WidgetKit's memory limits. +public enum WidgetImageDownscaler { + public static let compressionQuality = 0.8 + + /// Downscales image data to a compact JPEG whose shorter side is at least `targetPixelSize`. + /// + /// The aspect ratio is kept and images already at or below the target are re-encoded, never upscaled. + /// - Returns: JPEG data, or `nil` when the input can't be decoded. + public static func downscale(_ data: Data, targetPixelSize: Int) -> Data? { + guard let source = CGImageSourceCreateWithData(data as CFData, nil), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int, + width > 0, height > 0 else { + return nil + } + + let shorterSide = min(width, height) + let longerSide = max(width, height) + let maxPixelSize = shorterSide <= targetPixelSize + ? longerSide + : Int((Double(targetPixelSize) * Double(longerSide) / Double(shorterSide)).rounded(.up)) + + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: maxPixelSize + ] + guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { + return nil + } + + let output = NSMutableData() + guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { + return nil + } + let destinationOptions: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: compressionQuality] + CGImageDestinationAddImage(destination, image, destinationOptions as CFDictionary) + guard CGImageDestinationFinalize(destination) else { return nil } + return output as Data + } +} diff --git a/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetPostsCache.swift b/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetPostsCache.swift new file mode 100644 index 00000000..85eeabb1 --- /dev/null +++ b/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetPostsCache.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Keeps the last successfully fetched widget posts on disk so a failed refresh doesn't blank the widget. +public struct WidgetPostsCache: Sendable { + public let fileURL: URL + + public init(fileURL: URL) { + self.fileURL = fileURL + } + + /// Returns the cached posts, or an empty array when the file is missing or can't be decoded. + public func load() -> [WidgetData] { + guard let data = try? Data(contentsOf: fileURL), + let posts = try? JSONDecoder().decode([WidgetData].self, from: data) else { + return [] + } + return posts + } + + /// Overwrites the cache with `posts`. An empty array is ignored so the last good posts survive. + public func save(_ posts: [WidgetData]) throws { + guard !posts.isEmpty else { return } + let data = try JSONEncoder().encode(posts) + try data.write(to: fileURL, options: .atomic) + } +} diff --git a/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetRefreshSchedule.swift b/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetRefreshSchedule.swift new file mode 100644 index 00000000..d947e728 --- /dev/null +++ b/MacMagazine/Features/FeedLibrary/Sources/FeedLibrary/Services/WidgetRefreshSchedule.swift @@ -0,0 +1,12 @@ +import Foundation + +/// When the widget timeline asks WidgetKit to reload next. +public enum WidgetRefreshSchedule { + public static let successInterval: TimeInterval = 30 * 60 + public static let failureInterval: TimeInterval = 15 * 60 + + /// Returns the next refresh date: `successInterval` after a fetch with posts, `failureInterval` otherwise. + public static func nextRefresh(after now: Date, succeeded: Bool) -> Date { + now.addingTimeInterval(succeeded ? successInterval : failureInterval) + } +} diff --git a/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetImageDownscalerTests.swift b/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetImageDownscalerTests.swift new file mode 100644 index 00000000..02ed860f --- /dev/null +++ b/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetImageDownscalerTests.swift @@ -0,0 +1,109 @@ +import CoreGraphics +@testable import FeedLibrary +import Foundation +import ImageIO +import Testing +import UniformTypeIdentifiers + +@Suite("WidgetImageDownscaler Tests") +struct WidgetImageDownscalerTests { + + // MARK: - Downscaling Tests + + @Test("Large landscape image is downscaled to fill the target") + func downscalesLargeLandscapeImage() throws { + // Given + let input = try makePNG(width: 2000, height: 1000) + + // When + let output = try #require(WidgetImageDownscaler.downscale(input, targetPixelSize: 500)) + + // Then + let size = try pixelSize(of: output) + let shorterSide = min(size.width, size.height) + #expect(shorterSide >= 500) + #expect(shorterSide < 1000) + let ratio = Double(size.width) / Double(size.height) + #expect(abs(ratio - 2.0) / 2.0 < 0.01) + #expect(try imageType(of: output) == UTType.jpeg.identifier) + } + + @Test("Small image is re-encoded but not upscaled") + func doesNotUpscaleSmallImage() throws { + // Given + let input = try makePNG(width: 100, height: 50) + + // When + let output = try #require(WidgetImageDownscaler.downscale(input, targetPixelSize: 500)) + + // Then + let size = try pixelSize(of: output) + #expect(size.width == 100) + #expect(size.height == 50) + #expect(try imageType(of: output) == UTType.jpeg.identifier) + } + + @Test("Undecodable data returns nil") + func undecodableDataReturnsNil() { + // Given + let input = Data("not an image".utf8) + + // When + let output = WidgetImageDownscaler.downscale(input, targetPixelSize: 500) + + // Then + #expect(output == nil) + } + + @Test("Empty data returns nil") + func emptyDataReturnsNil() { + #expect(WidgetImageDownscaler.downscale(Data(), targetPixelSize: 500) == nil) + } +} + +// MARK: - Helpers + +private extension WidgetImageDownscalerTests { + struct FixtureError: Error {} + + func makePNG(width: Int, height: Int) throws -> Data { + guard let context = CGContext( + data: nil, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: 0, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + ) else { throw FixtureError() } + context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + guard let image = context.makeImage() else { throw FixtureError() } + + let output = NSMutableData() + guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else { + throw FixtureError() + } + CGImageDestinationAddImage(destination, image, nil) + guard CGImageDestinationFinalize(destination) else { throw FixtureError() } + return output as Data + } + + func pixelSize(of data: Data) throws -> (width: Int, height: Int) { + guard let source = CGImageSourceCreateWithData(data as CFData, nil), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int else { + throw FixtureError() + } + return (width, height) + } + + func imageType(of data: Data) throws -> String { + guard let source = CGImageSourceCreateWithData(data as CFData, nil), + let type = CGImageSourceGetType(source) else { + throw FixtureError() + } + return type as String + } +} diff --git a/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetPostsCacheTests.swift b/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetPostsCacheTests.swift new file mode 100644 index 00000000..6a7ff66f --- /dev/null +++ b/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetPostsCacheTests.swift @@ -0,0 +1,61 @@ +@testable import FeedLibrary +import Foundation +import Testing + +@Suite("WidgetPostsCache Tests") +struct WidgetPostsCacheTests { + private let directory: URL + private let cache: WidgetPostsCache + + init() throws { + directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + cache = WidgetPostsCache(fileURL: directory.appending(path: "widget-posts-systemSmall.json")) + } + + private let posts = [ + WidgetData( + postId: "1", + title: "First", + thumbnail: "https://example.com/1.jpg", + pubDate: Date(timeIntervalSince1970: 1_700_000_000), + link: "https://example.com/1", + imageData: Data([0xFF, 0xD8, 0xFF]) + ), + WidgetData( + postId: "2", + title: "Second", + thumbnail: "https://example.com/2.jpg", + pubDate: Date(timeIntervalSince1970: 1_700_000_100), + link: "https://example.com/2" + ) + ] + + @Test("Saved posts load back unchanged") + func roundTrip() throws { + try cache.save(posts) + + #expect(cache.load() == posts) + } + + @Test("Missing file loads as empty") + func missingFileLoadsEmpty() { + #expect(cache.load().isEmpty) + } + + @Test("Corrupt file loads as empty") + func corruptFileLoadsEmpty() throws { + try Data("not json".utf8).write(to: cache.fileURL) + + #expect(cache.load().isEmpty) + } + + @Test("Saving an empty array keeps the existing posts") + func savingEmptyKeepsExistingPosts() throws { + try cache.save(posts) + + try cache.save([]) + + #expect(cache.load() == posts) + } +} diff --git a/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetRefreshScheduleTests.swift b/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetRefreshScheduleTests.swift new file mode 100644 index 00000000..b301fd39 --- /dev/null +++ b/MacMagazine/Features/FeedLibrary/Tests/FeedLibraryTests/WidgetRefreshScheduleTests.swift @@ -0,0 +1,24 @@ +@testable import FeedLibrary +import Foundation +import Testing + +@Suite("WidgetRefreshSchedule Tests") +struct WidgetRefreshScheduleTests { + private let now = Date(timeIntervalSince1970: 1_700_000_000) + + @Test("Successful fetch refreshes after 30 minutes") + func successRefreshesAfterThirtyMinutes() { + let next = WidgetRefreshSchedule.nextRefresh(after: now, succeeded: true) + + #expect(next == now.addingTimeInterval(30 * 60)) + #expect(WidgetRefreshSchedule.successInterval == 30 * 60) + } + + @Test("Failed or empty fetch refreshes after 15 minutes") + func failureRefreshesAfterFifteenMinutes() { + let next = WidgetRefreshSchedule.nextRefresh(after: now, succeeded: false) + + #expect(next == now.addingTimeInterval(15 * 60)) + #expect(WidgetRefreshSchedule.failureInterval == 15 * 60) + } +} From aab87418f184ac03e9d23fa5f990ceab1c564e82 Mon Sep 17 00:00:00 2001 From: Cassio Rossi Date: Wed, 18 Nov 2026 19:06:07 +0000 Subject: [PATCH 2/2] fix(#340): bound widget network work, downscale thumbnails and cache last good posts Co-Authored-By: Claude Opus 5.5 --- .claude/rules/data-layer.md | 2 +- .../MacMagazineTimelineProvider.swift | 122 +++++++++++++----- 2 files changed, 94 insertions(+), 30 deletions(-) diff --git a/.claude/rules/data-layer.md b/.claude/rules/data-layer.md index db4a03c3..75c227f6 100644 --- a/.claude/rules/data-layer.md +++ b/.claude/rules/data-layer.md @@ -88,7 +88,7 @@ Global audio playback state injected via `@Environment`. Available everywhere. M ## Multi-platform - **watchOS (`WatchApp/`)** — Minimal feed reader: `FeedMainViewModel` fetches news via `FeedLibrary`, simple list with detail views. -- **iOS Widget (`Widget/`)** — Timeline provider fetches latest posts, renders with `WidgetView`. Live Activities via `MacMagazineWidgetLiveActivity`. +- **iOS Widget (`Widget/`)** — Timeline provider fetches latest posts (15 s deadline), downloads only the thumbnails the family shows in parallel (10 s timeout each) and downscales them with `WidgetImageDownscaler`, renders with `WidgetView`. Refreshes every 30 min (15 min after a failed or empty fetch, via `WidgetRefreshSchedule`) and falls back to the last good posts cached per family (`WidgetPostsCache`, Caches directory). Live Activities via `MacMagazineWidgetLiveActivity`. - **watchOS Widget (`WatchWidget/`)** — Separate widget extension. - **Widget data model** — `WidgetData` (postId, title, thumbnail, pubDate, link). - macOS and visionOS via `#if os()` where needed. Primary targets: iOS and watchOS. diff --git a/MacMagazine/Widget/Timeline/MacMagazineTimelineProvider.swift b/MacMagazine/Widget/Timeline/MacMagazineTimelineProvider.swift index adfe3444..1394e91e 100644 --- a/MacMagazine/Widget/Timeline/MacMagazineTimelineProvider.swift +++ b/MacMagazine/Widget/Timeline/MacMagazineTimelineProvider.swift @@ -14,48 +14,112 @@ struct MacMagazineTimelineProvider: TimelineProvider { } func getSnapshot(in context: Context, completion: @escaping (WidgetEntry) -> Void) { + let family = context.family + let displaySize = context.displaySize Task { - let posts = await getWidgetContent() - completion(WidgetEntry(date: Date(), posts: posts)) + let content = await getWidgetContent(family: family, displaySize: displaySize) + completion(WidgetEntry(date: Date(), posts: content.posts)) } } func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + let family = context.family + let displaySize = context.displaySize Task { - let posts = await getWidgetContent() - let timeline = Timeline(entries: [WidgetEntry(date: Date(), posts: posts)], policy: .atEnd) + let content = await getWidgetContent(family: family, displaySize: displaySize) + let now = Date() + let nextUpdate = WidgetRefreshSchedule.nextRefresh(after: now, succeeded: content.succeeded) + let timeline = Timeline(entries: [WidgetEntry(date: now, posts: content.posts)], policy: .after(nextUpdate)) completion(timeline) } } } private extension MacMagazineTimelineProvider { - func getWidgetContent() async -> [WidgetData] { - do { - var posts = [WidgetData]() - - let fetchedData = try await viewModel.getWidgetData() - for data in fetchedData { - var imageData: Data? - do { - if let thumbnailUrl = URL(string: data.thumbnail) { - let request = URLRequest(url: thumbnailUrl) - let (image, _) = try await URLSession.shared.data(for: request) - imageData = image - } - } catch {} - posts.append(WidgetData( - postId: data.postId, - title: data.title, - thumbnail: data.thumbnail, - pubDate: data.pubDate, - link: data.link, - imageData: imageData - )) + static let feedDeadline: Duration = .seconds(15) + static let imageTimeout: TimeInterval = 10 + static let pixelScale: CGFloat = 3 + + func getWidgetContent(family: WidgetFamily, displaySize: CGSize) async -> (posts: [WidgetData], succeeded: Bool) { + let cache = WidgetPostsCache(fileURL: URL.cachesDirectory.appending(path: "widget-posts-\(family.description).json")) + + let fetchedData = await fetchWithDeadline() + guard !fetchedData.isEmpty else { + return (cache.load(), false) + } + + let posts = await withImages( + fetchedData, + count: imageCount(for: family), + targetPixelSize: targetPixelSize(for: family, displaySize: displaySize) + ) + try? cache.save(posts) + return (posts, true) + } + + func fetchWithDeadline() async -> [WidgetData] { + await withTaskGroup(of: [WidgetData]?.self) { group in + group.addTask { @MainActor in + try? await viewModel.getWidgetData() + } + group.addTask { + try? await Task.sleep(for: Self.feedDeadline) + return nil + } + let first = await group.next() + group.cancelAll() + return first.flatMap { $0 } ?? [] + } + } + + func withImages(_ posts: [WidgetData], count: Int, targetPixelSize: Int) async -> [WidgetData] { + let images = await withTaskGroup(of: (Int, Data?).self) { group in + for (index, post) in posts.prefix(count).enumerated() { + let thumbnail = post.thumbnail + group.addTask { + (index, await Self.downscaledImage(from: thumbnail, targetPixelSize: targetPixelSize)) + } } - return posts - } catch { - return [] + var images = [Int: Data]() + for await (index, data) in group { + images[index] = data + } + return images + } + + return posts.enumerated().map { index, data in + WidgetData( + postId: data.postId, + title: data.title, + thumbnail: data.thumbnail, + pubDate: data.pubDate, + link: data.link, + imageData: images[index] + ) + } + } + + nonisolated static func downscaledImage(from thumbnail: String, targetPixelSize: Int) async -> Data? { + guard let thumbnailUrl = URL(string: thumbnail) else { return nil } + let request = URLRequest(url: thumbnailUrl, timeoutInterval: imageTimeout) + guard let (image, _) = try? await URLSession.shared.data(for: request) else { return nil } + return WidgetImageDownscaler.downscale(image, targetPixelSize: targetPixelSize) + } + + func imageCount(for family: WidgetFamily) -> Int { + switch family { + case .systemSmall, .accessoryRectangular, .accessoryInline: 1 + case .systemMedium: 2 + case .systemLarge: 3 + default: 1 + } + } + + func targetPixelSize(for family: WidgetFamily, displaySize: CGSize) -> Int { + switch family { + case .systemMedium: Int(40 * Self.pixelScale) + case .systemLarge: Int(60 * Self.pixelScale) + default: Int(max(displaySize.width, displaySize.height) * Self.pixelScale) } } }