]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Merge branch 'release/3.2.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import * as express from 'express'
2 import toInt from 'validator/lib/toInt'
3 import { LiveManager } from '@server/lib/live-manager'
4 import { getServerActor } from '@server/models/application/application'
5 import { VideosCommonQuery } from '../../../../shared'
6 import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
7 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
8 import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
9 import { logger } from '../../../helpers/logger'
10 import { getFormattedObjects } from '../../../helpers/utils'
11 import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
12 import { sequelizeTypescript } from '../../../initializers/database'
13 import { sendView } from '../../../lib/activitypub/send/send-view'
14 import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
15 import { JobQueue } from '../../../lib/job-queue'
16 import { Hooks } from '../../../lib/plugins/hooks'
17 import { Redis } from '../../../lib/redis'
18 import {
19 asyncMiddleware,
20 asyncRetryTransactionMiddleware,
21 authenticate,
22 checkVideoFollowConstraints,
23 commonVideosFiltersValidator,
24 optionalAuthenticate,
25 paginationValidator,
26 setDefaultPagination,
27 setDefaultVideosSort,
28 videoFileMetadataGetValidator,
29 videosCustomGetValidator,
30 videosGetValidator,
31 videosRemoveValidator,
32 videosSortValidator
33 } from '../../../middlewares'
34 import { VideoModel } from '../../../models/video/video'
35 import { VideoFileModel } from '../../../models/video/video-file'
36 import { blacklistRouter } from './blacklist'
37 import { videoCaptionsRouter } from './captions'
38 import { videoCommentRouter } from './comment'
39 import { videoImportsRouter } from './import'
40 import { liveRouter } from './live'
41 import { ownershipVideoRouter } from './ownership'
42 import { rateVideoRouter } from './rate'
43 import { updateRouter } from './update'
44 import { uploadRouter } from './upload'
45 import { watchingRouter } from './watching'
46
47 const auditLogger = auditLoggerFactory('videos')
48 const videosRouter = express.Router()
49
50 videosRouter.use('/', blacklistRouter)
51 videosRouter.use('/', rateVideoRouter)
52 videosRouter.use('/', videoCommentRouter)
53 videosRouter.use('/', videoCaptionsRouter)
54 videosRouter.use('/', videoImportsRouter)
55 videosRouter.use('/', ownershipVideoRouter)
56 videosRouter.use('/', watchingRouter)
57 videosRouter.use('/', liveRouter)
58 videosRouter.use('/', uploadRouter)
59 videosRouter.use('/', updateRouter)
60
61 videosRouter.get('/categories', listVideoCategories)
62 videosRouter.get('/licences', listVideoLicences)
63 videosRouter.get('/languages', listVideoLanguages)
64 videosRouter.get('/privacies', listVideoPrivacies)
65
66 videosRouter.get('/',
67 paginationValidator,
68 videosSortValidator,
69 setDefaultVideosSort,
70 setDefaultPagination,
71 optionalAuthenticate,
72 commonVideosFiltersValidator,
73 asyncMiddleware(listVideos)
74 )
75
76 videosRouter.get('/:id/description',
77 asyncMiddleware(videosGetValidator),
78 asyncMiddleware(getVideoDescription)
79 )
80 videosRouter.get('/:id/metadata/:videoFileId',
81 asyncMiddleware(videoFileMetadataGetValidator),
82 asyncMiddleware(getVideoFileMetadata)
83 )
84 videosRouter.get('/:id',
85 optionalAuthenticate,
86 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
87 asyncMiddleware(checkVideoFollowConstraints),
88 asyncMiddleware(getVideo)
89 )
90 videosRouter.post('/:id/views',
91 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
92 asyncMiddleware(viewVideo)
93 )
94
95 videosRouter.delete('/:id',
96 authenticate,
97 asyncMiddleware(videosRemoveValidator),
98 asyncRetryTransactionMiddleware(removeVideo)
99 )
100
101 // ---------------------------------------------------------------------------
102
103 export {
104 videosRouter
105 }
106
107 // ---------------------------------------------------------------------------
108
109 function listVideoCategories (_req: express.Request, res: express.Response) {
110 res.json(VIDEO_CATEGORIES)
111 }
112
113 function listVideoLicences (_req: express.Request, res: express.Response) {
114 res.json(VIDEO_LICENCES)
115 }
116
117 function listVideoLanguages (_req: express.Request, res: express.Response) {
118 res.json(VIDEO_LANGUAGES)
119 }
120
121 function listVideoPrivacies (_req: express.Request, res: express.Response) {
122 res.json(VIDEO_PRIVACIES)
123 }
124
125 async function getVideo (_req: express.Request, res: express.Response) {
126 // We need more attributes
127 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
128
129 const video = await Hooks.wrapPromiseFun(
130 VideoModel.loadForGetAPI,
131 { id: res.locals.onlyVideoWithRights.id, userId },
132 'filter:api.video.get.result'
133 )
134
135 if (video.isOutdated()) {
136 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
137 }
138
139 return res.json(video.toFormattedDetailsJSON())
140 }
141
142 async function viewVideo (req: express.Request, res: express.Response) {
143 const immutableVideoAttrs = res.locals.onlyImmutableVideo
144
145 const ip = req.ip
146 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
147 if (exists) {
148 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
149 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
150 }
151
152 const video = await VideoModel.load(immutableVideoAttrs.id)
153
154 const promises: Promise<any>[] = [
155 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
156 ]
157
158 let federateView = true
159
160 // Increment our live manager
161 if (video.isLive && video.isOwned()) {
162 LiveManager.Instance.addViewTo(video.id)
163
164 // Views of our local live will be sent by our live manager
165 federateView = false
166 }
167
168 // Increment our video views cache counter
169 if (!video.isLive) {
170 promises.push(Redis.Instance.addVideoView(video.id))
171 }
172
173 if (federateView) {
174 const serverActor = await getServerActor()
175 promises.push(sendView(serverActor, video, undefined))
176 }
177
178 await Promise.all(promises)
179
180 Hooks.runAction('action:api.video.viewed', { video, ip })
181
182 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
183 }
184
185 async function getVideoDescription (req: express.Request, res: express.Response) {
186 const videoInstance = res.locals.videoAll
187
188 const description = videoInstance.isOwned()
189 ? videoInstance.description
190 : await fetchRemoteVideoDescription(videoInstance)
191
192 return res.json({ description })
193 }
194
195 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
196 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
197
198 return res.json(videoFile.metadata)
199 }
200
201 async function listVideos (req: express.Request, res: express.Response) {
202 const query = req.query as VideosCommonQuery
203 const countVideos = getCountVideos(req)
204
205 const apiOptions = await Hooks.wrapObject({
206 start: query.start,
207 count: query.count,
208 sort: query.sort,
209 includeLocalVideos: true,
210 categoryOneOf: query.categoryOneOf,
211 licenceOneOf: query.licenceOneOf,
212 languageOneOf: query.languageOneOf,
213 tagsOneOf: query.tagsOneOf,
214 tagsAllOf: query.tagsAllOf,
215 nsfw: buildNSFWFilter(res, query.nsfw),
216 isLive: query.isLive,
217 filter: query.filter,
218 withFiles: false,
219 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
220 countVideos
221 }, 'filter:api.videos.list.params')
222
223 const resultList = await Hooks.wrapPromiseFun(
224 VideoModel.listForApi,
225 apiOptions,
226 'filter:api.videos.list.result'
227 )
228
229 return res.json(getFormattedObjects(resultList.data, resultList.total))
230 }
231
232 async function removeVideo (_req: express.Request, res: express.Response) {
233 const videoInstance = res.locals.videoAll
234
235 await sequelizeTypescript.transaction(async t => {
236 await videoInstance.destroy({ transaction: t })
237 })
238
239 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
240 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
241
242 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
243
244 return res.type('json')
245 .status(HttpStatusCode.NO_CONTENT_204)
246 .end()
247 }