1 import express from 'express'
2 import { extname } from 'path'
3 import { Feed } from '@peertube/feed'
4 import { mdToOneLinePlainText, toSafeHtml } from '@server/helpers/markdown'
5 import { getServerActor } from '@server/models/application/application'
6 import { getCategoryLabel } from '@server/models/video/formatter/video-format-utils'
7 import { MAccountDefault, MChannelBannerAccountDefault, MVideoFullLight } from '@server/types/models'
8 import { ActorImageType, VideoInclude } from '@shared/models'
9 import { buildNSFWFilter } from '../helpers/express-utils'
10 import { CONFIG } from '../initializers/config'
11 import { MIMETYPES, PREVIEWS_SIZE, ROUTE_CACHE_LIFETIME, WEBSERVER } from '../initializers/constants'
14 commonVideosFiltersValidator,
17 setFeedFormatContentType,
18 videoCommentsFeedsValidator,
21 videoSubscriptionFeedsValidator
22 } from '../middlewares'
23 import { cacheRouteFactory } from '../middlewares/cache/cache'
24 import { VideoModel } from '../models/video/video'
25 import { VideoCommentModel } from '../models/video/video-comment'
27 const feedsRouter = express.Router()
29 const cacheRoute = cacheRouteFactory({
30 headerBlacklist: [ 'Content-Type' ]
33 feedsRouter.get('/feeds/video-comments.:format',
35 setFeedFormatContentType,
36 cacheRoute(ROUTE_CACHE_LIFETIME.FEEDS),
37 asyncMiddleware(videoFeedsValidator),
38 asyncMiddleware(videoCommentsFeedsValidator),
39 asyncMiddleware(generateVideoCommentsFeed)
42 feedsRouter.get('/feeds/videos.:format',
46 setFeedFormatContentType,
47 cacheRoute(ROUTE_CACHE_LIFETIME.FEEDS),
48 commonVideosFiltersValidator,
49 asyncMiddleware(videoFeedsValidator),
50 asyncMiddleware(generateVideoFeed)
53 feedsRouter.get('/feeds/subscriptions.:format',
57 setFeedFormatContentType,
58 cacheRoute(ROUTE_CACHE_LIFETIME.FEEDS),
59 commonVideosFiltersValidator,
60 asyncMiddleware(videoSubscriptionFeedsValidator),
61 asyncMiddleware(generateVideoFeedForSubscriptions)
64 // ---------------------------------------------------------------------------
70 // ---------------------------------------------------------------------------
72 async function generateVideoCommentsFeed (req: express.Request, res: express.Response) {
74 const video = res.locals.videoAll
75 const account = res.locals.account
76 const videoChannel = res.locals.videoChannel
78 const comments = await VideoCommentModel.listForFeed({
80 count: CONFIG.FEEDS.COMMENTS.COUNT,
81 videoId: video ? video.id : undefined,
82 accountId: account ? account.id : undefined,
83 videoChannelId: videoChannel ? videoChannel.id : undefined
86 const { name, description, imageUrl } = buildFeedMetadata({ video, account, videoChannel })
88 const feed = initFeed({
92 resourceType: 'video-comments',
93 queryString: new URL(WEBSERVER.URL + req.originalUrl).search
96 // Adding video items to the feed, one at a time
97 for (const comment of comments) {
98 const localLink = WEBSERVER.URL + comment.getCommentStaticPath()
100 let title = comment.Video.name
101 const author: { name: string, link: string }[] = []
103 if (comment.Account) {
104 title += ` - ${comment.Account.getDisplayName()}`
106 name: comment.Account.getDisplayName(),
107 link: comment.Account.Actor.url
115 content: toSafeHtml(comment.text),
117 date: comment.createdAt
121 // Now the feed generation is done, let's send it!
122 return sendFeed(feed, req, res)
125 async function generateVideoFeed (req: express.Request, res: express.Response) {
127 const account = res.locals.account
128 const videoChannel = res.locals.videoChannel
129 const nsfw = buildNSFWFilter(res, req.query.nsfw)
131 const { name, description, imageUrl } = buildFeedMetadata({ videoChannel, account })
133 const feed = initFeed({
137 resourceType: 'videos',
138 queryString: new URL(WEBSERVER.URL + req.url).search
142 accountId: account ? account.id : null,
143 videoChannelId: videoChannel ? videoChannel.id : null
146 const server = await getServerActor()
147 const { data } = await VideoModel.listForApi({
149 count: CONFIG.FEEDS.VIDEOS.COUNT,
150 sort: req.query.sort,
151 displayOnlyForFollower: {
156 isLocal: req.query.isLocal,
157 include: req.query.include | VideoInclude.FILES,
163 addVideosToFeed(feed, data)
165 // Now the feed generation is done, let's send it!
166 return sendFeed(feed, req, res)
169 async function generateVideoFeedForSubscriptions (req: express.Request, res: express.Response) {
171 const account = res.locals.account
172 const nsfw = buildNSFWFilter(res, req.query.nsfw)
174 const { name, description, imageUrl } = buildFeedMetadata({ account })
176 const feed = initFeed({
180 resourceType: 'videos',
181 queryString: new URL(WEBSERVER.URL + req.url).search
184 const { data } = await VideoModel.listForApi({
186 count: CONFIG.FEEDS.VIDEOS.COUNT,
187 sort: req.query.sort,
190 isLocal: req.query.isLocal,
193 include: req.query.include | VideoInclude.FILES,
197 displayOnlyForFollower: {
198 actorId: res.locals.user.Account.Actor.id,
201 user: res.locals.user
204 addVideosToFeed(feed, data)
206 // Now the feed generation is done, let's send it!
207 return sendFeed(feed, req, res)
210 function initFeed (parameters: {
214 resourceType?: 'videos' | 'video-comments'
217 const webserverUrl = WEBSERVER.URL
218 const { name, description, resourceType, queryString, imageUrl } = parameters
222 description: mdToOneLinePlainText(description),
223 // updated: TODO: somehowGetLatestUpdate, // optional, default = today
227 favicon: webserverUrl + '/client/assets/images/favicon.png',
228 copyright: `All rights reserved, unless otherwise specified in the terms specified at ${webserverUrl}/about` +
229 ` and potential licenses granted by each content's rightholder.`,
230 generator: `ToraifÅsu`, // ^.~
232 json: `${webserverUrl}/feeds/${resourceType}.json${queryString}`,
233 atom: `${webserverUrl}/feeds/${resourceType}.atom${queryString}`,
234 rss: `${webserverUrl}/feeds/${resourceType}.xml${queryString}`
237 name: 'Instance admin of ' + CONFIG.INSTANCE.NAME,
238 email: CONFIG.ADMIN.EMAIL,
239 link: `${webserverUrl}/about`
244 function addVideosToFeed (feed: Feed, videos: VideoModel[]) {
245 for (const video of videos) {
246 const formattedVideoFiles = video.getFormattedVideoFilesJSON(false)
248 const torrents = formattedVideoFiles.map(videoFile => ({
250 url: videoFile.torrentUrl,
251 size_in_bytes: videoFile.size
254 const videoFiles = formattedVideoFiles.map(videoFile => {
256 type: MIMETYPES.VIDEO.EXT_MIMETYPE[extname(videoFile.fileUrl)],
258 height: videoFile.resolution.id,
259 fileSize: videoFile.size,
260 url: videoFile.fileUrl,
261 framerate: videoFile.fps,
262 duration: video.duration
265 if (video.language) Object.assign(result, { lang: video.language })
270 const categories: { value: number, label: string }[] = []
271 if (video.category) {
273 value: video.category,
274 label: getCategoryLabel(video.category)
278 const localLink = WEBSERVER.URL + video.getWatchStaticPath()
284 description: mdToOneLinePlainText(video.getTruncatedDescription()),
285 content: toSafeHtml(video.description),
288 name: video.VideoChannel.getDisplayName(),
289 link: video.VideoChannel.Actor.url
292 date: video.publishedAt,
297 video: videoFiles.length !== 0
299 url: videoFiles[0].url,
300 length: videoFiles[0].fileSize,
301 type: videoFiles[0].type
309 url: WEBSERVER.URL + video.getEmbedStaticPath(),
310 allowFullscreen: true
313 url: WEBSERVER.URL + video.getWatchStaticPath()
323 url: WEBSERVER.URL + video.getPreviewStaticPath(),
324 height: PREVIEWS_SIZE.height,
325 width: PREVIEWS_SIZE.width
332 function sendFeed (feed: Feed, req: express.Request, res: express.Response) {
333 const format = req.params.format
335 if (format === 'atom' || format === 'atom1') {
336 return res.send(feed.atom1()).end()
339 if (format === 'json' || format === 'json1') {
340 return res.send(feed.json1()).end()
343 if (format === 'rss' || format === 'rss2') {
344 return res.send(feed.rss2()).end()
347 // We're in the ambiguous '.xml' case and we look at the format query parameter
348 if (req.query.format === 'atom' || req.query.format === 'atom1') {
349 return res.send(feed.atom1()).end()
352 return res.send(feed.rss2()).end()
355 function buildFeedMetadata (options: {
356 videoChannel?: MChannelBannerAccountDefault
357 account?: MAccountDefault
358 video?: MVideoFullLight
360 const { video, videoChannel, account } = options
362 let imageUrl = WEBSERVER.URL + '/client/assets/images/icons/icon-96x96.png'
364 let description: string
367 name = videoChannel.getDisplayName()
368 description = videoChannel.description
370 if (videoChannel.Actor.hasImage(ActorImageType.AVATAR)) {
371 imageUrl = WEBSERVER.URL + videoChannel.Actor.Avatars[0].getStaticPath()
373 } else if (account) {
374 name = account.getDisplayName()
375 description = account.description
377 if (account.Actor.hasImage(ActorImageType.AVATAR)) {
378 imageUrl = WEBSERVER.URL + account.Actor.Avatars[0].getStaticPath()
382 description = video.description
384 name = CONFIG.INSTANCE.NAME
385 description = CONFIG.INSTANCE.DESCRIPTION
388 return { name, description, imageUrl }