import Foundation import ImageIO import UniformTypeIdentifiers enum InstagramError: LocalizedError { case noToken case api(String) case unreadable var errorDescription: String? { switch self { case .noToken: return "Instagram non è ancora collegato." case .api(let message): return message case .unreadable: return "Risposta di Instagram non leggibile." } } } /// Le due chiamate all'API di Instagram (Instagram API with Instagram Login). enum Instagram { private static let base = "https://graph.instagram.com" private static let version = "v26.0" struct Profile: Decodable { let username: String let followersCount: Int let pictureURL: String? enum CodingKeys: String, CodingKey { case username case followersCount = "followers_count" case pictureURL = "profile_picture_url" } } private struct Refreshed: Decodable { let accessToken: String enum CodingKeys: String, CodingKey { case accessToken = "access_token" } } private struct APIError: Decodable { struct Body: Decodable { let message: String } let error: Body } static func profile(token: String) async throws -> Profile { try await get("\(base)/\(version)/me", query: [ "fields": "username,followers_count,profile_picture_url", "access_token": token, ]) } /// Rinnova il token per altri 60 giorni. Funziona solo se ha almeno 24 ore ed è ancora valido. static func refresh(token: String) async throws -> String { let result: Refreshed = try await get("\(base)/refresh_access_token", query: [ "grant_type": "ig_refresh_token", "access_token": token, ]) return result.accessToken } private static func get(_ url: String, query: [String: String]) async throws -> T { var components = URLComponents(string: url)! components.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) } var request = URLRequest(url: components.url!) request.timeoutInterval = 20 let (data, _) = try await URLSession.shared.data(for: request) if let value = try? JSONDecoder().decode(T.self, from: data) { return value } if let failure = try? JSONDecoder().decode(APIError.self, from: data) { throw InstagramError.api(failure.error.message) } throw InstagramError.unreadable } } /// Legge i follower, li salva e rinnova il token quando serve. Usato da app e widget. enum Updater { @discardableResult static func update() async -> Snapshot { let store = FollowerStore.shared guard var token = store.token else { return Snapshot.current() } // Il token dura 60 giorni: lo rinnoviamo dopo 20, così c'è margine anche se il Mac resta spento a lungo. if let issued = store.tokenDate, Date().timeIntervalSince(issued) > 20 * 86_400, let fresh = try? await Instagram.refresh(token: token) { token = fresh store.token = fresh store.tokenDate = Date() } do { let profile = try await Instagram.profile(token: token) await save(profile) } catch { store.lastError = error.localizedDescription } return Snapshot.current() } /// Salva quello che è arrivato da Instagram, foto profilo compresa. static func save(_ profile: Instagram.Profile) async { let store = FollowerStore.shared store.add(profile.followersCount) store.username = profile.username store.lastUpdate = Date() store.lastError = nil await refreshAvatar(from: profile.pictureURL) } /// Scarica la foto profilo al massimo una volta al giorno, rimpicciolita per il widget. private static func refreshAvatar(from address: String?) async { let store = FollowerStore.shared guard let address, let url = URL(string: address), let file = store.avatarFile else { return } if let saved = store.avatarDate, Date().timeIntervalSince(saved) < 86_400, FileManager.default.fileExists(atPath: file.path) { return } guard let (data, _) = try? await URLSession.shared.data(from: url), let source = CGImageSourceCreateWithData(data as CFData, nil), let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: 96, ] as CFDictionary), let destination = CGImageDestinationCreateWithURL(file as CFURL, UTType.png.identifier as CFString, 1, nil) else { return } CGImageDestinationAddImage(destination, image, nil) if CGImageDestinationFinalize(destination) { store.avatarDate = Date() } } }