Files
lichtkasten/Sources/LichtkastenCore/Upload/ImmichClient.swift
T
Lichtkasten DevandClaude Opus 5.5 50d03fc4d7 Immich: Upload ohne Album möglich
Schalter „In Album einsortieren / Ohne Album“ im Upload-Fenster (⌘U, Ziel Immich) und in den
Einstellungen. Ohne Album landen die Bilder nur in der Bibliothek; die Album-Muster bleiben gespeichert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
2026-11-11 11:27:45 +00:00

194 lines
9.3 KiB
Swift

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
/// Off = photos are uploaded into the library only, without any album (patterns stay saved).
public var useAlbum: Bool = true
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, useAlbum }
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
useAlbum = (try? c.decode(Bool.self, forKey: .useAlbum)) ?? true
}
}
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?, progress: (@Sendable (Int64) -> Void)? = nil) async throws -> UploadResult {
do {
return try await upload(file: file, captureDate: captureDate, legacyFields: false, progress: progress)
} catch ImmichError.http(400, let body) where body.contains("deviceAssetId") || body.contains("deviceId") {
return try await upload(file: file, captureDate: captureDate, legacyFields: true, progress: progress)
}
}
/// Reports bytes sent for the live upload rate.
final class ProgressDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
let onSent: (@Sendable (Int64) -> Void)?
init(_ f: (@Sendable (Int64) -> Void)?) { onSent = f }
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64,
totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
onSent?(totalBytesSent)
}
}
private func upload(file: URL, captureDate: Date?, legacyFields: Bool,
progress: (@Sendable (Int64) -> Void)?) 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, delegate: ProgressDelegate(progress))
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 {
if let cached = cachedAlbum(name) { 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 {
cacheAlbum(name, id)
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 }
cacheAlbum(name, id)
return id
}
// NSLock must not be used directly in async functions → small synchronous helpers.
private func cachedAlbum(_ name: String) -> String? {
lock.lock(); defer { lock.unlock() }
return albumCache[name]
}
private func cacheAlbum(_ name: String, _ id: String) {
lock.lock(); defer { lock.unlock() }
albumCache[name] = id
}
public func add(assetIds: [String], toAlbum albumId: String) async throws {
_ = try await send(try request("albums/\(albumId)/assets", method: "PUT", json: ["ids": assetIds]))
}
}