-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
282 lines (236 loc) · 7.36 KB
/
server.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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package main
import (
"context"
"io"
"log"
"net/http"
"os"
"path"
"strings"
"time"
"github.com/andrewslotin/youcast/assets"
"github.com/eduncan911/podcast"
)
// PodcastMetadata contains metadata for the podcast feed.
type PodcastMetadata struct {
Title string
Link string
Description string
}
// Metadata contains metadata for a podcast item
type Metadata struct {
Type PodcastItemType
OriginalURL string
Title string
Description string
Author string
Duration time.Duration
MIMEType string
ContentLength int64
}
type audioSource interface {
Metadata(context.Context) (Metadata, error)
DownloadURL(context.Context) (string, error)
}
type audioSourceProvider interface {
Name() string
HandleRequest(http.ResponseWriter, *http.Request) audioSource
}
// FeedServer is an HTTP server that serves podcast feeds and manages podcast items.
type FeedServer struct {
svc *FeedService
meta PodcastMetadata
providers map[string]audioSourceProvider
}
// NewFeedServer creates a new FeedServer instance.
func NewFeedServer(meta PodcastMetadata, svc *FeedService) *FeedServer {
return &FeedServer{
svc: svc,
meta: meta,
providers: make(map[string]audioSourceProvider),
}
}
// ServeMux returns a ServeMux instance that can be used to serve the podcast feed.
func (srv *FeedServer) ServeMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/", srv.ServeFeed)
mux.HandleFunc("/add/", srv.HandleAddItem)
mux.HandleFunc("/feed", srv.ServeFeed)
mux.HandleFunc("/feed/", srv.HandleItem)
mux.HandleFunc("/favicon.ico", AssetHandler(assets.Icon, "image/png"))
mux.HandleFunc("/style.css", AssetHandler(assets.Stylesheet, "text/css"))
mux.HandleFunc("/script.js", AssetHandler(assets.JavaScript, "text/javascript"))
mux.HandleFunc("/downloads/", srv.ServeMedia)
return mux
}
// RegisterProvider registers a new audio source provider.
func (srv *FeedServer) RegisterProvider(subPath string, p audioSourceProvider) {
log.Printf("requests sent to /add%s will be handled by %s provider", subPath, p.Name())
srv.providers[subPath] = p
}
// ServeFeed serves the podcast feed.
func (srv *FeedServer) ServeFeed(w http.ResponseWriter, req *http.Request) {
scheme := reqScheme(req)
feed := Feed{
URL: srv.meta.Link,
IconURL: scheme + "://" + req.Host + "/favicon.ico",
Title: srv.meta.Title,
Description: srv.meta.Description,
}
if feed.URL == "" {
feed.URL = scheme + "://" + req.Host
}
items, err := srv.svc.Items()
if err != nil {
log.Println("failed to fetch podcast items: ", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
for _, item := range items {
feed.Items = append(feed.Items, DownloadablePodcastItem{
PodcastItem: item,
MediaURL: scheme + "://" + req.Host + "/downloads/" + item.FileName,
})
}
if len(items) > 0 {
feed.PubDate = items[len(items)-1].AddedAt
}
var view interface {
ContentType() string
Render(io.Writer, Feed) error
}
switch req.URL.Path {
case "/feed":
view = AtomRenderer{}
default:
tmpl := Templates
if args.DevMode {
tmpl = ParseTemplates(os.DirFS("./assets"))
}
view = HTMLRenderer{
Template: tmpl.Lookup("index.html.tmpl"),
}
}
w.Header().Set("Content-Type", view.ContentType())
if err := view.Render(w, feed); err != nil {
log.Println("failed to render feed to", view.ContentType(), ":", err)
}
}
// ServeMedia serves the podcast media files.
func (srv *FeedServer) ServeMedia(w http.ResponseWriter, req *http.Request) {
fileName := path.Base(req.URL.Path)
filePath := path.Join(srv.svc.storagePath, fileName)
fi, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
log.Printf("failed to stat %s: %s", filePath, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
fd, err := os.Open(filePath)
if err != nil {
log.Printf("failed to read %s: %s", filePath, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer fd.Close()
http.ServeContent(w, req, fileName, fi.ModTime(), fd)
}
// HandleItem handles requests to add a new podcast item.
func (srv *FeedServer) HandleAddItem(w http.ResponseWriter, req *http.Request) {
p, ok := srv.providers[strings.TrimPrefix(req.URL.Path, "/add")]
if !ok {
http.NotFound(w, req)
return
}
audio := p.HandleRequest(w, req)
if audio == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
meta, err := audio.Metadata(ctx)
if err != nil {
log.Printf("failed to fetch %s data: %s", p.Name(), err)
return
}
u, err := audio.DownloadURL(ctx)
if err != nil {
log.Printf("failed to fetch download URL for %s: %s", p.Name(), err)
return
}
if err := srv.svc.AddItem(NewPodcastItem(meta, time.Now()), u); err != nil {
log.Printf("failed to add %s item to the feed: %s", p.Name(), err)
return
}
}()
}
// HandleItem handles requests to update or remove a podcast item.
func (srv *FeedServer) HandleItem(w http.ResponseWriter, req *http.Request) {
switch {
case req.Method == http.MethodDelete:
fallthrough
case req.Method == http.MethodPost && strings.ToLower(req.FormValue("action")) == "delete":
srv.HandleRemoveItem(w, req)
case req.Method == http.MethodPatch:
fallthrough
case req.Method == http.MethodPost && strings.ToLower(req.FormValue("action")) == "patch":
srv.HandleUpdateItem(w, req)
}
}
// HandleRemoveItem handles requests to remove a podcast item.
func (srv *FeedServer) HandleRemoveItem(w http.ResponseWriter, req *http.Request) {
itemID := req.URL.Path[strings.LastIndexByte(req.URL.Path, '/')+1:]
if err := srv.svc.RemoveItem(itemID); err != nil {
log.Println("failed to remove podcast item", itemID, ":", err)
}
http.Redirect(w, req, req.Referer(), http.StatusSeeOther)
}
// HandleUpdateItem handles requests to update a podcast item.
func (srv *FeedServer) HandleUpdateItem(w http.ResponseWriter, req *http.Request) {
itemID := req.URL.Path[strings.LastIndexByte(req.URL.Path, '/')+1:]
desc := Description{
Title: strings.TrimSpace(req.FormValue("title")),
Body: strings.TrimSpace(req.FormValue("description")),
}
if desc.Title == "" {
http.Error(w, "Missing title", http.StatusBadRequest)
return
}
if err := srv.svc.UpdateItem(itemID, desc); err != nil {
log.Println("failed to update podcast item", itemID, ":", err)
}
http.Redirect(w, req, req.Referer(), http.StatusSeeOther)
}
// AssetHandler returns a http.HandlerFunc that serves the given asset with the
// given content type.
func AssetHandler(asset []byte, contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", contentType)
w.Write(asset)
}
}
func reqScheme(req *http.Request) string {
if req.TLS != nil {
return "https"
}
return "http"
}
func mimeTypeToEnclosureType(mime string) podcast.EnclosureType {
kv := strings.SplitN(mime, ";", 2)
switch kv[0] {
case "audio/mp4", "audio/mp4a.20.2", "audio/x-m4a":
return podcast.M4A
case "video/mp4", "video/x-m4v":
return podcast.M4V
case "audio/mpeg":
return podcast.MP3
default:
log.Printf("unknown MIME type %s, falling back to mp3", mime)
return podcast.MP3
}
}