Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Core/Images/ImageLoader.swift10// Description : chargement des photos — miniature WebP de l'API, repli sur11// l'originale, cache mémoire et disque.12// Module : LouKa13// Repository : https://git.spboucher.ai/lou-ka-ios-v314// Project Website : https://www.lou-ka.com15// Created : 2026-11-2516// Last Modified : 2026-11-2817//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 if let thumb = await APIClient.shared.url("api/img", query: ["u": source, "w": String(width.rawValue)]),125 let img = await ImageLoader.fetch(thumb, session: session, maxPixel: maxPixel) {126 return img127 }128 if let original = URL(string: source), let img = await ImageLoader.fetch(original, session: session, maxPixel: maxPixel) {129 return img130 }131 return nil132 }133 inflight[key] = t134 let img = await t.value135 inflight[key] = nil136 if let img {137 let cost = Int(img.size.width * img.size.height * img.scale * img.scale * 4)138 memory.setObject(img, forKey: key as NSString, cost: cost)139 }140 return img141 }142143 private static func fetch(_ url: URL, session: URLSession, maxPixel: CGFloat) async -> UIImage? {144 var req = URLRequest(url: url)145 req.setValue("image/webp,image/*;q=0.8", forHTTPHeaderField: "Accept")146 guard let (data, resp) = try? await session.data(for: req),147 (resp as? HTTPURLResponse).map({ (200..<300).contains($0.statusCode) }) ?? false,148 data.count > 64 else { return nil }149 // décodage réduit à la taille utile, hors du fil principal150 guard let src = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }151 let opts: [CFString: Any] = [152 kCGImageSourceCreateThumbnailFromImageAlways: true,153 kCGImageSourceCreateThumbnailWithTransform: true,154 kCGImageSourceShouldCacheImmediately: true,155 kCGImageSourceThumbnailMaxPixelSize: maxPixel,156 ]157 guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) else { return UIImage(data: data) }158 return UIImage(cgImage: cg)159 }160}161162/// Photo d'annonce : fondu à l'arrivée, visuel de secours sobre, jamais d'icône cassée.163struct RemoteImage: View {164 let source: String?165 var width: ThumbWidth = .small166 var contentMode: ContentMode = .fill167168 @State private var image: UIImage?169 @State private var failed = false170171 var body: some View {172 // le fond fixe la taille : la photo le remplit en surimpression sans jamais agrandir la mise en page173 // (les étiquettes posées par-dessus restent ainsi dans le cadre visible)174 Rectangle().fill(Theme.surface2)175 .overlay {176 if let image {177 Image(uiImage: image)178 .resizable()179 .aspectRatio(contentMode: contentMode)180 .transition(.opacity)181 } else if failed || source == nil {182 Image(systemName: "building.2")183 .font(.system(size: 30, weight: .light))184 .foregroundStyle(Theme.ink3.opacity(0.6))185 }186 }187 .clipped()188 .task(id: source) {189 image = nil190 failed = false191 guard let source else { return }192 let img = await ImageLoader.shared.image(for: source, width: width)193 if Task.isCancelled { return }194 withAnimation(.easeOut(duration: 0.25)) {195 image = img196 failed = img == nil197 }198 }199 .accessibilityHidden(true)200 }201}202