]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
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 {
ac81d1a0
C
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,
3fd3ab2d
C
19 VIDEO_PRIVACIES
20} from '../../../initializers'
0f320037
C
21import {
22 changeVideoChannelShare,
2186386c 23 federateVideoIfNeeded,
0f320037 24 fetchRemoteVideoDescription,
2186386c 25 getVideoActivityPubUrl
0f320037 26} from '../../../lib/activitypub'
2186386c 27import { sendCreateView } from '../../../lib/activitypub/send'
94a5ff8a 28import { JobQueue } from '../../../lib/job-queue'
b5c0e955 29import { Redis } from '../../../lib/redis'
65fcc311 30import {
ac81d1a0 31 asyncMiddleware,
90d4bb81 32 asyncRetryTransactionMiddleware,
ac81d1a0 33 authenticate,
d525fc39 34 commonVideosFiltersValidator,
0883b324 35 optionalAuthenticate,
ac81d1a0
C
36 paginationValidator,
37 setDefaultPagination,
38 setDefaultSort,
39 videosAddValidator,
40 videosGetValidator,
41 videosRemoveValidator,
ac81d1a0
C
42 videosSortValidator,
43 videosUpdateValidator
65fcc311 44} from '../../../middlewares'
3fd3ab2d
C
45import { TagModel } from '../../../models/video/tag'
46import { VideoModel } from '../../../models/video/video'
47import { VideoFileModel } from '../../../models/video/video-file'
65fcc311
C
48import { abuseVideoRouter } from './abuse'
49import { blacklistRouter } from './blacklist'
bf1f6508 50import { videoCommentRouter } from './comment'
571389d4 51import { rateVideoRouter } from './rate'
74d63469 52import { ownershipVideoRouter } from './ownership'
0883b324 53import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
06215f15 54import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
2baea0c7 55import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
40e87e9e 56import { videoCaptionsRouter } from './captions'
fbad87b0 57import { videoImportsRouter } from './import'
06215f15 58import { resetSequelizeInstance } from '../../../helpers/database-utils'
62689b94 59import { rename } from 'fs-extra'
65fcc311 60
80e36cd9 61const auditLogger = auditLoggerFactory('videos')
65fcc311 62const videosRouter = express.Router()
9f10b292 63
ac81d1a0
C
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)
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)
d33242b0 89
65fcc311
C
90videosRouter.get('/categories', listVideoCategories)
91videosRouter.get('/licences', listVideoLicences)
92videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 93videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 94
65fcc311
C
95videosRouter.get('/',
96 paginationValidator,
97 videosSortValidator,
1174a847 98 setDefaultSort,
f05a1c30 99 setDefaultPagination,
0883b324 100 optionalAuthenticate,
d525fc39 101 commonVideosFiltersValidator,
eb080476 102 asyncMiddleware(listVideos)
fbf1134e 103)
65fcc311
C
104videosRouter.put('/:id',
105 authenticate,
ac81d1a0 106 reqVideoFileUpdate,
a2431b7d 107 asyncMiddleware(videosUpdateValidator),
90d4bb81 108 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 109)
e95561cd 110videosRouter.post('/upload',
65fcc311 111 authenticate,
ac81d1a0 112 reqVideoFileAdd,
3fd3ab2d 113 asyncMiddleware(videosAddValidator),
90d4bb81 114 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 115)
9567011b
C
116
117videosRouter.get('/:id/description',
a2431b7d 118 asyncMiddleware(videosGetValidator),
9567011b
C
119 asyncMiddleware(getVideoDescription)
120)
65fcc311 121videosRouter.get('/:id',
a2431b7d 122 asyncMiddleware(videosGetValidator),
68ce3ae0 123 getVideo
fbf1134e 124)
1f3e9fec
C
125videosRouter.post('/:id/views',
126 asyncMiddleware(videosGetValidator),
127 asyncMiddleware(viewVideo)
128)
198b205c 129
65fcc311
C
130videosRouter.delete('/:id',
131 authenticate,
a2431b7d 132 asyncMiddleware(videosRemoveValidator),
90d4bb81 133 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 134)
198b205c 135
9f10b292 136// ---------------------------------------------------------------------------
c45f7f84 137
65fcc311
C
138export {
139 videosRouter
140}
c45f7f84 141
9f10b292 142// ---------------------------------------------------------------------------
c45f7f84 143
556ddc31 144function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 145 res.json(VIDEO_CATEGORIES)
6e07c3de
C
146}
147
556ddc31 148function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 149 res.json(VIDEO_LICENCES)
6f0c39e2
C
150}
151
556ddc31 152function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 153 res.json(VIDEO_LANGUAGES)
3092476e
C
154}
155
fd45e8f4
C
156function listVideoPrivacies (req: express.Request, res: express.Response) {
157 res.json(VIDEO_PRIVACIES)
158}
159
90d4bb81 160async function addVideo (req: express.Request, res: express.Response) {
8b917537
C
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
90d4bb81 168 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 169 const videoInfo: VideoCreate = req.body
9f10b292 170
e11f68a3
C
171 // Prepare data so we don't block the transaction
172 const videoData = {
173 name: videoInfo.name,
174 remote: false,
e11f68a3
C
175 category: videoInfo.category,
176 licence: videoInfo.licence,
177 language: videoInfo.language,
2186386c
C
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,
e11f68a3 182 description: videoInfo.description,
2422c46b 183 support: videoInfo.support,
e11f68a3
C
184 privacy: videoInfo.privacy,
185 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
186 channelId: res.locals.videoChannel.id
187 }
3fd3ab2d 188 const video = new VideoModel(videoData)
2186386c 189 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 190
2186386c 191 // Build the file object
056aa7f2 192 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
3a6f351b
C
193 const fps = await getVideoFileFPS(videoPhysicalFile.path)
194
e11f68a3
C
195 const videoFileData = {
196 extname: extname(videoPhysicalFile.filename),
056aa7f2 197 resolution: videoFileResolution,
3a6f351b
C
198 size: videoPhysicalFile.size,
199 fps
e11f68a3 200 }
3fd3ab2d 201 const videoFile = new VideoFileModel(videoFileData)
2186386c
C
202
203 // Move physical file
e11f68a3 204 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 205 const destination = join(videoDir, video.getVideoFilename(videoFile))
62689b94 206 await rename(videoPhysicalFile.path, destination)
e3a682a8
C
207 // This is important in case if there is another attempt in the retry process
208 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 209 videoPhysicalFile.path = destination
ac81d1a0
C
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 }
93e1258c 219
ac81d1a0
C
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 }
eb080476 228
2186386c 229 // Create the torrent file
ac81d1a0 230 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 231
94a5ff8a 232 const videoCreated = await sequelizeTypescript.transaction(async t => {
e11f68a3 233 const sequelizeOptions = { transaction: t }
eb080476 234
eb080476
C
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
7920c273 238
eb080476 239 videoFile.videoId = video.id
eb080476 240 await videoFile.save(sequelizeOptions)
e11f68a3
C
241
242 video.VideoFiles = [ videoFile ]
93e1258c 243
2baea0c7 244 // Create tags
2efd32f6 245 if (videoInfo.tags !== undefined) {
3fd3ab2d 246 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 247
3fd3ab2d 248 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
249 video.Tags = tagInstances
250 }
251
2baea0c7
C
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
2186386c 261 await federateVideoIfNeeded(video, true, t)
eb080476 262
993cef4b 263 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
264 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
265
266 return videoCreated
267 })
94a5ff8a 268
2186386c 269 if (video.state === VideoState.TO_TRANSCODE) {
94a5ff8a
C
270 // Put uuid because we don't have id auto incremented for now
271 const dataInput = {
0c948c16
C
272 videoUUID: videoCreated.uuid,
273 isNewVideo: true
94a5ff8a
C
274 }
275
276 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
277 }
278
90d4bb81
C
279 return res.json({
280 video: {
281 id: videoCreated.id,
282 uuid: videoCreated.uuid
283 }
284 }).end()
ed04d94f
C
285}
286
eb080476 287async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 288 const videoInstance: VideoModel = res.locals.video
7f4e7c36 289 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 290 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 291 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 292 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 293
ac81d1a0
C
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
eb080476 306 try {
3fd3ab2d 307 await sequelizeTypescript.transaction(async t => {
eb080476
C
308 const sequelizeOptions = {
309 transaction: t
310 }
0f320037 311 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 312
eb080476
C
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)
2186386c 318 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
2422c46b 319 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 320 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 321 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
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 }
7b1f49de 330
54141398 331 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 332
0f320037 333 // Video tags update?
2efd32f6 334 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 335 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 336
0f320037
C
337 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
338 videoInstanceUpdated.Tags = tagInstances
eb080476 339 }
7920c273 340
0f320037
C
341 // Video channel update?
342 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 343 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 344 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
345
346 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
347 }
348
2baea0c7
C
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 })
e94fc297
C
356 } else if (videoInfoToUpdate.scheduleUpdate === null) {
357 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
358 }
359
2186386c 360 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
e94fc297 361 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 362
80e36cd9 363 auditLogger.update(
993cef4b 364 getAuditIdFromRes(res),
80e36cd9
AB
365 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
366 oldVideoAuditView
367 )
368 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
369 })
eb080476 370 } catch (err) {
6fcd19ba
C
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!
eb080476 374 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
375
376 throw err
eb080476 377 }
90d4bb81
C
378
379 return res.type('json').status(204).end()
9f10b292 380}
8c308c2b 381
1f3e9fec
C
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) {
818f7987 389 const videoInstance = res.locals.video
9e167724 390
490b595a 391 const ip = req.ip
6b616860 392 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
b5c0e955
C
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
6b616860
C
398 await Promise.all([
399 Redis.Instance.addVideoView(videoInstance.id),
400 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
401 ])
b5c0e955 402
a2377d15 403 const serverActor = await getServerActor()
40ff5707 404
a2377d15 405 await sendCreateView(serverActor, videoInstance, undefined)
9e167724 406
1f3e9fec 407 return res.status(204).end()
9f10b292 408}
8c308c2b 409
9567011b
C
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 {
571389d4 417 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
418 }
419
420 return res.json({ description })
421}
422
eb080476 423async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
424 const resultList = await VideoModel.listForApi({
425 start: req.query.start,
426 count: req.query.count,
427 sort: req.query.sort,
06a05d5f 428 includeLocalVideos: true,
d525fc39
C
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),
48dce1c9
C
435 filter: req.query.filter as VideoFilter,
436 withFiles: false
437 })
eb080476
C
438
439 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 440}
c45f7f84 441
eb080476 442async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 443 const videoInstance: VideoModel = res.locals.video
91f6f169 444
3fd3ab2d 445 await sequelizeTypescript.transaction(async t => {
eb080476 446 await videoInstance.destroy({ transaction: t })
91f6f169 447 })
eb080476 448
993cef4b 449 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 450 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81
C
451
452 return res.type('json').status(204).end()
9f10b292 453}