-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
363 lines (315 loc) · 10.2 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package main
import (
"encoding/xml"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
)
var (
playlistCache = make(map[string]*PlaylistCacheItem)
cacheMutex sync.RWMutex
cacheExpiry time.Duration // Cache expiration duration
)
type Server struct {
apiUrl string
youtubeApiKey string
filterPattern string
convertToMp3 bool
}
// RSSFeed represents the structure of the RSS feed
type RSSFeed struct {
XMLName xml.Name `xml:"rss"`
Version string `xml:"version,attr"`
Channel RSSChannel `xml:"channel"`
}
type RSSChannel struct {
Title string `xml:"title"`
Description string `xml:"description"`
Link string `xml:"link"`
Image RSSImage `xml:"image"`
Items []RSSItem `xml:"item"`
}
type RSSImage struct {
URL string `xml:"url"`
Title string `xml:"title"`
Link string `xml:"link"`
}
type RSSItem struct {
Title string `xml:"title"`
Description string `xml:"description"`
Link string `xml:"link"`
GUID string `xml:"guid"`
Enclosure struct {
URL string `xml:"url,attr"`
Length string `xml:"length,attr"`
Type string `xml:"type,attr"`
} `xml:"enclosure"`
}
// Cache for playlist data
type PlaylistCacheItem struct {
Playlist *youtube.Playlist
PlaylistItems []*youtube.PlaylistItem
FetchedAt time.Time
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.handleRequest(w, r)
}
func (s *Server) handleRequest(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/health" {
s.healthCheck(w)
return
}
if len(path) < 2 {
http.NotFound(w, r)
return
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) == 1 && strings.HasSuffix(parts[0], ".xml") {
slug := strings.TrimSuffix(parts[0], ".xml")
log.Printf("Received RSS feed request for slug: %s", slug)
s.serveRSSFeed(w, r, slug)
} else if len(parts) == 2 {
slug, videoID := parts[0], parts[1]
log.Printf("Received audio request for slug: %s, videoID: %s", slug, videoID)
s.serveAudio(w, r, videoID)
} else {
http.NotFound(w, r)
}
}
func (s *Server) healthCheck(w http.ResponseWriter) {
w.WriteHeader(http.StatusOK)
}
func (s *Server) serveRSSFeed(w http.ResponseWriter, r *http.Request, slug string) {
playlistItems, playlist, err := s.getPlaylistItemsCached(slug, s.youtubeApiKey, r)
if err != nil {
http.Error(w, "Error fetching playlist items", http.StatusInternalServerError)
log.Printf("Error fetching playlist items for slug %s: %v", slug, err)
return
}
filteredItems := s.filterVideos(playlistItems)
rssFeed := s.generateRSSFeed(playlist, filteredItems, slug)
w.Header().Set("Content-Type", "application/rss+xml")
xmlData, err := xml.MarshalIndent(rssFeed, "", " ")
if err != nil {
http.Error(w, "Error generating RSS feed", http.StatusInternalServerError)
log.Printf("Error generating RSS feed for slug %s: %v", slug, err)
return
}
if _, err := w.Write([]byte(xml.Header)); err != nil {
http.Error(w, "Error generating RSS feed", http.StatusInternalServerError)
log.Printf("Error generating RSS feed for slug %s: %v", slug, err)
return
}
if _, err := w.Write(xmlData); err != nil {
http.Error(w, "Error generating RSS feed", http.StatusInternalServerError)
log.Printf("Error generating RSS feed for slug %s: %v", slug, err)
}
log.Printf("Served RSS feed for slug: %s", slug)
}
// Get playlist items with cache handling
func (s *Server) getPlaylistItemsCached(slug string, apiKey string, r *http.Request) ([]*youtube.PlaylistItem, *youtube.Playlist, error) {
cacheMutex.RLock()
cacheItem, cached := playlistCache[slug]
cacheMutex.RUnlock()
if cached && time.Since(cacheItem.FetchedAt) < cacheExpiry {
log.Printf("Using cached playlist items for slug: %s", slug)
return cacheItem.PlaylistItems, cacheItem.Playlist, nil
}
log.Printf("Fetching playlist items from YouTube API for slug: %s", slug)
ytService, err := youtube.NewService(r.Context(), option.WithAPIKey(apiKey))
if err != nil {
log.Printf("Error creating YouTube service: %v", err)
return nil, nil, err
}
// Fetch the playlist
playlist, err := fetchPlaylist(ytService, slug)
if err != nil {
log.Printf("Error fetching playlist for slug %s: %v", slug, err)
return nil, nil, err
}
playlistItems, err := fetchPlaylistItems(ytService, slug)
if err != nil {
log.Printf("Error fetching playlist items for slug %s: %v", slug, err)
return nil, nil, err
}
// Update the cache
cacheMutex.Lock()
playlistCache[slug] = &PlaylistCacheItem{
Playlist: playlist,
PlaylistItems: playlistItems,
FetchedAt: time.Now(),
}
cacheMutex.Unlock()
log.Printf("Updated cache for slug: %s", slug)
return playlistItems, playlist, nil
}
func fetchPlaylist(ytService *youtube.Service, playlistID string) (*youtube.Playlist, error) {
call := ytService.Playlists.List([]string{"snippet"}).Id(playlistID)
response, err := call.Do()
if err != nil {
log.Printf("Error fetching playlist from YouTube API: %v", err)
return nil, err
}
if len(response.Items) == 0 {
log.Printf("No playlist found with ID: %s", playlistID)
return nil, fmt.Errorf("no playlist found with ID: %s", playlistID)
}
return response.Items[0], nil
}
func fetchPlaylistItems(ytService *youtube.Service, playlistID string) ([]*youtube.PlaylistItem, error) {
var allItems []*youtube.PlaylistItem
nextPageToken := ""
for {
call := ytService.PlaylistItems.List([]string{"snippet"}).
PlaylistId(playlistID).
MaxResults(50).
PageToken(nextPageToken)
response, err := call.Do()
if err != nil {
log.Printf("Error fetching playlist items from YouTube API: %v", err)
return nil, err
}
allItems = append(allItems, response.Items...)
if response.NextPageToken == "" {
break
}
nextPageToken = response.NextPageToken
}
log.Printf("Fetched %d playlist items from YouTube API for playlistID: %s", len(allItems), playlistID)
return allItems, nil
}
func (s *Server) filterVideos(items []*youtube.PlaylistItem) []*youtube.PlaylistItem {
if s.filterPattern == "" {
return items
}
filtered := make([]*youtube.PlaylistItem, 0)
regex := regexp.MustCompile(s.filterPattern)
for _, item := range items {
title := item.Snippet.Title
if regex.MatchString(title) {
filtered = append(filtered, item)
}
}
log.Printf("Filtered %d videos out of %d using pattern: %s", len(filtered), len(items), s.filterPattern)
// Revert the list so new episodes show first
for i, j := 0, len(filtered)-1; i < j; i, j = i+1, j-1 {
filtered[i], filtered[j] = filtered[j], filtered[i]
}
return filtered
}
func (s *Server) generateRSSFeed(playlist *youtube.Playlist, items []*youtube.PlaylistItem, slug string) RSSFeed {
var rssItems []RSSItem
for _, item := range items {
videoID := item.Snippet.ResourceId.VideoId
rssItem := RSSItem{
Title: item.Snippet.Title,
Description: item.Snippet.Description,
Link: fmt.Sprintf("https://www.youtube.com/watch?v=%s", videoID),
GUID: videoID,
Enclosure: struct {
URL string `xml:"url,attr"`
Length string `xml:"length,attr"`
Type string `xml:"type,attr"`
}{
URL: fmt.Sprintf("%s/%s/%s", s.apiUrl, slug, videoID),
Length: "0",
Type: "audio/mpeg",
},
}
rssItems = append(rssItems, rssItem)
}
// Get the image URL from the playlist
var imageUrl string
if playlist.Snippet.Thumbnails != nil {
if playlist.Snippet.Thumbnails.High != nil {
imageUrl = playlist.Snippet.Thumbnails.High.Url
} else if playlist.Snippet.Thumbnails.Medium != nil {
imageUrl = playlist.Snippet.Thumbnails.Medium.Url
} else if playlist.Snippet.Thumbnails.Default != nil {
imageUrl = playlist.Snippet.Thumbnails.Default.Url
}
}
feed := RSSFeed{
Version: "2.0",
Channel: RSSChannel{
Title: playlist.Snippet.Title,
Description: playlist.Snippet.Description,
Link: fmt.Sprintf("%s/%s.xml", s.apiUrl, slug),
Image: RSSImage{
URL: imageUrl,
Title: playlist.Snippet.Title,
Link: fmt.Sprintf("%s/%s.xml", s.apiUrl, slug),
},
Items: rssItems,
},
}
log.Printf("Generated RSS feed with %d items for slug: %s", len(rssItems), slug)
return feed
}
func (s *Server) serveAudio(w http.ResponseWriter, r *http.Request, videoID string) {
var ext string
if s.convertToMp3 {
ext = "mp3"
} else {
ext = "m4a"
}
audioFilePath := filepath.Join(audioDir, fmt.Sprintf("%s.%s", videoID, ext))
if _, err := os.Stat(audioFilePath); os.IsNotExist(err) {
log.Printf("Audio file not found in cache, downloading videoID: %s", videoID)
err := s.downloadAudio(videoID, audioFilePath)
if err != nil {
http.Error(w, "Error downloading audio", http.StatusInternalServerError)
log.Printf("Error downloading audio for videoID %s: %v", videoID, err)
return
}
} else {
log.Printf("Serving cached audio file for videoID: %s", videoID)
}
// Open the audio file
audioFile, err := os.Open(audioFilePath)
if err != nil {
http.Error(w, "Error opening audio file", http.StatusInternalServerError)
log.Printf("Error opening audio file for videoID %s: %v", videoID, err)
return
}
defer audioFile.Close()
// Get file info
stat, err := audioFile.Stat()
if err != nil {
http.Error(w, "Error getting file info", http.StatusInternalServerError)
log.Printf("Error getting file info for videoID %s: %v", videoID, err)
return
}
// Serve the file with support for Range requests
http.ServeContent(w, r, stat.Name(), stat.ModTime(), audioFile)
}
func (s *Server) downloadAudio(videoID string, outputPath string) error {
videoUrl := fmt.Sprintf("https://www.youtube.com/watch?v=%s", videoID)
var cmd *exec.Cmd
if s.convertToMp3 {
cmd = exec.Command("yt-dlp", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "-o", outputPath, videoUrl)
} else {
cmd = exec.Command("yt-dlp", "-f", "bestaudio[ext=m4a]", "-o", outputPath, videoUrl)
}
// Set stdout and stderr to be real-time output
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Printf("Running yt-dlp command for videoID: %s", videoID)
err := cmd.Run()
if err != nil {
log.Printf("yt-dlp error for videoID %s: %v", videoID, err)
return err
}
log.Printf("Successfully downloaded audio for videoID: %s", videoID)
return nil
}