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