aboutsummaryrefslogtreecommitdiff
path: root/cmd/server/feed.go
blob: 212e5da7d36e65ca192e0d78c366dfe61a9fb2e8 (plain) (blame)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package main

import (
	"bytes"
	"encoding/xml"
	"errors"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"riedstra.dev/mitch/go-website/page"
)

type Author struct {
	Name  string `xml:"name"`          // Required
	Uri   string `xml:"uri,omitempty"` //nolint:golint,stylecheck
	Email string `xml:"email,omitempty"`
}

type Link struct {
	Href   string `xml:"href,attr,omitempty"`
	Rel    string `xml:"rel,attr,omitempty"`
	Type   string `xml:"type,attr,omitempty"`
	Title  string `xml:"Title,attr,omitempty"`
	Length string `xml:"Length,attr,omitempty"`
}

type Content struct {
	Type string `xml:"type,attr"`
	Data string `xml:",chardata"`
}

type Entry struct {
	// Spec requires this, autogenerated from Title and updated if otherwise
	// left empty
	Id string `xml:"id"` //nolint:golint,stylecheck

	Title     string     `xml:"title"`   // Required
	Updated   *time.Time `xml:"updated"` // Required
	Author    *Author    `xml:"author,omitempty"`
	Published *time.Time `xml:"published,omitempty"`
	Links     []Link     `xml:"link,omitempty"`
	Content   *Content   `xml:"content,omitempty"`
}

func (i Entry) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	type Alias Entry

	errs := []string{}
	if i.Title == "" {
		errs = append(errs, "Title Cannot be empty")
	}

	if i.Updated == nil {
		errs = append(errs, "Updated cannot be nil")
	}

	if len(errs) > 0 {
		return errors.New(strings.Join(errs, ",")) //nolint:goerr113
	}

	if i.Id == "" {
		i.Id = fmt.Sprintf("%s::%d", i.Title, i.Updated.Unix())
	}

	i2 := (*Alias)(&i)

	return e.EncodeElement(i2, start)
}

//nolint:stylecheck,golint
type Atom struct {
	Ns        string     `xml:"xmlns,attr"`
	Title     string     `xml:"title"`            // Required
	Id        string     `xml:"id"`               // Required
	Author    Author     `xml:"author,omitempty"` // Required
	Updated   *time.Time `xml:"updated"`          // Required
	Published *time.Time `xml:"published,omitempty"`
	Subtitle  string     `xml:"subtitle,omitempty"`
	Entries   []Entry    `xml:"entry"`
}

func (a Atom) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	type Alias Atom

	a.Ns = "http://www.w3.org/2005/Atom"
	errs := []string{}

	if a.Id == "" {
		errs = append(errs, "ID Cannot be empty")
	}

	if a.Author.Name == "" {
		errs = append(errs, "Author Name cannot be empty")
	}

	if a.Updated == nil {
		errs = append(errs, "Updated cannot be empty")
	}

	if len(errs) > 0 {
		return errors.New(strings.Join(errs, ",")) //nolint:goerr113
	}

	start.Name = xml.Name{Local: "feed"}

	a2 := (*Alias)(&a)

	return e.EncodeElement(a2, start)
}

// FeedHandler takes care of pulling from the index all of the relevant posts
// and dumping them into an Atom feed.
//
// Relevant query parameters are:
//
// "content" if unset, or set to false content is omitted from the feed
// "limit=n" stop at "n" and return the feed.
//
func (a *App) FeedHandler(w http.ResponseWriter, r *http.Request) { //nolint:funlen
	vars := mux.Vars(r)

	var (
		addContent bool
		limit      int
	)

	if _, ok := r.URL.Query()["content"]; ok {
		if r.URL.Query().Get("content") != "false" {
			addContent = true
		}
	}

	if l := r.URL.Query().Get("limit"); l != "" {
		i, err := strconv.Atoi(l)
		if err == nil {
			limit = i
		}
	}

	tag, ok := vars["tag"]
	if !ok {
		http.Error(w, "Tag not found or supplied", http.StatusNotFound)

		return
	}

	p := page.NewPage("index")

	index, err := p.Index()
	if err != nil {
		log.Println(err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)

		return
	}

	pages, ok := index[tag]
	if !ok {
		http.Error(w, "Invalid tag", http.StatusNotFound)

		return
	}

	pages, dateless := pages.RemoveDateless()
	for _, p := range dateless {
		log.Printf("Warning, page %s has no Date field. Skipping inclusion on feed", p)
	}

	pages.SortDate()

	feed := &Atom{
		Author:   a.Author,
		Title:    a.Title,
		Id:       a.FeedId,
		Updated:  &a.Updated.Time,
		Subtitle: a.Description,
	}

	entries := []Entry{}

	for n, p := range pages {
		if limit != 0 && n >= limit {
			break
		}

		if !p.Published {
			continue
		}

		content := &bytes.Buffer{}

		err := p.Render(content)
		if err != nil {
			log.Println(err)
			http.Error(w, "Internal server error", http.StatusInternalServerError)

			return
		}

		entry := Entry{
			Title:   p.Title(),
			Updated: &p.Date.Time,
			Links:   []Link{{Href: strings.Join([]string{a.SiteURL, p.Path()}, "/")}},
		}

		if p.AuthorName != "" {
			entry.Author = &Author{
				Name: p.AuthorName,
			}
			if p.AuthorEmail != "" {
				entry.Author.Email = p.AuthorEmail
			}
		}

		if addContent {
			entry.Content = &Content{Type: "html", Data: content.String()}
		}

		entries = append(entries, entry)
	}

	feed.Entries = entries

	w.Header().Add("Content-type", "application/xml")

	_, err = w.Write([]byte(xml.Header))
	if err != nil {
		log.Println("Writing xml: ", err)

		return
	}

	enc := xml.NewEncoder(w)
	enc.Indent("", "  ")

	err = enc.Encode(feed)
	if err != nil {
		log.Println(err)
		// Headers probably already sent, but we'll try anyway
		http.Error(w, "Internal server error", http.StatusInternalServerError)
	}
}