import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif public struct ImmichSettings: Codable, Hashable, Sendable { /// e.g. https://photos.example.com (without /api) public var serverURL: String /// Album pattern with variables, e.g. "{event}" or "{isodate} {event}" (created if missing). Empty = no album. public var albumName: String /// Used when the pattern resolves to nothing (image without event), e.g. "{isodate} {city}". Empty = no album. public var albumFallback: String = "{isodate} {city}" public var variant: UploadVariant public var enabled: Bool public init(serverURL: String = "", albumName: String = "", variant: UploadVariant = .jpeg, enabled: Bool = false) { self.serverURL = serverURL; self.albumName = albumName; self.variant = variant; self.enabled = enabled } public static let keychainAccount = "immich-api-key" enum CodingKeys: String, CodingKey { case serverURL, albumName, albumFallback, variant, enabled } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) serverURL = (try? c.decode(String.self, forKey: .serverURL)) ?? "" albumName = (try? c.decode(String.self, forKey: .albumName)) ?? "" albumFallback = (try? c.decode(String.self, forKey: .albumFallback)) ?? "{isodate} {city}" variant = (try? c.decode(UploadVariant.self, forKey: .variant)) ?? .jpeg enabled = (try? c.decode(Bool.self, forKey: .enabled)) ?? false } } public enum ImmichError: LocalizedError { case badURL, http(Int, String), decoding public var errorDescription: String? { switch self { case .badURL: return "Ungültige Immich-Server-URL." case .http(let code, let body): return "Immich antwortet mit HTTP \(code): \(body.prefix(300))" case .decoding: return "Unerwartete Antwort vom Immich-Server." } } } /// Minimal Immich REST client (API key auth). Uses /api/assets (Immich ≥ 1.118). public final class ImmichClient: @unchecked Sendable { let base: URL let apiKey: String let session: URLSession let deviceId = "Lichtkasten-Mac" private var albumCache: [String: String] = [:] private let lock = NSLock() public init(settings: ImmichSettings, apiKey: String) throws { var s = settings.serverURL.trimmingCharacters(in: .whitespacesAndNewlines) while s.hasSuffix("/") { s.removeLast() } if s.hasSuffix("/api") { s.removeLast(4) } guard let u = URL(string: s + "/api"), u.scheme?.hasPrefix("http") == true else { throw ImmichError.badURL } base = u self.apiKey = apiKey let cfg = URLSessionConfiguration.default cfg.timeoutIntervalForRequest = 120 cfg.timeoutIntervalForResource = 3600 session = URLSession(configuration: cfg) } private func request(_ path: String, method: String = "GET", json: Any? = nil) throws -> URLRequest { var r = URLRequest(url: base.appendingPathComponent(path)) r.httpMethod = method r.setValue(apiKey, forHTTPHeaderField: "x-api-key") r.setValue("application/json", forHTTPHeaderField: "Accept") if let json { r.httpBody = try JSONSerialization.data(withJSONObject: json) r.setValue("application/json", forHTTPHeaderField: "Content-Type") } return r } private func send(_ r: URLRequest) async throws -> Any? { let (data, resp) = try await session.data(for: r) let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 guard (200..<300).contains(code) else { throw ImmichError.http(code, String(decoding: data, as: UTF8.self)) } return data.isEmpty ? nil : try? JSONSerialization.jsonObject(with: data) } /// Returns the logged-in user's name (connection test). public func testConnection() async throws -> String { let obj = try await send(try request("users/me")) as? [String: Any] return (obj?["name"] as? String) ?? (obj?["email"] as? String) ?? "OK" } public struct UploadResult: Sendable { public let assetId: String; public let duplicate: Bool } /// Uploads one file as multipart/form-data (streamed from a temp file, RAWs can be large). /// Newer Immich (3.x) dropped deviceAssetId/deviceId; older servers require them → automatic retry. public func upload(file: URL, captureDate: Date?) async throws -> UploadResult { do { return try await upload(file: file, captureDate: captureDate, legacyFields: false) } catch ImmichError.http(400, let body) where body.contains("deviceAssetId") || body.contains("deviceId") { return try await upload(file: file, captureDate: captureDate, legacyFields: true) } } private func upload(file: URL, captureDate: Date?, legacyFields: Bool) async throws -> UploadResult { let attrs = try FileManager.default.attributesOfItem(atPath: file.path) let modified = (attrs[.modificationDate] as? Date) ?? Date() let size = (attrs[.size] as? NSNumber)?.int64Value ?? 0 let created = captureDate ?? modified let iso = ISO8601DateFormatter() iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds] let boundary = "----Lichtkasten\(UUID().uuidString)" let body = FileManager.default.temporaryDirectory.appendingPathComponent("immich-\(UUID().uuidString).multipart") FileManager.default.createFile(atPath: body.path, contents: nil) let h = try FileHandle(forWritingTo: body) defer { try? FileManager.default.removeItem(at: body) } func field(_ name: String, _ value: String) { h.write(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".utf8)) } if legacyFields { field("deviceAssetId", "\(file.lastPathComponent)-\(size)") field("deviceId", deviceId) } field("fileCreatedAt", iso.string(from: created)) field("fileModifiedAt", iso.string(from: modified)) field("filename", file.lastPathComponent) h.write(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"assetData\"; filename=\"\(file.lastPathComponent)\"\r\nContent-Type: application/octet-stream\r\n\r\n".utf8)) let src = try FileHandle(forReadingFrom: file) while true { let chunk = src.readData(ofLength: 4 << 20) if chunk.isEmpty { break } h.write(chunk) } try src.close() h.write(Data("\r\n--\(boundary)--\r\n".utf8)) try h.close() var r = try request("assets", method: "POST") r.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let (data, resp) = try await session.upload(for: r, fromFile: body) let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 guard (200..<300).contains(code) else { throw ImmichError.http(code, String(decoding: data, as: UTF8.self)) } guard let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any], let id = obj["id"] as? String else { throw ImmichError.decoding } return UploadResult(assetId: id, duplicate: (obj["status"] as? String) == "duplicate") } /// Finds or creates an album and returns its id. public func albumId(named name: String) async throws -> String { lock.lock(); let cached = albumCache[name]; lock.unlock() if let cached { return cached } if let list = try await send(try request("albums")) as? [[String: Any]], let existing = list.first(where: { ($0["albumName"] as? String) == name }), let id = existing["id"] as? String { lock.lock(); albumCache[name] = id; lock.unlock() return id } guard let created = try await send(try request("albums", method: "POST", json: ["albumName": name])) as? [String: Any], let id = created["id"] as? String else { throw ImmichError.decoding } lock.lock(); albumCache[name] = id; lock.unlock() return id } public func add(assetIds: [String], toAlbum albumId: String) async throws { _ = try await send(try request("albums/\(albumId)/assets", method: "PUT", json: ["ids": assetIds])) } }