Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Images/ImageLoader.swift10// Description : chargement des photos — miniature de l'API (v2), sinon11// l'originale réduite, cache mémoire et disque.12// Module : ImmoKa13// Repository : https://git.spboucher.ai/immo-ka-ios-v314// Project Website : https://www.immo-ka.com15// Created : 2026-11-2516// Last Modified : 2026-11-2517//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import ImageIO91import SwiftUI92import UIKit9394/// Largeurs de miniatures servies par `/api/img`.95enum ThumbWidth: Int, Sendable {96 case small = 480, medium = 800, large = 128097}9899actor ImageLoader {100 static let shared = ImageLoader()101102 private let session: URLSession103 private let memory = NSCache<NSString, UIImage>()104 private var inflight: [String: Task<UIImage?, Never>] = [:]105106 init() {107 let cfg = URLSessionConfiguration.default108 cfg.urlCache = URLCache(memoryCapacity: 24 << 20, diskCapacity: 400 << 20, directory: nil)109 cfg.requestCachePolicy = .returnCacheDataElseLoad110 cfg.timeoutIntervalForRequest = 15111 cfg.httpMaximumConnectionsPerHost = 6112 session = URLSession(configuration: cfg)113 memory.totalCostLimit = 96 << 20114 }115116 /// Image prête à afficher, ou nil si ni la miniature ni l'originale ne se chargent.117 func image(for source: String, width: ThumbWidth) async -> UIImage? {118 let key = "\(width.rawValue)|\(source)"119 if let hit = memory.object(forKey: key as NSString) { return hit }120 if let t = inflight[key] { return await t.value }121 let session = self.session122 let t = Task<UIImage?, Never> {123 let maxPixel = CGFloat(width.rawValue)124 // miniature servie par le service (v2 seulement) ; sinon, l'image d'origine réduite ici125 if await APIClient.shared.isV2(),126 let thumb = await APIClient.shared.url("api/img", query: ["u": source, "w": String(width.rawValue)]),127 let img = await ImageLoader.fetch(thumb, session: session, maxPixel: maxPixel) {128 return img129 }130 if let original = URL(string: source), let img = await ImageLoader.fetch(original, session: session, maxPixel: maxPixel) {131 return img132 }133 return nil134 }135 inflight[key] = t136 let img = await t.value137 inflight[key] = nil138 if let img {139 let cost = Int(img.size.width * img.size.height * img.scale * img.scale * 4)140 memory.setObject(img, forKey: key as NSString, cost: cost)141 }142 return img143 }144145 private static func fetch(_ url: URL, session: URLSession, maxPixel: CGFloat) async -> UIImage? {146 var req = URLRequest(url: url)147 req.setValue("image/webp,image/*;q=0.8", forHTTPHeaderField: "Accept")148 guard let (data, resp) = try? await session.data(for: req),149 (resp as? HTTPURLResponse).map({ (200..<300).contains($0.statusCode) }) ?? false,150 data.count > 64 else { return nil }151 // décodage réduit à la taille utile, hors du fil principal152 guard let src = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }153 let opts: [CFString: Any] = [154 kCGImageSourceCreateThumbnailFromImageAlways: true,155 kCGImageSourceCreateThumbnailWithTransform: true,156 kCGImageSourceShouldCacheImmediately: true,157 kCGImageSourceThumbnailMaxPixelSize: maxPixel,158 ]159 guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) else { return UIImage(data: data) }160 return UIImage(cgImage: cg)161 }162}163164/// Photo de propriété : fondu à l'arrivée, visuel de secours sobre, jamais d'icône cassée.165struct RemoteImage: View {166 let source: String?167 var width: ThumbWidth = .small168 var contentMode: ContentMode = .fill169 /// pictogramme de secours (type de propriété) quand il n'y a pas de photo170 var placeholder: String = "house"171172 @State private var image: UIImage?173 @State private var failed = false174175 var body: some View {176 // le fond fixe la taille : la photo le remplit en surimpression sans jamais agrandir la mise en page177 // (les étiquettes posées par-dessus restent ainsi dans le cadre visible)178 Rectangle().fill(Theme.surface2)179 .overlay {180 if let image {181 Image(uiImage: image)182 .resizable()183 .aspectRatio(contentMode: contentMode)184 .transition(.opacity)185 } else if failed || source == nil {186 Image(systemName: placeholder)187 .font(.system(size: 30, weight: .light))188 .foregroundStyle(Theme.ink3.opacity(0.6))189 }190 }191 .clipped()192 .task(id: source) {193 image = nil194 failed = false195 guard let source else { return }196 let img = await ImageLoader.shared.image(for: source, width: width)197 if Task.isCancelled { return }198 withAnimation(.easeOut(duration: 0.25)) {199 image = img200 failed = img == nil201 }202 }203 .accessibilityHidden(true)204 }205}206