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