|
| 1 | +// |
| 2 | +// DownloadCountService.swift |
| 3 | +// TablePro |
| 4 | +// |
| 5 | + |
| 6 | +import Foundation |
| 7 | +import os |
| 8 | + |
| 9 | +@MainActor @Observable |
| 10 | +final class DownloadCountService { |
| 11 | + static let shared = DownloadCountService() |
| 12 | + |
| 13 | + private var counts: [String: Int] = [:] |
| 14 | + private static let logger = Logger(subsystem: "com.TablePro", category: "DownloadCountService") |
| 15 | + |
| 16 | + private static let cacheKey = "downloadCountsCache" |
| 17 | + private static let cacheDateKey = "downloadCountsCacheDate" |
| 18 | + private static let cacheTTL: TimeInterval = 3_600 // 1 hour |
| 19 | + |
| 20 | + // swiftlint:disable:next force_unwrapping |
| 21 | + private static let releasesURL = URL(string: "https://api.github.com/repos/datlechin/TablePro/releases?per_page=100")! |
| 22 | + |
| 23 | + private let session: URLSession |
| 24 | + |
| 25 | + private init() { |
| 26 | + let config = URLSessionConfiguration.default |
| 27 | + config.timeoutIntervalForRequest = 15 |
| 28 | + config.timeoutIntervalForResource = 30 |
| 29 | + self.session = URLSession(configuration: config) |
| 30 | + |
| 31 | + loadCache() |
| 32 | + } |
| 33 | + |
| 34 | + // MARK: - Public |
| 35 | + |
| 36 | + func downloadCount(for pluginId: String) -> Int? { |
| 37 | + counts[pluginId] |
| 38 | + } |
| 39 | + |
| 40 | + func fetchCounts(for manifest: RegistryManifest?) async { |
| 41 | + guard let manifest else { return } |
| 42 | + |
| 43 | + if isCacheValid() { |
| 44 | + Self.logger.debug("Using cached download counts") |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + do { |
| 49 | + let releases = try await fetchReleases() |
| 50 | + let pluginReleases = releases.filter { $0.tagName.hasPrefix("plugin-") } |
| 51 | + let urlToPluginId = buildURLMap(from: manifest) |
| 52 | + |
| 53 | + var totals: [String: Int] = [:] |
| 54 | + for release in pluginReleases { |
| 55 | + for asset in release.assets { |
| 56 | + if let pluginId = urlToPluginId[asset.browserDownloadUrl] { |
| 57 | + totals[pluginId, default: 0] += asset.downloadCount |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + counts = totals |
| 63 | + saveCache(totals) |
| 64 | + Self.logger.info("Fetched download counts for \(totals.count) plugin(s)") |
| 65 | + } catch { |
| 66 | + Self.logger.error("Failed to fetch download counts: \(error.localizedDescription)") |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + // MARK: - GitHub API |
| 71 | + |
| 72 | + private func fetchReleases() async throws -> [GitHubRelease] { |
| 73 | + var request = URLRequest(url: Self.releasesURL) |
| 74 | + request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") |
| 75 | + |
| 76 | + let (data, response) = try await session.data(for: request) |
| 77 | + |
| 78 | + guard let httpResponse = response as? HTTPURLResponse, |
| 79 | + (200...299).contains(httpResponse.statusCode) else { |
| 80 | + throw URLError(.badServerResponse) |
| 81 | + } |
| 82 | + |
| 83 | + let decoder = JSONDecoder() |
| 84 | + decoder.keyDecodingStrategy = .convertFromSnakeCase |
| 85 | + return try decoder.decode([GitHubRelease].self, from: data) |
| 86 | + } |
| 87 | + |
| 88 | + // MARK: - URL Mapping |
| 89 | + |
| 90 | + private func buildURLMap(from manifest: RegistryManifest) -> [String: String] { |
| 91 | + var map: [String: String] = [:] |
| 92 | + for plugin in manifest.plugins { |
| 93 | + if let binaries = plugin.binaries { |
| 94 | + for binary in binaries { |
| 95 | + map[binary.downloadURL] = plugin.id |
| 96 | + } |
| 97 | + } |
| 98 | + if let url = plugin.downloadURL { |
| 99 | + map[url] = plugin.id |
| 100 | + } |
| 101 | + } |
| 102 | + return map |
| 103 | + } |
| 104 | + |
| 105 | + // MARK: - Cache |
| 106 | + |
| 107 | + private func isCacheValid() -> Bool { |
| 108 | + guard let cacheDate = UserDefaults.standard.object(forKey: Self.cacheDateKey) as? Date else { |
| 109 | + return false |
| 110 | + } |
| 111 | + return Date().timeIntervalSince(cacheDate) < Self.cacheTTL |
| 112 | + } |
| 113 | + |
| 114 | + private func loadCache() { |
| 115 | + guard isCacheValid(), |
| 116 | + let data = UserDefaults.standard.data(forKey: Self.cacheKey), |
| 117 | + let cached = try? JSONDecoder().decode([String: Int].self, from: data) else { |
| 118 | + counts = [:] |
| 119 | + return |
| 120 | + } |
| 121 | + counts = cached |
| 122 | + } |
| 123 | + |
| 124 | + private func saveCache(_ totals: [String: Int]) { |
| 125 | + if let data = try? JSONEncoder().encode(totals) { |
| 126 | + UserDefaults.standard.set(data, forKey: Self.cacheKey) |
| 127 | + UserDefaults.standard.set(Date(), forKey: Self.cacheDateKey) |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +// MARK: - GitHub API Models |
| 133 | + |
| 134 | +private struct GitHubRelease: Decodable { |
| 135 | + let tagName: String |
| 136 | + let assets: [GitHubAsset] |
| 137 | +} |
| 138 | + |
| 139 | +private struct GitHubAsset: Decodable { |
| 140 | + let name: String |
| 141 | + let downloadCount: Int |
| 142 | + let browserDownloadUrl: String |
| 143 | +} |
0 commit comments