]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
increase waitJobs pendingJobs timeout to 2000
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
93e1258c 2import { extname, join } from 'path'
2186386c 3import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
3a6f351b 4import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
ac81d1a0 5import { processImage } from '../../../helpers/image-utils'
da854ddd 6import { logger } from '../../../helpers/logger'
993cef4b 7import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
06215f15 8import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
65fcc311 9import {
14e2014a 10 CONFIG, MIMETYPES,
ac81d1a0
C
11 PREVIEWS_SIZE,
12 sequelizeTypescript,
13 THUMBNAILS_SIZE,
14 VIDEO_CATEGORIES,
15 VIDEO_LANGUAGES,
16 VIDEO_LICENCES,
3fd3ab2d
C
17 VIDEO_PRIVACIES
18} from '../../../initializers'
0f320037
C
19import {
20 changeVideoChannelShare,
2186386c 21 federateVideoIfNeeded,
0f320037 22 fetchRemoteVideoDescription,
2186386c 23 getVideoActivityPubUrl
0f320037 24} from '../../../lib/activitypub'
2186386c 25import { sendCreateView } from '../../../lib/activitypub/send'
94a5ff8a 26import { JobQueue } from '../../../lib/job-queue'
b5c0e955 27import { Redis } from '../../../lib/redis'
65fcc311 28import {
ac81d1a0 29 asyncMiddleware,
90d4bb81 30 asyncRetryTransactionMiddleware,
ac81d1a0 31 authenticate,
8d427346 32 checkVideoFollowConstraints,
d525fc39 33 commonVideosFiltersValidator,
0883b324 34 optionalAuthenticate,
ac81d1a0
C
35 paginationValidator,
36 setDefaultPagination,
37 setDefaultSort,
38 videosAddValidator,
39 videosGetValidator,
40 videosRemoveValidator,
ac81d1a0
C
41 videosSortValidator,
42 videosUpdateValidator
65fcc311 43} from '../../../middlewares'
3fd3ab2d
C
44import { TagModel } from '../../../models/video/tag'
45import { VideoModel } from '../../../models/video/video'
46import { VideoFileModel } from '../../../models/video/video-file'
65fcc311
C
47import { abuseVideoRouter } from './abuse'
48import { blacklistRouter } from './blacklist'
bf1f6508 49import { videoCommentRouter } from './comment'
571389d4 50import { rateVideoRouter } from './rate'
74d63469 51import { ownershipVideoRouter } from './ownership'
0883b324 52import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
06215f15 53import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
2baea0c7 54import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
40e87e9e 55import { videoCaptionsRouter } from './captions'
fbad87b0 56import { videoImportsRouter } from './import'
06215f15 57import { resetSequelizeInstance } from '../../../helpers/database-utils'
14e2014a 58import { move } from 'fs-extra'
6e46de09 59import { watchingRouter } from './watching'
65fcc311 60
80e36cd9 61const auditLogger = auditLoggerFactory('videos')
65fcc311 62const videosRouter = express.Router()
9f10b292 63
ac81d1a0
C
64const reqVideoFileAdd = createReqFiles(
65 [ 'videofile', 'thumbnailfile', 'previewfile' ],
14e2014a 66 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
ac81d1a0 67 {
6040f87d
C
68 videofile: CONFIG.STORAGE.TMP_DIR,
69 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
70 previewfile: CONFIG.STORAGE.TMP_DIR
ac81d1a0
C
71 }
72)
73const reqVideoFileUpdate = createReqFiles(
74 [ 'thumbnailfile', 'previewfile' ],
14e2014a 75 MIMETYPES.IMAGE.MIMETYPE_EXT,
ac81d1a0 76 {
6040f87d
C
77 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
78 previewfile: CONFIG.STORAGE.TMP_DIR
ac81d1a0
C
79 }
80)
8c308c2b 81
65fcc311
C
82videosRouter.use('/', abuseVideoRouter)
83videosRouter.use('/', blacklistRouter)
84videosRouter.use('/', rateVideoRouter)
bf1f6508 85videosRouter.use('/', videoCommentRouter)
40e87e9e 86videosRouter.use('/', videoCaptionsRouter)
fbad87b0 87videosRouter.use('/', videoImportsRouter)
74d63469 88videosRouter.use('/', ownershipVideoRouter)
6e46de09 89videosRouter.use('/', watchingRouter)
d33242b0 90
65fcc311
C
91videosRouter.get('/categories', listVideoCategories)
92videosRouter.get('/licences', listVideoLicences)
93videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 94videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 95
65fcc311
C
96videosRouter.get('/',
97 paginationValidator,
98 videosSortValidator,
1174a847 99 setDefaultSort,
f05a1c30 100 setDefaultPagination,
0883b324 101 optionalAuthenticate,
d525fc39 102 commonVideosFiltersValidator,
eb080476 103 asyncMiddleware(listVideos)
fbf1134e 104)
65fcc311
C
105videosRouter.put('/:id',
106 authenticate,
ac81d1a0 107 reqVideoFileUpdate,
a2431b7d 108 asyncMiddleware(videosUpdateValidator),
90d4bb81 109 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 110)
e95561cd 111videosRouter.post('/upload',
65fcc311 112 authenticate,
ac81d1a0 113 reqVideoFileAdd,
3fd3ab2d 114 asyncMiddleware(videosAddValidator),
90d4bb81 115 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 116)
9567011b
C
117
118videosRouter.get('/:id/description',
a2431b7d 119 asyncMiddleware(videosGetValidator),
9567011b
C
120 asyncMiddleware(getVideoDescription)
121)
65fcc311 122videosRouter.get('/:id',
6e46de09 123 optionalAuthenticate,
a2431b7d 124 asyncMiddleware(videosGetValidator),
8d427346 125 asyncMiddleware(checkVideoFollowConstraints),
68ce3ae0 126 getVideo
fbf1134e 127)
1f3e9fec
C
128videosRouter.post('/:id/views',
129 asyncMiddleware(videosGetValidator),
130 asyncMiddleware(viewVideo)
131)
198b205c 132
65fcc311
C
133videosRouter.delete('/:id',
134 authenticate,
a2431b7d 135 asyncMiddleware(videosRemoveValidator),
90d4bb81 136 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 137)
198b205c 138
9f10b292 139// ---------------------------------------------------------------------------
c45f7f84 140
65fcc311
C
141export {
142 videosRouter
143}
c45f7f84 144
9f10b292 145// ---------------------------------------------------------------------------
c45f7f84 146
556ddc31 147function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 148 res.json(VIDEO_CATEGORIES)
6e07c3de
C
149}
150
556ddc31 151function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 152 res.json(VIDEO_LICENCES)
6f0c39e2
C
153}
154
556ddc31 155function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 156 res.json(VIDEO_LANGUAGES)
3092476e
C
157}
158
fd45e8f4
C
159function listVideoPrivacies (req: express.Request, res: express.Response) {
160 res.json(VIDEO_PRIVACIES)
161}
162
90d4bb81 163async function addVideo (req: express.Request, res: express.Response) {
8b917537
C
164 // Processing the video could be long
165 // Set timeout to 10 minutes
166 req.setTimeout(1000 * 60 * 10, () => {
167 logger.error('Upload video has timed out.')
168 return res.sendStatus(408)
169 })
170
90d4bb81 171 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 172 const videoInfo: VideoCreate = req.body
9f10b292 173
e11f68a3
C
174 // Prepare data so we don't block the transaction
175 const videoData = {
176 name: videoInfo.name,
177 remote: false,
e11f68a3
C
178 category: videoInfo.category,
179 licence: videoInfo.licence,
180 language: videoInfo.language,
2186386c
C
181 commentsEnabled: videoInfo.commentsEnabled || false,
182 waitTranscoding: videoInfo.waitTranscoding || false,
183 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
184 nsfw: videoInfo.nsfw || false,
e11f68a3 185 description: videoInfo.description,
2422c46b 186 support: videoInfo.support,
e11f68a3
C
187 privacy: videoInfo.privacy,
188 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
189 channelId: res.locals.videoChannel.id
190 }
3fd3ab2d 191 const video = new VideoModel(videoData)
2186386c 192 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 193
2186386c 194 // Build the file object
056aa7f2 195 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
3a6f351b
C
196 const fps = await getVideoFileFPS(videoPhysicalFile.path)
197
e11f68a3
C
198 const videoFileData = {
199 extname: extname(videoPhysicalFile.filename),
056aa7f2 200 resolution: videoFileResolution,
3a6f351b
C
201 size: videoPhysicalFile.size,
202 fps
e11f68a3 203 }
3fd3ab2d 204 const videoFile = new VideoFileModel(videoFileData)
2186386c
C
205
206 // Move physical file
e11f68a3 207 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 208 const destination = join(videoDir, video.getVideoFilename(videoFile))
14e2014a 209 await move(videoPhysicalFile.path, destination)
e3a682a8
C
210 // This is important in case if there is another attempt in the retry process
211 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 212 videoPhysicalFile.path = destination
ac81d1a0
C
213
214 // Process thumbnail or create it from the video
215 const thumbnailField = req.files['thumbnailfile']
216 if (thumbnailField) {
217 const thumbnailPhysicalFile = thumbnailField[0]
218 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
219 } else {
220 await video.createThumbnail(videoFile)
221 }
93e1258c 222
ac81d1a0
C
223 // Process preview or create it from the video
224 const previewField = req.files['previewfile']
225 if (previewField) {
226 const previewPhysicalFile = previewField[0]
227 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
228 } else {
229 await video.createPreview(videoFile)
230 }
eb080476 231
2186386c 232 // Create the torrent file
ac81d1a0 233 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 234
94a5ff8a 235 const videoCreated = await sequelizeTypescript.transaction(async t => {
e11f68a3 236 const sequelizeOptions = { transaction: t }
eb080476 237
eb080476
C
238 const videoCreated = await video.save(sequelizeOptions)
239 // Do not forget to add video channel information to the created video
240 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 241
eb080476 242 videoFile.videoId = video.id
eb080476 243 await videoFile.save(sequelizeOptions)
e11f68a3
C
244
245 video.VideoFiles = [ videoFile ]
93e1258c 246
2baea0c7 247 // Create tags
2efd32f6 248 if (videoInfo.tags !== undefined) {
3fd3ab2d 249 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 250
3fd3ab2d 251 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
252 video.Tags = tagInstances
253 }
254
2baea0c7
C
255 // Schedule an update in the future?
256 if (videoInfo.scheduleUpdate) {
257 await ScheduleVideoUpdateModel.create({
258 videoId: video.id,
259 updateAt: videoInfo.scheduleUpdate.updateAt,
260 privacy: videoInfo.scheduleUpdate.privacy || null
261 }, { transaction: t })
262 }
263
2186386c 264 await federateVideoIfNeeded(video, true, t)
eb080476 265
993cef4b 266 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
267 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
268
269 return videoCreated
270 })
94a5ff8a 271
2186386c 272 if (video.state === VideoState.TO_TRANSCODE) {
94a5ff8a
C
273 // Put uuid because we don't have id auto incremented for now
274 const dataInput = {
0c948c16
C
275 videoUUID: videoCreated.uuid,
276 isNewVideo: true
94a5ff8a
C
277 }
278
279 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
280 }
281
90d4bb81
C
282 return res.json({
283 video: {
284 id: videoCreated.id,
285 uuid: videoCreated.uuid
286 }
287 }).end()
ed04d94f
C
288}
289
eb080476 290async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 291 const videoInstance: VideoModel = res.locals.video
7f4e7c36 292 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 293 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 294 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 295 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 296
ac81d1a0
C
297 // Process thumbnail or create it from the video
298 if (req.files && req.files['thumbnailfile']) {
299 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
300 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
301 }
302
303 // Process preview or create it from the video
304 if (req.files && req.files['previewfile']) {
305 const previewPhysicalFile = req.files['previewfile'][0]
306 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
307 }
308
eb080476 309 try {
3fd3ab2d 310 await sequelizeTypescript.transaction(async t => {
eb080476
C
311 const sequelizeOptions = {
312 transaction: t
313 }
0f320037 314 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 315
eb080476
C
316 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
317 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
318 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
319 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
320 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
2186386c 321 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
2422c46b 322 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 323 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 324 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
325 if (videoInfoToUpdate.privacy !== undefined) {
326 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
327 videoInstance.set('privacy', newPrivacy)
328
329 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
330 videoInstance.set('publishedAt', new Date())
331 }
332 }
7b1f49de 333
54141398 334 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 335
0f320037 336 // Video tags update?
2efd32f6 337 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 338 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 339
0f320037
C
340 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
341 videoInstanceUpdated.Tags = tagInstances
eb080476 342 }
7920c273 343
0f320037
C
344 // Video channel update?
345 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 346 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 347 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
348
349 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
350 }
351
2baea0c7
C
352 // Schedule an update in the future?
353 if (videoInfoToUpdate.scheduleUpdate) {
354 await ScheduleVideoUpdateModel.upsert({
355 videoId: videoInstanceUpdated.id,
356 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
357 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
358 }, { transaction: t })
e94fc297
C
359 } else if (videoInfoToUpdate.scheduleUpdate === null) {
360 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
361 }
362
2186386c 363 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
e94fc297 364 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 365
80e36cd9 366 auditLogger.update(
993cef4b 367 getAuditIdFromRes(res),
80e36cd9
AB
368 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
369 oldVideoAuditView
370 )
371 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
372 })
eb080476 373 } catch (err) {
6fcd19ba
C
374 // Force fields we want to update
375 // If the transaction is retried, sequelize will think the object has not changed
376 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 377 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
378
379 throw err
eb080476 380 }
90d4bb81
C
381
382 return res.type('json').status(204).end()
9f10b292 383}
8c308c2b 384
1f3e9fec
C
385function getVideo (req: express.Request, res: express.Response) {
386 const videoInstance = res.locals.video
387
04b8c3fb
C
388 if (videoInstance.isOutdated()) {
389 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', videoUrl: videoInstance.url } })
390 .catch(err => logger.error('Cannot create AP refresher job for video %s.', videoInstance.url, { err }))
391 }
392
1f3e9fec
C
393 return res.json(videoInstance.toFormattedDetailsJSON())
394}
395
396async function viewVideo (req: express.Request, res: express.Response) {
818f7987 397 const videoInstance = res.locals.video
9e167724 398
490b595a 399 const ip = req.ip
6b616860 400 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
b5c0e955
C
401 if (exists) {
402 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
403 return res.status(204).end()
404 }
405
6b616860
C
406 await Promise.all([
407 Redis.Instance.addVideoView(videoInstance.id),
408 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
409 ])
b5c0e955 410
a2377d15 411 const serverActor = await getServerActor()
dbe6aa69 412 await sendCreateView(serverActor, videoInstance, undefined)
9e167724 413
1f3e9fec 414 return res.status(204).end()
9f10b292 415}
8c308c2b 416
9567011b
C
417async function getVideoDescription (req: express.Request, res: express.Response) {
418 const videoInstance = res.locals.video
419 let description = ''
420
421 if (videoInstance.isOwned()) {
422 description = videoInstance.description
423 } else {
571389d4 424 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
425 }
426
427 return res.json({ description })
428}
429
04b8c3fb 430async function listVideos (req: express.Request, res: express.Response) {
48dce1c9
C
431 const resultList = await VideoModel.listForApi({
432 start: req.query.start,
433 count: req.query.count,
434 sort: req.query.sort,
06a05d5f 435 includeLocalVideos: true,
d525fc39
C
436 categoryOneOf: req.query.categoryOneOf,
437 licenceOneOf: req.query.licenceOneOf,
438 languageOneOf: req.query.languageOneOf,
439 tagsOneOf: req.query.tagsOneOf,
440 tagsAllOf: req.query.tagsAllOf,
441 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9 442 filter: req.query.filter as VideoFilter,
6e46de09 443 withFiles: false,
7ad9b984 444 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
48dce1c9 445 })
eb080476
C
446
447 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 448}
c45f7f84 449
eb080476 450async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 451 const videoInstance: VideoModel = res.locals.video
91f6f169 452
3fd3ab2d 453 await sequelizeTypescript.transaction(async t => {
eb080476 454 await videoInstance.destroy({ transaction: t })
91f6f169 455 })
eb080476 456
993cef4b 457 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 458 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81
C
459
460 return res.type('json').status(204).end()
9f10b292 461}