]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/feeds.ts
Fix migration and test
[github/Chocobozzz/PeerTube.git] / server / controllers / feeds.ts
1 import * as express from 'express'
2 import * as Feed from 'pfeed'
3 import { buildNSFWFilter } from '../helpers/express-utils'
4 import { CONFIG } from '../initializers/config'
5 import { FEEDS, ROUTE_CACHE_LIFETIME, THUMBNAILS_SIZE, WEBSERVER } from '../initializers/constants'
6 import {
7 asyncMiddleware,
8 commonVideosFiltersValidator,
9 feedsFormatValidator,
10 setDefaultVideosSort,
11 setFeedFormatContentType,
12 videoCommentsFeedsValidator,
13 videoFeedsValidator,
14 videosSortValidator,
15 videoSubscriptionFeedsValidator
16 } from '../middlewares'
17 import { cacheRoute } from '../middlewares/cache'
18 import { VideoModel } from '../models/video/video'
19 import { VideoCommentModel } from '../models/video/video-comment'
20 import { VideoFilter } from '../../shared/models/videos/video-query.type'
21
22 const feedsRouter = express.Router()
23
24 feedsRouter.get('/feeds/video-comments.:format',
25 feedsFormatValidator,
26 setFeedFormatContentType,
27 asyncMiddleware(cacheRoute({
28 headerBlacklist: [
29 'Content-Type'
30 ]
31 })(ROUTE_CACHE_LIFETIME.FEEDS)),
32 asyncMiddleware(videoFeedsValidator),
33 asyncMiddleware(videoCommentsFeedsValidator),
34 asyncMiddleware(generateVideoCommentsFeed)
35 )
36
37 feedsRouter.get('/feeds/videos.:format',
38 videosSortValidator,
39 setDefaultVideosSort,
40 feedsFormatValidator,
41 setFeedFormatContentType,
42 asyncMiddleware(cacheRoute({
43 headerBlacklist: [
44 'Content-Type'
45 ]
46 })(ROUTE_CACHE_LIFETIME.FEEDS)),
47 commonVideosFiltersValidator,
48 asyncMiddleware(videoFeedsValidator),
49 asyncMiddleware(generateVideoFeed)
50 )
51
52 feedsRouter.get('/feeds/subscriptions.:format',
53 videosSortValidator,
54 setDefaultVideosSort,
55 feedsFormatValidator,
56 setFeedFormatContentType,
57 asyncMiddleware(cacheRoute({
58 headerBlacklist: [
59 'Content-Type'
60 ]
61 })(ROUTE_CACHE_LIFETIME.FEEDS)),
62 commonVideosFiltersValidator,
63 asyncMiddleware(videoSubscriptionFeedsValidator),
64 asyncMiddleware(generateVideoFeedForSubscriptions)
65 )
66
67 // ---------------------------------------------------------------------------
68
69 export {
70 feedsRouter
71 }
72
73 // ---------------------------------------------------------------------------
74
75 async function generateVideoCommentsFeed (req: express.Request, res: express.Response) {
76 const start = 0
77 const video = res.locals.videoAll
78 const account = res.locals.account
79 const videoChannel = res.locals.videoChannel
80
81 const comments = await VideoCommentModel.listForFeed({
82 start,
83 count: FEEDS.COUNT,
84 videoId: video ? video.id : undefined,
85 accountId: account ? account.id : undefined,
86 videoChannelId: videoChannel ? videoChannel.id : undefined
87 })
88
89 let name: string
90 let description: string
91
92 if (videoChannel) {
93 name = videoChannel.getDisplayName()
94 description = videoChannel.description
95 } else if (account) {
96 name = account.getDisplayName()
97 description = account.description
98 } else {
99 name = video ? video.name : CONFIG.INSTANCE.NAME
100 description = video ? video.description : CONFIG.INSTANCE.DESCRIPTION
101 }
102 const feed = initFeed({
103 name,
104 description,
105 resourceType: 'video-comments',
106 queryString: new URL(WEBSERVER.URL + req.originalUrl).search
107 })
108
109 // Adding video items to the feed, one at a time
110 for (const comment of comments) {
111 const link = WEBSERVER.URL + comment.getCommentStaticPath()
112
113 let title = comment.Video.name
114 const author: { name: string, link: string }[] = []
115
116 if (comment.Account) {
117 title += ` - ${comment.Account.getDisplayName()}`
118 author.push({
119 name: comment.Account.getDisplayName(),
120 link: comment.Account.Actor.url
121 })
122 }
123
124 feed.addItem({
125 title,
126 id: comment.url,
127 link,
128 content: comment.text,
129 author,
130 date: comment.createdAt
131 })
132 }
133
134 // Now the feed generation is done, let's send it!
135 return sendFeed(feed, req, res)
136 }
137
138 async function generateVideoFeed (req: express.Request, res: express.Response) {
139 const start = 0
140 const account = res.locals.account
141 const videoChannel = res.locals.videoChannel
142 const nsfw = buildNSFWFilter(res, req.query.nsfw)
143
144 let name: string
145 let description: string
146
147 if (videoChannel) {
148 name = videoChannel.getDisplayName()
149 description = videoChannel.description
150 } else if (account) {
151 name = account.getDisplayName()
152 description = account.description
153 } else {
154 name = CONFIG.INSTANCE.NAME
155 description = CONFIG.INSTANCE.DESCRIPTION
156 }
157
158 const feed = initFeed({
159 name,
160 description,
161 resourceType: 'videos',
162 queryString: new URL(WEBSERVER.URL + req.url).search
163 })
164
165 const options = {
166 accountId: account ? account.id : null,
167 videoChannelId: videoChannel ? videoChannel.id : null
168 }
169
170 const resultList = await VideoModel.listForApi({
171 start,
172 count: FEEDS.COUNT,
173 sort: req.query.sort,
174 includeLocalVideos: true,
175 nsfw,
176 filter: req.query.filter as VideoFilter,
177 withFiles: true,
178 ...options
179 })
180
181 addVideosToFeed(feed, resultList.data)
182
183 // Now the feed generation is done, let's send it!
184 return sendFeed(feed, req, res)
185 }
186
187 async function generateVideoFeedForSubscriptions (req: express.Request, res: express.Response) {
188 const start = 0
189 const account = res.locals.account
190 const nsfw = buildNSFWFilter(res, req.query.nsfw)
191 const name = account.getDisplayName()
192 const description = account.description
193
194 const feed = initFeed({
195 name,
196 description,
197 resourceType: 'videos',
198 queryString: new URL(WEBSERVER.URL + req.url).search
199 })
200
201 const resultList = await VideoModel.listForApi({
202 start,
203 count: FEEDS.COUNT,
204 sort: req.query.sort,
205 includeLocalVideos: false,
206 nsfw,
207 filter: req.query.filter as VideoFilter,
208 withFiles: true,
209
210 followerActorId: res.locals.user.Account.Actor.id,
211 user: res.locals.user
212 })
213
214 addVideosToFeed(feed, resultList.data)
215
216 // Now the feed generation is done, let's send it!
217 return sendFeed(feed, req, res)
218 }
219
220 function initFeed (parameters: {
221 name: string
222 description: string
223 resourceType?: 'videos' | 'video-comments'
224 queryString?: string
225 }) {
226 const webserverUrl = WEBSERVER.URL
227 const { name, description, resourceType, queryString } = parameters
228
229 return new Feed({
230 title: name,
231 description,
232 // updated: TODO: somehowGetLatestUpdate, // optional, default = today
233 id: webserverUrl,
234 link: webserverUrl,
235 image: webserverUrl + '/client/assets/images/icons/icon-96x96.png',
236 favicon: webserverUrl + '/client/assets/images/favicon.png',
237 copyright: `All rights reserved, unless otherwise specified in the terms specified at ${webserverUrl}/about` +
238 ` and potential licenses granted by each content's rightholder.`,
239 generator: `Toraifōsu`, // ^.~
240 feedLinks: {
241 json: `${webserverUrl}/feeds/${resourceType}.json${queryString}`,
242 atom: `${webserverUrl}/feeds/${resourceType}.atom${queryString}`,
243 rss: `${webserverUrl}/feeds/${resourceType}.xml${queryString}`
244 },
245 author: {
246 name: 'Instance admin of ' + CONFIG.INSTANCE.NAME,
247 email: CONFIG.ADMIN.EMAIL,
248 link: `${webserverUrl}/about`
249 }
250 })
251 }
252
253 function addVideosToFeed (feed, videos: VideoModel[]) {
254 /**
255 * Adding video items to the feed object, one at a time
256 */
257 for (const video of videos) {
258 const formattedVideoFiles = video.getFormattedVideoFilesJSON()
259
260 const torrents = formattedVideoFiles.map(videoFile => ({
261 title: video.name,
262 url: videoFile.torrentUrl,
263 size_in_bytes: videoFile.size
264 }))
265
266 const videos = formattedVideoFiles.map(videoFile => {
267 const result = {
268 type: 'video/mp4',
269 medium: 'video',
270 height: videoFile.resolution.label.replace('p', ''),
271 fileSize: videoFile.size,
272 url: videoFile.fileUrl,
273 framerate: videoFile.fps,
274 duration: video.duration
275 }
276
277 if (video.language) Object.assign(result, { lang: video.language })
278
279 return result
280 })
281
282 const categories: { value: number, label: string }[] = []
283 if (video.category) {
284 categories.push({
285 value: video.category,
286 label: VideoModel.getCategoryLabel(video.category)
287 })
288 }
289
290 feed.addItem({
291 title: video.name,
292 id: video.url,
293 link: WEBSERVER.URL + '/videos/watch/' + video.uuid,
294 description: video.getTruncatedDescription(),
295 content: video.description,
296 author: [
297 {
298 name: video.VideoChannel.Account.getDisplayName(),
299 link: video.VideoChannel.Account.Actor.url
300 }
301 ],
302 date: video.publishedAt,
303 nsfw: video.nsfw,
304 torrent: torrents,
305 videos,
306 embed: {
307 url: video.getEmbedStaticPath(),
308 allowFullscreen: true
309 },
310 player: {
311 url: video.getWatchStaticPath()
312 },
313 categories,
314 community: {
315 statistics: {
316 views: video.views
317 }
318 },
319 thumbnail: [
320 {
321 url: WEBSERVER.URL + video.getMiniatureStaticPath(),
322 height: THUMBNAILS_SIZE.height,
323 width: THUMBNAILS_SIZE.width
324 }
325 ]
326 })
327 }
328 }
329
330 function sendFeed (feed, req: express.Request, res: express.Response) {
331 const format = req.params.format
332
333 if (format === 'atom' || format === 'atom1') {
334 return res.send(feed.atom1()).end()
335 }
336
337 if (format === 'json' || format === 'json1') {
338 return res.send(feed.json1()).end()
339 }
340
341 if (format === 'rss' || format === 'rss2') {
342 return res.send(feed.rss2()).end()
343 }
344
345 // We're in the ambiguous '.xml' case and we look at the format query parameter
346 if (req.query.format === 'atom' || req.query.format === 'atom1') {
347 return res.send(feed.atom1()).end()
348 }
349
350 return res.send(feed.rss2()).end()
351 }