]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Merge branch 'develop' of framagit.org:chocobozzz/PeerTube into develop
[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'
47564bbe 9import { createReqFiles, 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'
0883b324
C
22import {
23 fetchRemoteVideoDescription,
24 getVideoActivityPubUrl,
25 shareVideoByServerAndChannel
26} from '../../../lib/activitypub'
07197db4 27import { sendCreateVideo, sendCreateView, sendUpdateVideo } from '../../../lib/activitypub/send'
94a5ff8a 28import { JobQueue } from '../../../lib/job-queue'
b5c0e955 29import { Redis } from '../../../lib/redis'
65fcc311 30import {
ac81d1a0
C
31 asyncMiddleware,
32 authenticate,
0883b324 33 optionalAuthenticate,
ac81d1a0
C
34 paginationValidator,
35 setDefaultPagination,
36 setDefaultSort,
37 videosAddValidator,
38 videosGetValidator,
39 videosRemoveValidator,
40 videosSearchValidator,
41 videosSortValidator,
42 videosUpdateValidator
65fcc311 43} from '../../../middlewares'
3fd3ab2d
C
44import { TagModel } from '../../../models/video/tag'
45import { VideoModel } from '../../../models/video/video'
46import { VideoFileModel } from '../../../models/video/video-file'
65fcc311
C
47import { abuseVideoRouter } from './abuse'
48import { blacklistRouter } from './blacklist'
72c7248b 49import { videoChannelRouter } from './channel'
bf1f6508 50import { videoCommentRouter } from './comment'
571389d4 51import { rateVideoRouter } from './rate'
0883b324
C
52import { User } from '../../../../shared/models/users'
53import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
54import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
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)
72c7248b 79videosRouter.use('/', videoChannelRouter)
bf1f6508 80videosRouter.use('/', videoCommentRouter)
d33242b0 81
65fcc311
C
82videosRouter.get('/categories', listVideoCategories)
83videosRouter.get('/licences', listVideoLicences)
84videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 85videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 86
65fcc311
C
87videosRouter.get('/',
88 paginationValidator,
89 videosSortValidator,
1174a847 90 setDefaultSort,
f05a1c30 91 setDefaultPagination,
0883b324 92 optionalAuthenticate,
eb080476 93 asyncMiddleware(listVideos)
fbf1134e 94)
f3aaa9a9
C
95videosRouter.get('/search',
96 videosSearchValidator,
97 paginationValidator,
98 videosSortValidator,
1174a847 99 setDefaultSort,
f05a1c30 100 setDefaultPagination,
0883b324 101 optionalAuthenticate,
f3aaa9a9
C
102 asyncMiddleware(searchVideos)
103)
65fcc311
C
104videosRouter.put('/:id',
105 authenticate,
ac81d1a0 106 reqVideoFileUpdate,
a2431b7d 107 asyncMiddleware(videosUpdateValidator),
eb080476 108 asyncMiddleware(updateVideoRetryWrapper)
7b1f49de 109)
e95561cd 110videosRouter.post('/upload',
65fcc311 111 authenticate,
ac81d1a0 112 reqVideoFileAdd,
3fd3ab2d 113 asyncMiddleware(videosAddValidator),
eb080476 114 asyncMiddleware(addVideoRetryWrapper)
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),
eb080476 133 asyncMiddleware(removeVideoRetryWrapper)
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
ed04d94f
C
160// Wrapper to video add that retry the function if there is a database error
161// We need this because we run the transaction in SERIALIZABLE isolation that can fail
eb080476 162async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018 163 const options = {
556ddc31 164 arguments: [ req, res, req.files['videofile'][0] ],
d6a5b018
C
165 errorMessage: 'Cannot insert the video with many retries.'
166 }
ed04d94f 167
cadb46d8 168 const video = await retryTransactionWrapper(addVideo, options)
eb080476 169
cadb46d8
C
170 res.json({
171 video: {
172 id: video.id,
173 uuid: video.uuid
174 }
175 }).end()
ed04d94f
C
176}
177
e11f68a3 178async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
556ddc31 179 const videoInfo: VideoCreate = req.body
9f10b292 180
e11f68a3
C
181 // Prepare data so we don't block the transaction
182 const videoData = {
183 name: videoInfo.name,
184 remote: false,
185 extname: extname(videoPhysicalFile.filename),
186 category: videoInfo.category,
187 licence: videoInfo.licence,
188 language: videoInfo.language,
47564bbe 189 commentsEnabled: videoInfo.commentsEnabled,
e11f68a3
C
190 nsfw: videoInfo.nsfw,
191 description: videoInfo.description,
2422c46b 192 support: videoInfo.support,
e11f68a3
C
193 privacy: videoInfo.privacy,
194 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
195 channelId: res.locals.videoChannel.id
196 }
3fd3ab2d 197 const video = new VideoModel(videoData)
e11f68a3 198 video.url = getVideoActivityPubUrl(video)
eb080476 199
056aa7f2 200 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
6fcd19ba 201
e11f68a3
C
202 const videoFileData = {
203 extname: extname(videoPhysicalFile.filename),
056aa7f2 204 resolution: videoFileResolution,
e11f68a3
C
205 size: videoPhysicalFile.size
206 }
3fd3ab2d 207 const videoFile = new VideoFileModel(videoFileData)
e11f68a3 208 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 209 const destination = join(videoDir, video.getVideoFilename(videoFile))
e3a682a8 210
ac81d1a0 211 await renamePromise(videoPhysicalFile.path, destination)
e3a682a8
C
212 // This is important in case if there is another attempt in the retry process
213 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 214 videoPhysicalFile.path = destination
ac81d1a0
C
215
216 // Process thumbnail or create it from the video
217 const thumbnailField = req.files['thumbnailfile']
218 if (thumbnailField) {
219 const thumbnailPhysicalFile = thumbnailField[0]
220 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
221 } else {
222 await video.createThumbnail(videoFile)
223 }
93e1258c 224
ac81d1a0
C
225 // Process preview or create it from the video
226 const previewField = req.files['previewfile']
227 if (previewField) {
228 const previewPhysicalFile = previewField[0]
229 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
230 } else {
231 await video.createPreview(videoFile)
232 }
eb080476 233
ac81d1a0 234 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 235
94a5ff8a 236 const videoCreated = await sequelizeTypescript.transaction(async t => {
e11f68a3 237 const sequelizeOptions = { transaction: t }
eb080476 238
eb080476
C
239 const videoCreated = await video.save(sequelizeOptions)
240 // Do not forget to add video channel information to the created video
241 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 242
eb080476 243 videoFile.videoId = video.id
eb080476 244 await videoFile.save(sequelizeOptions)
e11f68a3
C
245
246 video.VideoFiles = [ videoFile ]
93e1258c 247
eb080476 248 if (videoInfo.tags) {
3fd3ab2d 249 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 250
3fd3ab2d 251 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
252 video.Tags = tagInstances
253 }
254
255 // Let transcoding job send the video to friends because the video file extension might change
cadb46d8 256 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
60862425 257 // Don't send video to remote servers, it is private
cadb46d8 258 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
eb080476 259
50d6de9c 260 await sendCreateVideo(video, t)
a7d647c4 261 await shareVideoByServerAndChannel(video, t)
eb080476 262
cadb46d8
C
263 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
264
265 return videoCreated
266 })
94a5ff8a
C
267
268 if (CONFIG.TRANSCODING.ENABLED === true) {
269 // Put uuid because we don't have id auto incremented for now
270 const dataInput = {
271 videoUUID: videoCreated.uuid
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 }
7b1f49de 314
eb080476
C
315 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
316 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
317 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
318 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
319 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
2422c46b 320 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 321 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 322 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
323 if (videoInfoToUpdate.privacy !== undefined) {
324 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
325 videoInstance.set('privacy', newPrivacy)
326
327 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
328 videoInstance.set('publishedAt', new Date())
329 }
330 }
7b1f49de 331
54141398 332 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 333
eb080476 334 if (videoInfoToUpdate.tags) {
3fd3ab2d 335 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 336
3fd3ab2d 337 await videoInstance.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
338 videoInstance.Tags = tagInstances
339 }
7920c273 340
eb080476 341 // Now we'll update the video's meta data to our friends
fd45e8f4 342 if (wasPrivateVideo === false) {
54141398 343 await sendUpdateVideo(videoInstanceUpdated, t)
fd45e8f4
C
344 }
345
60862425 346 // Video is not private anymore, send a create action to remote servers
f595d394 347 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
50d6de9c 348 await sendCreateVideo(videoInstanceUpdated, t)
a7d647c4 349 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
fd45e8f4 350 }
eb080476 351 })
6fcd19ba 352
eb080476
C
353 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
354 } catch (err) {
6fcd19ba
C
355 // Force fields we want to update
356 // If the transaction is retried, sequelize will think the object has not changed
357 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 358 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
359
360 throw err
eb080476 361 }
9f10b292 362}
8c308c2b 363
1f3e9fec
C
364function getVideo (req: express.Request, res: express.Response) {
365 const videoInstance = res.locals.video
366
367 return res.json(videoInstance.toFormattedDetailsJSON())
368}
369
370async function viewVideo (req: express.Request, res: express.Response) {
818f7987 371 const videoInstance = res.locals.video
9e167724 372
490b595a 373 const ip = req.ip
b5c0e955
C
374 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
375 if (exists) {
376 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
377 return res.status(204).end()
378 }
379
1f3e9fec 380 await videoInstance.increment('views')
b5c0e955
C
381 await Redis.Instance.setView(ip, videoInstance.uuid)
382
50d6de9c 383 const serverAccount = await getServerActor()
40ff5707 384
07197db4 385 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 386
1f3e9fec 387 return res.status(204).end()
9f10b292 388}
8c308c2b 389
9567011b
C
390async function getVideoDescription (req: express.Request, res: express.Response) {
391 const videoInstance = res.locals.video
392 let description = ''
393
394 if (videoInstance.isOwned()) {
395 description = videoInstance.description
396 } else {
571389d4 397 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
398 }
399
400 return res.json({ description })
401}
402
eb080476 403async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
0883b324
C
404 const resultList = await VideoModel.listForApi(
405 req.query.start as number,
406 req.query.count as number,
407 req.query.sort as VideoSortField,
408 isNSFWHidden(res),
409 req.query.filter as VideoFilter
410 )
eb080476
C
411
412 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 413}
c45f7f84 414
eb080476 415async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
91f6f169
C
416 const options = {
417 arguments: [ req, res ],
418 errorMessage: 'Cannot remove the video with many retries.'
419 }
8c308c2b 420
eb080476
C
421 await retryTransactionWrapper(removeVideo, options)
422
423 return res.type('json').status(204).end()
91f6f169
C
424}
425
eb080476 426async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 427 const videoInstance: VideoModel = res.locals.video
91f6f169 428
3fd3ab2d 429 await sequelizeTypescript.transaction(async t => {
eb080476 430 await videoInstance.destroy({ transaction: t })
91f6f169 431 })
eb080476
C
432
433 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
9f10b292 434}
8c308c2b 435
eb080476 436async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
66dc5907 437 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
0883b324
C
438 req.query.search as string,
439 req.query.start as number,
440 req.query.count as number,
441 req.query.sort as VideoSortField,
442 isNSFWHidden(res)
eb080476
C
443 )
444
445 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 446}
0883b324
C
447
448function isNSFWHidden (res: express.Response) {
449 if (res.locals.oauth) {
450 const user: User = res.locals.oauth.token.User
451 if (user) return user.nsfwPolicy === 'do_not_list'
452 }
453
454 return CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list'
455}