Add redis cache to feed route
[oweals/peertube.git] / server / controllers / feeds.ts
1 import * as express from 'express'
2 import { CONFIG, FEEDS } from '../initializers/constants'
3 import { asyncMiddleware, feedsValidator, setDefaultSort, videosSortValidator } from '../middlewares'
4 import { VideoModel } from '../models/video/video'
5 import * as Feed from 'pfeed'
6 import { ResultList } from '../../shared/models'
7 import { AccountModel } from '../models/account/account'
8 import { cacheRoute } from '../middlewares/cache'
9
10 const feedsRouter = express.Router()
11
12 feedsRouter.get('/feeds/videos.:format',
13   videosSortValidator,
14   setDefaultSort,
15   asyncMiddleware(feedsValidator),
16   asyncMiddleware(cacheRoute),
17   asyncMiddleware(generateFeed)
18 )
19
20 // ---------------------------------------------------------------------------
21
22 export {
23   feedsRouter
24 }
25
26 // ---------------------------------------------------------------------------
27
28 async function generateFeed (req: express.Request, res: express.Response, next: express.NextFunction) {
29   let feed = initFeed()
30   const start = 0
31
32   let resultList: ResultList<VideoModel>
33   const account: AccountModel = res.locals.account
34
35   if (account) {
36     resultList = await VideoModel.listAccountVideosForApi(
37       account.id,
38       start,
39       FEEDS.COUNT,
40       req.query.sort,
41       true
42     )
43   } else {
44     resultList = await VideoModel.listForApi(
45       start,
46       FEEDS.COUNT,
47       req.query.sort,
48       req.query.filter,
49       true
50     )
51   }
52
53   // Adding video items to the feed, one at a time
54   resultList.data.forEach(video => {
55     const formattedVideoFiles = video.getFormattedVideoFilesJSON()
56     const torrents = formattedVideoFiles.map(videoFile => ({
57       title: video.name,
58       url: videoFile.torrentUrl,
59       size_in_bytes: videoFile.size
60     }))
61
62     feed.addItem({
63       title: video.name,
64       id: video.url,
65       link: video.url,
66       description: video.getTruncatedDescription(),
67       content: video.description,
68       author: [
69         {
70           name: video.VideoChannel.Account.getDisplayName(),
71           link: video.VideoChannel.Account.Actor.url
72         }
73       ],
74       date: video.publishedAt,
75       language: video.language,
76       nsfw: video.nsfw,
77       torrent: torrents
78     })
79   })
80
81   // Now the feed generation is done, let's send it!
82   return sendFeed(feed, req, res)
83 }
84
85 function initFeed () {
86   const webserverUrl = CONFIG.WEBSERVER.URL
87
88   return new Feed({
89     title: CONFIG.INSTANCE.NAME,
90     description: CONFIG.INSTANCE.SHORT_DESCRIPTION,
91     // updated: TODO: somehowGetLatestUpdate, // optional, default = today
92     id: webserverUrl,
93     link: webserverUrl,
94     image: webserverUrl + '/client/assets/images/icons/icon-96x96.png',
95     favicon: webserverUrl + '/client/assets/images/favicon.png',
96     copyright: `All rights reserved, unless otherwise specified in the terms specified at ${webserverUrl}/about` +
97     ` and potential licenses granted by each content's rightholder.`,
98     generator: `Toraifōsu`, // ^.~
99     feedLinks: {
100       json: `${webserverUrl}/feeds/videos.json`,
101       atom: `${webserverUrl}/feeds/videos.atom`,
102       rss: `${webserverUrl}/feeds/videos.xml`
103     },
104     author: {
105       name: 'Instance admin of ' + CONFIG.INSTANCE.NAME,
106       email: CONFIG.ADMIN.EMAIL,
107       link: `${webserverUrl}/about`
108     }
109   })
110 }
111
112 function sendFeed (feed, req: express.Request, res: express.Response) {
113   const format = req.params.format
114
115   if (format === 'atom' || format === 'atom1') {
116     res.set('Content-Type', 'application/atom+xml')
117     return res.send(feed.atom1()).end()
118   }
119
120   if (format === 'json' || format === 'json1') {
121     res.set('Content-Type', 'application/json')
122     return res.send(feed.json1()).end()
123   }
124
125   if (format === 'rss' || format === 'rss2') {
126     res.set('Content-Type', 'application/rss+xml')
127     return res.send(feed.rss2()).end()
128   }
129
130   // We're in the ambiguous '.xml' case and we look at the format query parameter
131   if (req.query.format === 'atom' || req.query.format === 'atom1') {
132     res.set('Content-Type', 'application/atom+xml')
133     return res.send(feed.atom1()).end()
134   }
135
136   res.set('Content-Type', 'application/rss+xml')
137   return res.send(feed.rss2()).end()
138 }