]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Split ffmpeg utils with ffprobe utils
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
8054669f 2import { move } from 'fs-extra'
3f6b7aa1 3import { extname } from 'path'
8054669f
C
4import toInt from 'validator/lib/toInt'
5import { addOptimizeOrMergeAudioJob } from '@server/helpers/video'
6import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7import { changeVideoChannelShare } from '@server/lib/activitypub/share'
de94ac86 8import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
7a4ea932 9import { LiveManager } from '@server/lib/live-manager'
1ef65f4c 10import { buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
8054669f
C
11import { getVideoFilePath } from '@server/lib/video-paths'
12import { getServerActor } from '@server/models/application/application'
053aed43 13import { MVideoFullLight } from '@server/types/models'
1ef65f4c 14import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
8054669f
C
15import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
16import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
17import { resetSequelizeInstance } from '../../../helpers/database-utils'
18import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
daf6e480 19import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
da854ddd 20import { logger } from '../../../helpers/logger'
8dc8a34e 21import { getFormattedObjects } from '../../../helpers/utils'
8054669f 22import { CONFIG } from '../../../initializers/config'
b345a804
C
23import {
24 DEFAULT_AUDIO_RESOLUTION,
25 MIMETYPES,
26 VIDEO_CATEGORIES,
27 VIDEO_LANGUAGES,
28 VIDEO_LICENCES,
a1587156 29 VIDEO_PRIVACIES
b345a804 30} from '../../../initializers/constants'
8054669f
C
31import { sequelizeTypescript } from '../../../initializers/database'
32import { sendView } from '../../../lib/activitypub/send/send-view'
8dc8a34e 33import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
94a5ff8a 34import { JobQueue } from '../../../lib/job-queue'
8054669f
C
35import { Notifier } from '../../../lib/notifier'
36import { Hooks } from '../../../lib/plugins/hooks'
b5c0e955 37import { Redis } from '../../../lib/redis'
1ef65f4c 38import { generateVideoMiniature } from '../../../lib/thumbnail'
8054669f 39import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
65fcc311 40import {
ac81d1a0 41 asyncMiddleware,
90d4bb81 42 asyncRetryTransactionMiddleware,
ac81d1a0 43 authenticate,
8d427346 44 checkVideoFollowConstraints,
d525fc39 45 commonVideosFiltersValidator,
0883b324 46 optionalAuthenticate,
ac81d1a0
C
47 paginationValidator,
48 setDefaultPagination,
8054669f 49 setDefaultVideosSort,
d57d1d83 50 videoFileMetadataGetValidator,
ac81d1a0 51 videosAddValidator,
09209296 52 videosCustomGetValidator,
ac81d1a0
C
53 videosGetValidator,
54 videosRemoveValidator,
ac81d1a0 55 videosSortValidator,
d57d1d83 56 videosUpdateValidator
65fcc311 57} from '../../../middlewares'
8054669f 58import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
3fd3ab2d
C
59import { VideoModel } from '../../../models/video/video'
60import { VideoFileModel } from '../../../models/video/video-file'
65fcc311 61import { blacklistRouter } from './blacklist'
40e87e9e 62import { videoCaptionsRouter } from './captions'
8054669f 63import { videoCommentRouter } from './comment'
fbad87b0 64import { videoImportsRouter } from './import'
c6c0fa6c 65import { liveRouter } from './live'
8054669f
C
66import { ownershipVideoRouter } from './ownership'
67import { rateVideoRouter } from './rate'
6e46de09 68import { watchingRouter } from './watching'
65fcc311 69
80e36cd9 70const auditLogger = auditLoggerFactory('videos')
65fcc311 71const videosRouter = express.Router()
9f10b292 72
ac81d1a0
C
73const reqVideoFileAdd = createReqFiles(
74 [ 'videofile', 'thumbnailfile', 'previewfile' ],
14e2014a 75 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
ac81d1a0 76 {
6040f87d
C
77 videofile: CONFIG.STORAGE.TMP_DIR,
78 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
79 previewfile: CONFIG.STORAGE.TMP_DIR
ac81d1a0
C
80 }
81)
82const reqVideoFileUpdate = createReqFiles(
83 [ 'thumbnailfile', 'previewfile' ],
14e2014a 84 MIMETYPES.IMAGE.MIMETYPE_EXT,
ac81d1a0 85 {
6040f87d
C
86 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
87 previewfile: CONFIG.STORAGE.TMP_DIR
ac81d1a0
C
88 }
89)
8c308c2b 90
65fcc311
C
91videosRouter.use('/', blacklistRouter)
92videosRouter.use('/', rateVideoRouter)
bf1f6508 93videosRouter.use('/', videoCommentRouter)
40e87e9e 94videosRouter.use('/', videoCaptionsRouter)
fbad87b0 95videosRouter.use('/', videoImportsRouter)
74d63469 96videosRouter.use('/', ownershipVideoRouter)
6e46de09 97videosRouter.use('/', watchingRouter)
c6c0fa6c 98videosRouter.use('/', liveRouter)
d33242b0 99
65fcc311
C
100videosRouter.get('/categories', listVideoCategories)
101videosRouter.get('/licences', listVideoLicences)
102videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 103videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 104
65fcc311
C
105videosRouter.get('/',
106 paginationValidator,
107 videosSortValidator,
8054669f 108 setDefaultVideosSort,
f05a1c30 109 setDefaultPagination,
0883b324 110 optionalAuthenticate,
d525fc39 111 commonVideosFiltersValidator,
eb080476 112 asyncMiddleware(listVideos)
fbf1134e 113)
65fcc311
C
114videosRouter.put('/:id',
115 authenticate,
ac81d1a0 116 reqVideoFileUpdate,
a2431b7d 117 asyncMiddleware(videosUpdateValidator),
90d4bb81 118 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 119)
e95561cd 120videosRouter.post('/upload',
65fcc311 121 authenticate,
ac81d1a0 122 reqVideoFileAdd,
3fd3ab2d 123 asyncMiddleware(videosAddValidator),
90d4bb81 124 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 125)
9567011b
C
126
127videosRouter.get('/:id/description',
a2431b7d 128 asyncMiddleware(videosGetValidator),
9567011b
C
129 asyncMiddleware(getVideoDescription)
130)
8319d6ae
RK
131videosRouter.get('/:id/metadata/:videoFileId',
132 asyncMiddleware(videoFileMetadataGetValidator),
133 asyncMiddleware(getVideoFileMetadata)
134)
65fcc311 135videosRouter.get('/:id',
6e46de09 136 optionalAuthenticate,
09209296 137 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
8d427346 138 asyncMiddleware(checkVideoFollowConstraints),
09209296 139 asyncMiddleware(getVideo)
fbf1134e 140)
1f3e9fec 141videosRouter.post('/:id/views',
2c8776fc 142 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
1f3e9fec
C
143 asyncMiddleware(viewVideo)
144)
198b205c 145
65fcc311
C
146videosRouter.delete('/:id',
147 authenticate,
a2431b7d 148 asyncMiddleware(videosRemoveValidator),
90d4bb81 149 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 150)
198b205c 151
9f10b292 152// ---------------------------------------------------------------------------
c45f7f84 153
65fcc311
C
154export {
155 videosRouter
156}
c45f7f84 157
9f10b292 158// ---------------------------------------------------------------------------
c45f7f84 159
556ddc31 160function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 161 res.json(VIDEO_CATEGORIES)
6e07c3de
C
162}
163
556ddc31 164function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 165 res.json(VIDEO_LICENCES)
6f0c39e2
C
166}
167
556ddc31 168function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 169 res.json(VIDEO_LANGUAGES)
3092476e
C
170}
171
fd45e8f4
C
172function listVideoPrivacies (req: express.Request, res: express.Response) {
173 res.json(VIDEO_PRIVACIES)
174}
175
90d4bb81 176async function addVideo (req: express.Request, res: express.Response) {
8b917537
C
177 // Processing the video could be long
178 // Set timeout to 10 minutes
179 req.setTimeout(1000 * 60 * 10, () => {
180 logger.error('Upload video has timed out.')
181 return res.sendStatus(408)
182 })
183
90d4bb81 184 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 185 const videoInfo: VideoCreate = req.body
9f10b292 186
1ef65f4c
C
187 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
188 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
189 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
7ccddd7b 190
af4ae64f 191 const video = new VideoModel(videoData) as MVideoFullLight
de94ac86 192 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 193
46a6db24 194 const videoFile = new VideoFileModel({
e11f68a3 195 extname: extname(videoPhysicalFile.filename),
d7a25329 196 size: videoPhysicalFile.size,
8319d6ae 197 videoStreamingPlaylistId: null,
daf6e480 198 metadata: await getMetadataFromFile(videoPhysicalFile.path)
46a6db24 199 })
2186386c 200
ad3405d0
C
201 if (videoFile.isAudio()) {
202 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
203 } else {
536598cf
C
204 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
205 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
536598cf
C
206 }
207
2186386c 208 // Move physical file
d7a25329 209 const destination = getVideoFilePath(video, videoFile)
14e2014a 210 await move(videoPhysicalFile.path, destination)
e3a682a8 211 // This is important in case if there is another attempt in the retry process
d7a25329 212 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
82815eb6 213 videoPhysicalFile.path = destination
ac81d1a0 214
1ef65f4c
C
215 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
216 video,
217 files: req.files,
218 fallback: type => generateVideoMiniature(video, videoFile, type)
219 })
eb080476 220
2186386c 221 // Create the torrent file
d7a25329 222 await createTorrentAndSetInfoHash(video, videoFile)
eb080476 223
5b77537c 224 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
e11f68a3 225 const sequelizeOptions = { transaction: t }
eb080476 226
453e83ea 227 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
e8bafea3 228
3acc5084
C
229 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
230 await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 231
eb080476
C
232 // Do not forget to add video channel information to the created video
233 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 234
eb080476 235 videoFile.videoId = video.id
eb080476 236 await videoFile.save(sequelizeOptions)
e11f68a3
C
237
238 video.VideoFiles = [ videoFile ]
93e1258c 239
1ef65f4c 240 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
eb080476 241
2baea0c7
C
242 // Schedule an update in the future?
243 if (videoInfo.scheduleUpdate) {
244 await ScheduleVideoUpdateModel.create({
245 videoId: video.id,
246 updateAt: videoInfo.scheduleUpdate.updateAt,
247 privacy: videoInfo.scheduleUpdate.privacy || null
248 }, { transaction: t })
249 }
250
5b77537c 251 await autoBlacklistVideoIfNeeded({
6691c522
C
252 video,
253 user: res.locals.oauth.token.User,
254 isRemote: false,
255 isNew: true,
256 transaction: t
257 })
5b77537c 258 await federateVideoIfNeeded(video, true, t)
eb080476 259
993cef4b 260 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
cadb46d8
C
261 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
262
5b77537c 263 return { videoCreated }
cadb46d8 264 })
94a5ff8a 265
5b77537c 266 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
e8d246d5 267
2186386c 268 if (video.state === VideoState.TO_TRANSCODE) {
d57d1d83 269 await addOptimizeOrMergeAudioJob(videoCreated, videoFile)
94a5ff8a
C
270 }
271
b4055e1c
C
272 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
273
90d4bb81
C
274 return res.json({
275 video: {
276 id: videoCreated.id,
277 uuid: videoCreated.uuid
278 }
c6c0fa6c 279 })
ed04d94f
C
280}
281
eb080476 282async function updateVideo (req: express.Request, res: express.Response) {
453e83ea 283 const videoInstance = res.locals.videoAll
7f4e7c36 284 const videoFieldsSave = videoInstance.toJSON()
80e36cd9 285 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
556ddc31 286 const videoInfoToUpdate: VideoUpdate = req.body
46a6db24 287
22a73cb8
C
288 const wasConfidentialVideo = videoInstance.isConfidential()
289 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
7b1f49de 290
1ef65f4c
C
291 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
292 video: videoInstance,
293 files: req.files,
294 fallback: () => Promise.resolve(undefined),
295 automaticallyGenerated: false
296 })
ac81d1a0 297
eb080476 298 try {
e8d246d5
C
299 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
300 const sequelizeOptions = { transaction: t }
0f320037 301 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 302
6691c522
C
303 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
304 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
305 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
306 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
307 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
308 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
309 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
310 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
311 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
312 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
b718fd22
C
313
314 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
1735c825 315 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
1e74f19a 316 }
317
22a73cb8 318 let isNewVideo = false
2922e048 319 if (videoInfoToUpdate.privacy !== undefined) {
22a73cb8 320 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
2922e048 321
22a73cb8
C
322 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
323 videoInstance.setPrivacy(newPrivacy)
46a6db24 324
22a73cb8
C
325 // Unfederate the video if the new privacy is not compatible with federation
326 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
46a6db24
C
327 await VideoModel.sendDelete(videoInstance, { transaction: t })
328 }
2922e048 329 }
7b1f49de 330
453e83ea 331 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
7b1f49de 332
3acc5084
C
333 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
334 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
e8bafea3 335
0f320037 336 // Video tags update?
1ef65f4c
C
337 await setVideoTags({
338 video: videoInstanceUpdated,
339 tags: videoInfoToUpdate.tags,
340 transaction: t,
341 defaultValue: videoInstanceUpdated.Tags
342 })
7920c273 343
0f320037
C
344 // Video channel update?
345 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 346 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 347 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037 348
22a73cb8 349 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
350 }
351
2baea0c7
C
352 // Schedule an update in the future?
353 if (videoInfoToUpdate.scheduleUpdate) {
354 await ScheduleVideoUpdateModel.upsert({
355 videoId: videoInstanceUpdated.id,
356 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
357 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
358 }, { transaction: t })
e94fc297
C
359 } else if (videoInfoToUpdate.scheduleUpdate === null) {
360 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
361 }
362
6691c522
C
363 await autoBlacklistVideoIfNeeded({
364 video: videoInstanceUpdated,
365 user: res.locals.oauth.token.User,
366 isRemote: false,
367 isNew: false,
368 transaction: t
369 })
370
5b77537c 371 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
6fcd19ba 372
80e36cd9 373 auditLogger.update(
993cef4b 374 getAuditIdFromRes(res),
80e36cd9
AB
375 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
376 oldVideoAuditView
377 )
378 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
e8d246d5
C
379
380 return videoInstanceUpdated
80e36cd9 381 })
e8d246d5 382
22a73cb8 383 if (wasConfidentialVideo) {
5b77537c 384 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
e8d246d5 385 }
b4055e1c 386
7294aab0 387 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
eb080476 388 } catch (err) {
6fcd19ba
C
389 // Force fields we want to update
390 // If the transaction is retried, sequelize will think the object has not changed
391 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 392 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
393
394 throw err
eb080476 395 }
90d4bb81
C
396
397 return res.type('json').status(204).end()
9f10b292 398}
8c308c2b 399
09209296
C
400async function getVideo (req: express.Request, res: express.Response) {
401 // We need more attributes
402 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 403
89cd1275
C
404 const video = await Hooks.wrapPromiseFun(
405 VideoModel.loadForGetAPI,
453e83ea 406 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
407 'filter:api.video.get.result'
408 )
1f3e9fec 409
09209296
C
410 if (video.isOutdated()) {
411 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
412 }
413
09209296 414 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
415}
416
417async function viewVideo (req: express.Request, res: express.Response) {
e4bf7856 418 const immutableVideoAttrs = res.locals.onlyImmutableVideo
9e167724 419
490b595a 420 const ip = req.ip
e4bf7856 421 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
b5c0e955 422 if (exists) {
e4bf7856
C
423 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
424 return res.sendStatus(204)
b5c0e955
C
425 }
426
e4bf7856 427 const video = await VideoModel.load(immutableVideoAttrs.id)
b5c0e955 428
e4bf7856
C
429 const promises: Promise<any>[] = [
430 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
431 ]
9e167724 432
e4bf7856 433 let federateView = true
b4055e1c 434
e4bf7856
C
435 // Increment our live manager
436 if (video.isLive && video.isOwned()) {
437 LiveManager.Instance.addViewTo(video.id)
438
439 // Views of our local live will be sent by our live manager
440 federateView = false
441 }
442
443 // Increment our video views cache counter
444 if (!video.isLive) {
445 promises.push(Redis.Instance.addVideoView(video.id))
446 }
447
448 if (federateView) {
449 const serverActor = await getServerActor()
450 promises.push(sendView(serverActor, video, undefined))
451 }
452
453 await Promise.all(promises)
454
455 Hooks.runAction('action:api.video.viewed', { video, ip })
456
457 return res.sendStatus(204)
9f10b292 458}
8c308c2b 459
9567011b 460async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 461 const videoInstance = res.locals.videoAll
9567011b
C
462 let description = ''
463
464 if (videoInstance.isOwned()) {
465 description = videoInstance.description
466 } else {
571389d4 467 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
468 }
469
470 return res.json({ description })
471}
472
8319d6ae
RK
473async function getVideoFileMetadata (req: express.Request, res: express.Response) {
474 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 475
8319d6ae
RK
476 return res.json(videoFile.metadata)
477}
478
04b8c3fb 479async function listVideos (req: express.Request, res: express.Response) {
fe987656
C
480 const countVideos = getCountVideos(req)
481
b4055e1c 482 const apiOptions = await Hooks.wrapObject({
48dce1c9
C
483 start: req.query.start,
484 count: req.query.count,
485 sort: req.query.sort,
06a05d5f 486 includeLocalVideos: true,
d525fc39
C
487 categoryOneOf: req.query.categoryOneOf,
488 licenceOneOf: req.query.licenceOneOf,
489 languageOneOf: req.query.languageOneOf,
490 tagsOneOf: req.query.tagsOneOf,
491 tagsAllOf: req.query.tagsAllOf,
492 nsfw: buildNSFWFilter(res, req.query.nsfw),
48dce1c9 493 filter: req.query.filter as VideoFilter,
6e46de09 494 withFiles: false,
fe987656
C
495 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
496 countVideos
b4055e1c
C
497 }, 'filter:api.videos.list.params')
498
89cd1275
C
499 const resultList = await Hooks.wrapPromiseFun(
500 VideoModel.listForApi,
501 apiOptions,
b4055e1c
C
502 'filter:api.videos.list.result'
503 )
eb080476
C
504
505 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 506}
c45f7f84 507
eb080476 508async function removeVideo (req: express.Request, res: express.Response) {
453e83ea 509 const videoInstance = res.locals.videoAll
91f6f169 510
3fd3ab2d 511 await sequelizeTypescript.transaction(async t => {
eb080476 512 await videoInstance.destroy({ transaction: t })
91f6f169 513 })
eb080476 514
993cef4b 515 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 516 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 517
b4055e1c
C
518 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
519
90d4bb81 520 return res.type('json').status(204).end()
9f10b292 521}