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