Web Variante in Go V0.1
This commit is contained in:
1 parent
f9e3e94629
commit
692b9b6ef8
60 files changed
+13140
No files matched your search
@@ -0,0 +1,279 @@
|
||||
package liturgy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// APIError describes a failed online calendar request.
|
||||
type APIError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string { return e.Message }
|
||||
|
||||
func apiErrorf(format string, args ...any) error {
|
||||
return &APIError{Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
|
||||
// API talks to the eucharistiefeier.de calendar endpoint.
|
||||
type API struct {
|
||||
Diocese string
|
||||
Endpoint string
|
||||
Client *http.Client
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// NewAPI returns the default live client used by LektorenPlan.
|
||||
func NewAPI() *API {
|
||||
return &API{
|
||||
Diocese: "koeln",
|
||||
Endpoint: "https://www.eucharistiefeier.de/lk/api.php",
|
||||
Client: &http.Client{Timeout: 45 * time.Second},
|
||||
UserAgent: "LektorenPlan/1.0 (Linux; Pfarrei)",
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch downloads and parses one calendar year, filling gaps locally.
|
||||
func (a *API) Fetch(ctx context.Context, year int) ([]domain.LiturgicalDay, error) {
|
||||
endpoint, err := url.Parse(a.Endpoint)
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Die Kalender-URL konnte nicht erstellt werden.")
|
||||
}
|
||||
query := endpoint.Query()
|
||||
query.Set("kal", a.Diocese)
|
||||
query.Set("jahr", strconv.Itoa(year))
|
||||
query.Set("format", "json")
|
||||
query.Set("info", "wdtrflu")
|
||||
query.Set("dup", "e")
|
||||
query.Set("bahn", "j")
|
||||
endpoint.RawQuery = query.Encode()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Die Kalenderanfrage konnte nicht erstellt werden (%v).", err)
|
||||
}
|
||||
userAgent := a.UserAgent
|
||||
if userAgent == "" {
|
||||
userAgent = "LektorenPlan/1.0 (Linux; Pfarrei)"
|
||||
}
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
req.Header.Set("Accept", "application/json, text/plain, */*")
|
||||
|
||||
client := a.Client
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 45 * time.Second}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Der liturgische Kalender war nicht erreichbar (%v).", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return nil, apiErrorf("Der liturgische Kalender antwortete mit HTTP %d.", resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Die Kalenderdaten konnten nicht gelesen werden (%v).", err)
|
||||
}
|
||||
return Parse(data, year)
|
||||
}
|
||||
|
||||
var leadingNumber = regexp.MustCompile(`^\d{1,2}\.\s`)
|
||||
|
||||
// Parse converts the JSON payload of the online calendar into days.
|
||||
func Parse(data []byte, year int) ([]domain.LiturgicalDay, error) {
|
||||
var root map[string]any
|
||||
if err := json.Unmarshal(data, &root); err != nil {
|
||||
return nil, apiErrorf("Die Kalenderdaten konnten nicht gelesen werden (%v).", err)
|
||||
}
|
||||
rawCelebrations, ok := root["Zelebrationen"]
|
||||
if !ok {
|
||||
return nil, apiErrorf("Die Kalenderdaten konnten nicht gelesen werden (Zelebrationen fehlen).")
|
||||
}
|
||||
|
||||
entries := decodeEntries(rawCelebrations)
|
||||
grouped := map[string][]map[string]any{}
|
||||
for _, entry := range entries {
|
||||
date, _ := entry["Datum"].(string)
|
||||
grouped[date] = append(grouped[date], entry)
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(grouped))
|
||||
for key := range grouped {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
prefix := strconv.Itoa(year)
|
||||
var days []domain.LiturgicalDay
|
||||
for _, dateKey := range keys {
|
||||
if !strings.HasPrefix(dateKey, prefix) {
|
||||
continue
|
||||
}
|
||||
date, ok := domain.DateFromKey(dateKey)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var valid []map[string]any
|
||||
for _, entry := range grouped[dateKey] {
|
||||
title := stringField(entry, "Tl")
|
||||
remark := stringField(entry, "Bem")
|
||||
if strings.Contains(title, "Bahnlesungen") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(title, "Kommemoration") {
|
||||
continue
|
||||
}
|
||||
if title == "Weihe der eigenen Kirche" && strings.HasPrefix(remark, "Wenn") {
|
||||
continue
|
||||
}
|
||||
valid = append(valid, entry)
|
||||
}
|
||||
if len(valid) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
best := valid[0]
|
||||
bestScore := scoreEntry(best, date)
|
||||
for _, entry := range valid[1:] {
|
||||
if s := scoreEntry(entry, date); s > bestScore {
|
||||
best, bestScore = entry, s
|
||||
}
|
||||
}
|
||||
|
||||
readingEntry := best
|
||||
if stringField(best, "L1") == "" && stringField(best, "EV") == "" {
|
||||
bestLen := readingLength(readingEntry)
|
||||
for _, entry := range valid {
|
||||
if l := readingLength(entry); l > bestLen {
|
||||
readingEntry, bestLen = entry, l
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
title := stringField(best, "Tl")
|
||||
colorValue := stringField(best, "Farbe")
|
||||
if colorValue == "" {
|
||||
colorValue = stringField(readingEntry, "Farbe")
|
||||
}
|
||||
days = append(days, domain.LiturgicalDay{
|
||||
Date: date,
|
||||
Title: title,
|
||||
Rank: domain.LiturgicalRank(stringField(best, "Rang")),
|
||||
Color: domain.LiturgicalColorFromAPI(colorValue),
|
||||
Remark: stringField(best, "Bem"),
|
||||
Readings: domain.Readings{
|
||||
First: stringField(readingEntry, "L1"),
|
||||
Psalm: stringField(readingEntry, "AP"),
|
||||
Second: stringField(readingEntry, "L2"),
|
||||
Gospel: stringField(readingEntry, "EV"),
|
||||
},
|
||||
IsObligation: IsObligation(date, title),
|
||||
Source: SourceLabel,
|
||||
UpdatedAt: domain.Normalize(time.Now()),
|
||||
})
|
||||
}
|
||||
|
||||
if len(days) == 0 {
|
||||
return nil, apiErrorf("Für %d wurden keine liturgischen Daten geliefert.", year)
|
||||
}
|
||||
return FillLocalGaps(year, days), nil
|
||||
}
|
||||
|
||||
func decodeEntries(raw any) []map[string]any {
|
||||
var entries []map[string]any
|
||||
switch value := raw.(type) {
|
||||
case []any:
|
||||
for _, item := range value {
|
||||
if entry, ok := item.(map[string]any); ok {
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
}
|
||||
case map[string]any:
|
||||
for _, item := range value {
|
||||
if entry, ok := item.(map[string]any); ok {
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func stringField(entry map[string]any, key string) string {
|
||||
if value, ok := entry[key].(string); ok {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func readingLength(entry map[string]any) int {
|
||||
total := 0
|
||||
for _, key := range []string{"L1", "AP", "L2", "EV"} {
|
||||
total += utf8.RuneCountInString(stringField(entry, key))
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func scoreEntry(entry map[string]any, date time.Time) int {
|
||||
value := 0
|
||||
switch stringField(entry, "Rang") {
|
||||
case "H":
|
||||
value += 120
|
||||
case "F":
|
||||
value += 110
|
||||
case "G":
|
||||
value += 80
|
||||
case "g":
|
||||
value += 60
|
||||
default:
|
||||
value += 50
|
||||
}
|
||||
title := stringField(entry, "Tl")
|
||||
remark := stringField(entry, "Bem")
|
||||
lowerTitle := strings.ToLower(title)
|
||||
|
||||
if domain.IsSunday(date) {
|
||||
if strings.Contains(lowerTitle, "sonntag") || strings.Contains(lowerTitle, "taufe des herrn") {
|
||||
value += 100
|
||||
}
|
||||
if stringField(entry, "Rang") == "" {
|
||||
value += 30
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(remark, "Am Tag"):
|
||||
value += 18
|
||||
case strings.Contains(remark, "Am Morgen"):
|
||||
value += 12
|
||||
case strings.Contains(remark, "Am Vorabend"):
|
||||
value -= 4
|
||||
case strings.Contains(remark, "In der Heiligen Nacht"):
|
||||
value += 5
|
||||
}
|
||||
if strings.Contains(remark, "Hochfest") {
|
||||
value += 10
|
||||
}
|
||||
if leadingNumber.MatchString(title) {
|
||||
value -= 25
|
||||
}
|
||||
if stringField(entry, "L1") != "" || stringField(entry, "EV") != "" {
|
||||
value += 20
|
||||
}
|
||||
if strings.Contains(lowerTitle, "im jahreskreis") || strings.Contains(lowerTitle, "osterzeit") {
|
||||
value += 5
|
||||
}
|
||||
return value
|
||||
}
|
||||
Reference in new issue
Block a user