]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Fix import with when the imported file has the same extension than an
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
93e1258c 2import { extname, join } from 'path'
571389d4 3import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
da854ddd
C
4import { renamePromise } from '../../../helpers/core-utils'
5import { retryTransactionWrapper } from '../../../helpers/database-utils'
056aa7f2 6import { getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
ac81d1a0 7import { processImage } from '../../../helpers/image-utils'
da854ddd 8import { logger } from '../../../helpers/logger'
0626e7af 9import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
65fcc311 10import {
ac81d1a0
C
11 CONFIG,
12 IMAGE_MIMETYPE_EXT,
13 PREVIEWS_SIZE,
14 sequelizeTypescript,
15 THUMBNAILS_SIZE,
16 VIDEO_CATEGORIES,
17 VIDEO_LANGUAGES,
18 VIDEO_LICENCES,
19 VIDEO_MIMETYPE_EXT,
3fd3ab2d
C
20 VIDEO_PRIVACIES
21} from '../../../initializers'
0f320037
C
22import {
23 changeVideoChannelShare,
24 fetchRemoteVideoDescription,
25 getVideoActivityPubUrl,
26 shareVideoByServerAndChannel
27} from '../../../lib/activitypub'
07197db4 28import { sendCreateVideo, sendCreateView, sendUpdateVideo } from '../../../lib/activitypub/send'
94a5ff8a 29import { JobQueue } from '../../../lib/job-queue'
b5c0e955 30import { Redis } from '../../../lib/redis'
65fcc311 31import {
ac81d1a0
C
32 asyncMiddleware,
33 authenticate,
0883b324 34 optionalAuthenticate,
ac81d1a0
C
35 paginationValidator,
36 setDefaultPagination,
37 setDefaultSort,
38 videosAddValidator,
39 videosGetValidator,
40 videosRemoveValidator,
41 videosSearchValidator,
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'
0883b324
C
52import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
0626e7af 54import { isNSFWHidden, createReqFiles } from '../../../helpers/express-utils'
65fcc311
C
55
56const videosRouter = express.Router()
9f10b292 57
ac81d1a0
C
58const reqVideoFileAdd = createReqFiles(
59 [ 'videofile', 'thumbnailfile', 'previewfile' ],
60 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
61 {
62 videofile: CONFIG.STORAGE.VIDEOS_DIR,
63 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
64 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
65 }
66)
67const reqVideoFileUpdate = createReqFiles(
68 [ 'thumbnailfile', 'previewfile' ],
69 IMAGE_MIMETYPE_EXT,
70 {
71 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
72 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
73 }
74)
8c308c2b 75
65fcc311
C
76videosRouter.use('/', abuseVideoRouter)
77videosRouter.use('/', blacklistRouter)
78videosRouter.use('/', rateVideoRouter)
bf1f6508 79videosRouter.use('/', videoCommentRouter)
d33242b0 80
65fcc311
C
81videosRouter.get('/categories', listVideoCategories)
82videosRouter.get('/licences', listVideoLicences)
83videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 84videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 85
65fcc311
C
86videosRouter.get('/',
87 paginationValidator,
88 videosSortValidator,
1174a847 89 setDefaultSort,
f05a1c30 90 setDefaultPagination,
0883b324 91 optionalAuthenticate,
eb080476 92 asyncMiddleware(listVideos)
fbf1134e 93)
f3aaa9a9
C
94videosRouter.get('/search',
95 videosSearchValidator,
96 paginationValidator,
97 videosSortValidator,
1174a847 98 setDefaultSort,
f05a1c30 99 setDefaultPagination,
0883b324 100 optionalAuthenticate,
f3aaa9a9
C
101 asyncMiddleware(searchVideos)
102)
65fcc311
C
103videosRouter.put('/:id',
104 authenticate,
ac81d1a0 105 reqVideoFileUpdate,
a2431b7d 106 asyncMiddleware(videosUpdateValidator),
eb080476 107 asyncMiddleware(updateVideoRetryWrapper)
7b1f49de 108)
e95561cd 109videosRouter.post('/upload',
65fcc311 110 authenticate,
ac81d1a0 111 reqVideoFileAdd,
3fd3ab2d 112 asyncMiddleware(videosAddValidator),
eb080476 113 asyncMiddleware(addVideoRetryWrapper)
fbf1134e 114)
9567011b
C
115
116videosRouter.get('/:id/description',
a2431b7d 117 asyncMiddleware(videosGetValidator),
9567011b
C
118 asyncMiddleware(getVideoDescription)
119)
65fcc311 120videosRouter.get('/:id',
a2431b7d 121 asyncMiddleware(videosGetValidator),
68ce3ae0 122 getVideo
fbf1134e 123)
1f3e9fec
C
124videosRouter.post('/:id/views',
125 asyncMiddleware(videosGetValidator),
126 asyncMiddleware(viewVideo)
127)
198b205c 128
65fcc311
C
129videosRouter.delete('/:id',
130 authenticate,
a2431b7d 131 asyncMiddleware(videosRemoveValidator),
eb080476 132 asyncMiddleware(removeVideoRetryWrapper)
fbf1134e 133)
198b205c 134
9f10b292 135// ---------------------------------------------------------------------------
c45f7f84 136
65fcc311
C
137export {
138 videosRouter
139}
c45f7f84 140
9f10b292 141// ---------------------------------------------------------------------------
c45f7f84 142
556ddc31 143function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 144 res.json(VIDEO_CATEGORIES)
6e07c3de
C
145}
146
556ddc31 147function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 148 res.json(VIDEO_LICENCES)
6f0c39e2
C
149}
150
556ddc31 151function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 152 res.json(VIDEO_LANGUAGES)
3092476e
C
153}
154
fd45e8f4
C
155function listVideoPrivacies (req: express.Request, res: express.Response) {
156 res.json(VIDEO_PRIVACIES)
157}
158
ed04d94f
C
159// Wrapper to video add that retry the function if there is a database error
160// We need this because we run the transaction in SERIALIZABLE isolation that can fail
eb080476 161async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018 162 const options = {
556ddc31 163 arguments: [ req, res, req.files['videofile'][0] ],
d6a5b018
C
164 errorMessage: 'Cannot insert the video with many retries.'
165 }
ed04d94f 166
cadb46d8 167 const video = await retryTransactionWrapper(addVideo, options)
eb080476 168
cadb46d8
C
169 res.json({
170 video: {
171 id: video.id,
172 uuid: video.uuid
173 }
174 }).end()
ed04d94f
C
175}
176
e11f68a3 177async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
556ddc31 178 const videoInfo: VideoCreate = req.body
9f10b292 179
e11f68a3
C
180 // Prepare data so we don't block the transaction
181 const videoData = {
182 name: videoInfo.name,
183 remote: false,
184 extname: extname(videoPhysicalFile.filename),
185 category: videoInfo.category,
186 licence: videoInfo.licence,
187 language: videoInfo.language,
47564bbe 188 commentsEnabled: videoInfo.commentsEnabled,
e11f68a3
C
189 nsfw: videoInfo.nsfw,
190 description: videoInfo.description,
2422c46b 191 support: videoInfo.support,
e11f68a3
C
192 privacy: videoInfo.privacy,
193 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
194 channelId: res.locals.videoChannel.id
195 }
3fd3ab2d 196 const video = new VideoModel(videoData)
e11f68a3 197 video.url = getVideoActivityPubUrl(video)
eb080476 198
056aa7f2 199 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
6fcd19ba 200
e11f68a3
C
201 const videoFileData = {
202 extname: extname(videoPhysicalFile.filename),
056aa7f2 203 resolution: videoFileResolution,
e11f68a3
C
204 size: videoPhysicalFile.size
205 }
3fd3ab2d 206 const videoFile = new VideoFileModel(videoFileData)
e11f68a3 207 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 208 const destination = join(videoDir, video.getVideoFilename(videoFile))
e3a682a8 209
ac81d1a0 210 await renamePromise(videoPhysicalFile.path, destination)
e3a682a8
C
211 // This is important in case if there is another attempt in the retry process
212 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 213 videoPhysicalFile.path = destination
ac81d1a0
C
214
215 // Process thumbnail or create it from the video
216 const thumbnailField = req.files['thumbnailfile']
217 if (thumbnailField) {
218 const thumbnailPhysicalFile = thumbnailField[0]
219 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
220 } else {
221 await video.createThumbnail(videoFile)
222 }
93e1258c 223
ac81d1a0
C
224 // Process preview or create it from the video
225 const previewField = req.files['previewfile']
226 if (previewField) {
227 const previewPhysicalFile = previewField[0]
228 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
229 } else {
230 await video.createPreview(videoFile)
231 }
eb080476 232
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
2efd32f6 247 if (videoInfo.tags !== undefined) {
3fd3ab2d 248 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 249
3fd3ab2d 250 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
251 video.Tags = tagInstances
252 }
253
254 // Let transcoding job send the video to friends because the video file extension might change
cadb46d8 255 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
60862425 256 // Don't send video to remote servers, it is private
cadb46d8 257 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
eb080476 258
50d6de9c 259 await sendCreateVideo(video, t)
a7d647c4 260 await shareVideoByServerAndChannel(video, t)
eb080476 261
cadb46d8
C
262 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
263
264 return videoCreated
265 })
94a5ff8a
C
266
267 if (CONFIG.TRANSCODING.ENABLED === true) {
268 // Put uuid because we don't have id auto incremented for now
269 const dataInput = {
0c948c16
C
270 videoUUID: videoCreated.uuid,
271 isNewVideo: true
94a5ff8a
C
272 }
273
274 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
275 }
276
277 return videoCreated
7b1f49de
C
278}
279
eb080476 280async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
281 const options = {
282 arguments: [ req, res ],
283 errorMessage: 'Cannot update the video with many retries.'
284 }
ed04d94f 285
eb080476
C
286 await retryTransactionWrapper(updateVideo, options)
287
288 return res.type('json').status(204).end()
ed04d94f
C
289}
290
eb080476 291async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 292 const videoInstance: VideoModel = res.locals.video
7f4e7c36 293 const videoFieldsSave = videoInstance.toJSON()
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)
2422c46b 321 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 322 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 323 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
324 if (videoInfoToUpdate.privacy !== undefined) {
325 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
326 videoInstance.set('privacy', newPrivacy)
327
328 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
329 videoInstance.set('publishedAt', new Date())
330 }
331 }
7b1f49de 332
54141398 333 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 334
0f320037 335 // Video tags update?
2efd32f6 336 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 337 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 338
0f320037
C
339 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
340 videoInstanceUpdated.Tags = tagInstances
eb080476 341 }
7920c273 342
0f320037
C
343 // Video channel update?
344 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 345 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
0f320037
C
346 videoInstance.VideoChannel = res.locals.videoChannel
347
348 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
349 }
350
0f320037
C
351 // Now we'll update the video's meta data to our friends
352 if (wasPrivateVideo === false) await sendUpdateVideo(videoInstanceUpdated, t)
353
60862425 354 // Video is not private anymore, send a create action to remote servers
f595d394 355 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
50d6de9c 356 await sendCreateVideo(videoInstanceUpdated, t)
a7d647c4 357 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
fd45e8f4 358 }
eb080476 359 })
6fcd19ba 360
eb080476
C
361 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
362 } catch (err) {
6fcd19ba
C
363 // Force fields we want to update
364 // If the transaction is retried, sequelize will think the object has not changed
365 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 366 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
367
368 throw err
eb080476 369 }
9f10b292 370}
8c308c2b 371
1f3e9fec
C
372function getVideo (req: express.Request, res: express.Response) {
373 const videoInstance = res.locals.video
374
375 return res.json(videoInstance.toFormattedDetailsJSON())
376}
377
378async function viewVideo (req: express.Request, res: express.Response) {
818f7987 379 const videoInstance = res.locals.video
9e167724 380
490b595a 381 const ip = req.ip
b5c0e955
C
382 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
383 if (exists) {
384 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
385 return res.status(204).end()
386 }
387
1f3e9fec 388 await videoInstance.increment('views')
b5c0e955
C
389 await Redis.Instance.setView(ip, videoInstance.uuid)
390
50d6de9c 391 const serverAccount = await getServerActor()
40ff5707 392
07197db4 393 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 394
1f3e9fec 395 return res.status(204).end()
9f10b292 396}
8c308c2b 397
9567011b
C
398async function getVideoDescription (req: express.Request, res: express.Response) {
399 const videoInstance = res.locals.video
400 let description = ''
401
402 if (videoInstance.isOwned()) {
403 description = videoInstance.description
404 } else {
571389d4 405 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
406 }
407
408 return res.json({ description })
409}
410
eb080476 411async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
412 const resultList = await VideoModel.listForApi({
413 start: req.query.start,
414 count: req.query.count,
415 sort: req.query.sort,
416 hideNSFW: isNSFWHidden(res),
417 filter: req.query.filter as VideoFilter,
418 withFiles: false
419 })
eb080476
C
420
421 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 422}
c45f7f84 423
eb080476 424async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
91f6f169
C
425 const options = {
426 arguments: [ req, res ],
427 errorMessage: 'Cannot remove the video with many retries.'
428 }
8c308c2b 429
eb080476
C
430 await retryTransactionWrapper(removeVideo, options)
431
432 return res.type('json').status(204).end()
91f6f169
C
433}
434
eb080476 435async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 436 const videoInstance: VideoModel = res.locals.video
91f6f169 437
3fd3ab2d 438 await sequelizeTypescript.transaction(async t => {
eb080476 439 await videoInstance.destroy({ transaction: t })
91f6f169 440 })
eb080476
C
441
442 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
9f10b292 443}
8c308c2b 444
eb080476 445async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
66dc5907 446 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
0883b324
C
447 req.query.search as string,
448 req.query.start as number,
449 req.query.count as number,
450 req.query.sort as VideoSortField,
451 isNSFWHidden(res)
eb080476
C
452 )
453
454 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 455}