forked from arussellsaw/news
/
handle_generate_edition.go
91 lines (81 loc) · 2.03 KB
/
handle_generate_edition.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package handler
import (
"net/http"
"sort"
"time"
"unicode/utf8"
"github.com/RusticPotatoes/news/dao"
"github.com/RusticPotatoes/news/domain"
"github.com/monzo/slog"
)
func handleGenerateEdition(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
e, err := dao.GetEditionForTime(ctx, time.Now(), false)
if err != nil {
slog.Error(ctx, "Error getting edition: %s", err)
http.Error(w, err.Error(), 500)
return
}
if e != nil && r.URL.Query().Get("force") == "" {
slog.Info(ctx, "Edition %s - %s already exists and is within window", e.ID, e.Name)
w.Write([]byte(e.ID))
return
}
e, err = domain.NewEdition(ctx, time.Now())
if err != nil {
slog.Error(ctx, "Error creating edition: %s", err)
http.Error(w, err.Error(), 500)
return
}
start := time.Now().Add(-72 * time.Hour)
end := time.Now()
articles, _, err := dao.GetArticlesForOwner(ctx, "", start, end)
if err != nil {
httpError(ctx, w, "error getting articles", err)
return
}
newArticles := []domain.Article{}
L:
for _, a := range articles {
if a.Content.Title == "" || a.Content.TextContent == "" {
continue L
}
if !utf8.Valid([]byte(a.Content.Title)) ||
!utf8.Valid([]byte(a.Content.TextContent)) {
continue L
}
newArticles = append(newArticles, a)
}
e.Articles = newArticles
bySource := make(map[string][]domain.Article)
for _, a := range e.Articles {
bySource[a.Source.Name] = append(bySource[a.Source.Name], a)
}
newArticles = nil
for _, as := range bySource {
sort.Slice(as, func(i, j int) bool {
return as[i].Timestamp.After(as[j].Timestamp)
})
}
top:
for s, as := range bySource {
newArticles = append(newArticles, as[0])
bySource[s] = as[1:]
if len(bySource[s]) == 0 {
delete(bySource, s)
goto top
}
}
if len(bySource) != 0 {
goto top
}
e.Articles = newArticles
err = dao.SetEdition(ctx, e)
if err != nil {
slog.Error(ctx, "Error storing edition: %s", err)
http.Error(w, err.Error(), 500)
return
}
slog.Info(ctx, "Created new edition: %s - %s", e.ID, e.Name)
w.Write([]byte(e.ID))
}