Filter by category (#720)
[oweals/peertube.git] / server / controllers / feeds.ts
1 import * as express from 'express'
2 import { CONFIG, FEEDS, ROUTE_CACHE_LIFETIME } from '../initializers/constants'
3 import { asyncMiddleware, setDefaultSort, videoCommentsFeedsValidator, videoFeedsValidator, videosSortValidator } from '../middlewares'
4 import { VideoModel } from '../models/video/video'
5 import * as Feed from 'pfeed'
6 import { AccountModel } from '../models/account/account'
7 import { cacheRoute } from '../middlewares/cache'
8 import { VideoChannelModel } from '../models/video/video-channel'
9 import { VideoCommentModel } from '../models/video/video-comment'
10
11 const feedsRouter = express.Router()
12
13 feedsRouter.get('/feeds/video-comments.:format',
14   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.FEEDS)),
15   asyncMiddleware(videoCommentsFeedsValidator),
16   asyncMiddleware(generateVideoCommentsFeed)
17 )
18
19 feedsRouter.get('/feeds/videos.:format',
20   videosSortValidator,
21   setDefaultSort,
22   asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.FEEDS)),
23   asyncMiddleware(videoFeedsValidator),
24   asyncMiddleware(generateVideoFeed)
25 )
26
27 // ---------------------------------------------------------------------------
28
29 export {
30   feedsRouter
31 }
32
33 // ---------------------------------------------------------------------------
34
35 async function generateVideoCommentsFeed (req: express.Request, res: express.Response, next: express.NextFunction) {
36   const start = 0
37
38   const video = res.locals.video as VideoModel
39   const videoId: number = video ? video.id : undefined
40
41   const comments = await VideoCommentModel.listForFeed(start, FEEDS.COUNT, videoId)
42
43   const name = video ? video.name : CONFIG.INSTANCE.NAME
44   const description = video ? video.description : CONFIG.INSTANCE.DESCRIPTION
45   const feed = initFeed(name, description)
46
47   // Adding video items to the feed, one at a time
48   comments.forEach(comment => {
49     const link = CONFIG.WEBSERVER.URL + '/videos/watch/' + comment.Video.uuid + ';threadId=' + comment.getThreadId()
50
51     feed.addItem({
52       title: `${comment.Video.name} - ${comment.Account.getDisplayName()}`,
53       id: comment.url,
54       link,
55       content: comment.text,
56       author: [
57         {
58           name: comment.Account.getDisplayName(),
59           link: comment.Account.Actor.url
60         }
61       ],
62       date: comment.createdAt
63     })
64   })
65
66   // Now the feed generation is done, let's send it!
67   return sendFeed(feed, req, res)
68 }
69
70 async function generateVideoFeed (req: express.Request, res: express.Response, next: express.NextFunction) {
71   const start = 0
72
73   const account: AccountModel = res.locals.account
74   const videoChannel: VideoChannelModel = res.locals.videoChannel
75   const hideNSFW = CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list'
76
77   let name: string
78   let description: string
79
80   if (videoChannel) {
81     name = videoChannel.getDisplayName()
82     description = videoChannel.description
83   } else if (account) {
84     name = account.getDisplayName()
85     description = account.description
86   } else {
87     name = CONFIG.INSTANCE.NAME
88     description = CONFIG.INSTANCE.DESCRIPTION
89   }
90
91   const feed = initFeed(name, description)
92
93   const resultList = await VideoModel.listForApi({
94     start,
95     count: FEEDS.COUNT,
96     sort: req.query.sort,
97     hideNSFW,
98     filter: req.query.filter,
99     withFiles: true,
100     accountId: account ? account.id : null,
101     videoChannelId: videoChannel ? videoChannel.id : null
102   })
103
104   // Adding video items to the feed, one at a time
105   resultList.data.forEach(video => {
106     const formattedVideoFiles = video.getFormattedVideoFilesJSON()
107     const torrents = formattedVideoFiles.map(videoFile => ({
108       title: video.name,
109       url: videoFile.torrentUrl,
110       size_in_bytes: videoFile.size
111     }))
112
113     feed.addItem({
114       title: video.name,
115       id: video.url,
116       link: CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid,
117       description: video.getTruncatedDescription(),
118       content: video.description,
119       author: [
120         {
121           name: video.VideoChannel.Account.getDisplayName(),
122           link: video.VideoChannel.Account.Actor.url
123         }
124       ],
125       date: video.publishedAt,
126       language: video.language,
127       nsfw: video.nsfw,
128       torrent: torrents
129     })
130   })
131
132   // Now the feed generation is done, let's send it!
133   return sendFeed(feed, req, res)
134 }
135
136 function initFeed (name: string, description: string) {
137   const webserverUrl = CONFIG.WEBSERVER.URL
138
139   return new Feed({
140     title: name,
141     description,
142     // updated: TODO: somehowGetLatestUpdate, // optional, default = today
143     id: webserverUrl,
144     link: webserverUrl,
145     image: webserverUrl + '/client/assets/images/icons/icon-96x96.png',
146     favicon: webserverUrl + '/client/assets/images/favicon.png',
147     copyright: `All rights reserved, unless otherwise specified in the terms specified at ${webserverUrl}/about` +
148     ` and potential licenses granted by each content's rightholder.`,
149     generator: `Toraifōsu`, // ^.~
150     feedLinks: {
151       json: `${webserverUrl}/feeds/videos.json`,
152       atom: `${webserverUrl}/feeds/videos.atom`,
153       rss: `${webserverUrl}/feeds/videos.xml`
154     },
155     author: {
156       name: 'Instance admin of ' + CONFIG.INSTANCE.NAME,
157       email: CONFIG.ADMIN.EMAIL,
158       link: `${webserverUrl}/about`
159     }
160   })
161 }
162
163 function sendFeed (feed, req: express.Request, res: express.Response) {
164   const format = req.params.format
165
166   if (format === 'atom' || format === 'atom1') {
167     res.set('Content-Type', 'application/atom+xml')
168     return res.send(feed.atom1()).end()
169   }
170
171   if (format === 'json' || format === 'json1') {
172     res.set('Content-Type', 'application/json')
173     return res.send(feed.json1()).end()
174   }
175
176   if (format === 'rss' || format === 'rss2') {
177     res.set('Content-Type', 'application/rss+xml')
178     return res.send(feed.rss2()).end()
179   }
180
181   // We're in the ambiguous '.xml' case and we look at the format query parameter
182   if (req.query.format === 'atom' || req.query.format === 'atom1') {
183     res.set('Content-Type', 'application/atom+xml')
184     return res.send(feed.atom1()).end()
185   }
186
187   res.set('Content-Type', 'application/rss+xml')
188   return res.send(feed.rss2()).end()
189 }