248 lines
9.7 KiB
Swift
248 lines
9.7 KiB
Swift
import Foundation
|
|
|
|
// MARK: - Bundled offline snapshot
|
|
|
|
private struct SnapshotFile: Decodable {
|
|
struct Day: Decodable {
|
|
let date: String
|
|
let title: String
|
|
let rank: String
|
|
let color: String
|
|
let bem: String
|
|
let l1: String
|
|
let ap: String
|
|
let l2: String
|
|
let ev: String
|
|
let obligation: Bool
|
|
}
|
|
|
|
let version: Int
|
|
let source: String
|
|
let diocese: String
|
|
let years: [Int]
|
|
let days: [Day]
|
|
}
|
|
|
|
public enum LiturgicalSnapshot {
|
|
public static let sourceLabel = "Daten von www.eucharistiefeier.de"
|
|
|
|
public static func loadBundled() -> [LiturgicalDay] {
|
|
guard let url = bundledURL(),
|
|
let data = try? Data(contentsOf: url),
|
|
let file = try? JSONDecoder().decode(SnapshotFile.self, from: data)
|
|
else {
|
|
return []
|
|
}
|
|
return file.days.compactMap { day in
|
|
guard let date = DayMath.date(fromKey: day.date) else { return nil }
|
|
let rank = LiturgicalRank(rawValue: day.rank) ?? .weekday
|
|
return LiturgicalDay(
|
|
date: date,
|
|
title: day.title,
|
|
rank: rank,
|
|
color: LiturgicalColor(apiValue: day.color),
|
|
remark: day.bem,
|
|
readings: Readings(first: day.l1, psalm: day.ap, second: day.l2, gospel: day.ev),
|
|
isObligation: day.obligation,
|
|
source: sourceLabel
|
|
)
|
|
}
|
|
}
|
|
|
|
public static func bundledYears() -> [Int] {
|
|
guard let url = bundledURL(),
|
|
let data = try? Data(contentsOf: url),
|
|
let file = try? JSONDecoder().decode(SnapshotFile.self, from: data)
|
|
else { return [] }
|
|
return file.years
|
|
}
|
|
|
|
private static func bundledURL() -> URL? {
|
|
let candidates: [URL?] = [
|
|
Bundle.module.url(forResource: "liturgical-snapshot", withExtension: "json"),
|
|
Bundle.main.url(forResource: "liturgical-snapshot", withExtension: "json"),
|
|
Bundle.main.resourceURL?.appendingPathComponent("liturgical-snapshot.json")
|
|
]
|
|
return candidates.compactMap { $0 }.first { FileManager.default.fileExists(atPath: $0.path) }
|
|
}
|
|
}
|
|
|
|
// MARK: - Live API
|
|
|
|
public enum LiturgicalAPIError: LocalizedError {
|
|
case invalidURL
|
|
case badStatus(Int)
|
|
case invalidPayload(String)
|
|
case emptyYear(Int)
|
|
|
|
public var errorDescription: String? {
|
|
switch self {
|
|
case .invalidURL:
|
|
return "Die Kalender-URL konnte nicht erstellt werden."
|
|
case .badStatus(let code):
|
|
return "Der liturgische Kalender antwortete mit HTTP \(code)."
|
|
case .invalidPayload(let detail):
|
|
return "Die Kalenderdaten konnten nicht gelesen werden (\(detail))."
|
|
case .emptyYear(let year):
|
|
return "Für \(year) wurden keine liturgischen Daten geliefert."
|
|
}
|
|
}
|
|
}
|
|
|
|
public struct LiturgicalCalendarAPI: Sendable {
|
|
public var diocese: String
|
|
public var endpoint: URL
|
|
|
|
public init(diocese: String = "koeln", endpoint: URL = URL(string: "https://www.eucharistiefeier.de/lk/api.php")!) {
|
|
self.diocese = diocese
|
|
self.endpoint = endpoint
|
|
}
|
|
|
|
public func fetch(year: Int) async throws -> [LiturgicalDay] {
|
|
guard var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false) else {
|
|
throw LiturgicalAPIError.invalidURL
|
|
}
|
|
components.queryItems = [
|
|
URLQueryItem(name: "kal", value: diocese),
|
|
URLQueryItem(name: "jahr", value: String(year)),
|
|
URLQueryItem(name: "format", value: "json"),
|
|
URLQueryItem(name: "info", value: "wdtrflu"),
|
|
URLQueryItem(name: "dup", value: "e"),
|
|
URLQueryItem(name: "bahn", value: "j")
|
|
]
|
|
guard let url = components.url else { throw LiturgicalAPIError.invalidURL }
|
|
|
|
var request = URLRequest(url: url)
|
|
request.timeoutInterval = 45
|
|
request.setValue("LektorenPlan/0.1 (macOS; Pfarrei Bad Godesberg)", forHTTPHeaderField: "User-Agent")
|
|
request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: request)
|
|
if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
|
|
throw LiturgicalAPIError.badStatus(http.statusCode)
|
|
}
|
|
return try Self.parse(data: data, year: year)
|
|
}
|
|
|
|
public static func parse(data: Data, year: Int) throws -> [LiturgicalDay] {
|
|
guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let celebrations = object["Zelebrationen"]
|
|
else {
|
|
throw LiturgicalAPIError.invalidPayload("Zelebrationen fehlen")
|
|
}
|
|
|
|
var entries: [[String: Any]] = []
|
|
if let dict = celebrations as? [String: Any] {
|
|
entries = dict.values.compactMap { $0 as? [String: Any] }
|
|
} else if let array = celebrations as? [[String: Any]] {
|
|
entries = array
|
|
}
|
|
|
|
let grouped = Dictionary(grouping: entries) { ($0["Datum"] as? String) ?? "" }
|
|
var days: [LiturgicalDay] = []
|
|
|
|
for dateKey in grouped.keys.sorted() {
|
|
guard dateKey.hasPrefix(String(year)), let date = DayMath.date(fromKey: dateKey) else { continue }
|
|
let raw = grouped[dateKey] ?? []
|
|
let valid = raw.filter { entry in
|
|
let title = (entry["Tl"] as? String) ?? ""
|
|
let remark = (entry["Bem"] as? String) ?? ""
|
|
if title.contains("Bahnlesungen") { return false }
|
|
if title.hasPrefix("Kommemoration") { return false }
|
|
if title == "Weihe der eigenen Kirche" && remark.hasPrefix("Wenn") { return false }
|
|
return true
|
|
}
|
|
guard !valid.isEmpty else { continue }
|
|
|
|
let best = valid.max { score($0, date: date) < score($1, date: date) } ?? valid[0]
|
|
var readingEntry = best
|
|
let bestTitle = (best["Tl"] as? String) ?? ""
|
|
if ((best["L1"] as? String) ?? "").isEmpty && ((best["EV"] as? String) ?? "").isEmpty {
|
|
readingEntry = valid.max {
|
|
readingLength($0) < readingLength($1)
|
|
} ?? best
|
|
}
|
|
|
|
let title = bestTitle
|
|
let rank = LiturgicalRank(rawValue: (best["Rang"] as? String) ?? "") ?? .weekday
|
|
let colorValue = (best["Farbe"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
|
?? (readingEntry["Farbe"] as? String)
|
|
?? ""
|
|
let readings = Readings(
|
|
first: (readingEntry["L1"] as? String) ?? "",
|
|
psalm: (readingEntry["AP"] as? String) ?? "",
|
|
second: (readingEntry["L2"] as? String) ?? "",
|
|
gospel: (readingEntry["EV"] as? String) ?? ""
|
|
)
|
|
days.append(LiturgicalDay(
|
|
date: date,
|
|
title: title,
|
|
rank: rank,
|
|
color: LiturgicalColor(apiValue: colorValue),
|
|
remark: (best["Bem"] as? String) ?? "",
|
|
readings: readings,
|
|
isObligation: LiturgicalCalendarEngine.isObligation(date: date, title: title),
|
|
source: LiturgicalSnapshot.sourceLabel
|
|
))
|
|
}
|
|
|
|
guard !days.isEmpty else { throw LiturgicalAPIError.emptyYear(year) }
|
|
|
|
// Complete gaps with the local calendar so a plan never has empty rows.
|
|
let existing = Set(days.map(\.dateKey))
|
|
let start = DayMath.date(fromKey: DayMath.key(year: year, month: 1, day: 1))!
|
|
let end = DayMath.date(fromKey: DayMath.key(year: year, month: 12, day: 31))!
|
|
for day in DayMath.days(in: DayRange(start: start, end: end)) where !existing.contains(DayMath.key(day)) {
|
|
days.append(LiturgicalCalendarEngine.localDay(for: day))
|
|
}
|
|
|
|
return days.sorted { $0.date < $1.date }
|
|
}
|
|
|
|
private static func readingLength(_ entry: [String: Any]) -> Int {
|
|
["L1", "AP", "L2", "EV"].reduce(0) { total, key in
|
|
total + ((entry[key] as? String)?.count ?? 0)
|
|
}
|
|
}
|
|
|
|
private static func score(_ entry: [String: Any], date: Date) -> Int {
|
|
var value = 0
|
|
let rank = (entry["Rang"] as? String) ?? ""
|
|
switch rank {
|
|
case "H": value += 120
|
|
case "F": value += 110
|
|
case "G": value += 80
|
|
case "g": value += 60
|
|
default: value += 50
|
|
}
|
|
let title = (entry["Tl"] as? String) ?? ""
|
|
let remark = (entry["Bem"] as? String) ?? ""
|
|
let lowerTitle = title.lowercased()
|
|
|
|
if DayMath.isSunday(date) {
|
|
if lowerTitle.contains("sonntag") || lowerTitle.contains("taufe des herrn") {
|
|
value += 100
|
|
}
|
|
if rank.isEmpty { value += 30 }
|
|
}
|
|
if remark.contains("Am Tag") { value += 18 }
|
|
else if remark.contains("Am Morgen") { value += 12 }
|
|
else if remark.contains("Am Vorabend") { value -= 4 }
|
|
else if remark.contains("In der Heiligen Nacht") { value += 5 }
|
|
if remark.contains("Hochfest") { value += 10 }
|
|
if title.range(of: #"^\d{1,2}\.\s"#, options: .regularExpression) != nil { value -= 25 }
|
|
if !(((entry["L1"] as? String) ?? "").isEmpty && ((entry["EV"] as? String) ?? "").isEmpty) { value += 20 }
|
|
if lowerTitle.contains("im jahreskreis") || lowerTitle.contains("osterzeit") { value += 5 }
|
|
return value
|
|
}
|
|
}
|
|
|
|
// MARK: - Combined loader
|
|
|
|
public enum LiturgicalData {
|
|
/// Inserts the bundled snapshot when the database does not yet know these years.
|
|
public static func bundledDays(notOlderThan existing: Set<String>) -> [LiturgicalDay] {
|
|
LiturgicalSnapshot.loadBundled().filter { !existing.contains($0.dateKey) }
|
|
}
|
|
}
|