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