]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Add ability to update a video channel
[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
eb080476 247 if (videoInfo.tags) {
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 = {
270 videoUUID: videoCreated.uuid
271 }
272
273 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
274 }
275
276 return videoCreated
7b1f49de
C
277}
278
eb080476 279async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
280 const options = {
281 arguments: [ req, res ],
282 errorMessage: 'Cannot update the video with many retries.'
283 }
ed04d94f 284
eb080476
C
285 await retryTransactionWrapper(updateVideo, options)
286
287 return res.type('json').status(204).end()
ed04d94f
C
288}
289
eb080476 290async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 291 const videoInstance: VideoModel = res.locals.video
7f4e7c36 292 const videoFieldsSave = videoInstance.toJSON()
556ddc31 293 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 294 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 295
ac81d1a0
C
296 // Process thumbnail or create it from the video
297 if (req.files && req.files['thumbnailfile']) {
298 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
299 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
300 }
301
302 // Process preview or create it from the video
303 if (req.files && req.files['previewfile']) {
304 const previewPhysicalFile = req.files['previewfile'][0]
305 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
306 }
307
eb080476 308 try {
3fd3ab2d 309 await sequelizeTypescript.transaction(async t => {
eb080476
C
310 const sequelizeOptions = {
311 transaction: t
312 }
0f320037 313 const oldVideoChannel = videoInstance.VideoChannel
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
0f320037 334 // Video tags update?
eb080476 335 if (videoInfoToUpdate.tags) {
3fd3ab2d 336 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 337
0f320037
C
338 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
339 videoInstanceUpdated.Tags = tagInstances
eb080476 340 }
7920c273 341
0f320037
C
342 // Video channel update?
343 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
344 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel)
345 videoInstance.VideoChannel = res.locals.videoChannel
346
347 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
348 }
349
0f320037
C
350 // Now we'll update the video's meta data to our friends
351 if (wasPrivateVideo === false) await sendUpdateVideo(videoInstanceUpdated, t)
352
60862425 353 // Video is not private anymore, send a create action to remote servers
f595d394 354 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
50d6de9c 355 await sendCreateVideo(videoInstanceUpdated, t)
a7d647c4 356 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
fd45e8f4 357 }
eb080476 358 })
6fcd19ba 359
eb080476
C
360 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
361 } catch (err) {
6fcd19ba
C
362 // Force fields we want to update
363 // If the transaction is retried, sequelize will think the object has not changed
364 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 365 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
366
367 throw err
eb080476 368 }
9f10b292 369}
8c308c2b 370
1f3e9fec
C
371function getVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
373
374 return res.json(videoInstance.toFormattedDetailsJSON())
375}
376
377async function viewVideo (req: express.Request, res: express.Response) {
818f7987 378 const videoInstance = res.locals.video
9e167724 379
490b595a 380 const ip = req.ip
b5c0e955
C
381 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
382 if (exists) {
383 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
384 return res.status(204).end()
385 }
386
1f3e9fec 387 await videoInstance.increment('views')
b5c0e955
C
388 await Redis.Instance.setView(ip, videoInstance.uuid)
389
50d6de9c 390 const serverAccount = await getServerActor()
40ff5707 391
07197db4 392 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 393
1f3e9fec 394 return res.status(204).end()
9f10b292 395}
8c308c2b 396
9567011b
C
397async function getVideoDescription (req: express.Request, res: express.Response) {
398 const videoInstance = res.locals.video
399 let description = ''
400
401 if (videoInstance.isOwned()) {
402 description = videoInstance.description
403 } else {
571389d4 404 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
405 }
406
407 return res.json({ description })
408}
409
eb080476 410async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
411 const resultList = await VideoModel.listForApi({
412 start: req.query.start,
413 count: req.query.count,
414 sort: req.query.sort,
415 hideNSFW: isNSFWHidden(res),
416 filter: req.query.filter as VideoFilter,
417 withFiles: false
418 })
eb080476
C
419
420 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 421}
c45f7f84 422
eb080476 423async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
91f6f169
C
424 const options = {
425 arguments: [ req, res ],
426 errorMessage: 'Cannot remove the video with many retries.'
427 }
8c308c2b 428
eb080476
C
429 await retryTransactionWrapper(removeVideo, options)
430
431 return res.type('json').status(204).end()
91f6f169
C
432}
433
eb080476 434async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 435 const videoInstance: VideoModel = res.locals.video
91f6f169 436
3fd3ab2d 437 await sequelizeTypescript.transaction(async t => {
eb080476 438 await videoInstance.destroy({ transaction: t })
91f6f169 439 })
eb080476
C
440
441 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
9f10b292 442}
8c308c2b 443
eb080476 444async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
66dc5907 445 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
0883b324
C
446 req.query.search as string,
447 req.query.start as number,
448 req.query.count as number,
449 req.query.sort as VideoSortField,
450 isNSFWHidden(res)
eb080476
C
451 )
452
453 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 454}