706 lines
25 KiB
Go
706 lines
25 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"html"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type feedSource struct {
|
|
ID int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
FeedURL string `json:"feed_url"`
|
|
WebsiteURL string `json:"website_url"`
|
|
SourceType string `json:"source_type"`
|
|
PublicationMode string `json:"publication_mode"`
|
|
RightsStatus string `json:"rights_status"`
|
|
AllowSummary bool `json:"allow_summary"`
|
|
AllowImage bool `json:"allow_image"`
|
|
AttributionText string `json:"attribution_text"`
|
|
ETag string `json:"etag"`
|
|
LastModified string `json:"last_modified"`
|
|
FetchIntervalSeconds int `json:"fetch_interval_seconds"`
|
|
}
|
|
|
|
type feedRecord struct {
|
|
ID int64 `json:"id"`
|
|
SourceID int64 `json:"source_id"`
|
|
SourceName string `json:"source_name"`
|
|
SourceWebsite string `json:"source_website"`
|
|
ExternalID string `json:"external_id"`
|
|
URL string `json:"canonical_url"`
|
|
Title string `json:"title"`
|
|
Summary string `json:"summary"`
|
|
Author string `json:"author"`
|
|
PublishedAt time.Time `json:"published_at"`
|
|
ImageURL string `json:"image_url"`
|
|
Status string `json:"status"`
|
|
Attribution string `json:"attribution"`
|
|
Regions []string `json:"regions"`
|
|
}
|
|
|
|
type rssEngine struct {
|
|
db *postgresStore
|
|
client *http.Client
|
|
logger *log.Logger
|
|
stop chan struct{}
|
|
done chan struct{}
|
|
once sync.Once
|
|
}
|
|
|
|
func newRSSEngine(db *postgresStore, logger *log.Logger) *rssEngine {
|
|
return &rssEngine{db: db, logger: logger, client: &http.Client{Timeout: envDuration("LANDWELLE_RSS_TIMEOUT", 12*time.Second)}, stop: make(chan struct{}), done: make(chan struct{})}
|
|
}
|
|
func (e *rssEngine) Start() {
|
|
if e == nil || e.db == nil || !e.db.Enabled() {
|
|
return
|
|
}
|
|
go func() {
|
|
defer close(e.done)
|
|
ticker := time.NewTicker(envDuration("LANDWELLE_RSS_POLL_INTERVAL", 60*time.Second))
|
|
defer ticker.Stop()
|
|
e.runOnce(context.Background())
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
e.runOnce(context.Background())
|
|
case <-e.stop:
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
func (e *rssEngine) Stop(ctx context.Context) {
|
|
if e == nil || e.db == nil || !e.db.Enabled() {
|
|
return
|
|
}
|
|
e.once.Do(func() { close(e.stop) })
|
|
select {
|
|
case <-e.done:
|
|
case <-ctx.Done():
|
|
}
|
|
}
|
|
func (e *rssEngine) runOnce(parent context.Context) {
|
|
ctx, cancel := context.WithTimeout(parent, 50*time.Second)
|
|
defer cancel()
|
|
sources, err := e.sources(ctx)
|
|
if err != nil {
|
|
e.logger.Printf("RSS Quellen laden: %v", err)
|
|
return
|
|
}
|
|
for _, source := range sources {
|
|
if err := e.fetchSource(ctx, source); err != nil {
|
|
e.logger.Printf("RSS %s: %v", source.Name, err)
|
|
}
|
|
}
|
|
}
|
|
func (e *rssEngine) sources(ctx context.Context) ([]feedSource, error) {
|
|
var out []feedSource
|
|
q := `SELECT COALESCE(json_agg(row_to_json(x)), '[]'::json)::text FROM (
|
|
SELECT id,name,feed_url,COALESCE(website_url,'') website_url,source_type,publication_mode,rights_status,allow_summary,allow_image,attribution_text,COALESCE(etag,'') etag,COALESCE(last_modified,'') last_modified,fetch_interval_seconds
|
|
FROM feed_sources WHERE enabled=true AND next_fetch_at<=now() ORDER BY priority DESC,id LIMIT 25) x;`
|
|
if err := e.db.queryJSON(ctx, q, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
type parsedFeedItem struct {
|
|
ID, Link, Title, Summary, Author, Image string
|
|
Published time.Time
|
|
}
|
|
type rssMediaContent struct {
|
|
URL string `xml:"url,attr"`
|
|
Type string `xml:"type,attr"`
|
|
Medium string `xml:"medium,attr"`
|
|
}
|
|
|
|
type rssMediaThumbnail struct {
|
|
URL string `xml:"url,attr"`
|
|
}
|
|
|
|
type rssMediaGroup struct {
|
|
Contents []rssMediaContent `xml:"http://search.yahoo.com/mrss/ content"`
|
|
Thumbnails []rssMediaThumbnail `xml:"http://search.yahoo.com/mrss/ thumbnail"`
|
|
}
|
|
|
|
type rssDoc struct {
|
|
Channel struct {
|
|
Items []struct {
|
|
Guid string `xml:"guid"`
|
|
Link string `xml:"link"`
|
|
Title string `xml:"title"`
|
|
Description string `xml:"description"`
|
|
ContentEncoded string `xml:"http://purl.org/rss/1.0/modules/content/ encoded"`
|
|
Author string `xml:"author"`
|
|
PubDate string `xml:"pubDate"`
|
|
Enclosure struct {
|
|
URL string `xml:"url,attr"`
|
|
Type string `xml:"type,attr"`
|
|
} `xml:"enclosure"`
|
|
MediaContents []rssMediaContent `xml:"http://search.yahoo.com/mrss/ content"`
|
|
MediaThumbnails []rssMediaThumbnail `xml:"http://search.yahoo.com/mrss/ thumbnail"`
|
|
MediaGroups []rssMediaGroup `xml:"http://search.yahoo.com/mrss/ group"`
|
|
} `xml:"item"`
|
|
} `xml:"channel"`
|
|
}
|
|
type atomDoc struct {
|
|
Entries []struct {
|
|
ID string `xml:"id"`
|
|
Title string `xml:"title"`
|
|
Summary string `xml:"summary"`
|
|
Content string `xml:"content"`
|
|
Updated string `xml:"updated"`
|
|
Published string `xml:"published"`
|
|
Author struct {
|
|
Name string `xml:"name"`
|
|
} `xml:"author"`
|
|
Links []struct {
|
|
Href string `xml:"href,attr"`
|
|
Rel string `xml:"rel,attr"`
|
|
Type string `xml:"type,attr"`
|
|
} `xml:"link"`
|
|
} `xml:"entry"`
|
|
}
|
|
|
|
func (e *rssEngine) fetchSource(ctx context.Context, source feedSource) error {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, source.FeedURL, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Accept", "application/rss+xml, application/atom+xml, application/xml, text/xml")
|
|
req.Header.Set("User-Agent", "LandwelleRadio/"+applicationVersion+" (+https://landwelle.de)")
|
|
if source.ETag != "" {
|
|
req.Header.Set("If-None-Match", source.ETag)
|
|
}
|
|
if source.LastModified != "" {
|
|
req.Header.Set("If-Modified-Since", source.LastModified)
|
|
}
|
|
resp, err := e.client.Do(req)
|
|
if err != nil {
|
|
e.markFailure(ctx, source.ID, 0, err)
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode == http.StatusNotModified {
|
|
return e.markNotModified(ctx, source.ID, resp.StatusCode, source.FetchIntervalSeconds)
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
err = fmt.Errorf("HTTP %d", resp.StatusCode)
|
|
e.markFailure(ctx, source.ID, resp.StatusCode, err)
|
|
return err
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 3<<20))
|
|
if err != nil {
|
|
e.markFailure(ctx, source.ID, resp.StatusCode, err)
|
|
return err
|
|
}
|
|
items, err := parseFeed(body)
|
|
if err != nil {
|
|
e.markFailure(ctx, source.ID, resp.StatusCode, err)
|
|
return err
|
|
}
|
|
feedImages, articleImages := e.enrichTagesschauImages(ctx, source, items)
|
|
if isTagesschauFeedURL(source.FeedURL) {
|
|
e.logger.Printf("RSS %s: %d Meldungen, %d Bilder aus RSS, %d Bilder aus Artikel-Metadaten", source.Name, len(items), feedImages, articleImages)
|
|
}
|
|
inserted := 0
|
|
validItems := 0
|
|
seenExternalIDs := make([]string, 0, len(items))
|
|
for _, item := range items {
|
|
if strings.TrimSpace(item.Title) == "" || strings.TrimSpace(item.Link) == "" {
|
|
continue
|
|
}
|
|
if _, err := url.ParseRequestURI(item.Link); err != nil {
|
|
continue
|
|
}
|
|
validItems++
|
|
if !source.AllowSummary {
|
|
item.Summary = ""
|
|
}
|
|
if !source.AllowImage {
|
|
item.Image = ""
|
|
}
|
|
if err := e.upsertItem(ctx, source, item); err == nil {
|
|
inserted++
|
|
seenExternalIDs = append(seenExternalIDs, item.ID)
|
|
}
|
|
}
|
|
if source.FeedURL == ndrNiedersachsenFeedURL && validItems > 0 && inserted == validItems {
|
|
if err := e.pruneSourceItems(ctx, source.ID, seenExternalIDs); err != nil {
|
|
e.logger.Printf("RSS %s: veraltete Einträge konnten nicht entfernt werden: %v", source.Name, err)
|
|
}
|
|
}
|
|
return e.markSuccess(ctx, source.ID, resp.StatusCode, len(items), inserted, resp.Header.Get("ETag"), resp.Header.Get("Last-Modified"), source.FetchIntervalSeconds)
|
|
}
|
|
func parseFeed(body []byte) ([]parsedFeedItem, error) {
|
|
var probe struct{ XMLName xml.Name }
|
|
if err := xml.Unmarshal(body, &probe); err != nil {
|
|
return nil, err
|
|
}
|
|
switch strings.ToLower(probe.XMLName.Local) {
|
|
case "rss", "rdf":
|
|
var d rssDoc
|
|
if err := xml.Unmarshal(body, &d); err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]parsedFeedItem, 0, len(d.Channel.Items))
|
|
for _, v := range d.Channel.Items {
|
|
media := append([]rssMediaContent(nil), v.MediaContents...)
|
|
thumbnails := append([]rssMediaThumbnail(nil), v.MediaThumbnails...)
|
|
for _, group := range v.MediaGroups {
|
|
media = append(media, group.Contents...)
|
|
thumbnails = append(thumbnails, group.Thumbnails...)
|
|
}
|
|
img := rssItemImageURL(v.Link, v.Enclosure.URL, v.Enclosure.Type, media, thumbnails, v.ContentEncoded, v.Description)
|
|
out = append(out, parsedFeedItem{ID: firstNonEmpty(v.Guid, v.Link), Link: v.Link, Title: cleanFeedText(v.Title), Summary: cleanFeedText(v.Description), Author: cleanFeedText(v.Author), Image: img, Published: parseFeedTime(v.PubDate)})
|
|
}
|
|
return out, nil
|
|
case "feed":
|
|
var d atomDoc
|
|
if err := xml.Unmarshal(body, &d); err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]parsedFeedItem, 0, len(d.Entries))
|
|
for _, v := range d.Entries {
|
|
link, img := "", ""
|
|
for _, l := range v.Links {
|
|
if (l.Rel == "" || l.Rel == "alternate") && link == "" {
|
|
link = l.Href
|
|
}
|
|
if strings.HasPrefix(l.Type, "image/") {
|
|
img = l.Href
|
|
}
|
|
}
|
|
out = append(out, parsedFeedItem{ID: firstNonEmpty(v.ID, link), Link: link, Title: cleanFeedText(v.Title), Summary: cleanFeedText(firstNonEmpty(v.Summary, v.Content)), Author: cleanFeedText(v.Author.Name), Image: img, Published: parseFeedTime(firstNonEmpty(v.Published, v.Updated))})
|
|
}
|
|
return out, nil
|
|
default:
|
|
return nil, errors.New("unbekanntes Feedformat: " + probe.XMLName.Local)
|
|
}
|
|
}
|
|
|
|
var (
|
|
feedTags = regexp.MustCompile(`<[^>]+>`)
|
|
feedImageTag = regexp.MustCompile(`(?is)<img\b[^>]*>`)
|
|
feedImageSrc = regexp.MustCompile(`(?i)\b(?:src|data-src|data-original)\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))`)
|
|
feedImageSrcset = regexp.MustCompile(`(?i)\bsrcset\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))`)
|
|
feedImageFileHint = regexp.MustCompile(`(?i)\.(?:avif|gif|jpe?g|png|webp)(?:$|[?#])`)
|
|
)
|
|
|
|
func rssItemImageURL(articleURL, enclosureURL, enclosureType string, media []rssMediaContent, thumbnails []rssMediaThumbnail, contentEncoded, description string) string {
|
|
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(enclosureType)), "image/") || (strings.TrimSpace(enclosureType) == "" && feedImageFileHint.MatchString(enclosureURL)) {
|
|
if image := normalizeFeedImageURL(enclosureURL, articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
for _, candidate := range media {
|
|
isImage := strings.EqualFold(strings.TrimSpace(candidate.Medium), "image") || strings.HasPrefix(strings.ToLower(strings.TrimSpace(candidate.Type)), "image/") || feedImageFileHint.MatchString(candidate.URL)
|
|
if !isImage {
|
|
continue
|
|
}
|
|
if image := normalizeFeedImageURL(candidate.URL, articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
for _, candidate := range thumbnails {
|
|
if image := normalizeFeedImageURL(candidate.URL, articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
for _, markup := range []string{contentEncoded, description} {
|
|
if image := extractFeedImageURL(markup, articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func extractFeedImageURL(markup, articleURL string) string {
|
|
markup = unescapeFeedMarkup(markup)
|
|
if markup == "" {
|
|
return ""
|
|
}
|
|
for _, tag := range feedImageTag.FindAllString(markup, -1) {
|
|
if match := feedImageSrc.FindStringSubmatch(tag); len(match) > 0 {
|
|
for _, value := range match[1:] {
|
|
if image := normalizeFeedImageURL(value, articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
}
|
|
if match := feedImageSrcset.FindStringSubmatch(tag); len(match) > 0 {
|
|
for _, value := range match[1:] {
|
|
if strings.TrimSpace(value) == "" {
|
|
continue
|
|
}
|
|
first := strings.Fields(strings.Split(value, ",")[0])
|
|
if len(first) > 0 {
|
|
if image := normalizeFeedImageURL(first[0], articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func unescapeFeedMarkup(markup string) string {
|
|
markup = strings.TrimSpace(markup)
|
|
for i := 0; i < 4; i++ {
|
|
next := html.UnescapeString(markup)
|
|
if next == markup {
|
|
break
|
|
}
|
|
markup = next
|
|
}
|
|
return markup
|
|
}
|
|
|
|
var (
|
|
feedMetaTag = regexp.MustCompile(`(?is)<meta\b[^>]*>`)
|
|
feedLinkTag = regexp.MustCompile(`(?is)<link\b[^>]*>`)
|
|
feedHTMLAttr = regexp.MustCompile(`(?is)([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))`)
|
|
)
|
|
|
|
func htmlTagAttributes(tag string) map[string]string {
|
|
attrs := make(map[string]string)
|
|
for _, match := range feedHTMLAttr.FindAllStringSubmatch(tag, -1) {
|
|
if len(match) < 5 {
|
|
continue
|
|
}
|
|
value := firstNonEmpty(match[2], match[3], match[4])
|
|
attrs[strings.ToLower(strings.TrimSpace(match[1]))] = html.UnescapeString(strings.TrimSpace(value))
|
|
}
|
|
return attrs
|
|
}
|
|
|
|
func extractArticleMetaImage(markup, articleURL string) string {
|
|
for _, tag := range feedMetaTag.FindAllString(markup, -1) {
|
|
attrs := htmlTagAttributes(tag)
|
|
key := strings.ToLower(firstNonEmpty(attrs["property"], attrs["name"], attrs["itemprop"]))
|
|
switch key {
|
|
case "og:image", "og:image:url", "og:image:secure_url", "twitter:image", "twitter:image:src", "image", "thumbnailurl":
|
|
if image := normalizeTagesschauImageURL(attrs["content"], articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
}
|
|
for _, tag := range feedLinkTag.FindAllString(markup, -1) {
|
|
attrs := htmlTagAttributes(tag)
|
|
rel := strings.ToLower(strings.TrimSpace(attrs["rel"]))
|
|
if rel == "image_src" || strings.Contains(" "+rel+" ", " image_src ") {
|
|
if image := normalizeTagesschauImageURL(attrs["href"], articleURL); image != "" {
|
|
return image
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func isTagesschauHost(host string) bool {
|
|
host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
|
return host == "tagesschau.de" || strings.HasSuffix(host, ".tagesschau.de")
|
|
}
|
|
|
|
func isTagesschauFeedURL(rawURL string) bool {
|
|
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
|
return err == nil && parsed.Scheme == "https" && isTagesschauHost(parsed.Hostname())
|
|
}
|
|
|
|
func isTagesschauArticleURL(rawURL string) bool {
|
|
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
|
return err == nil && parsed.Scheme == "https" && isTagesschauHost(parsed.Hostname()) && strings.HasSuffix(strings.ToLower(parsed.Path), ".html")
|
|
}
|
|
|
|
func normalizeTagesschauImageURL(rawURL, articleURL string) string {
|
|
image := normalizeFeedImageURL(rawURL, articleURL)
|
|
if image == "" {
|
|
return ""
|
|
}
|
|
parsed, err := url.Parse(image)
|
|
if err != nil || parsed.Scheme != "https" || !isTagesschauHost(parsed.Hostname()) {
|
|
return ""
|
|
}
|
|
return parsed.String()
|
|
}
|
|
|
|
func (e *rssEngine) enrichTagesschauImages(ctx context.Context, source feedSource, items []parsedFeedItem) (int, int) {
|
|
if e == nil || !source.AllowImage || !isTagesschauFeedURL(source.FeedURL) || len(items) == 0 {
|
|
return 0, 0
|
|
}
|
|
feedImages := 0
|
|
missing := make([]int, 0, len(items))
|
|
for i := range items {
|
|
if strings.TrimSpace(items[i].Image) != "" {
|
|
feedImages++
|
|
continue
|
|
}
|
|
if isTagesschauArticleURL(items[i].Link) {
|
|
missing = append(missing, i)
|
|
}
|
|
}
|
|
if len(missing) == 0 {
|
|
return feedImages, 0
|
|
}
|
|
|
|
workers := 4
|
|
if len(missing) < workers {
|
|
workers = len(missing)
|
|
}
|
|
jobs := make(chan int)
|
|
var wg sync.WaitGroup
|
|
var mu sync.Mutex
|
|
articleImages := 0
|
|
for worker := 0; worker < workers; worker++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
for index := range jobs {
|
|
requestCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
|
image := e.fetchTagesschauArticleImage(requestCtx, items[index].Link)
|
|
cancel()
|
|
if image == "" {
|
|
continue
|
|
}
|
|
mu.Lock()
|
|
items[index].Image = image
|
|
articleImages++
|
|
mu.Unlock()
|
|
}
|
|
}()
|
|
}
|
|
for _, index := range missing {
|
|
select {
|
|
case jobs <- index:
|
|
case <-ctx.Done():
|
|
close(jobs)
|
|
wg.Wait()
|
|
return feedImages, articleImages
|
|
}
|
|
}
|
|
close(jobs)
|
|
wg.Wait()
|
|
return feedImages, articleImages
|
|
}
|
|
|
|
func (e *rssEngine) fetchTagesschauArticleImage(ctx context.Context, articleURL string) string {
|
|
if e == nil || !isTagesschauArticleURL(articleURL) {
|
|
return ""
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, articleURL, nil)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
req.Header.Set("Accept", "text/html,application/xhtml+xml")
|
|
req.Header.Set("User-Agent", "LandwelleRadio/"+applicationVersion+" (+https://landwelle.de)")
|
|
transport := http.RoundTripper(http.DefaultTransport)
|
|
if e.client != nil && e.client.Transport != nil {
|
|
transport = e.client.Transport
|
|
}
|
|
client := &http.Client{
|
|
Transport: transport,
|
|
Timeout: 6 * time.Second,
|
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
|
if len(via) >= 3 || req.URL.Scheme != "https" || !isTagesschauHost(req.URL.Hostname()) {
|
|
return http.ErrUseLastResponse
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK || resp.Request == nil || resp.Request.URL == nil || !isTagesschauHost(resp.Request.URL.Hostname()) {
|
|
return ""
|
|
}
|
|
contentType := strings.ToLower(resp.Header.Get("Content-Type"))
|
|
if contentType != "" && !strings.Contains(contentType, "text/html") && !strings.Contains(contentType, "application/xhtml+xml") {
|
|
return ""
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return extractArticleMetaImage(string(body), resp.Request.URL.String())
|
|
}
|
|
|
|
func normalizeFeedImageURL(rawURL, articleURL string) string {
|
|
rawURL = strings.TrimSpace(html.UnescapeString(rawURL))
|
|
if rawURL == "" || strings.HasPrefix(strings.ToLower(rawURL), "data:") {
|
|
return ""
|
|
}
|
|
if strings.HasPrefix(rawURL, "//") {
|
|
rawURL = "https:" + rawURL
|
|
}
|
|
parsed, err := url.Parse(rawURL)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
if !parsed.IsAbs() {
|
|
base, baseErr := url.Parse(strings.TrimSpace(articleURL))
|
|
if baseErr != nil || !base.IsAbs() {
|
|
return ""
|
|
}
|
|
parsed = base.ResolveReference(parsed)
|
|
}
|
|
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
|
return ""
|
|
}
|
|
return parsed.String()
|
|
}
|
|
|
|
func cleanFeedText(v string) string {
|
|
v = html.UnescapeString(feedTags.ReplaceAllString(v, " "))
|
|
return strings.Join(strings.Fields(v), " ")
|
|
}
|
|
func firstNonEmpty(values ...string) string {
|
|
for _, v := range values {
|
|
if strings.TrimSpace(v) != "" {
|
|
return strings.TrimSpace(v)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
func parseFeedTime(v string) time.Time {
|
|
for _, layout := range []string{time.RFC3339, time.RFC3339Nano, time.RFC1123Z, time.RFC1123, time.RFC822Z, time.RFC822, "Mon, 02 Jan 2006 15:04:05 MST"} {
|
|
if t, err := time.Parse(layout, strings.TrimSpace(v)); err == nil {
|
|
return t.UTC()
|
|
}
|
|
}
|
|
return time.Now().UTC()
|
|
}
|
|
func (e *rssEngine) upsertItem(ctx context.Context, s feedSource, item parsedFeedItem) error {
|
|
sum := sha256.Sum256([]byte(strings.ToLower(item.Title) + "\n" + item.Link))
|
|
hash := hex.EncodeToString(sum[:])
|
|
status := "imported"
|
|
if s.PublicationMode == "automatic" && s.RightsStatus != "blocked" && s.RightsStatus != "review_required" {
|
|
status = "published"
|
|
}
|
|
published := item.Published.UTC().Format(time.RFC3339)
|
|
sql := fmt.Sprintf(`INSERT INTO feed_items(source_id,external_id,canonical_url,title,summary,author,published_at,image_url,content_hash,status,metadata)
|
|
VALUES(%d,%s,%s,%s,%s,NULLIF(%s,''),%s::timestamptz,NULLIF(%s,''),%s,%s,jsonb_build_object('attribution',%s))
|
|
ON CONFLICT(source_id,external_id) DO UPDATE SET canonical_url=EXCLUDED.canonical_url,title=EXCLUDED.title,summary=EXCLUDED.summary,author=EXCLUDED.author,published_at=EXCLUDED.published_at,image_url=EXCLUDED.image_url,updated_at=now();`, s.ID, sqlText(item.ID), sqlText(item.Link), sqlText(item.Title), sqlText(item.Summary), sqlText(item.Author), sqlText(published), sqlText(item.Image), sqlText(hash), sqlText(status), sqlText(s.AttributionText))
|
|
_, err := e.db.exec(ctx, sql)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, _ = e.db.exec(ctx, fmt.Sprintf(`INSERT INTO feed_item_regions(item_id,region_id,assignment_method)
|
|
SELECT fi.id,fsr.region_id,'source' FROM feed_items fi JOIN feed_source_regions fsr ON fsr.source_id=fi.source_id
|
|
WHERE fi.source_id=%d AND fi.external_id=%s ON CONFLICT(item_id,region_id) DO NOTHING;`, s.ID, sqlText(item.ID)))
|
|
return nil
|
|
}
|
|
func (e *rssEngine) pruneSourceItems(ctx context.Context, sourceID int64, currentExternalIDs []string) error {
|
|
if e == nil || e.db == nil || !e.db.Enabled() || sourceID < 1 || len(currentExternalIDs) == 0 {
|
|
return nil
|
|
}
|
|
quoted := make([]string, 0, len(currentExternalIDs))
|
|
for _, externalID := range currentExternalIDs {
|
|
if strings.TrimSpace(externalID) != "" {
|
|
quoted = append(quoted, sqlText(externalID))
|
|
}
|
|
}
|
|
if len(quoted) == 0 {
|
|
return nil
|
|
}
|
|
_, err := e.db.exec(ctx, fmt.Sprintf(`DELETE FROM feed_items WHERE source_id=%d AND external_id NOT IN (%s);`, sourceID, strings.Join(quoted, ",")))
|
|
return err
|
|
}
|
|
|
|
func (e *rssEngine) markSuccess(ctx context.Context, id int64, status, seen, inserted int, etag, lastModified string, interval int) error {
|
|
_, err := e.db.exec(ctx, fmt.Sprintf(`UPDATE feed_sources SET etag=NULLIF(%s,''),last_modified=NULLIF(%s,''),last_success_at=now(),consecutive_failures=0,next_fetch_at=now()+(%d||' seconds')::interval,updated_at=now() WHERE id=%d;`, sqlText(etag), sqlText(lastModified), interval, id))
|
|
return err
|
|
}
|
|
func (e *rssEngine) markNotModified(ctx context.Context, id int64, status, interval int) error {
|
|
_, err := e.db.exec(ctx, fmt.Sprintf(`UPDATE feed_sources SET last_success_at=now(),consecutive_failures=0,next_fetch_at=now()+(%d||' seconds')::interval WHERE id=%d;`, interval, id))
|
|
return err
|
|
}
|
|
func (e *rssEngine) markFailure(ctx context.Context, id int64, status int, cause error) {
|
|
_, _ = e.db.exec(ctx, fmt.Sprintf(`UPDATE feed_sources SET last_error_at=now(),consecutive_failures=consecutive_failures+1,next_fetch_at=now()+LEAST(interval '1 hour',(%d*GREATEST(1,consecutive_failures+1)||' seconds')::interval),updated_at=now() WHERE id=%d;`, 60, id))
|
|
}
|
|
func (e *rssEngine) PublicItems(ctx context.Context, limit int, cursor string, region string) ([]feedRecord, string, error) {
|
|
if e == nil || e.db == nil || !e.db.Enabled() {
|
|
return nil, "", nil
|
|
}
|
|
if limit < 1 || limit > 500 {
|
|
limit = 20
|
|
}
|
|
where := `fi.status='published' AND fs.enabled=true`
|
|
if cursor != "" {
|
|
id, err := strconv.ParseInt(cursor, 10, 64)
|
|
if err != nil || id < 1 {
|
|
return nil, "", errors.New("ungültiger Cursor")
|
|
}
|
|
where += fmt.Sprintf(` AND fi.id < %d`, id)
|
|
}
|
|
var out []feedRecord
|
|
q := fmt.Sprintf(`SELECT COALESCE(json_agg(row_to_json(x)), '[]'::json)::text FROM (SELECT fi.id,fi.source_id,fs.name source_name,COALESCE(fs.website_url,'') source_website,fi.external_id,fi.canonical_url,fi.title,fi.summary,COALESCE(fi.author,'') author,COALESCE(fi.published_at,fi.created_at) published_at,COALESCE(fi.image_url,'') image_url,fi.status,COALESCE(fi.metadata->>'attribution','') attribution, COALESCE((SELECT json_agg(r.slug ORDER BY r.sort_order,r.name) FROM feed_item_regions fir JOIN regions r ON r.id=fir.region_id WHERE fir.item_id=fi.id),'[]'::json) regions FROM feed_items fi JOIN feed_sources fs ON fs.id=fi.source_id WHERE %s ORDER BY COALESCE(fi.published_at,fi.created_at) DESC,fi.id DESC LIMIT %d) x;`, where, limit+1)
|
|
if err := e.db.queryJSON(ctx, q, &out); err != nil {
|
|
return nil, "", err
|
|
}
|
|
next := ""
|
|
if len(out) > limit {
|
|
next = fmt.Sprint(out[limit-1].ID)
|
|
out = out[:limit]
|
|
}
|
|
return out, next, nil
|
|
}
|
|
func (e *rssEngine) PublicItemByID(ctx context.Context, id int64) (feedRecord, bool, error) {
|
|
if e == nil || e.db == nil || !e.db.Enabled() || id < 1 {
|
|
return feedRecord{}, false, nil
|
|
}
|
|
var out []feedRecord
|
|
q := fmt.Sprintf(`SELECT COALESCE(json_agg(row_to_json(x)), '[]'::json)::text FROM (
|
|
SELECT fi.id,fi.source_id,fs.name source_name,COALESCE(fs.website_url,'') source_website,fi.external_id,
|
|
fi.canonical_url,fi.title,fi.summary,COALESCE(fi.author,'') author,
|
|
COALESCE(fi.published_at,fi.created_at) published_at,COALESCE(fi.image_url,'') image_url,
|
|
fi.status,COALESCE(fi.metadata->>'attribution','') attribution,
|
|
COALESCE((SELECT json_agg(r.slug ORDER BY r.sort_order,r.name) FROM feed_item_regions fir JOIN regions r ON r.id=fir.region_id WHERE fir.item_id=fi.id),'[]'::json) regions
|
|
FROM feed_items fi JOIN feed_sources fs ON fs.id=fi.source_id
|
|
WHERE fi.id=%d AND fi.status='published' AND fs.enabled=true LIMIT 1) x;`, id)
|
|
if err := e.db.queryJSON(ctx, q, &out); err != nil {
|
|
return feedRecord{}, false, err
|
|
}
|
|
if len(out) == 0 {
|
|
return feedRecord{}, false, nil
|
|
}
|
|
return out[0], true, nil
|
|
}
|
|
|
|
func (e *rssEngine) Status(ctx context.Context) map[string]any {
|
|
result := map[string]any{"enabled": false}
|
|
if e == nil || e.db == nil || !e.db.Enabled() {
|
|
return result
|
|
}
|
|
var rows []map[string]any
|
|
_ = e.db.queryJSON(ctx, `SELECT COALESCE(json_agg(row_to_json(x)), '[]'::json)::text FROM (SELECT count(*)::int sources,count(*) FILTER(WHERE enabled)::int enabled_sources,COALESCE(sum(consecutive_failures),0)::int failures,max(last_success_at) last_success_at FROM feed_sources) x;`, &rows)
|
|
result["enabled"] = true
|
|
if len(rows) > 0 {
|
|
for k, v := range rows[0] {
|
|
result[k] = v
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
func feedRecordJSON(r *http.Request, item feedRecord) map[string]any {
|
|
return map[string]any{"id": item.ID, "content_type": "rss", "title": item.Title, "summary": item.Summary, "author": item.Author, "image_url": item.ImageURL, "published_at": item.PublishedAt, "regions": item.Regions, "external_url": item.URL, "deep_link": fmt.Sprintf("%s/aktuelles?news=%d", strings.TrimRight(publicURL(r, ""), "/"), item.ID), "source": map[string]any{"name": item.SourceName, "website_url": item.SourceWebsite, "attribution": item.Attribution}}
|
|
}
|
|
func encodeJSON(v any) string { b, _ := json.Marshal(v); return string(b) }
|