SPB Git

Repository Public License

MediaLibrary.swift 13.1 KB 299 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Sources/ORIXImaging/Media/MediaLibrary.swift10// Description      : SwiftData index of the app-owned library (items, albums,11//                    favourites, edit recipes) over CaptureStorage. The files12//                    are the source of truth: `reconcile` re-indexes any media13//                    file the database does not know.14// Module           : ORIXImaging15// Repository       : https://git.spboucher.ai/orix-camera16// Project Website  : https://www.orixlab.dev17// Created          : 2026-11-2118// Last Modified    : 2026-11-2119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import SwiftData9596public enum MediaKind: String, Sendable, Codable, CaseIterable {97    case photo, raw, proRAW, video, timeLapse, slowMotion, longExposure, lightTrails, hdrFusion, noiseStack9899    public var isVideo: Bool { self == .video || self == .timeLapse || self == .slowMotion }100    public var isRAW: Bool { self == .raw || self == .proRAW }101    public var isComputational: Bool { [.longExposure, .lightTrails, .hdrFusion, .noiseStack].contains(self) }102}103104@Model105public final class MediaItem {106    @Attribute(.unique) public var id: UUID107    public var createdAt: Date108    public var kindRaw: String109    /// Primary file in the media directory.110    public var fileName: String111    /// Processed companion of a RAW capture (HEIC/JPEG), when one was saved.112    public var companionFileName: String?113    public var pixelWidth: Int114    public var pixelHeight: Int115    public var duration: Double116    public var byteSize: Int64117    public var isFavorite: Bool118    public var title: String119    /// Capture facts recorded at the shutter (lens, ISO, shutter, mode…), searchable text.120    public var captureSummary: String121    /// JSON of the EditRecipe; nil when the item has no edits.122    public var recipeData: Data?123    /// Visual difference hash (bit pattern stored as Int64).124    public var visualHash: Int64?125    /// True when the frames came from the simulator's synthetic scene instead of a camera.126    public var isSynthetic: Bool127    @Relationship(inverse: \MediaAlbum.items) public var albums: [MediaAlbum] = []128129    public init(id: UUID = UUID(), createdAt: Date = Date(), kind: MediaKind, fileName: String, companionFileName: String? = nil,130                pixelWidth: Int = 0, pixelHeight: Int = 0, duration: Double = 0, byteSize: Int64 = 0, title: String = "",131                captureSummary: String = "", isSynthetic: Bool = false) {132        self.id = id; self.createdAt = createdAt; self.kindRaw = kind.rawValue; self.fileName = fileName133        self.companionFileName = companionFileName; self.pixelWidth = pixelWidth; self.pixelHeight = pixelHeight134        self.duration = duration; self.byteSize = byteSize; self.isFavorite = false; self.title = title135        self.captureSummary = captureSummary; self.isSynthetic = isSynthetic136    }137138    public var kind: MediaKind { MediaKind(rawValue: kindRaw) ?? .photo }139140    public var recipe: EditRecipe? {141        get { recipeData.flatMap { try? JSONDecoder().decode(EditRecipe.self, from: $0) } }142        set {143            if let newValue, !newValue.isIdentity { recipeData = try? JSONEncoder().encode(newValue) } else { recipeData = nil }144        }145    }146    public var hasEdits: Bool { recipeData != nil }147}148149@Model150public final class MediaAlbum {151    @Attribute(.unique) public var id: UUID152    public var name: String153    public var createdAt: Date154    public var items: [MediaItem] = []155    public init(name: String) { id = UUID(); self.name = name; createdAt = Date() }156}157158public enum MediaFilter: String, Sendable, CaseIterable {159    case all, photos, videos, raw, favorites, edited, computational160}161162public enum MediaSort: String, Sendable, CaseIterable {163    case newest, oldest, largest, name164}165166@MainActor167public final class MediaLibrary {168    public let container: ModelContainer169    public let context: ModelContext170    public let storage: CaptureStorage171172    public init(storage: CaptureStorage, inMemory: Bool = false) throws {173        self.storage = storage174        let schema = Schema([MediaItem.self, MediaAlbum.self])175        let configuration = inMemory ? ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)176                                     : ModelConfiguration(schema: schema, url: storage.root.appendingPathComponent("Library.store"))177        container = try ModelContainer(for: schema, configurations: [configuration])178        context = ModelContext(container)179        context.autosaveEnabled = false180    }181182    public func save() { try? context.save() }183184    @discardableResult185    public func add(_ item: MediaItem) -> MediaItem {186        if item.byteSize == 0 { item.byteSize = storage.size(of: item.fileName) + (item.companionFileName.map(storage.size(of:)) ?? 0) }187        context.insert(item)188        save()189        return item190    }191192    public func allItems() -> [MediaItem] {193        (try? context.fetch(FetchDescriptor<MediaItem>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)]))) ?? []194    }195196    public func item(id: UUID) -> MediaItem? {197        (try? context.fetch(FetchDescriptor<MediaItem>(predicate: #Predicate { $0.id == id })))?.first198    }199200    /// Filtered, searched and sorted items. Search matches title, file name, kind and the capture summary.201    public func items(filter: MediaFilter = .all, search: String = "", sort: MediaSort = .newest, album: MediaAlbum? = nil) -> [MediaItem] {202        var items = album.map { $0.items } ?? allItems()203        switch filter {204        case .all: break205        case .photos: items = items.filter { !$0.kind.isVideo }206        case .videos: items = items.filter { $0.kind.isVideo }207        case .raw: items = items.filter { $0.kind.isRAW }208        case .favorites: items = items.filter(\.isFavorite)209        case .edited: items = items.filter(\.hasEdits)210        case .computational: items = items.filter { $0.kind.isComputational }211        }212        let terms = search.lowercased().split(separator: " ").map(String.init)213        if !terms.isEmpty {214            items = items.filter { item in215                let haystack = "\(item.title) \(item.fileName) \(item.kindRaw) \(item.captureSummary)".lowercased()216                return terms.allSatisfy { haystack.contains($0) }217            }218        }219        switch sort {220        case .newest: items.sort { $0.createdAt > $1.createdAt }221        case .oldest: items.sort { $0.createdAt < $1.createdAt }222        case .largest: items.sort { $0.byteSize > $1.byteSize }223        case .name: items.sort { $0.fileName.localizedStandardCompare($1.fileName) == .orderedAscending }224        }225        return items226    }227228    public func toggleFavorite(_ item: MediaItem) { item.isFavorite.toggle(); save() }229230    public func setRecipe(_ recipe: EditRecipe?, for item: MediaItem) { item.recipe = recipe; save() }231232    /// Removes the item and its files. The caller confirms with the user first.233    public func delete(_ item: MediaItem) {234        storage.delete(item.fileName)235        if let companion = item.companionFileName { storage.delete(companion) }236        context.delete(item)237        save()238    }239240    // MARK: Albums241242    public func albums() -> [MediaAlbum] {243        (try? context.fetch(FetchDescriptor<MediaAlbum>(sortBy: [SortDescriptor(\.name)]))) ?? []244    }245246    @discardableResult247    public func createAlbum(named name: String) -> MediaAlbum {248        let album = MediaAlbum(name: name.trimmingCharacters(in: .whitespacesAndNewlines))249        context.insert(album); save()250        return album251    }252253    public func add(_ item: MediaItem, to album: MediaAlbum) {254        guard !album.items.contains(where: { $0.id == item.id }) else { return }255        album.items.append(item); save()256    }257258    public func remove(_ item: MediaItem, from album: MediaAlbum) {259        album.items.removeAll { $0.id == item.id }; save()260    }261262    /// Deletes the album only; its items stay in the library.263    public func delete(_ album: MediaAlbum) { context.delete(album); save() }264265    // MARK: Integrity266267    /// Indexes media files that have no row (crash between write and index). Returns the recovered items.268    @discardableResult269    public func reconcile() -> [MediaItem] {270        let items = allItems()271        var known = Set(items.map(\.fileName))272        for item in items { if let companion = item.companionFileName { known.insert(companion) } }273        var recovered: [MediaItem] = []274        for name in storage.orphans(known: known) {275            let ext = (name as NSString).pathExtension.lowercased()276            let kind: MediaKind = ["mov", "mp4", "m4v"].contains(ext) ? .video : (ext == "dng" ? .raw : .photo)277            let created = (try? storage.url(for: name).resourceValues(forKeys: [.creationDateKey]))?.creationDate ?? Date()278            var width = 0, height = 0279            if !kind.isVideo, let meta = MetadataInspector.readImage(url: storage.url(for: name)) { width = meta.pixelWidth ?? 0; height = meta.pixelHeight ?? 0 }280            let item = MediaItem(createdAt: created, kind: kind, fileName: name, pixelWidth: width, pixelHeight: height, captureSummary: "recovered")281            recovered.append(add(item))282        }283        return recovered284    }285286    /// Rows whose primary file has disappeared (reported to the user, never silently dropped).287    public func itemsMissingFiles() -> [MediaItem] { allItems().filter { !storage.exists($0.fileName) } }288289    /// Groups of visually near-identical items (difference hash within `threshold` bits).290    public func duplicateGroups(threshold: Int = 4) -> [[MediaItem]] {291        let items = allItems().filter { $0.visualHash != nil }292        let byID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })293        let groups = DuplicateDetector.groups(items.map { (id: $0.id, hash: UInt64(bitPattern: $0.visualHash!)) }, threshold: threshold)294        return groups.map { $0.compactMap { byID[$0] }.sorted { $0.createdAt < $1.createdAt } }295    }296297    public var totalBytes: Int64 { allItems().reduce(0) { $0 + $1.byteSize } }298}299
Files main
Menu

Theme