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